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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

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