-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpuzzle1.rb
executable file
·61 lines (48 loc) · 1.3 KB
/
puzzle1.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#!/usr/bin/env ruby
# lines = File.readlines("sample.txt") # Answer: 288
lines = File.readlines("input.txt") # Answer: 588588
times = lines
.grep(/Time/)
.map(&:split)
.flatten
.filter {|s| s =~ /\d+/}
.map(&:to_i)
distances = lines
.grep(/Distance/)
.map(&:split)
.flatten
.filter {|s| s =~ /\d+/}
.map(&:to_i)
races = times
.zip(distances)
.map {|a| {time: a[0], distance: a[1]}}
puts "Races"
puts "-----"
puts races
def quadratic_roots(a:, b:, c:)
[
((-1 * b + Math.sqrt(b**2 - 4*a*c)) / 2*a),
((-1 * b - Math.sqrt(b**2 - 4*a*c)) / 2*a),
]
end
def count_ways_to_win_race(time:, distance:)
roots = quadratic_roots(a: -1, b: time, c: -distance)
# Raise lowest boundary if root is an integer
lowest_boundary = roots.min.ceil
lowest_boundary += 1 if (roots.min - lowest_boundary).zero?
# Lower highest boundary if root is an integer
highest_boundary = roots.max.floor
highest_boundary -= 1 if (roots.max - highest_boundary).zero?
(lowest_boundary..highest_boundary).size
end
ways = races.map do |race|
count_ways_to_win_race time: race[:time], distance: race[:distance]
end
puts ""
puts "Ways"
puts "----"
puts ways
puts ""
puts "Answer"
puts "------"
puts ways.reduce(:*)