TLA+ model checker fails to generate states - proof

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.

Related

Recursive definition of nat_to_bin is ill-formed

I am currently reading the first volume of the softwarefoundations series. In one of the exercises I am supposed to write a function which turns a natural number (unary form) into the equivalent binary number.
This is my code/approach:
Inductive bin : Type :=
| Z
| B0 (n : bin)
| B1 (n : bin).
Fixpoint evenb (n:nat) : bool :=
match n with
| O => true
| S O => false
| S (S n') => evenb n'
end.
Fixpoint nat_to_bin (n:nat) : bin :=
match n with
| 0 => Z
| 1 => B1 Z
| 2 => B0 (B1 Z)
| m => match evenb(m) with
| true => B0 (nat_to_bin (Nat.div m 2))
| false => B1 (nat_to_bin (Nat.modulo m 2))
end
end.
I am using https://jscoq.github.io/scratchpad.html to work on these exercises.
Now I get this error message:
Recursive definition of nat_to_bin is ill-formed. In environment
nat_to_bin : nat -> bin
n : nat
n0 : nat
n1 : nat
n2 : nat
Recursive call to nat_to_bin has principal argument equal to "Nat.div
n 2 " instead of one of the following variables: "n0" "n1" "n2" .
Recursive definition is: "fun n : nat => match n with
| 0 => Z
| 1 => B1 Z
| 2 => B0 (B1 Z )
| S (S (S _) ) =>
if evenb n then B0 (nat_to_bin (Nat.div n 2 ) )
else B1 (nat_to_bin (Nat.modulo n 2 ) )
end " .
To retain good logical properties, all functions definable in Coq are terminating. To enforce that, there is a restriction on fixpoint definitions, like the one you are trying to do, called the guard condition. This restriction is roughly that the recursive call can only be done on subterms of the argument of the function.
This is not the case in your definition, where you apply nat_to_bin to the terms (Nat.div n 2) and (Nat.modulo n 2) which are functions applied to n. Although you can mathematically prove that those are always smaller than n, they are no subterms of n, so your function does not respect the guard condition.
If you wanted to define nat_to_bin in the way you are doing, you would need to resort to well-founded induction, which would use the well-foundedness of the order on nat to allow you to call you function on any term you can prove smaller than n. However, this solution is quite complex, because it would force you to do some proofs that are not that easy.
Instead, I would advise going another way: just above in the book, it is suggested to define a function incr : bin -> bin that increments a binary number by one. You can use that one to define nat_to_bin by a simple recursion on n, like this:
Fixpoint nat_to_bin (n:nat) : bin :=
match n with
| 0 => Z
| S n' => incr (nat_to_bin n')
end.
As for incr itself, you should also be able to write it down using a simple recursion on your binary number, as they are written with low-order bit outside.

Multiple Constructors in Prolog

I was trying to implement various forms of queries on Hailstone Sequence.
Hailstone sequences are sequences of positive integers with the following properties:
1 is considered the terminating value for a sequence.
For any even positive integer i, the value that comes after i in the sequence is i/2.
For any odd positive integer j > 1, the value that comes after j in the sequence is 3j+1
Queries can be
hailSequence(Seed,Sequence): where the Sequence is the hailstone sequence generated from the given Seed.
hailStone(M,N): where N is the number that follows M in a hailstone sequence. E.g. if M is 5 then N should be 16, if M is 20 then N should be 10, etc.
hailStorm(Seed,Depth,HailTree): where HailTree is the tree of values that could preceed Seed in a sequence of the specified depth.
Example:
| ?- hailStorm(1,4,H).
H = hs(1,hs(2,hs(4,hs(8)))) ?
yes
| ?- hailStorm(5,3,H).
H = hs(5,hs(10,hs(3),hs(20))) ?
yes
Pictorial Representation
Now I've implemented the first two predicates:
hailSequence(1,[1]) :- !.
hailSequence(N,[N|S]) :- 0 is N mod 2, N1 is round(N / 2), hailSequence(N1,S).
hailSequence(N,[N|S]) :- 1 is N mod 2, N1 is (3 * N) + 1, hailSequence(N1, S).
hailStone(X,Y) :- nonvar(X), 0 is X mod 2, Y is round(X / 2).
hailStone(X,Y) :- nonvar(X), 1 is X mod 2, Y is (3 * X) + 1.
hailStone(X,Y) :- nonvar(Y), 1 is Y mod 3, T is round( (Y - 1) / 3), 1 is T mod 2, X is T.
For the hailStorm/2 predicate, I've written the following code, but it is not working as expected:
make_hs1(S,hs(S)).
make_hs2(S,R,hs(S,make_hs1(R,_))).
make_hs3(S,L,R,hs(S,make_hs1(L,_),make_hs1(R,_))).
hailStorm(S,1,hs(S)) :- !.
hailStorm(S,D,H) :- nonvar(S), nonvar(D), 4 is S mod 6, S=\= 4, make_hs3(S,hailStorm(round((S-1)/3),D-1,_X),hailStorm(2*S,D-1,_Y),H).
hailStorm(S,D,H) :- nonvar(S), nonvar(D), make_hs2(S,hailStorm(2*S,D-1,_X),H).
Output:
| ?- hailStorm(5,2,H).
H = hs(5,make_hs1(hailStorm(2*5,2-1,_),_))
yes
which is not the desired output,i.e.,
H = hs(5,hs(10)) ?
There are several issues expressed in the problem statement:
In Prolog, there are predicates and terms but not functions. Thinking of them as functions leads one to believe you can write terms such as, foo(bar(3), X*2)) and expect that Prolog will call bar(3) and evaluate X*2 and then pass these results as the two arguments to foo. But what Prolog does is pass these just as terms as you see them (actually, X*2 internally is the term, *(X,2)). And if bar(3) were called, it doesn't return a value, but rather either succeeds or fails.
is/2 is not a variable assignment operator, but rather an arithmetic expression evaluator. It evaluates the expression in the second argument and unifies it with the variable or atom on the left. It succeeds if it can unify and fails otherwise.
Although expressions such as 0 is N mod 2, N1 is round(N / 2) will work, you can take more advantage of integer arithmetic in Prolog and write it more appropriately as, 0 =:= N mod 2, N1 is N // 2 where =:= is the arithmetic comparison operator. You can also use bit operations: N /\ 1 =:= 0, N1 is N // 2.
You haven't defined a consistent definition for what a hail storm tree looks like. For example, sometimes your hs term has one argument, and sometimes it has three. This will lead to unification failures if you don't explicitly sort it out in your predicate hailStorm.
So your hailSequence is otherwise correct, but you don't need the cut. I would refactor it a little as:
hail_sequence(1, [1]).
hail_sequence(Seed, [Seed|Seq]) :-
Seed > 1,
Seed /\ 1 =:= 0,
S is Seed // 2,
hail_sequence(S, Seq).
hail_sequence(Seed, [Seed|Seq]) :-
Seed > 1,
Seed /\ 1 =:= 1,
S is Seed * 3 + 1,
hail_sequence(S, Seq).
Or more compactly, using a Prolog if-else pattern:
hail_sequence(1, [1]).
hail_sequence(Seed, [Seed|Seq]) :-
Seed > 1,
( Seed /\ 1 =:= 0
-> S is Seed // 2
; S is Seed * 3 + 1
),
hail_sequence(S, Seq).
Your description for hailStone doesn't say it needs to be "bidirectional" but your implementation implies that's what you wanted. As such, it appears incomplete since it's missing the case:
hailStone(X, Y) :- nonvar(Y), Y is X * 2.
I would refactor this using a little CLPFD since it will give the "bidirectionality" without having to check var and nonvar. I'm also going to distinguish hail_stone1 and hail_stone2 for reasons you'll see later. These represent the two ways in which a hail stone can be generated.
hail_stone(S, P) :-
hail_stone1(S, P) ; hail_stone2(S, P).
hail_stone1(S, P) :-
S #> 1,
0 #= S rem 2,
P #= S // 2.
hail_stone2(S, P) :-
S #> 1,
1 #= S rem 2,
P #= S * 3 + 1.
Note that S must be constrained to be > 1 since there is no hail stone after 1. If you want these using var and nonvar, I'll leave that as an exercise to convert back. :)
Now to the sequence. First, I would make a clean definition of what a tree looks like. Since it's a binary tree, the common representation would be:
hs(N, Left, Right)
Where Left and Right are branchs (sub-trees), which could have the value nul, n, nil or whatever other atom you wish to represent an empty tree. Now we have a consistent, 3-argument term to represent the tree.
Then the predicate can be more easily defined to yield a hail storm:
hail_storm(S, 1, hs(S, nil, nil)). % Depth of 1
hail_storm(S, N, hs(S, HSL, HSR)) :-
N > 1,
N1 is N - 1,
% Left branch will be the first hail stone sequence method
( hail_stone1(S1, S) % there may not be a sequence match
-> hail_storm(S1, N1, HSL)
; HSL = nil
),
% Right branch will be the second hail stone sequence method
( hail_stone2(S2, S) % there may not be a sequence match
-> hail_storm(S2, N1, HSR)
; HSR = nil
).
From which we get, for example:
| ?- hail_storm(10, 4, Storm).
Storm = hs(10,hs(20,hs(40,hs(80,nil,nil),hs(13,nil,nil)),nil),hs(3,hs(6,hs(12,nil,nil),nil),nil)) ? ;
(1 ms) no
If you want to use the less symmetrical and, arguably, less canonical definition of binary tree:
hs(N) % leaf node
hs(N, S) % one sub tree
hs(N, L, R) % two sub trees
Then the hail_storm/3 predicate becomes slightly more complex but manageable:
hail_storm(S, 1, hs(S)).
hail_storm(S, N, HS) :-
N > 1,
N1 is N - 1,
( hail_stone1(S1, S)
-> hail_storm(S1, N1, HSL),
( hail_stone2(S2, S)
-> hail_storm(S2, N1, HSR),
HS = hs(S, HSL, HSR)
; HS = hs(S, HSL)
)
; ( hail_stone2(S2, S)
-> hail_storm(S2, N1, HSR),
HS = hs(S, HSR)
; HS = hs(S)
)
).
From which we get:
| ?- hail_storm1(10, 4, Storm).
Storm = hs(10,hs(20,hs(40,hs(80),hs(13))),hs(3,hs(6,hs(12)))) ? ;
no

Reducing a boolean expression

I am having an expression, suppose,
a = 1 && (b = 1 || b != 0 ) && (c >= 35 || d != 5) && (c >= 38 || d = 6)
I expect it to be reduced to,
a = 1 && b != 0 && (c >= 38 || d = 6)
Does anyone have any suggestions? Pointers to any algorithm?
Nota Bene: Karnaugh Map or Quine-McCluskey are not an option here, I believe. As these methods don't handle grey cases. I mean, expression can only be reduced as far as things are like, A or A' or nothing, or say black or white or absense-of-colour. But here I'm having grey shades, as you folks can see.
Solution: I have written the program for this in Clojure. I used map of a map containing a function as value. That came pretty handy, just a few rules for a few combinations and you are good. Thanks for your helpful answers.
I think you should be able to achieve what you want by using Constraint Handling Rules. You would need to write rules that simplify the OR- and AND-expressions.
The main difficulty would be the constraint entailment check that tells you which parts you can drop. E.g., (c >= 35 || d != 5) && (c >= 38 || d = 6) simplifies to (c >= 38 || d = 6) because the former is entailed by the latter, i.e., the latter is more specific. For the OR-expressions, you would need to choose the more general part, though.
Google found a paper on an extension of CHR with entailment check for user-defined constraints. I don't know enough CHR to be able to tell you whether you would need such an extension.
I believe these kinds of things are done regularly in constraint logic programming. Unfortunatly I'm not experienced enough in it to give more accurate details, but that should be a good starting point.
The general principle is simple: an unbound variable can have any value; as you test it against inequalities, it's set of possible values are restricted by one or more intervals. When/if those intervals converge to a single point, that variable is bound to that value. If, OTOH, any of those inequalities are deemed unsolvable for every value in the intervals, a [programming] logic failure occurs.
See also this, for an example of how this is done in practice using swi-prolog. Hopefully you will find links or references to the underlying algorithms, so you can reproduce them in your platform of choice (maybe even finding ready-made libraries).
Update: I tried to reproduce your example using swi-prolog and clpfd, but didn't get the results I expected, only close ones. Here's my code:
?- [library(clpfd)].
simplify(A,B,C,D) :-
A #= 1 ,
(B #= 1 ; B #\= 0 ) ,
(C #>= 35 ; D #\= 5) ,
(C #>= 38 ; D #= 6).
And my results, on backtracking (line breaks inserted for readability):
10 ?- simplify(A,B,C,D).
A = 1,
B = 1,
C in 38..sup ;
A = 1,
B = 1,
D = 6,
C in 35..sup ;
A = 1,
B = 1,
C in 38..sup,
D in inf..4\/6..sup ;
A = 1,
B = 1,
D = 6 ;
A = 1,
B in inf.. -1\/1..sup,
C in 38..sup ;
A = 1,
D = 6,
B in inf.. -1\/1..sup,
C in 35..sup ;
A = 1,
B in inf.. -1\/1..sup,
C in 38..sup,
D in inf..4\/6..sup ;
A = 1,
D = 6,
B in inf.. -1\/1..sup.
11 ?-
So, the program yielded 8 results, among those the 2 you were interested on (5th and 8th):
A = 1,
B in inf.. -1\/1..sup,
C in 38..sup ;
A = 1,
D = 6,
B in inf.. -1\/1..sup.
The other were redundant, and maybe could be eliminated using simple, automatable logic rules:
1st or 5th ==> 5th [B == 1 or B != 0 --> B != 0]
2nd or 4th ==> 4th [C >= 35 or True --> True ]
3rd or 1st ==> 1st ==> 5th [D != 5 or True --> True ]
4th or 8th ==> 8th [B == 1 or B != 0 --> B != 0]
6th or 8th ==> 8th [C >= 35 or True --> True ]
7th or 3rd ==> 3rd ==> 5th [B == 1 or B != 0 --> B != 0]
I know it's a long way behind being a general solution, but as I said, hopefully it's a start...
P.S. I used "regular" AND and OR (, and ;) because clpfd's ones (#/\ and #\/) gave a very weird result that I couldn't understand myself... maybe someone more experienced can cast some light on it...

Code Golf: Connecting the dots

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.
You may remember these drawings from when you were a child, but now it's time to let the computer draw them (in full ascii splendour). Have fun!
Description:
The input are multiple lines (terminated by a newline) which describe a 'field'. There are 'numbers' scattered across this field (seperated by whitespace). All lines can be considered to be the same length (you can pad spaces to the end).
the numbers always start at 1
they follow the ordering of the natural numbers: every 'next number' is incremented with 1
every number is surrounded by (at least) one whitespace on its left and right
Task:
Draw lines between these numbers in their natural order
(1 -> 2 -> 3 -> ...N) (assume N <= 99) with the following characteristics:
replace a number with a '+' character
for horizontal lines: use '-'
for vertical lines: use '|'
going left and down or right and up: /
going left and up or right and down: \
Important notes:
When drawing lines of type 4 and 5 you can assume (given the points to connect with coordinates x1, y1 and x2, y2) that distance(x1,x2) == distance(y1,y2). Or in other words (as user jball commented): "consecutive elements that are not horizontally or vertically aligned always align to the slope of the slash or backslash".
It is important to follow the order in which the dots are connected (newer lines can strike out older lines).
-- Sample input 1 --
8
7 6
10 9
5
3 4
11
12 13
1 2
-- Sample output 1 --
+
/|
/ +--+
+--------+ \
/ \
/ +
/ |
/ +--+
+ |
\ |
+------------------------+
+--------------------------+
-- Sample input 2 --
64
63
62 61
1 65
66 57 58
2 56 59 45
67 55 46
3 44
54 60 47
53 52 49 48
4 51 50 43
5 42
41
6 23
22 25 26 40
20 21 24 34
7 13 12 33
19 27 32
14 35
8 15
16
39
17 18 28 31 36
9 38
10 11 29 30 37
-- Sample output 2 -- (unicorn reference)
+
/+
//
//
//
/+--+
+ + \
| + +-\+
+ \ + \ +
/ + + \ +\
+ \ \ | +
| + + +/
| +--+ +-------+/
+ +--+ +
/ \
+ +
| +
+ + /
\ +\ +---+ +
\ +--+ + \ /+
+ +--+ / \ /+|
/ | |+ + /+ |
/ + || / // +
+ + || / // /
\ + || / // /
\ | || / +/ /
\ +---+ + +\ +
+ | | | +|
+--+ +---+ +
Winner:
Shortest solution (by code character count). Input can be read via standard input.
Commodore 64 BASIC - 313 chars
EDIT: See below for the golfed version
A little trip down the memory lane with PET graphics, POKEs and PEEKs and everything :)
The program operates directly in the screen memory, so you just go ahead, clear the screen, place your dots, and type RUN:
You have to wait a minute or so while it finds the dots and then it starts to draw. It isn't fast - you can actually see the lines being drawn, but that's the coolest part :)
Golfed version:
Commodore BASIC seems like a great language for golfing, because it doesn't require whitespace :) You can also shorten most of the commands by entering an unshifted first letter followed by a shifted second letter. For example, POKE can be typed as P[SHIFT+O], which appears as P┌ on the screen:
Perl, 222 char (211)
Perl, 384 365 276 273 253 225 222 218 211 chars (222 when contest ended). Newlines are for "readability" only and are not included in the character count.
Last edit: no longer overwriting $", and printing #S directly
$_=join'',#S=map{$n=s/$/$"x97/e;(/./g)[0..95],$/}<>;
while(/\b$n /){$S[$q=$-[0]]='+';($P,$Q)=sort{$a-$b}$q,$p||$q;
for(qw'\98 |97 /96 -1'){/\D/;$S[$P]=$&until($Q-$P)%$'||$Q<=($P+=$')}
$n++;$p=$q}s/\d/ /,print for#S
Explanation:
$_=join'',#S=map{$n=s/$/$"x97/e;(/./g)[0..95],$/}<>;
This task will be easier if all the lines are the same length (say, 97 characters).
This statement takes each line of input, replaces the end-of-line character with
96 spaces, then pushes the first 96 characters plus a newline into the array #S.
Note we are also setting $n=1, as 1 is the first number we'll look for in
the input.
The join statement creates a single string from the array #S.
It is more convenient to use the scalar variable $_ for pattern matching, and more convenient to use the array #S for making updates to the picture.
while(/\b$n /){
Search for the number $n in the variable $_. Evaluating regular expressions in Perl
has several side-effects. One is to set the special variable $-[0] with the position of the start of the matched pattern within the matched string. This gives us the position of the number $n in the string $_ and also the array #S.
Of course, the loop will end when $n is high enough that we can't find it in the input.
$S[$q=$-[0]]='+';
Let $q be the position of the number $n in the string $_ and the array #S,
and assign the character '+' at that position.
$P=($p||=$q)+$q-($Q=$q>$p?$q:$p)
($P,$Q)=sort{$a-$b}$p||$q,$q;
The first time through the loop, set $p to $q. After the
first time, $p will hold the previous value of $q (which
will refer to the position in the input of the previous number).
Assign $P and $Q such that $P=min($p,$q),
$Q=max($p,$q)
for(qw'\98 |97 /96 -1'){
By construction, consecutive numbers are either
connected by a vertical line. Since the input is constructed
to have 97 characters on each line, this case means that
$p-$q is divisible by 97.
"aligned to the slope of a backslash", which would make
$p-$q divisible by 98
"aligned to the slope of a forward slash", which would make
$p-$q divisible by 96
on the same horizontal line
The elements of this list encode the possible number of positions
between line segments, and the character to encode that segment.
/\D/;
Another trivial regex evaluation. As a side-effect, it sets the
special variable $& (the MATCH variable) to the line segment
character (\ | / or -) and $' (the POSTMATCH variable) to
the number (98 97 96 or 1) encoded in the list element.
$S[$P]=$&until($Q-$P)%$'||$Q<=($P+=$')
This statement draws the line segment between two numbers.
If $Q-$P is divisible by $', then keep incrementing $P by $'
and assigning the character $& to $S[$P] until $P reaches $Q.
More concretely, for example if $Q-$P is divisible by 97, then
increment $P by 97 and set $S[$P]='|'. Repeat until $P>=$Q.
$n++;$p=$q
Prepare for the next iteration of the loop. Increment $n to the
next number to search for in the input, and let $p hold the
position of the previous number.
s/\d/ /,print for#S
Output the array, converting any leftover digits (from double
digit identifiers in the input where we only overwrote the first
digit with a '+') to spaces as we go.
MS-DOS Batch (yes, you read right!)
I often hear (or read) people say batch isn't very powerful and you can't do much with them, well to them I say, behold, the power of BATCH!
The actual script (script.bat):
set file=%~1
call :FindNextNum 1
for /F "tokens=2 delims=:" %%i IN ('find /c /V "" "%file%"') DO set /a totalLines=%%i
set maxLen=0
for /F "delims=" %%i IN (%file%) DO (
call :CountChars "%%i"
if /i !charCount! gtr !maxLen! set maxLen=!charCount!
)
for /L %%i IN (0,1,%totalLines%) DO set "final_%%i=" & for /L %%j IN (0,1,%maxLen%) DO set "final_%%i=!final_%%i! "
:MainLoop
set currLineNum=%lineNum%
set currCol=%linePos%
set currNum=%nextNum%
set /a targetNum=%currNum%+1
call :FindNextNum %targetNum%
if "%nextNum%"=="" goto MainEnd
REM echo %currNum% -^> %nextNum%
if /I %currLineNum% lss %lineNum% (
call :DrawLine %currCol% %currLineNum% %linePos% %lineNum%
) else (
call :DrawLine %linePos% %lineNum% %currCol% %currLineNum%
)
goto MainLoop
:MainEnd
for /L %%i IN (0,1,%totalLines%) DO echo.!final_%%i!
goto:eof
:DrawLine
if /I %2 equ %4 goto:DrawHoriz
set "char=" & set "pos=%1" & set "inc=0"
if /I %1 LSS %3 set "char=\" & set "pos=%1" & set "inc=1"
if /I %1 GTR %3 set "char=/" & set "pos=%1" & set "inc=-1"
for /L %%i IN (%2,1,%4) DO call :DrawChar %%i !pos! %char% & set /a "pos+=%inc%"
goto:DrawEnds
:DrawHoriz
set "start=%1+1" & set "end=%3"
if /I %start% gtr %end% set "start=%3+1" & set "end=%1"
set /a lineEnd=%end%+1
set lineEnd=!final_%2:~%lineEnd%!
for /L %%i IN (%start%,1,%end%) DO set final_%2=!final_%2:~0,%%i!-
set final_%2=!final_%2!!lineEnd!
:DrawEnds
call :DrawChar %2 %1 +
call :DrawChar %4 %3 +
goto:eof
:DrawChar
set /a skip2=%2+1
if "%3"=="" (
set final_%1=!final_%1:~0,%2!^|!final_%1:~%skip2%!
) else (
set final_%1=!final_%1:~0,%2!%3!final_%1:~%skip2%!
)
goto:eof
:CountChars
set charCount=0
set val=%~1
:CountChars_loop
if not "%val:~1%"=="" (
set /a charCount+=1
set val=!val:~1!
goto CountChars_loop
)
goto:eof
:FindNextNum
for /F "delims=" %%i IN ('type "%file%" ^| find /V /N ""') DO (
for /F "tokens=1,2 delims=[]" %%j IN ("%%i") DO (
set /a lineNum=%%j-1
call :FindNext_internal "%%k" %1
if /I !nextNum! equ %1 goto :eof
)
)
goto:eof
:FindNext_internal
set currLine=%~1
set linePos=0
:FindNext_internal_loop
call :NextNumInLine "%currLine%"
set /a linePos+=%spaceInterval%
if "%nextNum%"=="" goto :EOF
if /I %nextNum% equ %2 goto :EOF
set /a spaceInterval+=1
set /a linePos+=1
if /I %nextNum% GTR 9 set /a "spaceInterval+=1" & set /a linePos+=1
set currLine=!currLine:~%spaceInterval%!
goto FindNext_internal_loop
:NextNumInLine
set nextNum=
for /F %%i IN (%1) DO set /a nextNum=%%i
if "%nextNum%"=="" goto :eof
set /a spaceInterval=0
set val=%~1
:NextNumInLine_loop
if "%val:~0,1%"==" " (
set /a spaceInterval+=1
set val=!val:~1!
goto NextNumInLine_loop
)
goto :eof
And this is how you call it
echo off
setlocal ENABLEDELAYEDEXPANSION
call script.bat input.txt
where "input.txt" is a file that contains the input for the "program".
P.S. This isn't actually optimized for line length yet, I've already spent a couple of hours getting to this point and now I need to sleep... I'll see if I can improve it tomorrow (currently 'script.bat' sits at 2755 bytes)
Rebmu: 218 chars
Ma L{-|\/}Qb|[sg?SBaB]Da|[feSm[TfiSrj[spAsp]iT[++Tbr]]t]Xa|[i?A]Ya|[i?FImHDa]Ca|[skPCmSCaBKfsA]wh[Jd++N][roG[xJyJ]]Bf+GwhB[JcB Ff+GiF[KcF HqXkXj VqYkYju[chCbPClEZv1[ezH2[eeHv3 4]]e?A+bRE[hV]f]]chJeFIlSCj{+}{+ }Jk Bf]wM
I'm getting pretty good at reading and editing it natively in its pig-latin form. (Though I do use line breaks!!) :)
But here's how the dialect is transformed by the interpreter when the case-insensitive "mushing" trick is boiled away, and one gets accustomed to it. I'll add some comments. (Tips: fi is find, fe is foreach, sp is a space character, i? is index, hd is head, ch is change, sk is skip, pc is pick, bk is break, i is if, e is either, ee is either equal, ad nauseum)
; copy program argument into variable (m)atrix
m: a
; string containing the (l)etters used for walls
l: {-|\/}
; q is a "b|function" (function that takes two parameters, a and b)
; it gives you the sign of subtracting b from a (+1, -1, or 0)
q: b| [sg? sb a b]
; d finds you the iterator position of the first digit of a two digit
; number in the matrix
d: a| [fe s m [t: fi s rj [sp a sp] i t [++ t br]] t]
; given an iterator position, this tells you the x coordinate of the cell
x: a| [i? a]
; given an iterator position, this tells you the y coordinate of the cell
y: a| [i? fi m hd a]
; pass in a coordinate pair to c and it will give you the iterator position
; of that cell
c: a| [sk pc m sc a bk fr a]
; n defaults to 1 in Rebmu. we loop through all the numbers up front and
; gather their coordinate pairs into a list called g
wh [j: d ++ n] [ro g [x j y j]]
; b is the (b)eginning coordinate pair for our stroke. f+ returns the
; element at G's current position and advances G (f+ = "first+")
; advance g's iteration position
b: f+ g
wh b [
; j is the iterator position of the beginning stroke
j: c b
; f is the (f)inishing coordinate pair for our stroke
f: f+ g
; if there is a finishing pair, we need to draw a line
i f [
; k is the iterator position of the end of the stroke
k: c f
; the (h)orizontal and (v)ertical offsets we'll step by (-1,0,1)
h: q x k x j
v: q y k y j
u [
; change the character at iterator location for b (now our
; current location) based on an index into the letters list
; that we figure out based on whether v is zero, h is zero,
; v equals h, or v doesn't equal h.
ch c b pc l ez v 1 [ez h 2 [ee h v 3 4]]
; if we update the coordinate pair by the offset and it
; equals finish, then we're done with the stroke
e? a+ b re [h v] f
]
]
; whether we overwrite the number with a + or a plus and space
; depends on whether we detect one of our wall "letters" already
; one step to the right of the iterator position
ch j e fi l sc j {+} {+ }
; update from finish pair to be new begin pair for next loop iteration
j: k
b: f
]
; write out m
w m
Both the language and sample are new and in an experimental stage. For instance, ad couldn't be used to add together vectors and matrices before I changed it to help with this sample. But I think that's just the sort of thing that a language designed specifically for code golf has to have anyway. It's a subtle line between "language" and "library".
Latest source with comments available on GitHub
Haskell, 424 chars
Current char count: 424 430 451 466 511 515 516 518 525 532 541 545 550 556 569 571 577 582 586 592.
import List
x%c=[(i,c)|i<-x]
l k p q|p>q=l k q p|True=head[[p,p+j..q]%c|m<-zip[k-1,k,k+1,1]"/|\\-",let (j,c)=m,mod(q-p)j==0]
w=map snd
q(k,m,x)z=w$sort$nubBy((==)&fst)$x%'+'++(concat$zipWith(l k)x$tail x)++z%'\n'++[1..m]%' '
r(z,m,x)=q(last z,m-1,w$sort x)z
u[(m,_)]n x=(-m::Int,n):x;u _ _ x=x
t(z,n,x)s|s=="\n"=(n:z,n+1,x)|True=(z,n+length s,u(reads s)n x)
y&x=(.x).y.x
main=interact$r.foldl t([],1,[]).groupBy((&&)&(>' '))
This version takes a lot of inspiration from the original Haskell entry below, but makes some significant changes. Most importantly, it represents image locations with a single index, not a pair of coordinates.
There are some changes:
The input must now have all lines padded to the same length (allowed by the rules.)
No longer needs either language extension
Original version:
(Needs -XTupleSections, and maybe -XNoMonomorphismRestriction)
import List
b=length
f=map
g=reverse
a(x,y)" "=(x,y+1)
a(x,y)z=([y,read z]:x,y+b z)
x%y=[min x y+1..max x y-1]
j([x,y],[w,z])|y==z=f(,'-')$f(y,)$x%w|x==w=f(,'|')$f(,x)$y%z|(y<z)==(x<w)=f(,'\\')$zip(y%z)$x%w|True=f(,'/')$zip(y%z)$g$x%w
k 0='\n'
k _=' '
y&x=(.x).y.x
y?x=f y.sort.x.concat
r z=snd?(nubBy((==)&fst).g)$[((y,x),k x)|x<-[0..maximum$f b d],y<-[1..b d]]:[((y,x),'+')|[x,y]<-e]:(f j$zip e$tail e)where d=f(groupBy$(&&)&(>' '))$lines z;e=tail?f g$zipWith(f.(:))[1..]$f(fst.foldl a([],1))d
main=interact r
Explanation:
(1) d=...: Splits the input into spaces and numbers, e.g.
z = " 6 5\n\n1 2\n\n 4 3\n\n 7"
=> d = [[" ","6"," "," ","5"],[],["1"," "," "," "," "," "," "," ","2"],[],[" "," "," "," ","4"," "," "," ","3"],[],[" ","7"]]
(2) e=...: Converts d into a list of (y, x) coordinates for each number.
e = [[1,3],[9,3],[9,5],[5,5],[5,1],[2,1],[2,7]]
--- // 1 2 3 4 5 6 7
(3)
[((y,x),k x)|...] is an empty board. (k returns a space or a \n depending on the x-coordinate.)
[((y,x),'+'))|...] are the plus signs at the numbers.
(f j$zip e$tail e) are the lines connecting the numbers. (j maps a pair of coordinates into a list of (coordinate, character) which represents a line.)
These 3 components are concatenated and filtered to form the actual output. Note that the order is important, so that nubBy(...).g can only keep the last character in the same location.
AWK - 296 317 321 324 334 340
Not a prize winner (yet), but I am pleased with the effort (line breaks for display). This new version uses VT-100 escape sequences. The '^[' is just one character, Escape!!! Cut and paste will not work with this version, since the sequence "^[" has to be replaced with the real ESC character. To make it forum friendly, ESC could be specified as "\0x1b", but it takes too much space...
BEGIN{FS="[ ]"}{for(j=i=0;i<NF;j+=length(g)){if(g=$++i){x[g]=k=i+j;y[g]=NR;
m=m>k?m:k}}}END{printf"^[[2J[%d;%dH+",Y=y[i=1],X=x[1];while(a=x[++i])
{a-=X;b=y[i]-Y;t=a?b?a*b>0?92:47:45:124;A=a?a>0?1:-1:0;B=b?b>0?1:-1:0;
for(r=a?a*A:b*B;--r;){printf"^[[%d;%dH%c",Y+=B,X+=A,t}
printf"^[[%d;%dH+",Y+=B,X+=A}}
The older standard version
BEGIN{FS="[ ]"}{for(j=i=0;i<NF;j+=length(g)){if(g=$++i){x[g]=k=i+j;y[g]=NR;
m=m>k?m:k}}}END{q[X=x[1],Y=y[i=1]]=43;while(a=x[++i]){a-=X;b=y[i]-Y;
t=a?b?a*b>0?92:47:45:124;A=a?a>0?1:-1:0;B=b?b>0?1:-1:0;for(r=a?a*A:b*B;--r;
q[X+=A,Y+=B]=t);q[X+=A,Y+=B]=43}for(j=0;++j<NR;){for(i=0;i<m;){t=q[i++,j];
printf"%c",t?t:32}print}}
Now a little explanation
# This will break the input in fields separated by exactly 1 space,
# i.e. the fields will be null or a number.
BEGIN{FS="[ ]"}
# For each line we loop over all fields, if the field is not null
# it is a number, hence store it.
# Also account for the fact the numbers use space.
# Also, find the maximum width of the line.
{
for(j=i=0;i<NF;j+=length(g)){
if(g=$++i){
k=j+i;x[g]=k;y[g]=NR;m=m>k?m:k
}
}
}
# Once we have all the data, let start cooking.
END{
# First, create a matrix with the drawing.
# first point is a +
q[X=x[1],Y=y[i=1]]=43;
# loop over all points
while(a=x[++i]){
# Check next point and select character
# If a == 0 -> -
# If b == 0 -> |
# If a and b have same sign -> \ else /
a-=X;b=y[i]-Y;t=a?b?a*b>0?92:47:45:124;
# there is no sgn() function
A=a?a>0?1:-1:0;B=b?b>0?1:-1:0;
# Draw the line between the points
for(k=0;++k<(a?a*A:b*B);){
q[X+=A,Y+=B]=t
}
# store + and move to next point
q[X+=A,Y+=B]=43
}
# Now output all lines. If value in point x,y is 0, emit space
for(j=0;++j<NR;){
for(i=0;i<m;){
t=q[i++,j];printf("%c",t?t:32)
}
print
}
}
C, 386
402 386 character in C. Newlines after the first are only for readability.
#include <stdio.h>
int x[101],y[101],c=1,r,w,h,b,i,j,k,m,n;
int main(){
while((b=getchar())-EOF)
b-' '?b-'\n'?ungetc(b,stdin),scanf("%d",&b),x[b]=c++,y[b]=h,c+=b>9:(w=c>w?c:w,++h,c=1):++c;
for(r=0;r<h&&putchar('\n');++r)
for(c=0;c<w;++c){
for(b=' ',i=2,m=x[1]-c,n=y[1]-r;j=m,k=n,m=x[i]-c,n=y[i]-r,x[i++];)
b=j|k&&m|n?j*m>0|k|n?k*n<0?(j-k|m-n?j+k|m+n?j|m?b:'|':'/':'\\'):b:'-':'+';
putchar(b);
}
}
Intel Assembler
Assembled size: 506 bytes
Source: 2252 bytes (hey, it's not a trivial problem this one)
To Assemble: Use A86
To Run: Tested with a WinXP DOS box. Invocation jtd.com < input > output
mov ax,3
int 10h
mov ax,0b800h
mov es,ax
mov ah,0bh
int 21h
mov bx,255
cmp al,bl
mov dh,bh
mov si,offset a12
push offset a24
je a1
mov si,offset a14
a1: inc bl
a2: mov dl,255
call si
cmp al,10
jb a4
a3: cmp al,10-48
jne a1
inc bh
mov bl,dh
jmp a2
a4: mov dl,al
call si
cmp al,10
jae a5
mov ah,dl
aad
mov dl,al
a5: mov di,dx
mov ch,al
shl di,2
mov [di+a32],bx
cmp bl,[offset a30]
jb a6
mov [offset a30],bl
a6: cmp bh,[offset a31]
jb a7
mov [offset a31],bh
a7: push offset a19
mov al,80
mul bh
add al,bl
adc ah,0
add ax,ax
lea di,[di+2+a32]
mov [di],ax
add di,2
cmp di,[a22-3]
jbe a8
mov [a22-3],di
mov [a25-3],di
a8: mov di,ax
mov al,dl
aam
cmp ah,0
je a10
a9: add ah,48
mov es:[di],ah
add di,2
a10:add al,48
mov es:[di],al
mov al,ch
inc bl
jmp a3
a11:jmp si
a12:mov ah,0bh
int 21h
cmp al,255
jne a15
mov ah,8
int 21h
a13:cmp al,13
je a11
sub al,48
ret
a14:mov ah,1
int 21h
cmp al,26
jne a13
mov si,offset a15
ret
a15:cmp dl,255
je a16
mov al,32
ret
a16:mov si,offset a32 + 4
lodsw
mov cx,ax
mov dx,ax
lodsw
mov di,ax
mov b es:[di],1
mov bp,0f000h
call a26
add sp,6
mov bx,[a22-3]
mov ax,[offset a31]
inc ax
a17:mov bp,[offset a30]
a18:mov b[bx],32
inc bx
dec bp
jnz a18
mov w[bx],0a0dh
add bx,2
dec ax
jnz a17
mov b[bx],'$'
add w[a30],2
a19:lodsw
xchg ax,dx
cmp ah,dh
lahf
mov bl,ah
cmp al,dl
lahf
shr bl,6
shr ah,4
and ah,12
or bl,ah
mov bh,0
shl bx,3
a20:mov b es:[di],43
a21:mov al,b[a30]
mul ch
add al,cl
adc ah,0
mov bp,ax
mov b[bp+100h],43
a22:add di,[bx + a29]
add cl,[bx + a29 + 4]
add ch,[bx + a29 + 6]
mov b es:[di],1
mov al,[bx + a29 + 2]
mov [a21-1],al
mov [a22-1],al
mov bp,01000h
call a26
cmp di,[si]
jne a20
mov al,es:[di+2]
sub al,48
cmp al,10
jae a23
mov b es:[di+2],0
a23:mov b[a21-1],43
mov b[a22-1],43
mov b es:[di],43
lodsw
ret
a24:mov al,b[a30]
mul ch
add al,cl
adc ah,0
mov bp,ax
mov b[bp+100h],43
a25:mov dx,[a22-3]
mov ah,9
int 21h
ret
a26:pusha
a27:mov cx,0ffffh
a28:loop a28
dec bp
jnz a27
popa
ret
a29:dw -162,92,-1,-1,-2,45,-1,0,158,47,-1,1,0,0,0,0,-160,124,0,-1
a30:dw 0
a31:dw 0,0,0,160,124,0,1,0,0,0,0,-158,47,1,-1,2,45,1,0,162,92,1,1
a32:
Interesting features: self modifying code, animated output (the second example works, but is too big to display), abuse of 'ret' to implement a loop counter, interesting way of determining line/movement direction.
F#, 725 chars
open System
let mutable h,s,l=0,Set.empty,Console.ReadLine()
while l<>null do
l.Split([|' '|],StringSplitOptions.RemoveEmptyEntries)
|>Seq.iter(fun t->s<-s.Add(int t,h,(" "+l+" ").IndexOf(" "+t+" ")))
h<-h+1;l<-Console.ReadLine()
let w=Seq.map(fun(k,h,x)->x)s|>Seq.max
let o=Array2D.create h (w+1)' '
Seq.sort s|>Seq.pairwise|>Seq.iter(fun((_,b,a),(_,y,x))->
let a,b,x,y=if b>y then x,y,a,b else a,b,x,y
o.[b,a]<-'+'
o.[y,x]<-'+'
if b=y then for x in(min a x)+1..(max a x)-1 do o.[y,x]<-'-'
elif a=x then for h in b+1..y-1 do o.[h,x]<-'|'
elif a<x then for i in 1..y-b-1 do o.[b+i,a+i]<-'\\'
else for i in 1..y-b-1 do o.[b+i,a-i]<-'/')
for h in 0..h-1 do
for x in 0..w do printf"%c"o.[h,x]
printfn""
Legend:
h = height
s = set
l = curLine
w = (one less than) width
o = output array of chars
Lines 1-6: I keep a set of (number, lineNum, xCoord) tuples; as I read in each line of input I find all the numbers and add them to the set.
Line 7-8: Then I create an array of output chars, initialized to all spaces.
Line 9: Sort the set (by 'number'), then take each adjacent pair and ...
Lines 10-16: ... sort so (a,b) is the 'highest' of the two points and (x,y) is the other. Put the '+' signs, and then if horizontal, draw that, else if vertical, draw that, else draw the correct diagonal. If the input is not 'valid', then who knows what happens (this code was littered with 'asserts' before I golf-ized it).
Lines 17-19: Print the result
Powershell, 328 304 characters
$i=$l=0;$k=#{}
$s=#($input|%{[regex]::matches($_,"\d+")|%{$k[1*$_.Value]=#{y=$l
x=$_.Index}};$l++;""})
while($a=$k[++$i]){
if($i-eq1){$x=$a.x;$y=$a.y}
do{$d=$a.x.CompareTo($x);$e=$a.y.CompareTo($y)
$s[$y]=$s[($y+=$e)].PadRight($x+1).Remove($x,1).Insert(($x+=$d),
"\-/|+|/-\"[4+$d*3+$e])}while($d-or$e)}$s
and here's a pretty-printed version with comments:
# Usage: gc testfile.txt | dots.ps1
$l=$i=0 # line, dot index (used below)
$k=#{} # hashtable that maps dot index to coordinates
# Apply regular expression to each line of the input
$s=#( $input | foreach{
[regex]::matches($_,"\d+") | foreach{
# Store each match in the hashtable
$k[ 1*$_.Value ] = #{ y = $l; x = $_.Index }
}
$l++; # Next line
"" # For each line return an empty string.
# The strings are added to the array $s which
# is used to produce the final output
}
)
# Connect the dots!
while( $a = $k[ ++$i ] )
{
if( $i -eq 1 ) # First dot?
{
# Current position is ($x, $y)
$x = $a.x;
$y = $a.y
}
do
{
$d = $a.x.CompareTo( $x ) # sign( $a.x - $x )
$e = $a.y.CompareTo( $y ) # sign( $a.y - $y )
$c = '\-/|+|/-\'[ 4 + $d * 3 + $e ] # character '
# Move
$x += $d
$y += $e
# "Replace" the charcter at the current position
# PadRight() ensures the string is long enough
$s[ $y ]=$s[ $y ].PadRight( $x+1 ).Remove( $x, 1 ).Insert( $x, $c )
} while( $d -or $e ) # Until the next dot is reached
}
# Print the resulting string array
$s
Python - 381
import re
b=list(iter(raw_input,''))
c=sum((zip([i]*999,re.finditer('\\d+',x))for i,x in enumerate(b)),[])
d=sorted((int(m.group()),i,m.start())for i,m in c)
e=[[' ']*max(map(len,b))for x in b]
for(t,u,v),(x,y,z)in zip(d,d[1:]+d[-1:]):
e[u][v]='+'
while u!=y or v!=z:i,j=(u<y)-(u>y),(v<z)-(v>z);u+=i;v+=j;e[u][v]=['|','/\\-'[(i==j)+2*(i==0)]][j!=0]
print'\n'.join(map(''.join,e))
C#, 422 chars
758 754 641 627 584 546 532 486 457 454 443 440 422 chars (next time maybe I won't submit so soon.)
using A=System.Console;class B{static int C,o,d,e,G,O=1,f,F,u,n;static
void Main(){var s=A.In.ReadToEnd();A.Clear();while(++u<s.Length){f++;if
(s[u]<32){u++;F++;f= 0;}if(s[u]>32){if(int.Parse(s[u]+""+s[++u])==O){o=
e>f?1:f>e?-1:0;C=d>F?1:F>d?-1:0 ;G=e+o;n=d+C;if(O++>1)while(n!=F||G!=f)
{A.SetCursorPosition(G-=o,n-=C);A.Write( "+/-|\\"[n==d&&G==e?0:n==F&&G
==f?0:C+o==0?1:C==0?2:o==0?3:4]);}e=f;d=F;F=0;f=u=-1 ;}f++;}}A.Read();}}
Usage: run, paste (or type) the input, ensure the last line is terminated, press CTRL-Z or F6, press Enter.
Formatted but still basically unintelligable version:
using A = System.Console;
class B
{
// code golf fun!
static int C, o, d, e, G, O = 1, f, F, u, n;
static void Main()
{
// read the input into a string char by char until EOF
var s = A.In.ReadToEnd();
A.Clear(); // clear console, ready to draw picture
// O is the "dot" number we're looking for
// f is current column
// F is current row
// loop over the field looking for numbers sequentially
// until no more are found
while (++u < s.Length)
{
f++;
// any char <32 is expected to be a CR/LF
// increment the current row and reset the current column
if (s[u] < 32)
{
u++; // skip the other half of the CR/LF pair
F++; // next row
f = 0; // column reset
}
// any char >32 is expected to be a number
if (s[u] > 32)
{
// parse the current + next char and see if it's
// the number we want
if (int.Parse(s[u] + "" + s[++u]) == O)
{
// set up coordinates, compare X1 with X2
// and Y1 with Y2 to figure out line direction
// horizontal direction (same as o=e.CompareTo(f))
o = e > f ? 1 : f > e ? - 1 : 0;
// vertical direction (same as C=d.CompareTo(F))
C = d > F ? 1 : F > d ? - 1 : 0;
// initial offsets compensate for off-by-one
G = e + o;
n = d + C;
// draw the line (except for the very first dot)
if (O++ > 1)
while (n != F || G != f)
{
// update coords and write desired char
A.SetCursorPosition(G -= o, n -= C);
// this lovely line decides which char to
// print, and prints it
A.Write(
"+/-|\\"[n == d && G == e ? 0 : n == F && G
== f ? 0 : C + o == 0 ? 1 : C == 0 ? 2 : o
== 0 ? 3 : 4]);
}
// remember end point of this line, to use as start point
// of next line
e = f;
d = F;
// reset current row (F), column (f), field position (u)
F = 0;
f = u = -1;
}
// bump current column because we parse 2 chars when we
// find a dot
f++;
}
}
A.Read(); // prevent command prompt from overwriting picture
}
}
Here goes!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int sign(int x) {
if (x < 0)
return -1;
if (x > 0)
return +1;
return 0;
}
#define MAX_ROWS 100
#define MAX_COLS 100
#define MAX_DIGITS 100
int main(void)
{
// Read in the digits
int number[MAX_DIGITS][2];
int rows = 0;
int cols = 0;
char row[MAX_COLS];
int maxvalue = 0;
int i, j, value, x;
for (i = 0; i < MAX_ROWS; i++) {
if (row != fgets(row, MAX_COLS, stdin))
break;
value = 0;
for (j=0; row[j] != 0; j++) {
if (row[j] >= '0' && row[j] <= '9') {
x = j;
value = 0;
do {
value = 10*value + (row[j]-'0');
j++;
} while (row[j] >= '0' && row[j] <= '9');
number[value][0] = i;
number[value][1] = x;
if (maxvalue < value) maxvalue = value;
if (rows < i+1) rows = i+1;
if (cols < x+1) cols = x+1;
}
}
}
// Create an empty field
char field[rows][cols];
memset(field, ' ', rows*cols);
char lines[] = "\\|/-+-/|\\";
int dr,dc;
// Draw the numbers and lines
field[number[1][0]][number[1][1]] = '+';
for (i = 2; i <= maxvalue; ++i) {
int r = number[i-1][0];
int c = number[i-1][1];
int rt = number[i][0];
int ct = number[i][1];
dr = sign(rt-r);
dc = sign(ct-c);
char line = lines[(dr+1)*3+dc+1];
while (r != rt || c != ct) {
r += dr;
c += dc;
field[r][c] = line;
}
field[r][c] = '+';
}
for (i = 0; i < rows; ++i) {
for (j = 0; j < cols; ++j)
putchar(field[i][j]);
putchar('\n');
}
return 0;
}
C#, 638 chars
using System;
using System.Linq;
using System.Text.RegularExpressions;
class C
{
static void Main()
{
int i=0,j;
var p = Console.In.ReadToEnd()
.Split('\n')
.SelectMany(
r =>
{
i++; j =0;
return Regex.Matches(r, "\\s+(\\d+)").Cast<Match>()
.Select(m => { j += m.Length; return new { X = j, Y = i-1, N = int.Parse(m.Groups[1].Value) }; });
}
).OrderBy(a=>a.N).ToList();
var W = p.Max(a => a.X)+1;
var k = new char[W*i+W];
i = 0;
while (i < p.Count)
{
var b = p[i > 0 ? i - 1 : 0]; var a = p[i];
int h = a.Y - b.Y, w = a.X - b.X;
var s = "|-/\\"[h == 0 ? 1 : w == 0 ? 0 : h / w > 0 ? 3 : 2];
while ((h | w) != 0) { k[b.X + w + W * (b.Y + h)] = s; h -= h.CompareTo(0); w -= w.CompareTo(0); }
k[a.X + a.Y * W] = '+';
k[W * ++i] = '\n';
}
Console.Write(k);
}
}
I cannot do multi-line in a comment, so I will demonstrate here.
In the following examples, distance(x1,x2) == distance(y1,y2):
+
|\
+-+
+
|\
| \
+--+
+
|\
| \
| \
+---+
With the rules as explained, distance(x1,x2) == distance(y1,y2)+2:
+\
| \
+--\+
+\
| \
| \
+---\+
+\
| \
| \
| \
+----\+
C++ 637
#include <iostream>
#include <string>
#include <vector>
#define S(x)((x)<0?-1:x>0?1:0)
using namespace std;enum{R=100,C=100,D=100};int main(){string s;
int N[D][2],M=0,q=0,p=0,i,j,V,L,a,b;for(i=0;j=0,(i<R)&&getline(cin,s);i++)
while((j=s.find_first_not_of(" ",j))<=s.size()){L=sscanf(&s[j],"%d",&V);
N[V][0]=i;N[V][1]=j;if(M<V)M=V;if(q<=i)q=i+1;if(p<=j)p=j+1;j+=L+1;}
string F(q*p,' '),l="\\|/-+-/|\\";F[p*N[1][0]+N[1][1]]='+';for(i=2;i<=M;++i){
int r=N[i-1][0],c=N[i-1][1],d=N[i][0],e=N[i][1];for(a=S(d-r),b=S(e-c);r!=d||c!=e;)
r+=a,c+=b,F[p*r+c]=l[(a+1)*3+b+1];F[p*r+c]='+';}for(i=0;i<q;i++)
cout<<string(&F[i*p],p)+"\n";}
Indented, and with a few slightly more meaningful names, that looks like:
#include <iostream>
#include <string>
#include <vector>
#define S(x)((x)<0?-1:x>0?1:0)
using namespace std;
enum{R=100,C=100,D=100};
int main(){
string s;
int N[D][2],M=0,rs=0,cs=0,i,j,V,L,dr,dc;
for(i=0;j=0,(i<R)&&getline(cin,s);i++)
while((j=s.find_first_not_of(" ",j))<=s.size()){
L=sscanf(&s[j],"%d",&V);
N[V][0]=i;
N[V][1]=j;
if(M<V)M=V;
if(rs<=i)rs=i+1;
if(cs<=j)cs=j+1;
j+=L+1;
}
string F(rs*cs,' '),lines="\\|/-+-/|\\";
F[cs*N[1][0]+N[1][1]]='+';
for(i=2;i<=M;++i){
int r=N[i-1][0],c=N[i-1][1],rt=N[i][0],ct=N[i][1];
for(dr=S(rt-r),dc=S(ct-c);r!=rt||c!=ct;)
r+=dr,c+=dc,F[cs*r+c]=lines[(dr+1)*3+dc+1];
F[cs*r+c]='+';
}
for(i=0;i<rs;i++)
cout<<string(&F[i*cs],cs)+"\n";
}
Despite superficial differences, it's a blatant theft of morotspaj's code.

Code Golf: Sierpinski's Triangle

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(_).