Skip to content

Instantly share code, notes, and snippets.

@athos

athos/hanoi.erl

Created Sep 13, 2010
Embed
What would you like to do?
-module(hanoi).
-compile(export_all).
hanoi(N) ->
hanoi(N, a, c, [], fun lists:reverse/1).
hanoi(0, _, _, Moves, K) ->
K(Moves);
hanoi(N, From, To, Moves, K) ->
[Temp] = [a,b,c] -- [From, To],
hanoi(N-1, From, Temp, Moves,
fun(Moves) ->
hanoi(N-1, Temp, To, [{N, From, To}|Moves], K)
end).
print_moves([]) ->
done;
print_moves([{N, From, To}|Moves]) ->
io:format("move disk ~w from ~w to ~w~n", [N, From, To]),
print_moves(Moves).
main([N]) ->
print_moves(hanoi(list_to_integer(atom_to_list(N)))).
%%
% Example:
% $ erl -noshell -s hanoi main 3 -s init stop
% move disk 1 from a to c
% move disk 2 from a to b
% move disk 1 from c to b
% move disk 3 from a to c
% move disk 1 from b to a
% move disk 2 from b to c
% move disk 1 from a to c
% $
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.