Skip to content

Instantly share code, notes, and snippets.

@takashi1975
Last active January 26, 2020 01:37
Show Gist options
  • Save takashi1975/399d051bd050f9a210880477d5f58a90 to your computer and use it in GitHub Desktop.
Save takashi1975/399d051bd050f9a210880477d5f58a90 to your computer and use it in GitHub Desktop.
ハノイの塔
/**
* 「解く手順を考えた結果、再帰でできそうだ、という流れ」 の解説図がわかりやすいです。
* https://qiita.com/ting/items/134b37bbeb756655ca6b
*/
//ハノイの塔(再帰関数)
function hanoi(saucer, from, to, work) {
if (saucer == 0) return;
//ハノイの塔 再帰呼び出し
hanoi(saucer - 1, from, work, to);
//移動
let v = from.array.pop();
to.array.push(v);
//移動確認
console.log(`move: saucer:${saucer} [from]${from.name}:${from.array} -(${v} を移動)-> [to]${to.name}:${to.array}`);
//ハノイの塔 再帰呼び出し
hanoi(saucer - 1, work, to, from);
}
//変数
let a = { name: "A", array: [3, 2, 1] };
let b = { name: "B", array: [] };
let c = { name: "C", array: [] };
//実行前の状態確認
console.log(`before: ${a.name}:${a.array}, ${b.name}:${b.array}, ${c.name}:${c.array}`);
//実行
hanoi(a.array.length, a, b, c);
//実行後の状態確認
//console.log(`after : ${a.name}:${a.array}, ${b.name}:${b.array}, ${c.name}:${c.array}`);
console.log("after :", a, b, c);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment