Skip to content

Commit

Permalink
Refactor Day 11 and Puzzle 2
Browse files Browse the repository at this point in the history
  • Loading branch information
ariejan committed Dec 11, 2024
1 parent 4e70bc4 commit bd88671
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 29 deletions.
75 changes: 52 additions & 23 deletions lib/solutions/day_11.rb
Original file line number Diff line number Diff line change
@@ -1,37 +1,66 @@
class Day11
attr_accessor :stones, :blinks
attr_accessor :stones, :iterations, :cache

# Notes:
# - Keeping input as String is faster when splitting, only convert to int when needed
# - Caching is key
# - Count, don't keep resulting stone values in memory.

def initialize
@cache = {}
end

def part_one(input)
@stones = input.split(' ').map(&:to_i)
run(input, 25)
end

def part_two(input)
run(input, 75)
end

25.times { blink! }
def run(input, iterations)
@stones = input.split(' ')
@iterations = iterations

@stones.size
result = 0
@stones.each { |s| result += count_stones_after(s, iterations) }
result
end

def blink!
new_stones = []
@stones.each_with_index do |stone, i|
value_s = stone.to_s
def count_stones_after(stone, iterations)
return 1 if iterations == 0

if stone == 0
new_stones[i] = 1
elsif value_s.length.even?
split = value_s.length / 2
new_stones[i] = [value_s[0...split].to_i, value_s[split..-1].to_i]
else
new_stones[i] = stone * 2024
end
end

@stones = new_stones.flatten!
cache_key = [stone, iterations].freeze
return @cache[cache_key] if @cache.key?(cache_key)

next_iter = blink(stone)

total = 0
next_iter.each { |s| total += count_stones_after(s, iterations - 1) }
@cache[cache_key] = total
total
end

def part_two(input)
@stones = input.split(' ').map(&:to_i)
def blink(stone)
if stone == '0'
['1']
elsif stone.size.even?
split_digits(stone)
else
[multiply(stone, 2024)]
end
end

75.times { blink! }
def multiply(stone, factor)
(stone.to_i * factor).to_s
end

@stones.size
def split_digits(stone)
split = stone.size / 2
left = stone[0...split].sub(/^0+/, '') # Remove leading zeros on left half
left = '0' if left.empty?
right = stone[split..-1].sub(/^0+/, '') # Remove leading zeros on right half
right = '0' if right.empty?
[left, right]
end
end
6 changes: 0 additions & 6 deletions spec/solutions/day_11_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,4 @@
expect(subject.part_one(input)).to eq(55_312)
end
end

describe '#part_two' do
it 'calculates the correct solutions for part two' do
expect(subject.part_two(input)).to eq(0)
end
end
end

0 comments on commit bd88671

Please sign in to comment.