DEV Community

Caleb Weeks
Caleb Weeks

Posted on

Advent of Code #6 (in Crystal)

Yesterday, I got by without optimizing my program for part 2. Although it took hours to compute, I got the right answer in the end.

Today, that was not an option. The numbers grow so large, that calculating all of them is impractical if not impossible. Thankfully, it was fairly straightforward to come up with a shortcut.

Just like this post, the code is short:

input = File.read("input").strip

time, distance = input.split("\n").map do |line|
  line.scan(/\d+/).map(&.[0].to_i)
end

pairs = time.zip(distance)

part1 = pairs.map do |time, distance|
  (1..(time - 1)).map { |x| x * (time - x) }.count { |x| x > distance }
end.product

puts part1

time, distance = input.split("\n").map do |line|
  line.gsub(' ', "").scan(/\d+/)[0][0].to_i64
end

part2 = time - (1..(time - 1)).take_while do |x|
  x.to_i64 * (time - x.to_i64) <= distance
end.size * 2 - (time % 2 == 0 ? 1 : 0)

puts part2
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay