Performance optimizations to day 7

This commit is contained in:
Riley Apeldoorn 2021-12-07 13:29:48 +01:00
parent 7db9fd389e
commit e2fdb863ee

View file

@ -9,18 +9,37 @@ main = do
-- Problem 2 -- Problem 2
print $ g x print $ g x
where where
f = solve distance f x = solve distance [ minimum x .. maximum x ] x
g = solve (\a -> tri . distance a) g x | length x >= 100 = solve triangle [ sum x `div` length x ] x
| otherwise = solve triangle [ minimum x .. maximum x ] x
-- NOTE for part 2 (`g`):
-- Just testing against the mean value of `x` only gives accurate results if the
-- sample is large enough. Here, lists of size 100 or larger are deemed "large enough",
-- but that's pretty arbitrary.
-- | Split on comma and interpret each element as an integer
parse :: String -> [Int] parse :: String -> [Int]
parse = map read . wordsBy (== ',') parse = map read . wordsBy (== ',')
solve :: (Int -> Int -> Int) -> [Int] -> Int -- | Solve the problem by finding the minimum of a list of integers, where
solve f x = minimum $ map g [minimum x .. maximum x] -- | each element is the total amount of fuel needed for each crab to reach
where g t = sum $ map (f t) x -- | that position.
solve :: (Int -> Int -> Int) -- ^ Fuel calculation to get between two points
-> [Int] -- ^ List of possible target positions
-> [Int] -- ^ List of initial positions
-> Int
solve f a x = minimum $ map g a
where
g t = sum $ map (f t) x
tri :: Int -> Int -- | Calculate the fuel usage based on the triangle number of the distance
tri x = x * (x + 1) `div` 2 -- | between the two numbers.
triangle :: Int -> Int -> Int
triangle a b = tri $ distance a b
where
tri n = n * (n + 1) `div` 2 -- Calculate nth triangle number
-- | Calculate the absolute distance between two numbers
distance :: Int -> Int -> Int distance :: Int -> Int -> Int
distance n a = abs (n - a) distance a b = abs (a - b)