Day 6

Author

Julia Romanowska

The input

The races’ times and distances:

root = dirname(@__FILE__);
input_file = joinpath(root, "..", "..", "DATA", "2023", "input_day06.txt");
input_data = read(open(input_file, "r"), String);
println(input_data)
Time:        58     81     96     76
Distance:   434   1041   2219   1218
time_line , dist_line = split(input_data, "\n")[1:2]
times = split(time_line, r"\s+")[2:end] |>
    x -> parse.(Int64, x)
distances = split(dist_line, r"\s+")[2:end] |>
    x -> parse.(Int64, x)
4-element Vector{Int64}:
  434
 1041
 2219
 1218

Part 1

The problem

For each race, we can hold the button to charge the boat for varying number of miliseconds but not exceed the maximum time given in the input file. With each milisecond of holding the button, the boat gains 1ms/mm velocity.

function find_max_dist(time_hold_button::Int64, max_time::Int64)
    return (max_time - time_hold_button)*time_hold_button
end
find_max_dist (generic function with 1 method)

The solution

We need to find the number of ways we can get larger distance than what is in the input file.

all_winning_approaches = Int64[];
for idx in 1:lastindex(times)
    cur_max_time = times[idx];
    cur_max_dist = distances[idx];
    cur_winning_approaches = 0;
    for t in 1:(cur_max_time - 1)
        max_dist = find_max_dist(t, cur_max_time)
        if max_dist > cur_max_dist
            cur_winning_approaches += 1;
        end
    end
    push!(all_winning_approaches, cur_winning_approaches);
end

The total number of ways to win all the races: 1159152.

Part 2

Instead of the input showing many races, it’s actually one!

one_time = parse(Int64, string(times...))
one_distance = parse(Int64, string(distances...))

cur_winning_approaches = 0;
for t in 1:(one_time - 1)
    max_dist = find_max_dist(t, one_time)
    if max_dist > one_distance
        cur_winning_approaches += 1;
    end
end

The solution

The total number of ways to win the long race: 41513103.