Mob coding through tower of hanoi

This commit is contained in:
Logan McGrath 2021-09-30 17:04:16 -07:00
parent 0aa6f36b88
commit 5462d22be8
6 changed files with 45 additions and 32 deletions

View File

@ -24,7 +24,7 @@ library
exposed-modules:
Homework
Homework.Ch01.CreditCards
Homework.Ch01.TowerOfHanoi
Homework.Ch01.Hanoi
Homework.Ch02.Log
Homework.Ch02.LogAnalysis
other-modules:
@ -34,6 +34,7 @@ library
ghc-options: -Wall -Werror -Wcompat -Widentities -Wincomplete-patterns -Wincomplete-record-updates -Wincomplete-uni-patterns -Wmissing-home-modules -Wname-shadowing -Wpartial-fields -Wredundant-constraints -Wunused-packages -Wunused-type-patterns
build-depends:
base >=4.14 && <5
, unordered-containers
default-language: Haskell2010
executable homework
@ -53,7 +54,7 @@ test-suite test
main-is: Spec.hs
other-modules:
Homework.Ch01.CreditCardsSpec
Homework.Ch01.TowerOfHanoiSpec
Homework.Ch01.HanoiSpec
Paths_homework
hs-source-dirs:
test

View File

@ -0,0 +1,26 @@
module Homework.Ch01.Hanoi where
import qualified Data.HashMap.Strict as HashMap
newtype Peg = Peg ()
data Move = Move {moveFrom :: String, moveTo :: String} deriving (Eq, Show)
data Disc = Disc {discSize :: Int}
hanoi :: Int -> String -> String -> String -> Either String [Move]
hanoi numDisks pegLabelA pegLabelB pegLabelC =
let _pegs =
HashMap.fromList
[ (pegLabelA, fillPegWithDiscs),
(pegLabelB, []),
(pegLabelC, [])
]
in Right
[ Move "a" "c",
Move "a" "b",
Move "c" "b"
]
where
fillPegWithDiscs :: [Disc]
fillPegWithDiscs = Disc <$> [1 .. numDisks] -- start here: make sure this is initialized correctly

View File

@ -1,16 +0,0 @@
module Homework.Ch01.TowerOfHanoi where
type Peg = String
type Move = (Peg, Peg)
hanoi :: Integer -> Peg -> Peg -> Peg -> [Move]
hanoi n x y z = runHanoi [] (reverse $ initStack n) [] []
where
initStack 0 = []
initStack xx = xx : initStack (xx - 1)
runHanoi moves (itemX : stackX) [] [] = runHanoi ((x, z) : moves) stackX [] [itemX]
runHanoi moves (itemX : stackX) [] (itemZ : stackZ)
| itemX > itemZ = runHanoi ((x, y) : moves) stackX [itemX] (itemZ : stackZ)
runHanoi moves ()

View File

@ -16,7 +16,8 @@ dependencies:
library:
source-dirs: lib
dependencies: []
dependencies:
- unordered-containers
executables:
homework:

View File

@ -0,0 +1,14 @@
module Homework.Ch01.HanoiSpec where
import Homework.Ch01.Hanoi
import Test.Hspec
spec :: Spec
spec = describe "hanoi" $ do
it "can solve for stack of 2 and three pegs" $ do
hanoi 2 "a" "b" "c"
`shouldBe` Right
[ Move "a" "c",
Move "a" "b",
Move "c" "b"
]

View File

@ -1,13 +0,0 @@
module Homework.Ch01.TowerOfHanoiSpec where
import Homework.Ch01.TowerOfHanoi
import Test.Hspec
spec :: Spec
spec = describe "hanoi" $ do
it "explodes" $ do
hanoi 2 "a" "b" "c"
`shouldBe` [ ("a", "c"),
("a", "b"),
("c", "b")
]