2015 Day 09 in Haskell
This commit is contained in:
parent
e46ff8585d
commit
931c038c43
28
2015/day09/day09.hs
Normal file
28
2015/day09/day09.hs
Normal file
@ -0,0 +1,28 @@
|
||||
import Aoc
|
||||
import Data.List ( nub )
|
||||
import Data.Tuple ( swap )
|
||||
import Control.Applicative ( (<|>) )
|
||||
import Data.Maybe ( fromMaybe )
|
||||
|
||||
parseFile :: [String] -> [((String, String), Int)]
|
||||
parseFile = map (\line ->
|
||||
let [a, "to", b, "=", dist] = words line in
|
||||
((a, b), read dist))
|
||||
|
||||
symLookup :: Eq a => (a, a) -> [((a,a), b)] -> Maybe b
|
||||
symLookup a ls = lookup a ls <|> lookup (swap a) ls
|
||||
|
||||
process :: [((String, String), Int)] -> [Int]
|
||||
process connections = map (totalLength . adjacents) (permutations cities)
|
||||
where
|
||||
cities = nub $ concatMap (unpair . fst) connections
|
||||
totalLength = sum . map (fromMaybe undefined . (`symLookup` connections))
|
||||
|
||||
|
||||
part1 :: [Int] -> Int
|
||||
part1 = minimum
|
||||
|
||||
part2 :: [Int] -> Int
|
||||
part2 = maximum
|
||||
|
||||
main = aocMain (process . parseFile) part1 part2
|
15
aoc.hs
15
aoc.hs
@ -19,7 +19,7 @@ const' :: (a -> b) -> a -> c -> b
|
||||
const' f a _ = f a
|
||||
|
||||
enumerate :: [a] -> [(Int, a)]
|
||||
enumerate xs = zip [0..length xs] xs
|
||||
enumerate = zip [0..]
|
||||
|
||||
unimplemented :: Show p => p -> Int
|
||||
unimplemented = error . show
|
||||
@ -27,6 +27,9 @@ unimplemented = error . show
|
||||
pair :: [a] -> (a, a)
|
||||
pair as = let [a1, a2] = as in (a1, a2)
|
||||
|
||||
unpair :: (a, a) -> [a]
|
||||
unpair (a, b) = [a, b]
|
||||
|
||||
triplet :: [a] -> (a, a, a)
|
||||
triplet as = let [a1, a2, a3] = as in (a1, a2, a3)
|
||||
|
||||
@ -38,3 +41,13 @@ both f (a, b) = (f a, f b)
|
||||
|
||||
lastSplit :: Int -> [a] -> ([a], [a])
|
||||
lastSplit n as = splitAt (length as - n) as
|
||||
|
||||
remove :: Int -> [a] -> (a, [a])
|
||||
remove n xs = let (front, a:rest) = splitAt n xs in (a, front ++ rest)
|
||||
|
||||
permutations :: [a] -> [[a]]
|
||||
permutations [] = [[]]
|
||||
permutations xs = concatMap (\n -> let (a, rest) = remove n xs in map (a:) $ permutations rest) [0..length xs-1]
|
||||
|
||||
adjacents :: [a] -> [(a, a)]
|
||||
adjacents as = zip as $ tail as
|
Loading…
Reference in New Issue
Block a user