Skip to content

Instantly share code, notes, and snippets.

@scizo
Forked from bmabey/creditcard.hs
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scizo/752ee985865691f5e0ec to your computer and use it in GitHub Desktop.
Save scizo/752ee985865691f5e0ec to your computer and use it in GitHub Desktop.
-- Exercise 1
lastDigit :: Integer -> Integer
lastDigit = (`mod` 10)
dropLastDigit :: Integer -> Integer
dropLastDigit = (`div` 10)
-- Exercise 2
-- The return value is low digit first, which is breaking from the specification
-- given in the assignment, but that is a dumb specification. :)
toDigits :: Integer -> [Integer]
toDigits n
| n > 0 = lastDigit n : toDigits (dropLastDigit n)
| otherwise = []
-- Exercise 3
doubleEveryOther :: [Integer] -> [Integer]
doubleEveryOther = zipWith ($) (cycle [id, (* 2)])
-- Exercise 4
sumDigits :: [Integer] -> Integer
sumDigits = sum . (map (sum . toDigits))
-- Exercise 5
validate :: Integer -> Bool
validate = (== 0) . lastDigit . sumDigits . doubleEveryOther . toDigits
-- Exercise 6
hanoi :: Integer -> t -> t -> t -> [(t, t)]
hanoi n a b c
| n < 1 = []
| otherwise = (hanoi (n-1) a c b) ++ [(a, b)] ++ (hanoi (n-1) c b a)
-- Exercise 7
-- Frame-Stewart algorithm with I think a fairly naive partition parameter k
-- Someone's homework assignment on the optimal k for Frame-Stewart:
-- https://www2.bc.edu/~grigsbyj/Rand_Final.pdf
hanoiR :: Int -> [t] -> [(t, t)]
hanoiR 0 _ = []
hanoiR 1 (a:b:rest) = [(a,b)]
hanoiR n (a:b:c:rest) =
hanoiR k (a:c:b:rest) ++
hanoiR (n-k) (a:b:rest) ++
hanoiR k (c:b:a:rest)
where k = if (null rest) then n - 1 else n `div` 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment