diff --git a/2015/day09/day09.hs b/2015/day09/day09.hs new file mode 100644 index 0000000..885d0ca --- /dev/null +++ b/2015/day09/day09.hs @@ -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 \ No newline at end of file diff --git a/aoc.hs b/aoc.hs index 57c327d..8bc603e 100644 --- a/aoc.hs +++ b/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) @@ -37,4 +40,14 @@ both :: (a -> b) -> (a, a) -> (b, b) both f (a, b) = (f a, f b) lastSplit :: Int -> [a] -> ([a], [a]) -lastSplit n as = splitAt (length as - n) as \ No newline at end of file +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 \ No newline at end of file