DEV Community

Cover image for Wait For It
Robert Mion
Robert Mion

Posted on

Wait For It

Advent of Code 2023 Day 6

Part 1

Seeing the bell curve in the bullet points

Btn.
----------------------------------------|
7 -                     .               |
6                   -   .               |
5                       .       X       |
4                       .             X |
3                       .             X |
2                       .       X       |
1                   -   .               |
0 -                     .               |
  0  1  2  3  4  5  6  7. 8  9 10 11 12 | Dist.
Enter fullscreen mode Exit fullscreen mode

Cool!

Verifying second race stats

In the second race, you could hold the button for at least 4 milliseconds and at most 11 milliseconds and beat the record

Time:      15
Distance:  40
Enter fullscreen mode Exit fullscreen mode
  • Hold for 4 time units
  • Go 4 distance units per time unit
Time: 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
Dist: 0  0  0  0  4  8 12 16 20 24 28 32 36 40 44
Enter fullscreen mode Exit fullscreen mode

I feel like I'm starting to see how I could programmatically calculate this.

Thinking algorithmically

Set winners to 0
For all times i from 1 to N - 1 where N is the race time
  Calculate the product of i and N - i
  Compare to distance target
    If greater, increment winners by 1
Enter fullscreen mode Exit fullscreen mode

Using Time: 7 as example:

For i from 1 to 7
  1 * 6 = 6
  6 < 7
  LOSE

  2 * 5 = 10
  10 > 7
  WIN

  3 * 4 = 12
  12 > 7
  WIN

  4 * 3 = 12
  12 > 7
  WIN

  5 * 2 = 10
  10 > 7
  WIN

  6 * 1 = 6
  6 < 7
  LOSE

Winners: 4
Enter fullscreen mode Exit fullscreen mode

If all bell curves are symmetrical, then this algorithm could stop as soon as i is greater than N - i, and just double that winner count at that point.

Time to write this program!

My working JavaScript algorithm

times.reduce((product, time, index) => {
  let winners = 0
  for (let i = 1; i < time; i++) {
    winners += (i * (time - i)) > distances[index] ? 1 : 0
  }
  return product *= winners
}, 1)
Enter fullscreen mode Exit fullscreen mode

It generates the correct answer for the example input.

And it generates the correct answer for my puzzle input!

Part 2

A nod to kerning? Hahahaha!

It may come in handy to halve my algorithm's operations for this performance test, since my puzzle input requires checking nearly 50 million times.

First, I'll just try it brute-force, evaluating every permutation of i.

My working JavaScript algorithm

time = parseInt(times.join(''))
distance = parseInt(distances.join(''))
let winners = 0
for (let i = 1; i < time; i++) {
  winners += (i * (time - i)) > distance ? 1 : 0
}
return winners
Enter fullscreen mode Exit fullscreen mode

It completed in milliseconds, even on my puzzle input.

And it generated the correct answer!

That was a breath of fresh air compared to Day 5!

Fun with bell curves. Who knew?

Top comments (0)