stanosphere

Advent of Code 2020 Day 9 (practice before AoC 2026 happens)

Puzzle: 2020 day 9 · Code: Day9.hs

Initial Thoughts

So all told I should be able to brute force this. However I have a feeling part 2 will do something evil like consider sums of like 20 numbers or do something weird with multiplication. I think there’s probably something you can do where you don’t recompute the sums from scratch each time too.

Code for Part 1

module Day9 where

import Data.Foldable (find)
import qualified Data.Set as S
  ( Set,
    fromList,
    member,
  )
import Utils.Grouping (windows)

part1 :: IO (Maybe Int)
part1 = fmap last . find (not . isValid) . windows 26 <$> getInput "./fixtures/input9.txt"

-- takes 26 numbers and checks if the last number is the sum of any pair of the previous 25
isValid :: [Int] -> Bool
isValid xs = S.member (last xs) (getAllSums . take 25 $ xs)

getAllSums :: [Int] -> S.Set Int
getAllSums xs = S.fromList [(x + y) | (i, x) <- zipped, (j, y) <- zipped, i < j]
  where
    zipped :: [(Int, Int)]
    zipped = zip [0 ..] xs

getInput :: FilePath -> IO [Int]
getInput = fmap (map read) . fmap lines . readFile

Where I’ve used one of my helpers from previous years, which I’ll also show here:

-- like scala's `sliding`
-- works on infinite lists and everything
windows :: Int -> [a] -> [[a]]
windows n = takeWhile ((n ==) . length) . map (take n) . tails

Thoughts on Part 2

Ok so this isn’t at all the part 2 I was anticipating! In fact I suspect I’m wildly wrong more often than not about what the part 2 will be!

Ok so I have my answer from part 1 and I need to find a contiguous run of numbers that sum to it.

There will surely be a clever way to do this. For example you could build up your sequences starting from the start and once your sum goes over the threshold you move to a new starting point. In fact that sounds easier than finding all subsequences lol, so I’ll do that.

Ok so what I need to do is

I guess in general it is not guaranteed that there exists exactly one subsequence like this but the question setter will surely have ensured that for everyone’s input this in fact is the case!

Code for Part 2

part2 :: IO Int
part2 = do
  part1Answer <- fromJust <$> part1
  input <- getInput "./fixtures/input9.txt"
  return . getMaxPlusMin . findContiguousSubSequence part1Answer $ input

getMaxPlusMin :: [Int] -> Int
getMaxPlusMin xs = minimum xs + maximum xs

findContiguousSubSequence :: Int -> [Int] -> [Int]
findContiguousSubSequence target xs = case find ((>= target) . sum) . inits $ xs of
  Just res | sum res == target -> res
  _ -> findContiguousSubSequence target (drop 1 xs)

findContiguousSubSequence perhaps warrants some explanation. I know that all the numbers are positive so adding more numbers will increase the sum. So I find the first case where we either hit or exceed our target, that’s why I use the inequality. Then I do a second (maybe wasteful) check to see if we have hit our target or not. And if we haven’t we just try the next starting point. The idea behind using find is it won’t process any more than it needs to so I’m basically making sure we stop early where we can!

Final Thoughts

I’m mostly glad I can still write code. I did this to make sure I’m set up for AoC 2026 and this is one of the problems I hadn’t got around to yet!

This was interesting in the sense that the answer to part 2 directly depended on the answer to part 1. I guess this manifests as somewhat cumbersome do notation, although I think this could be avoided by using suitable applicative combinators but I’m too out of practice for that!

I feel my solution is fine but not great, I imagine there’s a way to solve this that involves fewer scans than what I’m doing. In fact I think I could probably modify my solution to use one of the scan functions so that I do not have to compute a sum each time… But like I say I think there must be an overall more optimal approach than even this! I think if I was doing this live I’d be glued to the solution thread to find a better approach.

A miscellaneous observation is that I really like ghci’s interactiveness. It was super easy for me to be like “oh what does inits do again?” without any faff at all really. I guess in my first job I was raised on repl.it so I just love a repl! Although repl.it itself now seems to be a lot more than just a repl.

Final Full Solution

I did decide to try using scanl and it works! I could maybe have checked the performance gain, oh well. Here’s the full solution with that change and a couple of minor improvements too.

module Day9 where

import Data.Foldable (find)
import Data.List (tails)
import Data.Maybe (fromJust)
import qualified Data.Set as S
  ( Set,
    fromList,
    member,
  )
import Utils.Grouping (windows)

part2 :: IO Int
part2 = do
  part1Answer <- fromJust <$> part1
  input <- getInput "./fixtures/input9.txt"
  return . getMaxPlusMin . findContiguousSubSequence part1Answer $ input

getMaxPlusMin :: [Int] -> Int
getMaxPlusMin xs = minimum xs + maximum xs

findContiguousSubSequence :: Int -> [Int] -> [Int]
findContiguousSubSequence target xs =
  case findWithIndex (>= target) . scanl (+) 0 $ xs of
    Just (i, s) | s == target -> take i xs
    _ -> findContiguousSubSequence target (drop 1 xs)
  where
    findWithIndex :: (a -> Bool) -> [a] -> Maybe (Int, a)
    findWithIndex p = find (p . snd) . zip [0 ..]

part1 :: IO (Maybe Int)
part1 = fmap last . find (not . isValid) . windows 26 <$> getInput "./fixtures/input9.txt"

-- takes 26 numbers and checks if the last number is the sum of any pair of the previous 25
isValid :: [Int] -> Bool
isValid xs = S.member (last xs) (getAllSums . take 25 $ xs)

getAllSums :: [Int] -> S.Set Int
getAllSums xs = S.fromList [x + y | (x : ys) <- tails xs, y <- ys]

getInput :: FilePath -> IO [Int]
getInput = fmap (map read . lines) . readFile

I find that in real AoC rather than this practice I do like to tidy up my solutions a little even after I’ve got the answer!