Day 4: Giant Squid

Puzzle Description

Advent of Code 2021, Day 4

Scala Center Advent of Code 2021, Day 4

Full Solution Source

My Solution for 2021, Day 4

This is one I've solved twice due to some weird happenings with file placement (my haskell source was found sitting on my recovery installation medium, but I only discovered that in 2026.) I had rewritten my source in Scala already but now I will come back and add the haskell.

Solution Summary

  1. Parse input into a List[BingoCard]
  2. Make function to advance bingo card with each callout
  3. Find the card
    • For part 1, find the card that completes first
    • For part 2, find the card that completes last
  4. Score the card

Part 1

Our types are a bit weird, so let's get it out of the way now:

type BingoCard = Grid[Int]
type RealBingoCard = Grid[(Int, Boolean)]

(the grid impl wraps a Vector[Vector[A]] with some convenience functions)

type BingoCard = [(Int, Bool)]

I don't use a fancy Grid in haskell, I just use a list because I know the width already.

Now let's parse our input:

def parse(str: String): (List[Int], List[BingoCard]) =
  val blocks = str.split("\n\n")
  val callouts = blocks.head.trim.split(',').map(_.toInt)
  val cards = blocks.tail.map: block =>
    Grid:
      block.linesIterator.map: it =>
        it.trim.split(raw"\s+").map(_.toInt)

  (callouts.toList, cards.toList)
import Data.List.Extra (splitOn, trim)

shoddyReadList :: Read a => String -> [a]
shoddyReadList str = read ("[" ++ str ++ "]")

readBingoCard :: String -> BingoCard
readBingoCard str = map (\x -> (read x, False)) (words str)

parse :: String -> ([Int], [BingoCard])
parse input =
  let callouts : cards = splitOn "\n\n" (trim input)
      bingoCallouts = shoddyReadList callouts :: [Int]
      bingoCards = map readBingoCard cards in
        (bingoCallouts, bingoCards)

We'll need to convert the BingoCard into a RealBingoCard, so let's make a function for that:

def makeCard(base: BingoCard): RealBingoCard =
  base.map(it => (it, false))

As seen above, haskell doesn't actually need to do this because I already inserted the falses.

We'll also add some extension methods to the RealBingoCard to advance the state, score the card, and test if we've won.

extension (card: RealBingoCard)
  def acceptCallout(callout: Int): RealBingoCard =
    card.map((n, x) => (n, (n == callout) || x))

  def score(lastCall: Int): Int =
    card.flatten.filterNot(_._2).map(_._1).sum * lastCall

  def won: Boolean =
    card.rows.exists(_.forall(_._2)) || card.columns.exists(_.forall(_._2))

I added convienience methods for Haskell to do the mapping as due to Haskell being purely functional there are no extension methods, everything is a toplevel function.

import Data.List.Extra (chunksOf, transpose)

markCard :: Int -> BingoCard -> BingoCard
markCard callout = map (\(x, m) -> (x, x == callout || m))

markCards callout = map (markCard callout)

-- As a reminder, haskell is lazy so this is more efficient than you might think
checkCard :: BingoCard -> (BingoCard, Bool)
checkCard card =
  let rows = chunksOf 5 card
      columns = transpose rows in
        (card, any (all snd) rows || any (all snd) columns)

checkCards = map checkCard

scoreCard :: BingoCard -> Int -> Int
scoreCard card lastDraw =
  let card' = filter (not . snd) card
      card'' = map fst card' in
        sum card'' * lastDraw

Part 1 is a simple foldLeft:

def part1(input: (List[Int], List[BingoCard])): Int =
  val (callouts, cards) = input
  val realCards = cards.map(makeCard)

  callouts.foldLeft((Option.empty[Int], realCards)):
    case ((r @ Some(_), c), _) => (r, c)
    case ((_, cards), callout) =>
      val newCards = cards.map(_.acceptCallout(callout))
      (newCards.find(_.won).map(_.score(callout)), newCards)
  ._1.get

... or a simple recursive function. Haskell is well suited to recursive functions, and I'm pretty sure can even handle ones that normally nuke the stack.

part1 :: [Int] -> [BingoCard] -> Int
part1 [] cards = undefined
part1 (callout : callouts) cards =
  let cards' = markCards callout cards in
    case find snd (checkCards cards') of
      Just c ->
        scoreCard (fst c) callout
      Nothing ->
        part1 callouts cards'

Part 2

Surprisingly, our tools we made are enough for us to do part 2 in less than a second. Instead of checking if we already found a card and doing nothing if we have, we'll override the current score if we got a new result and subtract the cards that won from our running list.

def part2(input: (List[Int], List[BingoCard])): Int =
  val (callouts, cards) = input
  val realCards = cards.map(makeCard)

  callouts.foldLeft((Option.empty[Int], realCards.toSet)):
    case ((f, cards), callout) =>
      val newCards = cards.map(_.acceptCallout(callout))
      val winningCards = newCards.filter(_.won)
      (newCards.find(_.won).map(_.score(callout)).orElse(f), newCards -- winningCards)
  ._1.get

Haskell does something different. I don't remember the exact thought process of this code, but here's my guess:

-- Use a special function to avoid forcing the entire list
unary :: [a] -> Bool
unary (a : []) = True
unary _ = False

part2 :: [Int] -> [BingoCard] -> Int
part2 [] cards = undefined
part2 (callout : callouts) cards =
  let cards' = markCards callout cards
      -- If there's only one card left then don't get rid of it, otherwise
      -- remove all cards that are winners from the pool
      cards'' if unary cards' then cards' else filter (not . snd . checkCard) cards' in
        if unary cards'' && snd (checkCard $ head cards'') then
          -- If the single card we have just won, then score it
          scoreCard (head cards'') callout
        else
          part2 callouts cards''

If I had to guess this is slightly more optimized than the scala version as it doesn't need to go through all the callouts.

Final Code

type BingoCard = Grid[Int]
type RealBingoCard = Grid[(Int, Boolean)]

def parse(str: String): (List[Int], List[BingoCard]) =
  val blocks = str.split("\n\n")
  val callouts = blocks.head.trim.split(',').map(_.toInt)
  val cards = blocks.tail.map: block =>
    Grid:
      block.linesIterator.map: it =>
        it.trim.split(raw"\s+").map(_.toInt)

  (callouts.toList, cards.toList)


def makeCard(base: BingoCard): RealBingoCard =
  base.map(it => (it, false))

extension (card: RealBingoCard)
  def acceptCallout(callout: Int): RealBingoCard =
    card.map((n, x) => (n, (n == callout) || x))

  def score(lastCall: Int): Int =
    card.flatten.filterNot(_._2).map(_._1).sum * lastCall

  def won: Boolean =
    card.rows.exists(_.forall(_._2)) || card.columns.exists(_.forall(_._2))

def part1(input: (List[Int], List[BingoCard])): Int =
  val (callouts, cards) = input
  val realCards = cards.map(makeCard)

  callouts.foldLeft((Option.empty[Int], realCards)):
    case ((r @ Some(_), c), _) => (r, c)
    case ((_, cards), callout) =>
      val newCards = cards.map(_.acceptCallout(callout))
      (newCards.find(_.won).map(_.score(callout)), newCards)
  ._1.get

def part2(input: (List[Int], List[BingoCard])): Int =
  val (callouts, cards) = input
  val realCards = cards.map(makeCard)

  callouts.foldLeft((Option.empty[Int], realCards.toSet)):
    case ((f, cards), callout) =>
      val newCards = cards.map(_.acceptCallout(callout))
      val winningCards = newCards.filter(_.won)
      (newCards.find(_.won).map(_.score(callout)).orElse(f), newCards -- winningCards)
  ._1.get
import Data.List.Extra (chunksOf, splitOn, transpose, trim)
import Data.List (find)

type BingoCard = [(Int, Bool)]

shoddyReadList :: Read a => String -> [a]
shoddyReadList str = read ("[" ++ str ++ "]")

readBingoCard :: String -> BingoCard
readBingoCard str = map (\x -> (read x, False)) (words str)

parse :: String -> ([Int], [BingoCard])
parse input =
  let callouts : cards = splitOn "\n\n" (trim input)
      bingoCallouts = shoddyReadList callouts :: [Int]
      bingoCards = map readBingoCard cards in
        (bingoCallouts, bingoCards)

markCard :: Int -> BingoCard -> BingoCard
markCard callout = map (\(x, m) -> (x, x == callout || m))

markCards callout = map (markCard callout)

checkCard :: BingoCard -> (BingoCard, Bool)
checkCard card =
  let rows = chunksOf 5 card
      columns = transpose rows in
        (card, any (all snd) rows || any (all snd) columns)

checkCards = map checkCard

scoreCard :: BingoCard -> Int -> Int
scoreCard card lastDraw =
  let card' = filter (not . snd) card
      card'' = map fst card' in
        sum card'' * lastDraw

part1 :: [Int] -> [BingoCard] -> Int
part1 [] cards = undefined
part1 (callout : callouts) cards =
  let cards' = markCards callout cards in
    case find snd (checkCards cards') of
      Just c ->
        scoreCard (fst c) callout
      Nothing ->
        part1 callouts cards'

unary :: [a] -> Bool
unary (a : []) = True
unary _ = False

part2 :: [Int] -> [BingoCard] -> Int
part2 [] cards = undefined
part2 (callout : callouts) cards =
  let cards' = markCards callout cards
      cards'' if unary cards' then cards' else filter (not . snd . checkCard) cards' in
        if unary cards'' && snd (checkCard $ head cards'') then
          scoreCard (head cards'') callout
        else
          part2 callouts cards''

Benchmark

Part 1

Mean

Error

JVM

2.178 ms

+/- 0.055 ms

JS

3.743 ms

+/- 0.013 ms

Native

6.522 ms

+/- 0.004 ms

Part 2

Mean

Error

JVM

10.366 ms

+/- 0.180 ms

JS

35.809 ms

+/- 0.359 ms

Native

29.708 ms

+/- 0.034 ms

Run it in the browser!