Skip to content

Instantly share code, notes, and snippets.

@kohyama kohyama/plexho.clj
Created Nov 8, 2012

Embed
What would you like to do?
Hanoi Operations
(defn hanoi-ops [s t d n]
(if (zero? n) '()
(concat
(hanoi s d t (dec n))
(list [n s d])
(hanoi t s d (dec n)))))
(hanoi-ops 'A 'B 'C 4)
; -> ([1 A B] [2 A C] [1 B C] [3 A B] [1 C A] [2 C B] [1 A B] [4 A C]
; [1 B C] [2 B A] [1 C A] [3 B C] [1 A B] [2 A C] [1 B C])
hanoi_ops s t d n
| n == 0 = []
| otherwise = hanoi_ops s d t (n - 1) ++
[(n, s, d)] ++
hanoi_ops t s d (n - 1)
hanoi_ops 'A' 'B' 'C' 4
-- -> [(1,'A','B'),(2,'A','C'),(1,'B','C'),(3,'A','B'),
-- (1,'C','A'),(2,'C','B'),(1,'A','B'),(4,'A','C'),
-- (1,'B','C'),(2,'B','A'),(1,'C','A'),(3,'B','C'),
-- (1,'A','B'),(2,'A','C'),(1,'B','C')]
function hanoi_ops(s, t, d, n) {
if (0 < n)
return hanoi_ops(s, d, t, n - 1).concat(
[[n, s, d]]).concat(
hanoi_ops(t, s, d, n - 1));
return [];
}
hanoi_ops('A', 'B', 'C', 4);
// -> [ [ 1, 'A', 'B' ], [ 2, 'A', 'C' ], [ 1, 'B', 'C' ], [ 3, 'A', 'B' ],
// [ 1, 'C', 'A' ], [ 2, 'C', 'B' ], [ 1, 'A', 'B' ], [ 4, 'A', 'C' ],
// [ 1, 'B', 'C' ], [ 2, 'B', 'A' ], [ 1, 'C', 'A' ], [ 3, 'B', 'C' ],
// [ 1, 'A', 'B' ], [ 2, 'A', 'C' ], [ 1, 'B', 'C' ] ]
(defun hanoi-ops (s tmp d n)
(if (zerop n) '()
(append (hanoi-ops s d tmp (- n 1))
`((,n ,s ,d))
(hanoi-ops tmp s d (- n 1)))))
(hanoi-ops 'A 'B 'C 4)
; -> ((1 A B) (2 A C) (1 B C) (3 A B) (1 C A) (2 C B) (1 A B) (4 A C)
; (1 B C) (2 B A) (1 C A) (3 B C) (1 A B) (2 A C) (1 B C))
(define (hanoi-ops s t d n)
(if (zero? n) '()
(append (hanoi-ops s d t (- n 1))
`((,n ,s ,d))
(hanoi-ops t s d (- n 1)))))
(hanoi-ops 'A 'B 'C 4)
; -> ((1 A B) (2 A C) (1 B C) (3 A B) (1 C A) (2 C B) (1 A B) (4 A C)
; (1 B C) (2 B A) (1 C A) (3 B C) (1 A B) (2 A C) (1 B C))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.