Rules: no spoilers.
The other rules are made up as we go along.
Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.
Rules: no spoilers.
The other rules are made up as we go along.
Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.
Day 4: Scratchcards
Scheme code and explanations
This problem feels a bit more Scheme-shaped. To keep things interesting, I have chosen to stick to pure functional programming.
A card consists of three components – a card number (which turned out to be completely unnecessary), a list of winning numbers, and a list of numbers. Here’s a function to parse a card from a string, turning it into a 3-element list:
The value of a card is easy enough to compute. The first matched winning number sets the value to 1, every subsequent one doubles it.
Solving part 1 is now straightforward:
But oh no! Turns out I (or the elf) got the rules wrong, and apparently the game requires so many dead trees to play that I think it was probably designed by Jair Bolsonaro.
A function to count the card matches (eg. how many numbers match a winning number) is easily adapted from the above:
My strategy here is to have two lists: One of the card matches of all cards, the other of how many instances I have of each card. The second list will start as
(1 1 1 1 ... )
, and I need to be able to add some numberx
to the firstn
cards in the list. For example, if I have 4 instances of the first card, and it has 2 matches, then I’ll want to add 4 to however many instances I have of the next 2 cards. Here’s a function that reaches into a list and does just that:Using this, here’s a recursive function that counts cards, given the two aforementioned lists:
Solving part 2 is now easy:
There you have it. It’d have been shorter if I had allowed myself some side effects, but pure functional programming is terrific fun.