Towers of Hanoi: Difference between revisions
Content added Content deleted
(→{{header|NewLISP}}: changed name) |
m (→{{header|J}}: formating) |
||
Line 491: | Line 491: | ||
=={{header|J}}== |
=={{header|J}}== |
||
'''Solutions''' |
|||
<lang j>H =: i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * |
<lang j>H =: i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * NB. tacit using anonymous recursion |
||
H1=: monad define |
H1=: monad define NB. explicit equivalent of H |
||
if. y do. |
if. y do. |
||
({&0 2 1 , 0 2 , {&1 0 2) H1 y-1 |
({&0 2 1 , 0 2 , {&1 0 2) H1 y-1 |
||
Line 500: | Line 501: | ||
end. |
end. |
||
)</lang> |
)</lang> |
||
'''Example use''' |
|||
<tt>H</tt> employs anonymous recursion; <tt>H1</tt> is an "explicit" statement of the same computation. For example: |
|||
<lang j> H 3 |
<lang j> H 3 |
||
0 2 |
0 2 |
||
Line 511: | Line 512: | ||
The result is a 2-column table; a row <tt>i,j</tt> is interpreted as: move a disk (the top disk) from peg <tt>i</tt> to peg<tt> j</tt> . |
The result is a 2-column table; a row <tt>i,j</tt> is interpreted as: move a disk (the top disk) from peg <tt>i</tt> to peg<tt> j</tt> . |
||
'''Alternative solution'''<br> |
|||
If a textual display is desired, similar to some of the other solutions here: |
|||
<lang J>hanoi=:monad define |
<lang J>hanoi=: monad define |
||
moves=. i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * y |
moves=. i.@,&2 ` (({&0 2 1,0 2,{&1 0 2)@$:@<:) @. * y |
||
disks=. $~` ((],[,]) $:@<:) @.* y |
disks=. $~` ((],[,]) $:@<:) @.* y |
||
Line 520: | Line 522: | ||
For example: |
For example: |
||
<lang J> hanoi 3 |
<lang J> hanoi 3 |
||
move disk 1 from peg 1 to peg 3 |
move disk 1 from peg 1 to peg 3 |