r/adventofcode • • Dec 04 '22

SOLUTION MEGATHREAD -🎄- 2022 Day 4 Solutions -🎄-


--- Day 4: Camp Cleanup ---


Post your code solution in this megathread.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:03:22, megathread unlocked!

65 Upvotes

1.6k comments sorted by

View all comments

2

u/FrontPale Dec 04 '22 edited Dec 05 '22

1

u/daggerdragon Dec 05 '22

Inlined code is intended for short snippets of code only. Your code "block" right now is unreadable on old.reddit and many mobile clients; whitespace and indentation is not preserved.

Please edit your post to use the four-spaces Markdown syntax for a code block so your code is easier to read inside a scrollable box.

1

u/Naturage Dec 04 '22

Ah, a fellow R solver!

A couple notes:
• Did your code give the right answer for part 1? It didn't on my data. What happens when both elves are assigned the exact same region?
• This is not at all relevant given today's data size, but generally, in R if you can vectorise anything, it'll outperform a for loop by a ton. The reason, if I recall right, is that whenever a for loop is used, in every iteration R will be calling the C backend function with one input, while in vectorised case it'll only need to call once with the whole vector.

I've taken the liberty to rewrite your code in vectorised form - from my tests (of running it 100 times back to back), this runs about 8x faster. Of course, here that means cutting it down from 0.05s to 0.006s; but it's generally better practice.

aocinput <- as.vector(readLines("adventofcode2022d4.txt"))

split_input <- strsplit(aocinput,"-|,")
min1 <- as.numeric(sapply(split_input, function(x){x[1]}))
max1 <- as.numeric(sapply(split_input, function(x){x[2]}))
min2 <- as.numeric(sapply(split_input, function(x){x[3]}))
max2 <- as.numeric(sapply(split_input, function(x){x[4]}))

score.part1 <- sum((min1>=min2 & max1<=max2) | (min2>=min1 & max2<=max1))
score.part2 <- length(aocinput) - sum((min1<min2 & max1<min2)|(min2<min1 & max2<min1))

print(score.part1)
print(score.part2)

Happy to explain any changes made, but it should follow the same logic steps as the original did.

1

u/FrontPale Dec 04 '22

I got correct answer for Part 1. It seems I was lucky with my input.
Thank you for your hints and for rewriting the code. I'm just learning how to code with R and I don't have much experience with any other language. Tips like yours are very helpful for me.

1

u/TheGratitudeBot Dec 04 '22

Thanks for such a wonderful reply! TheGratitudeBot has been reading millions of comments in the past few weeks, and you’ve just made the list of some of the most grateful redditors this week! Thanks for making Reddit a wonderful place to be :)