Percent delimiters %w, zip - Day 06 - Advent of Code 2023
Вставка
- Опубліковано 26 сер 2024
- See how to solve the Day 6 "Race" puzzle for the advent of code with Ruby! We’ll determine how long to press a boat's speed button to beat distance records. We’ll talk about Ruby's %w delimiter to extract race times and distances. Then use `zip` to combine the time and distance arrays together.
We’ll increment a counter when the distance beats the record. By reducing these counters per race, we can find the final product.
While this approach works, faster alternative solutions are using the quadratic formula for a mathematical model or counting below threshold distances. This allows skipping unnecessary iterations.
Advent of Code: adventofcode.com/
My Solutions: gist.github.co...
Playlist • Advent of Code
#adventofcode #ruby
Finally i manged to complete day 5 - it was hard. Today's puzzles are tricky. I had to back to my school time when I was 15-19 yo - more then 20 years ago to re-learn how to do quadratic equations.
class ToyBoat
def initialize time_given, record
@time_given = time_given
@record = record
end
def get_winning_range
delta = @time_given ** 2 - 4 * (@record+1)
time1 = (@time_given - Math.sqrt(delta))/2
time1 = time1.ceil
time2 = (@time_given + Math.sqrt(delta))/2
time2 = time2.floor
(time1..time2)
end
end
time, record = $stdin.read.split("
").map(&:split)
p time = time[1..-1].join.to_i
p record = record[1..-1].join.to_i
race = ToyBoat.new(time,record)
p race
p gwr = race.get_winning_range
p nums_of_ways = gwr.size
Nice job! Way to stay with it.
the => result is new to me, so we can assign to variable at the end of block ? cool
Oh yes! Checkout the earlier episode called rightward assignment where we talk a lot about that new Ruby feature
BTW: What is that vim/neovim plugin that shows warnings while typing?
I'm using ale - github.com/dense-analysis/ale