this post was submitted on 04 Dec 2023
1 points (100.0% liked)
Advent Of Code
1012 readers
1 users here now
An unofficial home for the advent of code community on programming.dev!
Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.
AoC 2024
Solution Threads
M | T | W | T | F | S | S |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 |
Rules/Guidelines
- Follow the programming.dev instance rules
- Keep all content related to advent of code in some way
- If what youre posting relates to a day, put in brackets the year and then day number in front of the post title (e.g. [2024 Day 10])
- When an event is running, keep solutions in the solution megathread to avoid the community getting spammed with posts
Relevant Communities
Relevant Links
Credits
Icon base by Lorc under CC BY 3.0 with modifications to add a gradient
console.log('Hello World')
founded 2 years ago
MODERATORS
Python
Questions and feedback welcome!
import collections
import re
from .solver import Solver
class Day04(Solver):
def __init__(self):
super().__init__(4)
self.cards = []
def presolve(self, input: str):
lines = input.rstrip().split('\n')
self.cards = []
for line in lines:
left, right = re.split(r' +\| +', re.split(': +', line)[1])
left, right = map(int, re.split(' +', left)), map(int, re.split(' +', right))
self.cards.append((list(left), list(right)))
def solve_first_star(self):
points = 0
for winning, having in self.cards:
matches = len(set(winning) & set(having))
if not matches:
continue
points += 1 << (matches - 1)
return points
def solve_second_star(self):
factors = collections.defaultdict(lambda: 1)
count = 0
for i, (winning, having) in enumerate(self.cards):
count += factors[i]
matches = len(set(winning) & set(having))
if not matches:
continue
for j in range(i + 1, i + 1 + matches):
factors[j] = factors[j] + factors[i]
return count
Factor on github (with comments and imports):
: line>cards ( line -- winning-nums player-nums )
":|" split rest
[
[ CHAR: space = ] trim
split-words harvest [ string>number ] map
] map first2
;
: points ( winning-nums player-nums -- n )
intersect length
dup 0 > [ 1 - 2^ ] when
;
: part1 ( -- )
"vocab:aoc-2023/day04/input.txt" utf8 file-lines
[ line>cards points ] map-sum .
;
: follow-card ( i commons -- n )
[ 1 ] 2dip
2dup nth swapd
over + (a..b]
[ over follow-card ] map-sum
nip +
;
: part2 ( -- )
"vocab:aoc-2023/day04/input.txt" utf8 file-lines
[ line>cards intersect length ] map
dup length swap '[ _ follow-card ]
map-sum .
;