Skip to content

Instantly share code, notes, and snippets.

@shangaslammi
Created February 3, 2011 09:15
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 shangaslammi/809248 to your computer and use it in GitHub Desktop.
Save shangaslammi/809248 to your computer and use it in GitHub Desktop.
Sample implementation of KataPotter (http://codingdojo.org/cgi-bin/wiki.pl?KataPotter) in Haskell (FYI, it's my first program in Haskell, so it might not be all that idiomatic)
import List
import Array
import System (getArgs)
discounts = listArray (1,5) ([1.0, 0.95, 0.9, 0.8, 0.75]::[Float])
bookPrice = 8.0::Float
grouped :: Ord a => [a] -> [Int]
grouped = sort . (map length) . group . sort
variations :: [Int] -> [[Int]]
variations = takeWhile (not . null) . iterate (sort . next)
where next (1:x:xs) = (x+1):xs
next (x:x':xs) = (x-1):(x'+1):xs
next _ = []
groupedPrice :: [Int] -> Float
groupedPrice = minimum . map (variationPrice) . variations
where variationPrice = sum . map (priceOfSet) . toSets
priceOfSet s = bookPrice * (fromIntegral s) * (discounts ! s)
toSets [] = []
toSets xs = replicate (head xs) (length xs) ++ rest
where rest = toSets $ map (subtract (head xs)) $ tail xs
orderPrice :: Ord a => [a] -> Float
orderPrice = groupedPrice . grouped
main = do
args <- getArgs
print $ argPrice args
where argPrice = groupedPrice . sort . map read
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment