-
Notifications
You must be signed in to change notification settings - Fork 0
/
day7.rb
95 lines (76 loc) · 2.04 KB
/
day7.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
require_relative "spec_helper"
class Crabs
def initialize(positions)
@positions = positions
end
def fuel_for(new_position)
positions.map do |position|
fuel_for_distance((new_position - position).abs)
end.sum
end
def min_fuel_to_align
min, max = positions.minmax
(min..max).map do |position|
[position, fuel_for(position)]
end.min_by { _2 }.last
end
private
attr_reader :positions
def fuel_for_distance(distance)
# @cache ||= {}
# @cache[distance] ||= distance.times.sum { _1 + 1 }
# a + (a+1) + (a+2) + .. + (a+n) = n (n + a) / 2
(distance * distance + distance) / 2
end
end
RSpec.describe "Day 7" do
let(:example) do
parse_nums(
<<~INPUT
16,1,2,0,4,2,7,1,2,14
INPUT
)
end
let(:input) { parse_nums(File.read("day7_input.txt").split("\n").first) }
def parse_nums(nums)
nums.split(",").map(&:to_i)
end
describe "Crabs" do
skip "constant fuel rate" do
specify "single crab" do
expect(Crabs.new([1]).fuel_for(10)).to eql 9
end
specify "single crab - reverse" do
expect(Crabs.new([10]).fuel_for(1)).to eql 9
end
specify "several crabs" do
expect(Crabs.new(example).fuel_for(2)).to eql 37
end
end
describe "real fuel rate" do
specify "single crab" do
expect(Crabs.new([5]).fuel_for(16)).to eql 66
end
specify "single crab - reverse" do
expect(Crabs.new([16]).fuel_for(5)).to eql 66
end
specify "several crabs" do
expect(Crabs.new(example).fuel_for(2)).to eql 206
end
end
end
skip "constant fuel rate" do
specify "part 1 - example" do
expect(Crabs.new(example).min_fuel_to_align).to eql 37
end
specify "part 1 - answer" do
expect(Crabs.new(input).min_fuel_to_align).to eql 343441
end
end
specify "part 2 - example" do
expect(Crabs.new(example).min_fuel_to_align).to eql 168
end
specify "part 2 - answer" do
expect(Crabs.new(input).min_fuel_to_align).to eql 98925151
end
end