2016年2月3日水曜日

JavaScriptによるハノイの塔



ハノイの塔の実行は赤い部分だけで済んでしまうのには驚きます。
(参照: ゼロからわかるJavaScript超入門 河西朝雄 著(技術評論社)

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="utf-8" />
    <title>ハノイの塔(テキスト版)</title>
    <script type="text/javascript">
        var result;
        function hanoi(n, a, b, c) {
            if (n > 0) {
                hanoi(n - 1, a, c, b);
                result.value += "板" + n + ": " + a + " --> " + b + "\n";
                hanoi(n - 1, c, b, a);
            }
        }
        function start() {
            var N = document.getElementById("level").value;
            result = document.getElementById("result");
            result.value = "";
            hanoi(N, "a", "b", "c");          
        }
    </script>
</head>
<body>
    <div>ハノイの塔</div>
    <input id="level" type="text" size="2" value="4"/>
    <input type="button" value="START" onclick="start()" />
    <br />
    <textarea id="result" rows="20" cols="20"></textarea>
</body>
</html>