diff --git a/Main.hs b/Main.hs index f20794f..d7ad0c9 100644 --- a/Main.hs +++ b/Main.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 () diff --git a/src/Day1.hs b/src/Day1.hs index 716a947..973fc3c 100644 --- a/src/Day1.hs +++ b/src/Day1.hs @@ -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 \ No newline at end of file +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 \ No newline at end of file