Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
The challenge
The shortest code, by character count to output an ASCII representation of Sierpinski's Triangle of N iterations made from the following ASCII triangle:
/\
/__\
Input is a single positive number.
Test cases
Input:
2
Output:
/\
/__\
/\ /\
/__\/__\
Input:
3
Output:
/\
/__\
/\ /\
/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\/__\/__\
Input:
5
Output:
/\
/__\
/\ /\
/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\ /__\/__\
/\ /\ /\ /\
/__\ /__\ /__\ /__\
/\ /\ /\ /\ /\ /\ /\ /\
/__\/__\/__\/__\/__\/__\/__\/__\
/\ /\
/__\ /__\
/\ /\ /\ /\
/__\/__\ /__\/__\
/\ /\ /\ /\
/__\ /__\ /__\ /__\
/\ /\ /\ /\ /\ /\ /\ /\
/__\/__\/__\/__\ /__\/__\/__\/__\
/\ /\ /\ /\
/__\ /__\ /__\ /__\
/\ /\ /\ /\ /\ /\ /\ /\
/__\/__\ /__\/__\ /__\/__\ /__\/__\
/\ /\ /\ /\ /\ /\ /\ /\
/__\ /__\ /__\ /__\ /__\ /__\ /__\ /__\
/\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\ /\
/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\/__\
Code count includes input/output (i.e full program).
J
46 characters, reading from stdin.
(,.~,~[,.~' '$~#,#)^:(<:".1!:1]3)' /\',:'/__\'
\n always delimits sentences, which made it impossible to fit inside S3 (only 54 characters to play with). S4 is a bit big at 162, so I padded it to fit. Serendipitously, /\ is a legal adverb. ☺
/\
i=:3
/\ /\
%r=:1!:1
/\ /\
t=:] [r+i
/\ /\ /\ /\
b=:' /\',:'/__\'
/\ /\
i=:1 -".t
/\ /\ /\ /\
h=:(' '$ ~#,#),.]
/\ /\ /\ /\
s=:( h^:1 ,d=: ,.~)
/\ /\ /\ /\ /\ /\ /\ /\
(,,&(10{a.)"1[s^:(-i)b)(1!:2)(4)
Sorry I'm late. This is based on A. Rex's Perl solution:
&I
;for
$x (2
..<>){$E
.= $E
;my$ y;3*
33 +3 ** 3;
s".+"$y.=$n.$&x2
,$ E.
$&.$ E"ge
;; $_ .= $y
}print;; sub I{($
E, $n ,$ F,
$B,$ U)=( $",$ /,qw
(/ \ _ )) ;$ _= $E .$
F.$B.$E.$n.$F.$U.$U.$B};33333333
Golfscript - 46
' /\ /__\ '4/{).+: ;.{ \ ++}%\{.+}%+~ ]}#~(*n*
Golfscript - 47
' /\ /__\ '4/): ;{ +: ;.{ \ ++}%\{.+}%+}#~(*n*
Golfscript - 48
' ': '/\ /__\\'+4/{2 *: ;.{ \ ++}%\{.+}%+}#~(*n*
Golfscript - 51
~' ': '/\ /__\\'+4/\(,{;2 *: ;.{ \ ++}%\{.+}%+}%;n*
Same algorithm as my shorter python ( and ruby ) answer
Golfscript - 78
2\~(?,{-1*}$1: ;{" ":$*. 2base.{[$$+' /\ ']=}%n+##{[$$+"/__\\"]=}%n .2*^: ;}%
Same algorithm as my longer python solution
This one has significant newlines
2\~(?,{-1*}$1: ;{" ":
*. 2base.{[
2*' /\ ']=}%n+##{[
2*"/__\\"]=}%n .2*^: ;}%
Go, 273 characters
package main
import(f"fmt";"os";s"strconv";)func main(){var
t=[2]string{" /\\ ","/__\\"};
n,_:=s.Atoi(os.Args[1]);a:=1;N:=a<<uint(n);for
N>0{N-=2;for
k:=0;k<2;k++{for
j:=0;j<N;j++{f.Print(" ")}b:=a;for
b>0{o:=t[k];if
b&1==0{o=" "}f.Print(o);b>>=1}f.Print("\n")}a^=a*2}}
Whitespace is all significant.
Unminized with gofmt sierpinski-3.go | perl -p -e's/\t/ /g':
package main
import (
"fmt";
"os";
"strconv";
)
func main() {
var t = [2]string{" /\\ ", "/__\\"};
n, _ := strconv.Atoi(os.Args[1]);
a := 1;
N := a << uint(n);
for N > 0 {
N -= 2;
for k := 0; k < 2; k++ {
for j := 0; j < N; j++ {
fmt.Print(" ")
}
b := a;
for b > 0 {
o := t[k];
if b&1 == 0 {
o = " "
}
fmt.Print(o);
b >>= 1;
}
fmt.Print("\n");
}
a ^= a * 2;
}
}
I got a good hint for Go golf here.
Python - 102
a=" /\ ","/__\\"
j=' '
for n in~-input()*j:j+=j;a=[j+x+j for x in a]+[x*2for x in a]
print"\n".join(a)
Python - 105
a=" /\ ","/__\\"
j=' '
for n in(input()-1)*j:j+=j;a=[j+x+j for x in a]+[x+x for x in a]
print"\n".join(a)
Python - 109
a=" /\ ","/__\\"
for n in range(1,input()):j=' '*2**n;a=[j+x+j for x in a]+[x+x for x in a]
print"\n".join(a)
Python2.6 - 120
N=1<<input()
a=1
while N:
N-=2
for s in" /\ ","/__\\":print' '*N+bin(a)[2:].replace('0',' '*4).replace('1',s)
a=a^a*2
Perl, 82 strokes
This version no longer prints a trailing newline. Only the first newline is necessary:
$_=' /\
/__\\';
for$x(2..<>){
my$y;
$".=$";
s#.+#$y.=$/.$&x2,$".$&.$"#ge;
$_.=$y
}
print
If command-line switches are allowed, then by traditional Perl golf scoring, this is 77+3 strokes (the first newline is literal):
#!perl -p
$\=' /\
/__\\';
$y="",
$".=$",
$\=~s#.+#$y.=$/.$&x2,$".$&.$"#ge,
$\.=$y
for 2..$_
Please feel free to edit my answer if you find an improvement.
Haskell, 153 149 137 125 118 112 characters:
Using tail recursion:
(%)=zipWith(++)
p=" ":p
g t _ 1=t
g t s(n+1)=g(s%t%s++t%t)(s%s)n
main=interact$unlines.g[" /\\ ","/__\\"]p.read
earlier version, #118 characters:
(%)=zipWith(++)
f 1=[" /\\ ","/__\\"]
f(n+1)=s%t%s++t%t where t=f n;s=replicate(2^n)' ':s
main=interact$unlines.f.read
Using the (justly deprecated!) n+k pattern saved 4 characters.
I like how it comes out halfway readable even in compressed form.
edit:old main
main=do{n<-getLine;putStr$unlines$f$read n}
Perl
94 characters when newlines are removed.
$c=2**<>;$\=$/;for$a(0..--$c){print$"x($c-$a&~1),
map$_*2&~$a?$"x4:$a&1?'/__\\':' /\ ',0..$a/2}
Ruby — 85
a=' /\ ','/__\\'
j=' '
2.upto(gets.to_i){j+=j;a=a.map{|x|j+x+j}+a.map{|x|x+x}}
puts a
101 chars — /\-modified solution from Rosetta Code
(a=2**gets.to_i).times{|y|puts" "*(a-y-1)+(0..y).map{|x|~y&x>0?' ':y%2>0?x%2>0?'_\\':'/_':'/\\'}*''}
Python, 135 chars
S=lambda n:[" /\\ ","/__\\"]if n==1 else[" "*(1<<n-1)+x+" "*(1<<n-1)for x in S(n-1)]+[x+x for x in S(n-1)]
for s in S(input()):print s
MATLAB - 64 characters (script version)
This assumes that you have the variable N already defined in your workspace:
A=[' /\ ';'/__\'];for i=1:N-1,B=32*ones(2^i);A=[B A B;A A];end;A
MATLAB - 78 characters (m-file function version)
Pass N as an argument to the function s:
function A=s(N),A=[' /\ ';'/__\'];for i=1:N-1,B=32*ones(2^i);A=[B A B;A A];end
C
Same algorithm as the Perl answer, but weighing in heavier, at 131 necessary characters.
a,b;main(c,v)char**v;{c=1<<atoi(v[1]);for(a=0;a<c;a++,puts(""))
for(b=c;b--;write(1,b&~a?" ":a&1?"/__\\":" /\\ ",4-2*(b>a)))--b;}
I thought write(1,…) was UNIX API, but this seems to compile and run fine on Windows too.
If you replace char by int, it saves one character and still works, but it's of questionable legality.
Logo (not exactly following the requirements): 47 characters
to F:n if:n[repeat 3[F(:n-1)fd 2^:n rt 120]]end
I tested this only with http://www.calormen.com/Logo/ so I don't know if it's portable. It doesn't follow the requirements, but surely logo must be the appropriate language here? :) I love that at the time of writing logo is one character short of equalling golfscript and J.
Lua, 139 characters
t={" /\\ ","/__\\"}for i=2,(...)do for j=1,#t do
t[#t+1]=t[j]:rep(2)k=(" "):rep(#t[j]/2)t[j]=k..t[j]..k end end
print(table.concat(t,"\n"))
Nroff, 542
$ nroff -rn=5 file.n
.pl 1
.nf
.de b
. nr i 0
. while d\\$1\\ni \{\
. \\$3 \\$1\\ni \\$2\\ni
. nr i +1
. \}
..
.de push
. nr i 0
. while d\\$2\\ni \{\
. nr i +1
. \}
. nr j 0
. while d\\$1\\nj \{\
. ds \\$2\\ni \&\\*[\\$1\\nj]
. nr i +1
. nr j +1
. \}
..
.ds l0 \& /\[rs] \&
.ds l1 "/__\[rs]
.ds s \&\
.de o
. ds \\$2 \&\\*s\\*[\\$1]\\*s
..
.de p
. ds \\$2 \&\\*[\\$1]\\*[\\$1]
..
.de assign
. ds \\$2 \&\\*[\\$1]
..
.nr a 2
.while \na<=\nn \{\
. ds s \&\*s\*s
. b l m o
. b l n p
. b m l assign
. push n l
. nr a +1
.\}
.de t
\\*[\\$1]
..
.b l zz t
F#, 225 chars
let rec p n=if n=1 then" "else p(n-1)+p(n-1)
and S n=if n=1 then[" /\\ ";"/__\\"]else let s=S(n-1)in List.append(List.map(fun s->p(n)+s+p(n))s)(List.map(fun x->x+x)s)
for s in S(int(System.Console.ReadLine()))do printfn"%s"s
Clojure: 174 characters
Algorithm stolen from others above.
(doseq[q((fn f[n](if(= n 1)[" /\\ ""/__\\"](let[z(f(dec n))](concat(map #(let[y(repeat(Math/pow 2(dec n))\ )](apply str(concat y % y)))z)(map str z z)))))(read))](println q))
38 of those characters are parentheses. : (
(doseq [q ((fn f [n]
(if (= n 1)
[" /\\ " "/__\\"]
(let [z (f (dec n))]
(concat
(map #(let [y (repeat (Math/pow 2 (dec n))\ )]
(apply str (concat y % y))) z)
(map str z z))))) (read))]
(println q))
Python, 120 characters (recursive solution)
S=lambda n:n<2and[" /\ ","/__\\"]or[" "*n+x+" "*n for x in S(n/2)]+[x+x for x in S(n/2)]
print"\n".join(S(1<<input()-1))
I started putting on the green where #fserb left off...
GolfScript (45 44 chars)
~(' /\ /__\ '4/)#{.+\.{[2$.]*}%\{.+}%+\}*;n*
Similar to gnibbler's solution. My initial attempt was already quite similar, and then I looked at his and borrowed some ideas.
Python, 186 chars (UNIX line termination)
for j in range(1,n):
for s in p:
print s
x=2**j;y=2*x;p.extend(['']*x)
for i in range(y-1,-1,-1):
if i<x:
s=' '*x;p[i]=s+p[i]+s
else:
q=p[i-x];p[i]=q+q
Prolog, 811 Chars
:- module(sierpinsky, [draw/1]).
% draw(+Level)
draw(N) :- K is 2^(N+1)-1,
for(Line, 0, K),
draw2(N, Line, true, nl),
fail.
draw(_).
% draw2(+Level, +Line, +Before, +After)
draw2(0, 0, Before, After) :- !,
Before, write(' /\\ '), After.
draw2(0, 1, Before, After) :- !,
Before, write('/__\\'), After.
draw2(N, Line, Before, After) :- N>0, K is 2^N, Line < K, !, M is N-1,
draw2(M, Line, (Before, tab(K)), (tab(K), After)).
draw2(N, Line, Before, After) :- N>0, K is 2^N, Line >= K, !, M is N-1,
Line2 is Line - K,
draw2(M, Line2, Before, draw2(M, Line2, true, After)).
% for(+Variable, +Integer, +Integer)
for(V, N, M) :- N =< M, V = N.
for(V, N, M) :- N < M, K is N+1, for(V, K, M).
% tab(+Integer)
tab(N) :- for(_, 1, N), write(' '), fail.
tab(_).
Related
I've been following this course https://learntla.com/introduction/example/ however I'm having difficulty running the model. It does not generates any states at all
Version TLA+ = 1.8
------------------------------ MODULE Example ------------------------------
=============================================================================
\* Modification History
\* Last modified Fri Sep 03 17:43:29 IST 2021 by faish
\* Created Fri Sep 03 17:15:54 IST 2021 by faish
EXTENDS Naturals, TLC
(* --algorithm transfer
variables alice_account = 10, bob_account = 10, money \in 1..20
begin
A: alice_account := alice_account - money;
B: bob_account := bob_account + money;
C: assert alice_account >= 0;
end algorithm*)
\* BEGIN TRANSLATION (chksum(pcal) = "4f516040" /\ chksum(tla) = "66759d32")
VARIABLES alice_account, bob_account, money, pc
vars == << alice_account, bob_account, money, pc >>
Init == (* Global variables *)
/\ alice_account = 10
/\ bob_account = 10
/\ money \in 1..20
/\ pc = "A"
A == /\ pc = "A"
/\ alice_account' = alice_account - money
/\ pc' = "B"
/\ UNCHANGED << bob_account, money >>
B == /\ pc = "B"
/\ bob_account' = bob_account + money
/\ pc' = "C"
/\ UNCHANGED << alice_account, money >>
C == /\ pc = "C"
/\ Assert(alice_account >= 0,
"Failure of assertion at line 16, column 4.")
/\ pc' = "Done"
/\ UNCHANGED << alice_account, bob_account, money >>
(* Allow infinite stuttering to prevent deadlock on termination. *)
Terminating == pc = "Done" /\ UNCHANGED vars
Next == A \/ B \/ C
\/ Terminating
Spec == Init /\ [][Next]_vars
Termination == <>(pc = "Done")
\* END TRANSLATION
Here is the console output
Starting... (2021-09-03 18:07:58)
Computing initial states...
Finished computing initial states: 0 distinct states generated at 2021-09-03 18:08:03.
Model checking completed. No error has been found.
Estimates of the probability that TLC did not check all reachable states
because two distinct states had the same fingerprint:
calculated (optimistic): val = 0.0
Progress(1) at 2021-09-03 18:08:03: 0 states generated (0 s/min), 0 distinct states found (0 ds/min), 0 states left on queue.
0 states generated, 0 distinct states found, 0 states left on queue.
The depth of the complete state graph search is 1.
Finished in 6116ms at (2021-09-03 18:08:03)
Here is the model
I don't understand why it's choosing "No Behaviour Spec". The option list doesn't have anything else in it. The course however selects a "Temporal Formula". Where do I find that option?
TLC ignores everything below the ==== line. Move that after the "End Translation" line, and then in the model, under What is the Behavior Spec, set it to Temporal Formula and set the formula to Spec. Then it should work.
I'm doing a past Function Programming exam paper and have this question:
Here are two ways of writing essentially the same expression:
f (g(x,y),z,h(t))
f (g x y) z (h t)
(a) Illustrate the different structures of the two expressions by drawing them as two different kinds of tree.
(b) Define Haskell data types Bush a and Tree a to capture the two different structures.
I'm kind of stuck because I've never done any thing like this in my course. It's pretty obvious from a later part that the first expression should be represented by Tree a and the second by Bush a, but I don't really know where to go from here. I guessed something like:
data Tree a = Leaf a | Node (Tree a) (Tree a)
data Bush a = Node a [Bush a]
But I don't think the Binary tree type is the right one to use. Could someone point me in the right direction?
Actually, the first expression is represented by Bush and the second by Tree.
In Haskell, g x y means that g x is applied to y; in C, g(x, y) means that g is applied to a collection of arguments — {x, y}. Therefore, in C:
f(g(x,y),z,h(t)) = Bush f [Bush g [Bush x [], Bush y []], Bush z [], Bush h [Bush t []]]
f
+--g
| +--x
| +--y
|
+--z
|
+--h
+--t
And in Haskell:
f (g x y) z (h t) = App (App (App f (App (App g x) y)) z) (App h t)
+
/ \
/ /\
+ h t
/ \
/\ z
f +
/ \
/\ y
g x
Trying to prove correctness of a insertion function of elements into a bst I got stuck trying to prove a seemingly trivial lemma.
My attempt so far:
Inductive tree : Set :=
| leaf : tree
| node : tree -> nat -> tree -> tree.
Fixpoint In (n : nat) (T : tree) {struct T} : Prop :=
match T with
| leaf => False
| node l v r => In n l \/ v = n \/ In n r
end.
(* all_lte is the proposition that all nodes in tree t
have value at most n *)
Definition all_lte (n : nat) (t : tree) : Prop :=
forall x, In x t -> (x <= n).
Lemma all_lte_trans: forall n m t, n <= m /\ all_lte n t -> all_lte m t.
Proof.
intros.
destruct H.
unfold all_lte in H0.
unfold all_lte.
intros.
Clearly if everything in the tree is smaller than n and n <= m everything is smaller than m, but I cannot seem to make coq believe me. How do I continue?
You have to use the le_trans theorem :
le_trans: forall n m p : nat, n <= m -> m <= p -> n <= p
that comes from Le package.
It meas that you have to import Le or more generally Arith with :
Require Import Arith.
at the beginning of your file. Then, you can do :
eapply le_trans.
eapply H0; trivial.
trivial.
Is there a difference between 4 ^ 2 and Math.pow(4, 2); in Actionscript 3?
Is there a difference between 4 ^ 2 and Math.pow(4, 2);
Yes, ^ is the binary xor operator, whereas Math.pow(x, y) raises x to the y power.
410 ^ 210 == 610 // 01002 xor 00102 == 01102
Math.pow(4, 2) == 16 // 42 == 16
As of ES2016, the shorthand for Math.pow(x, y) is x**y
console.log('Using `Math.pow(4, 2)`:', Math.pow(4, 2))
console.log('Using `4**2`:', 4**2)
How does one prove (forall x, P x /\ Q x) -> (forall x, P x) in Coq? Been trying for hours and can't figure out how to break down the antecedent to something that Coq can digest. (I'm a newb, obviously :)
You can do it more quickly by just applying H, but this script
should be more clear.
Lemma foo : forall (A:Type) (P Q: A-> Prop), (forall x, P x /\ Q x) -> (forall x, P x).
intros.
destruct (H x).
exact H0.
Qed.
Try
elim (H x).
Actually, I figured this one out when I found this:
Mathematics for Computer Scientists 2
In lesson 5 he solves the exact same problem and uses "cut (P x /\ Q x)" which re-writes the goal from "P x" to "P x /\ Q x -> P x". From there you can do some manipulations and when the goal is just "P x /\ Q x" you can apply "forall x : P x /\ Q x" and the rest is straightforward.
Assume ForAll x: P(x) /\ Q(x)
var x;
P(x) //because you assumed it earlier
ForAll x: P(x)
(ForAll x: P(x) /\ Q(x)) => (ForAll x: P(x))
Intuitivly, if for all x, P(x) AND Q(x) hold, then for all x, P(x) holds.
here is the answer:
Lemma fa_dist_and (A : Set) (P : A -> Prop) (Q: A -> Prop):
(forall x, P x) /\ (forall x, Q x) <-> (forall x : A, P x /\ Q x).
Proof.
split.
intro H.
(destruct H).
intro H1.
split.
(apply H).
(apply H0).
intro H.
split.
intro H1.
(apply H).
intro H1.
(apply H).
Qed.
you can find other solved exercises in this file: https://cse.buffalo.edu/~knepley/classes/cse191/ClassNotes.pdf