-
Notifications
You must be signed in to change notification settings - Fork 0
/
day13.rb
executable file
·56 lines (41 loc) · 1001 Bytes
/
day13.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
#!/usr/bin/env ruby
def get_mod_inverse(n, m)
n = n % m
(1..m).each do |x|
if ((n * x) % m == 1)
return x
end
end
return 1
end
def part_a(lines)
departing_ts = lines[0].to_i
lines[1]
.split(',')
.reject { |id| id == 'x' }
.map { |id| id.to_i }
.map { |id| [id, id * (departing_ts / id + 1) - departing_ts] }
.sort_by { |_, waiting_time| waiting_time }[0]
.reduce(:*)
end
def part_b(lines)
offset = 0
ids = {}
lines[1].split(',')
.each do |token|
if token != 'x'
ids[token.to_i] = offset > 0 ? token.to_i - offset : 0
end
offset += 1
end
n_all = ids.keys.reduce(:*)
sum = ids.map { |id, offset| [id, offset, n_all/id] }.sum { |id, offset, ni| offset * ni * get_mod_inverse(ni, id) }
loop do
break if sum - n_all < 0
sum -= n_all
end
sum
end
lines = File.readlines(ARGV[0]).map(&:strip)
p part_a(lines)
p part_b(lines)