Tower of Hanoi

Add a reply

Posted by flagitious 596 days ago:
A classic problem. Format would be similar to the reverse challenge. Output any sequence of moves that solves the puzzle.

Like/dislike?
Posted by mick 593 days ago:
A classic problem. Format would be similar to the reverse challenge. Output any sequence of moves that solves the puzzle.

Like/dislike?

Are you thinking of the classic puzzle "What's the sequence to move the tower from peg A to peg B", or something more similar to reverse, like "Given a board with the disks in disarray, assemble the tower"?

I like them both, and I slightly prefer the latter idea. To flesh it out a bit, if "1" is the smallest disk and larger numbers are larger disks, then something like this:

Input:
peg A: 2
peg B: 3
peg C: 1

Output: (moves to build the tower on peg A)
1 to B
2 to C
1 to C
3 to A
1 to B
2 to A
1 to A

Of course, there's a much shorter solution, which is just to build the tower on peg B:
2 to B
1 to B

Yeah, I like this one...sounds good!

If you're thinking about writing it up, one request: Python lags so far behind in these competitions that it might be a nice change of pace to put the input in a Python-friendly format, like [[1,5], [3], [2,4]] to mean that disks 1 and 5 are on the first peg, 3 is on the second peg, and 2 and 4 are on the last peg.
Posted by flagitious 593 days ago:
I was thinking input would be the number of disks on peg A, and output would be any sequence of moves to get them all to peg C. This would be python friendly input :)

I had not considered starting from arbitrary positions, I'll have to think about that more.
Posted by mick 593 days ago:
I was thinking input would be the number of disks on peg A, and output would be any sequence of moves to get them all to peg C. This would be python friendly input :)

I had not considered starting from arbitrary positions, I'll have to think about that more.

Just to test this out, I whipped up quick solutions for both. My data point is that I experienced roughly a 50% increase in code size, and I'd estimate maybe a 2-3x increase in the amount of time it took me to get a working solution.

My unoptimized Python code to do "standard" Hanoi was 180 bytes, assuming the input was a single number that represents the number of disks. My unoptimized Python code to do "random-starting position" Hanoi was 260 bytes, assuming the input looks like this:

1
2 4
3

and the goal is to build the tower on any of the three pegs.

By the way, my solver produced this output for the above input:

1 to B
1 to A
2 to C
1 to C
1 to B
2 to A
1 to A
3 to B
1 to C
2 to B
1 to B

Note that it builds a tower on the middle (B) peg, so that the bottom disk (4) never has to move. Changing this solver to always build the result on the (C) peg is slightly longer (maybe 5-10 bytes?)

Add a reply