Solve day 1, part 2

pull/1/head
Gaël Depreeuw 4 years ago
parent e4878ae47c
commit 03759d2e79
Signed by: Mithror
GPG Key ID: 8AB218ABA4867F78
  1. 4
      Main.hs
  2. 24
      src/Day1.hs

@ -6,7 +6,9 @@ day1 :: IO ()
day1 = do
r <- readFile "./input/day1"
putStr "[Day 1-1] fix: "
print . Day1.fixExpenseReport . fmap read . lines $ r
print . Day1.fixExpenseReport 2020 2 . fmap read . lines $ r
putStr "[Day 1-2] fix: "
print . Day1.fixExpenseReport 2020 3 . fmap read . lines $ r
main :: IO ()

@ -3,17 +3,23 @@ module Day1 (fixExpenseReport) where
import qualified Data.IntSet as DIS
import Data.Maybe (mapMaybe)
yearToFind :: Int
yearToFind = 2020
type Target = Int
type Expenses = [Int]
type Expenses' = DIS.IntSet
-- Turn the list into an IntSet. For each element in the set, look up the
-- number in the set to make it 2020. If found, return the multiplication of
-- the two numbers.
fixExpenseReport :: [Int] -> Int
fixExpenseReport expenses =
let s = DIS.fromList expenses in
head $ mapMaybe (`findOther` s) expenses
fixExpenseReport :: Target -> Int -> Expenses -> Maybe Int
fixExpenseReport t c es
| c <= 0 = error "unsupported"
| otherwise = fixExpenseReport' t c (DIS.fromList es)
findOther :: Int -> DIS.IntSet -> Maybe Int
findOther n s = let n' = yearToFind - n in
if DIS.member n' s then Just (n*n') else Nothing
fixExpenseReport' :: Target -> Int -> Expenses' -> Maybe Int
fixExpenseReport' t 1 es = if DIS.member t es then Just t else Nothing
fixExpenseReport' t c es =
let foo x = (*x) <$> fixExpenseReport' (t-x) (c-1) (DIS.delete x es)
bar = mapMaybe foo (DIS.toList es) in
case bar of
[] -> Nothing
(x:_) -> Just x
Loading…
Cancel
Save