Advent of Code 2024 Day 1

Participating the Advent of Code this year, as far as I am able to. That is, depending on how busy I am at work and at home.

Last year I got 30 stars, about 15 days of participation, last day I got stars (2) was Dec 16th. I missed some second stars for some days. As warmup for this year, I finished one missing second star from last year, now totaling 31 stars out of 50.

For today, the first day, I got two stars:

$ swift run -c release AdventOfCode 1 --benchmark 
Building for production...
...
Build of product 'AdventOfCode' complete! (0.35s)
Executing Advent of Code challenge 1...
Part 1: 1938424
Part 2: 22014209
Part 1 took 0.000817167 seconds, part 2 took 0.0012365 seconds.

Update (16.40 pm): I took a closer look at the Part 2 and managed to get a significant (relative) performance increase:

Part 1 took 0.000780209 seconds, part 2 took 0.000682292 seconds.

Improved time of 0.000682292 seconds is 55% of the original time of 0.0012365 seconds so almost a half.

The goal here is basically to find how many times a value in table 1 appears in table 2. I first sorted both tables and used Swift filter() to filter out and count the matching values from table 2 (original timing above).

Then I changed it to a simple O(n2) loop without any sorting, which to my surprise performs nicely with the data where n = 1000 (only). That takes about 0.00098nn seconds, usually, better than the original solution using sorting and filtering.

Then I wanted to see how much time I can slice off when adding back sorting of the tables and then use binary search to search for the first occurrence of the value in the second table, and step through the equal values in the table 2, counting how many times they occur. This was the fastest solution. Thought the first was shortest in lines of code, this is much faster.

End update.

Not taking too much stress out of this, not aiming to be fast and do not attempt to be at top of the leaderboards. Today I am 33rd on private SwiftLang leaderboard, but may soon fall down.

I’ve heard last year was more difficult than usual. Last year was my first, and this year I am more prepared. I brought in some utility code I wrote last year to this year project, and also searched for some nice snippets from others, porting some code from other languages to Swift.