Skip to content

Commit

Permalink
chore: impl for day23b
Browse files Browse the repository at this point in the history
switch to queue based approach to avoid stack overflow
  • Loading branch information
Jaxwood committed Aug 14, 2024
1 parent c2174e9 commit 183ad95
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
41 changes: 41 additions & 0 deletions lib/day23.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,40 @@ def find_longest_path
@current_longest
end

def longest_path_queue
queue = Queue.new
queue << [@start, Set.new([@start]), [@start]]

until queue.empty?
current, visited, path = queue.pop

if current == @goal && path.length > @current_longest
@current_longest = path.length - 1
else
next_positions = case [@forest_map[current], @dry]
when [:right, false]
[[current[0] + 1, current[1]]]
when [:down, false]
[[current[0], current[1] + 1]]
else
neighbors(current)
end

next_positions.each do |next_pos|
next unless @forest_map.key?(next_pos) && !visited.include?(next_pos) && @forest_map[next_pos] != :tree

new_visited = visited.dup
new_visited.add(next_pos)
new_path = path.dup
new_path << next_pos
queue << [next_pos, new_visited, new_path]
end
end
end

@current_longest
end

private

def dfs(current, visited, path)
Expand Down Expand Up @@ -79,4 +113,11 @@ def part1
forest = Forest.new(@maze, start, goal)
forest.find_longest_path
end

def part2
start = find(:start)
goal = find(:end)
forest = Forest.new(@maze, start, goal)
forest.longest_path_queue
end
end
12 changes: 12 additions & 0 deletions test/unit/day23_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,21 @@ def test_day23a
assert_equal(94, sut.part1)
end

def test_day23b
sut = Day23.new
sut.load('data/day23a.txt')
assert_equal(154, sut.part2)
end

def test_day23a_part1
sut = Day23.new
sut.load('data/day23.txt')
assert_equal(2430, sut.part1)
end

def _test_day23a_part2
sut = Day23.new
sut.load('data/day23.txt')
assert_equal(0, sut.part2)
end
end

0 comments on commit 183ad95

Please sign in to comment.