Mercurial > repos > other > adventofcode2023
changeset 7:6e0615e54e71
Restructure input parsing for day6b
The rest of the algorithm is the same
author | IBBoard <dev@ibboard.co.uk> |
---|---|
date | Thu, 07 Dec 2023 08:23:04 +0000 |
parents | 9d89489bc939 |
children | 51e5f26dc81e |
files | day6.txt day6b.rb |
diffstat | 2 files changed, 39 insertions(+), 0 deletions(-) [+] |
line wrap: on
line diff
--- a/day6.txt Thu Dec 07 08:16:30 2023 +0000 +++ b/day6.txt Thu Dec 07 08:23:04 2023 +0000 @@ -43,3 +43,21 @@ To see how much margin of error you have, determine the number of ways you can beat the record in each race; in this example, if you multiply these values together, you get 288 (4 * 8 * 9). Determine the number of ways you could beat the record in each race. What do you get if you multiply these numbers together? + +--- Part Two --- + +As the race is about to start, you realize the piece of paper with race times and record distances you got earlier actually just has very bad kerning. There's really only one race - ignore the spaces between the numbers on each line. + +So, the example from before: + +Time: 7 15 30 +Distance: 9 40 200 + +...now instead means this: + +Time: 71530 +Distance: 940200 + +Now, you have to figure out how many ways there are to win this single race. In this example, the race lasts for 71530 milliseconds and the record distance you need to beat is 940200 millimeters. You could hold the button anywhere from 14 to 71516 milliseconds and beat the record, a total of 71503 ways! + +How many ways can you beat the record in this one much longer race?
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/day6b.rb Thu Dec 07 08:23:04 2023 +0000 @@ -0,0 +1,21 @@ +#! /usr/bin/env ruby + +if ARGV.length != 1 + abort("Incorrect arguments - needs input file") +elsif not File.exist? (ARGV[0]) + abort("File #{ARGV[0]} did not exist") +end + +file = ARGV[0] + +time, distance = File.open(file, "r").each_line(chomp: true).map {|v| v.split(":")[1].split(" ").join("").to_i} +events = [[time, distance]] + +product = events.map do |event| + mid = (event[0].to_f / 2).floor + first_success = (1..mid).bsearch {|i| (event[0] - i) * i > event[1]} + num_success = (mid - first_success + 1) * 2 + event[0].odd? ? num_success : num_success - 1 +end.reduce(:*) + +puts product \ No newline at end of file