Skip to content
This repository was archived by the owner on Jul 24, 2023. It is now read-only.

Commit babea83

Browse files
author
cd155
committed
add solution for the hanoi tower
1 parent e123505 commit babea83

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/Recursion.hs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,3 +262,40 @@ newPair (x:xs) len =
262262
newPairHelper :: [Nat] -> [Nat] -> [[Nat]]
263263
newPairHelper _ [] = []
264264
newPairHelper a (x:xs) = (a ++ [x]): newPairHelper a xs
265+
266+
{-
267+
8.6
268+
Towers of Hanoi:
269+
In the classic problem of the Towers of Hanoi, you have 3 towers and
270+
N disks of different sizes which can slide onto any tower. The puzzle
271+
starts with disks sorted in ascending order of size from top to bottom
272+
(i.e., each disk sits on top of an even larger one).
273+
274+
You have the following constraints:
275+
1. Only one disk can be moved at a time.
276+
2. A disk is moved from the top of one tower to another tower.
277+
3. A disk cannot be placed on top of a smaller disk.
278+
279+
Write a program to move the disks from the first tower to the last
280+
using stacks.
281+
-}
282+
type Peg = String
283+
type Move = (Peg, Peg)
284+
285+
{-
286+
inputs:
287+
number fo discs
288+
three peg name
289+
290+
output: move sequence
291+
292+
Rationale:
293+
1. move n-1 stack from start peg to a temp peg,
294+
2. move start peg to the end peg
295+
3. move n-1 stack from temp peg to end peg
296+
-}
297+
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
298+
hanoi 0 _ _ _ = []
299+
hanoi 1 start _ end = [(start, end)]
300+
hanoi n start temp end =
301+
hanoi (n-1) start end temp ++ [(start, end)] ++ hanoi (n-1) temp start end

0 commit comments

Comments
 (0)