Created
March 10, 2018 17:45
-
-
Save venil7/6ff7efc76734be4ad97ca89fb5959da7 to your computer and use it in GitHub Desktop.
quick implementation of the Tower Of Hanoi problem
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type rod = list(int); | |
exception InvalidMove(int, int); | |
exception OtherMove(rod, rod); | |
let moveRods = (a: rod, b: rod) : (rod, rod) => | |
switch (a, b) { | |
| ([x, ...xs], []) => (xs, [x]) | |
| ([x, ...xs], [y, ...ys]) when x < y => (xs, [x, y, ...ys]) | |
| ([x, ...xs], [y, ...ys]) => raise(InvalidMove(x, y)) | |
| (xs, ys) => raise(OtherMove(xs, ys)) | |
}; | |
let rec move = (n: int, src: rod, dst: rod, aux: rod) : (rod, rod, rod) => | |
if (n > 0) { | |
let (src, aux, dst) = move(n - 1, src, aux, dst); | |
let (src, dst) = moveRods(src, dst); | |
let (aux, dst, src) = move(n - 1, aux, dst, src); | |
(src, dst, aux); | |
} else { | |
(src, dst, aux); | |
}; | |
let hanoi = (src: rod) => move(src |> List.length, src, [], []); | |
let _init = Array.init(23, x => x) |> Array.to_list; | |
let (a, b, c) = hanoi(_init); | |
Js.log(b); /*would be exactly same as `a`*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment