Skip to content

Commit

Permalink
Day 15
Browse files Browse the repository at this point in the history
  • Loading branch information
gregawoods committed Dec 15, 2023
1 parent 494e969 commit 5657157
Show file tree
Hide file tree
Showing 3 changed files with 73 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/15.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
rn=1,cm-,qp=3,cm=2,qp-,pc=4,ot=9,ab=5,pc-,pc=6,ot=7
54 changes: 54 additions & 0 deletions lib/days/15.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
class Day15

def part1(input)
input.split(',').map { |s| compute_hash(s) }.sum
end

def compute_hash(str)
str.chars.reduce(0) do |value, char|
code = char.ord
value += code
value *= 17
value %= 256
value
end
end

Lens = Struct.new(:label, :focal_length)

def part2(input)
boxes = {}

input.split(',').each do |step|
if step.include?('=')
label, value = step.split('=')
box_num = compute_hash(label)

boxes[box_num] ||= []
new_lens = Lens.new(label, value.to_i)

index = boxes[box_num].index { |b| b.label == label }
if index
boxes[box_num][index] = new_lens
else
boxes[box_num] << new_lens
end
else
label = step[0...-1]
box_num = compute_hash(label)

if boxes[box_num]
index = boxes[box_num].index { |b| b.label == label }
boxes[box_num].delete_at(index) if index
end
end
end

boxes.sum do |box_num, box|
box.each_with_index.sum do |lens, index|
(box_num + 1) * (index + 1) * lens.focal_length
end
end
end

end
18 changes: 18 additions & 0 deletions test/15_test.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
require 'minitest/autorun'
require 'minitest/pride'
require_relative '../app'

class TestDay15 < Minitest::Test
def setup
@data = File.read(File.join(APP_ROOT, 'examples', '15.txt')).rstrip
@day = Day15.new
end

def test_part1
assert_equal @day.part1(@data), 1320
end

def test_part2
assert_equal @day.part2(@data), 145
end
end

0 comments on commit 5657157

Please sign in to comment.