[2018][ruby][17.1] water moves down

sorbet
Alpha Chen 6 years ago
parent feb1b7b125
commit 0004f96f22

@ -1,3 +1,5 @@
require "set"
require "minitest" require "minitest"
require "minitest/pride" require "minitest/pride"
@ -16,10 +18,30 @@ class Slice
def initialize(squares) def initialize(squares)
@squares = squares @squares = squares
@squares[[500, 0]] = ?+ @squares[[500, 0]] = ?+
@active = Set[[500, 0]]
end end
def simulate def simulate
return enum_for(__method__) unless block_given?
loop do
@active.to_a.each do |x, y|
@active.delete([x, y])
case @squares.fetch([x, y])
when ?+
@squares[[x, y+1]] = ?|
@active << [x, y+1]
when ?|
@squares[[x, y+1]] = ?|
@active << [x, y+1]
end
end
yield self
end
end
def water
end end
def to_s def to_s
@ -31,8 +53,8 @@ class Slice
end end
class TestSlice < Minitest::Test class TestSlice < Minitest::Test
def test_parse_to_s def setup
slice = Slice.parse(<<~SLICE) @slice = Slice.parse(<<~SLICE)
x=495, y=2..7 x=495, y=2..7
y=7, x=495..501 y=7, x=495..501
x=501, y=3..7 x=501, y=3..7
@ -42,8 +64,10 @@ class TestSlice < Minitest::Test
x=504, y=10..13 x=504, y=10..13
y=13, x=498..504 y=13, x=498..504
SLICE SLICE
end
assert_equal <<~SLICE.chomp, slice.to_s def test_parse_to_s
assert_equal <<~SLICE.chomp, @slice.to_s
......+....... ......+.......
............#. ............#.
.#..#.......#. .#..#.......#.
@ -60,6 +84,29 @@ class TestSlice < Minitest::Test
....#######... ....#######...
SLICE SLICE
end end
def test_simulate
simulation = @slice.simulate
slice = 5.times { simulation.next }
assert_equal <<~SLICE.chomp, @slice.to_s
......+.......
......|.....#.
.#..#.|.....#.
.#..#.|#......
.#..#.|#......
.#....|#......
.#.....#......
.#######......
..............
..............
....#.....#...
....#.....#...
....#.....#...
....#######...
SLICE
end
end end
def solve(input) def solve(input)

Loading…
Cancel
Save