2015 Day 09 in Haskell

This commit is contained in:
germax26 2024-12-03 06:47:58 +11:00
parent e46ff8585d
commit 931c038c43
Signed by: germax26
SSH Key Fingerprint: SHA256:N3w+8798IMWBt7SYH8G1C0iJlIa2HIIcRCXwILT5FvM
2 changed files with 43 additions and 2 deletions

28
2015/day09/day09.hs Normal file
View 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
View File

@ -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