-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
76 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
#!/usr/bin/env ruby | ||
|
||
class RouteFinder | ||
attr_reader :route | ||
|
||
def initialize(input_lines) | ||
@sketch = input_lines.map.with_index do |line, idx| | ||
offset = line.index("S") | ||
@start = {x: offset, y: idx, tile: "S"} if offset | ||
line.chomp.chars | ||
end | ||
|
||
@finished = false | ||
@route = [@start] | ||
@range_x, @range_y = (0...@sketch[0].length), (0...@sketch.length) | ||
end | ||
|
||
def move | ||
pos = @route.last | ||
warn "looking at #{pos}" | ||
[ | ||
{coords: {x: pos[:x] - 1, y: pos[:y]}, good_from: "S-7J", good_to: "S-LF"}, | ||
{coords: {x: pos[:x] + 1, y: pos[:y]}, good_from: "S-FL", good_to: "S-J7"}, | ||
{coords: {x: pos[:x], y: pos[:y] - 1}, good_from: "S|JL", good_to: "S|7F"}, | ||
{coords: {x: pos[:x], y: pos[:y] + 1}, good_from: "S|7F", good_to: "S|JL"} | ||
].each do |next_pos| | ||
warn "considering #{next_pos}" | ||
next unless on_sketch?(next_pos[:coords]) | ||
warn "#{next_pos} is on sketch" | ||
|
||
tile = @sketch[next_pos[:coords][:y]][next_pos[:coords][:x]] | ||
warn "tile: #{tile}" | ||
|
||
next unless next_pos[:good_from].include?(pos[:tile]) | ||
next unless next_pos[:good_to].include?(tile) | ||
|
||
if tile == "S" && @route.length > 2 | ||
warn "looped around to start!" | ||
@finished = true | ||
break | ||
end | ||
|
||
warn "#{tile} could connect" | ||
next if route.length > 1 && same_pos?(next_pos[:coords], route[-2]) | ||
warn "#{next_pos} is not moving backwards, is next!" | ||
|
||
route << next_pos[:coords].merge({tile: tile}) | ||
break | ||
end | ||
end | ||
|
||
def finished? = @finished | ||
|
||
def draw_route | ||
filtered = @sketch.map.with_index do |row, y| | ||
row.map.with_index { |tile, x| route.include?({x: x, y: y, tile: tile}) ? tile : "." }.join | ||
end | ||
|
||
puts filtered | ||
end | ||
|
||
private def on_sketch?(point) | ||
@range_x.include?(point[:x]) && @range_y.include?(point[:y]) | ||
end | ||
|
||
private def same_pos?(a, b) | ||
a[:x] == b[:x] && a[:y] == b[:y] | ||
end | ||
end | ||
|
||
file = File.open(ARGV[0]) | ||
|
||
finder = RouteFinder.new(file.readlines) | ||
finder.move until finder.finished? | ||
|
||
puts finder.route.length / 2 |