ocaml: phase 5.1 hanoi.ml baseline (Tower of Hanoi move count, n=10 -> 1023)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 26s

Classic doubly-recursive solution returning the move count:

  hanoi n from to via =
    if n = 0 then 0
    else hanoi (n-1) from via to + 1 + hanoi (n-1) via to from

For n = 10, returns 2^10 - 1 = 1023.

Exercises 4-arg recursion, conditional base case, and tail-position
addition. Uses 'to_' instead of 'to' for the destination param to
avoid collision with the 'to' keyword in for-loops — the OCaml
conventional workaround.

37 baseline programs total.
This commit is contained in:
2026-05-09 08:21:19 +00:00
parent 1a828d5b9f
commit 39f4c7a9a8
3 changed files with 20 additions and 0 deletions

View File

@@ -14,6 +14,7 @@
"factorial.ml": 3628800,
"fraction.ml": 7,
"frequency.ml": 5,
"hanoi.ml": 1023,
"fizzbuzz.ml": 57,
"list_ops.ml": 30,
"json_pretty.ml": 24,

View File

@@ -0,0 +1,11 @@
let rec hanoi n from to_ via =
if n = 0 then 0
else
let a = hanoi (n - 1) from via to_ in
let b = 1 in
let c = hanoi (n - 1) via to_ from in
a + b + c
;;
hanoi 10 1 3 2