Skip to content

Instantly share code, notes, and snippets.

@athos
Created September 13, 2010 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save athos/577442 to your computer and use it in GitHub Desktop.
Save athos/577442 to your computer and use it in GitHub Desktop.
-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