Language: Python
Advent Of Code
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')
Started 4 days late so coming up from behind. Day 5 was the first solution I am somewhat proud of. I used interval arithmetics. I had to somewhat extend a class interval from pyinterval into something I called PointedInterval. In the end part 2 was completed in 0.32 seconds. It does not reverse engineer the solution starting from 0 location and inverse mapping until you find a seed (that was how I was initially planning to do it). It maps forward everything as intervals. There is a bit of a boiler plate which is in the utils file.
Odin
When I read the problem description I expected the input to also be 2 digit numbers. When I looked at it I just had to say "huh."
Second part I think you definitely have to do in reverse (edit: if you are doing a linear search for the answer), as that allows you to nope out as soon as you find a match, whereas with doing it forward you have to keep checking just in case.
package day5
import "core:fmt"
import "core:strings"
import "core:slice"
import "core:strconv"
Range :: struct {
dest: int,
src: int,
range: int,
}
Mapper :: struct {
ranges: []Range,
}
parse_range :: proc(s: string) -> (ret: Range) {
rest := s
parseLen := -1
destOk: bool
ret.dest, destOk = strconv.parse_int(rest, 10, &parseLen)
rest = strings.trim_left_space(rest[parseLen:])
srcOk: bool
ret.src, srcOk = strconv.parse_int(rest, 10, &parseLen)
rest = strings.trim_left_space(rest[parseLen:])
rangeOk: bool
ret.range, rangeOk = strconv.parse_int(rest, 10, &parseLen)
return
}
parse_mapper :: proc(ss: []string) -> (ret: Mapper) {
ret.ranges = make([]Range, len(ss)-1)
for s, i in ss[1:] {
ret.ranges[i] = parse_range(s)
}
return
}
parse_mappers :: proc(ss: []string) -> []Mapper {
mapsStr := make([dynamic][]string)
defer delete(mapsStr)
restOfLines := ss
isLineEmpty :: proc(s: string)->bool {return len(s)==0}
for i, found := slice.linear_search_proc(restOfLines, isLineEmpty);
found;
i, found = slice.linear_search_proc(restOfLines, isLineEmpty) {
append(&mapsStr, restOfLines[:i])
restOfLines = restOfLines[i+1:]
}
append(&mapsStr, restOfLines[:])
return slice.mapper(mapsStr[1:], parse_mapper)
}
apply_mapper :: proc(mapper: Mapper, num: int) -> int {
for r in mapper.ranges {
if num >= r.src && num - r.src < r.range do return num - r.src + r.dest
}
return num
}
p1 :: proc(input: []string) {
maps := parse_mappers(input)
defer {
for m in maps do delete(m.ranges)
delete(maps)
}
restSeeds := input[0][len("seeds: "):]
min := 0x7fffffff
for len(restSeeds) > 0 {
seedLen := -1
seed, seedOk := strconv.parse_int(restSeeds, 10, &seedLen)
restSeeds = strings.trim_left_space(restSeeds[seedLen:])
fmt.print(seed)
for m in maps {
seed = apply_mapper(m, seed)
fmt.print(" ->", seed)
}
fmt.println()
if seed < min do min = seed
}
fmt.println(min)
}
apply_mapper_reverse :: proc(mapper: Mapper, num: int) -> int {
for r in mapper.ranges {
if num >= r.dest && num - r.dest < r.range do return num - r.dest + r.src
}
return num
}
p2 :: proc(input: []string) {
SeedRange :: struct {
start: int,
len: int,
}
seeds := make([dynamic]SeedRange)
restSeeds := input[0][len("seeds: "):]
for len(restSeeds) > 0 {
seedLen := -1
seedS, seedSOk := strconv.parse_int(restSeeds, 10, &seedLen)
restSeeds = strings.trim_left_space(restSeeds[seedLen:])
seedL, seedLOk := strconv.parse_int(restSeeds, 10, &seedLen)
restSeeds = strings.trim_left_space(restSeeds[seedLen:])
append(&seeds, SeedRange{seedS, seedL})
}
maps := parse_mappers(input)
defer {
for m in maps do delete(m.ranges)
delete(maps)
}
for i := 0; true; i += 1 {
rseed := i
#reverse for m in maps {
rseed = apply_mapper_reverse(m, rseed)
}
found := false
for sr in seeds {
if rseed >= sr.start && rseed < sr.start + sr.len {
found = true
break
}
}
if found {
fmt.println(i)
break
}
}
}
Nim
Woof. Part 1 was simple enough. I thought I could adapt my solution to part 2 pretty easily, just add all the values in the ranges to the starting set. Worked fine for the example, but the ranges for the actual input are too large. Ended up taking 16gb of RAM and crunching forever.
I finally abandoned my quick and dirty approach when rewriting part 2, and made some proper types and functions. Treated each range as an object, and used set operations on them. The difference operation tends to fragment the range that it's used on, so I meant to write some code to defragment the ranges after each round of mappings. Forgot to do so, but the code ran quick enough this time anyway.
Treated each range as an object, and used set operations on them
That's smart. Honestly, I don't understand how it works. π
The difference operation tends to fragment the range that itβs used on, so I meant to write some code to defragment the ranges after each round of mappings. Forgot to do so, but the code ran quick enough this time anyway.
I've got different solution from yours, but this part is the same, lol. My code slices the ranges into 1-3 parts on each step, so I also planned to 'defragment' them. But performance is plenty without this step, ~450 microseconds for both parts on my PC.
Treated each range as an object, and used set operations on them
Thatβs smart. Honestly, I donβt understand how it works. π
"Set operations" should probably be in quotes. I just mean that I implemented the *
(intersection) and -
(difference) operators for my ValueRange type. The intersection operator works like it does for sets, just returning the overlap. The difference operator has to work a little differently, because ranges have to be contiguous, whereas sets don't, so it returns a sequence of ValueRange objects.
My ValueMapping type uses a ValueRange for it's source, so applying it to a range just involves using the intersection operator to determine what part of the range needs to move, and the difference operator to determine which parts are left.
Well, then we have the same solution but coded very differently. Here's mine.
ruleApplied
is one function with almost all logic. I take a range and compare it to a rule's source range (50 98 2 is a rule). Overlaps get transformed and collected into the first sequence and everything that left goes in the second. I need two seq
s there, for transformed values to skip next rules in the same map.
Repeat for each rule and each map (seq[Rule]). And presto, it's working!
Yeah, roughly the same idea. I guess I could have just used HSlice for my range type, I thought maybe there was some special magic to it.
It looks like your if-else ladder misses a corner case, where one range only intersects with the first or last element of the other. Switching to <=
and >=
for those should take care of it though.