Day 1
This commit is contained in:
35
01/gold.hs
Normal file
35
01/gold.hs
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
|
||||||
|
import Data.List -- sort
|
||||||
|
import Data.Map (Map)
|
||||||
|
import qualified Data.Map.Strict as Map.Strict
|
||||||
|
import qualified Data.Map as Map
|
||||||
|
|
||||||
|
mapTuple :: (a -> b) -> (a, a) -> (b, b)
|
||||||
|
mapTuple f (a1, a2) = (f a1, f a2)
|
||||||
|
|
||||||
|
countH :: Ord a => Map a Integer -> [a] -> Map a Integer
|
||||||
|
countH m (x:xs) = countH newmap xs
|
||||||
|
where newmap = Map.Strict.insertWith (+) x 1 m
|
||||||
|
countH m _ = m
|
||||||
|
|
||||||
|
count :: Ord a => [a] -> Map a Integer
|
||||||
|
count = countH Map.empty
|
||||||
|
|
||||||
|
applyToSecond :: (b->c) -> (a, b) -> (a, c)
|
||||||
|
applyToSecond f (x, y) = (x, f y)
|
||||||
|
|
||||||
|
toColumnsH :: [a] -> [a] -> [a] -> ([a], [a])
|
||||||
|
toColumnsH ls rs (x:xs) = toColumnsH rs (ls++[x]) xs
|
||||||
|
toColumnsH ls rs _ = (ls, rs)
|
||||||
|
|
||||||
|
toColumns :: [a] -> ([a], [a])
|
||||||
|
toColumns = toColumnsH [] []
|
||||||
|
|
||||||
|
similarityH :: Integer -> Map Integer Integer -> [Integer] -> Integer
|
||||||
|
similarityH acc m (x:xs) = similarityH (acc + x * (Map.findWithDefault 0 x m)) m xs
|
||||||
|
similarityH acc m _ = acc
|
||||||
|
|
||||||
|
similarity :: ([Integer], Map Integer Integer) -> Integer
|
||||||
|
similarity (xs, m) = similarityH 0 m xs
|
||||||
|
|
||||||
|
main = interact $ show . similarity . applyToSecond count . mapTuple sort . toColumns . map read . words
|
||||||
21
01/silver.hs
Normal file
21
01/silver.hs
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
|
||||||
|
import Data.List -- sort
|
||||||
|
|
||||||
|
mapTuple :: (a -> b) -> (a, a) -> (b, b)
|
||||||
|
mapTuple f (a1, a2) = (f a1, f a2)
|
||||||
|
|
||||||
|
-- helper function for split
|
||||||
|
splitH :: [a] -> [a] -> [a] -> ([a], [a])
|
||||||
|
splitH ls rs (x:xs) = splitH rs (ls++[x]) xs
|
||||||
|
splitH ls rs _ = (ls, rs)
|
||||||
|
|
||||||
|
-- split: split list into two by alternating between left and right
|
||||||
|
split :: [a] -> ([a], [a])
|
||||||
|
split = splitH [] []
|
||||||
|
|
||||||
|
-- calculates the sum of the absolute distance between two lists
|
||||||
|
dist :: Int -> ([Int], [Int]) -> Int
|
||||||
|
dist acc (l:ls, r:rs) = dist (acc + abs (r - l)) (ls, rs)
|
||||||
|
dist acc _ = acc
|
||||||
|
|
||||||
|
main = interact $ show . dist 0 . mapTuple sort . split . map (read :: String -> Int) . words
|
||||||
3
01/test.txt
Normal file
3
01/test.txt
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
5 6
|
||||||
|
3 4
|
||||||
|
1 2
|
||||||
Reference in New Issue
Block a user