Oleksandr Gavenko's blog
2017-01-28 22:40 Solution for Hanoi problem in JS

"Tower of Hanoi" is famous task. It has simple recursive solution.

One liner in JavaScript look like:

function han(src, dst, aux, n) {if (n > 0) {han(src, aux, dst, n-1); console.log("%s => %s: %d", src, dst, n); han(aux, dst, src, n-1);}}

Or more verbose:

function han(src, dst, aux, n) {
  if (n > 0) {
    han(src, aux, dst, n-1);
    console.log("%s => %s: %d", src, dst, n);
    han(aux, dst, src, n-1);
  }
}

Tests:

han("src", "dst", "aux", 1);
han("src", "dst", "aux", 2);
han("src", "dst", "aux", 3);

Example of output for n=3:

src => dst: 1
src => aux: 2
dst => aux: 1
src => dst: 3
aux => src: 1
aux => dst: 2
src => dst: 1

Solution have such number of moves:

N(n) = 2^n - 1

Compare my implementation with http://interglacial.com/hoj/hoj.html

See also:

https://en.wikipedia.org/wiki/Tower_of_Hanoi

Wikipedia description of mathematical task "Tower of Hanoi".

problem, js

Feeds

all / emacs / java / python

Tags

admin(1), anki(1), blog(1), css(2), cygwin(2), emacs(3), fs(1), git(2), gradle(1), hg(2), html(1), interview(11), java(2), js(3), lang(2), lighttpd(1), mobile(1), naming(1), oracle(1), print(1), problem(5), quiz(6), rst(1), security(1), sql(2), srs(1), style(1), unit(1), utils(1), vcs(3), web(2), win(2)

Archive