131 lines
2.3 KiB
Ruby
131 lines
2.3 KiB
Ruby
def walk(matrix)
|
|
should_continue = true
|
|
|
|
i, j = get_current_position(matrix)
|
|
start_i = i
|
|
start_j = j
|
|
start_symbol = matrix[i][j]
|
|
|
|
history = {}
|
|
|
|
while should_continue
|
|
history["#{i},#{j}"] = true
|
|
should_continue, i, j = make_step(matrix, i, j)
|
|
end
|
|
|
|
matrix[start_i][start_j] = start_symbol
|
|
history.length
|
|
end
|
|
|
|
def make_step(matrix, i, j)
|
|
case matrix[i][j]
|
|
when '^'
|
|
if i == 0
|
|
matrix[i][j] = '.'
|
|
return [false, -1, -1]
|
|
end
|
|
|
|
if matrix[i - 1][j] == '#'
|
|
matrix[i][j] = '>'
|
|
return [true, i, j]
|
|
end
|
|
|
|
matrix[i - 1][j] = '^'
|
|
matrix[i][j] = '.'
|
|
[true, i - 1, j]
|
|
when 'v'
|
|
if i == matrix.length - 1
|
|
matrix[i][j] = '.'
|
|
return [false, -1, -1]
|
|
end
|
|
|
|
if matrix[i + 1][j] == '#'
|
|
matrix[i][j] = '<'
|
|
return [true, i, j]
|
|
end
|
|
|
|
matrix[i + 1][j] = 'v'
|
|
matrix[i][j] = '.'
|
|
[true, i + 1, j]
|
|
when '>'
|
|
if j == matrix[i].length - 1
|
|
matrix[i][j] = '.'
|
|
return [false, -1, -1]
|
|
end
|
|
|
|
if matrix[i][j + 1] == '#'
|
|
matrix[i][j] = 'v'
|
|
return [true, i, j]
|
|
end
|
|
|
|
matrix[i][j + 1] = '>'
|
|
matrix[i][j] = '.'
|
|
[true, i, j + 1]
|
|
when '<'
|
|
if j == 0
|
|
matrix[i][j] = '.'
|
|
return [false, -1, -1]
|
|
end
|
|
|
|
if matrix[i][j - 1] == '#'
|
|
matrix[i][j] = '^'
|
|
return [true, i, j]
|
|
end
|
|
|
|
matrix[i][j - 1] = '<'
|
|
matrix[i][j] = '.'
|
|
[true, i, j - 1]
|
|
end
|
|
end
|
|
|
|
def get_current_position(matrix)
|
|
for i in 0..matrix.length - 1 do
|
|
for j in 0..matrix[i].length - 1 do
|
|
return [i, j] if ['^', '>', 'v', '<'].include?(matrix[i][j])
|
|
end
|
|
end
|
|
|
|
[]
|
|
end
|
|
|
|
def count_possible_obstructions(matrix)
|
|
count = 0
|
|
|
|
start_i, start_j = get_current_position(matrix)
|
|
start_symbol = matrix[start_i][start_j]
|
|
|
|
for i in 0..matrix.length - 1 do
|
|
for j in 0..matrix[i].length - 1 do
|
|
next if matrix[i][j] != '.'
|
|
|
|
matrix[i][j] = '#'
|
|
count += 1 if test_loop(matrix, start_i, start_j)
|
|
matrix[i][j] = '.'
|
|
matrix[start_i][start_j] = start_symbol
|
|
end
|
|
end
|
|
|
|
count
|
|
end
|
|
|
|
def test_loop(matrix, i, j)
|
|
should_continue = true
|
|
|
|
history = {}
|
|
|
|
while should_continue
|
|
symbol = matrix[i][j]
|
|
key = "#{i},#{j},#{symbol}"
|
|
|
|
if history.include?(key)
|
|
matrix[i][j] = '.'
|
|
return true
|
|
end
|
|
|
|
history[key] = true
|
|
|
|
should_continue, i, j = make_step(matrix, i, j)
|
|
end
|
|
|
|
false
|
|
end
|