Skip to content

Commit 7c60b8f

Browse files
committed
Lesson 5 - Fish (from scratch)
1 parent ae3dec4 commit 7c60b8f

File tree

1 file changed

+17
-34
lines changed

1 file changed

+17
-34
lines changed

fish.rb

Lines changed: 17 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,37 @@
1-
# http://codereview.stackexchange.com/questions/33716/fish-food-chain-on/34081#34081
21
def fish(a, b)
2+
stack = []
33
survivors = 0
4-
flowing_up = []
54

6-
a.zip(b).each do |size, direction|
7-
if direction == 0
8-
if flowing_up.empty?
9-
survivors += 1
10-
else
11-
while flowing_up.any?
12-
if size > flowing_up.last
13-
flowing_up.pop
14-
else
15-
break
16-
end
17-
end
18-
if flowing_up.empty?
19-
survivors += 1
20-
end
21-
end
22-
else
23-
flowing_up << size
5+
a.each_index do |i|
6+
if b[i] == 1
7+
stack << a[i]
8+
next
249
end
10+
while stack.any? && a[i] > stack.last
11+
stack.pop
12+
end
13+
survivors += 1 if stack.empty?
2514
end
2615

27-
survivors + flowing_up.size
16+
stack.size + survivors
2817
end
2918

3019
require 'minitest/autorun'
3120

32-
# this test coverage is incomplete
33-
# you can still write passing code which is wrong
3421
class Tests < MiniTest::Unit::TestCase
35-
def test_all_upstream
36-
assert_equal 3, fish([1, 2, 3], [0, 0, 0])
22+
def test_one_fish_downstream
23+
assert_equal 1, fish([1], [1])
3724
end
3825

39-
def test_all_downstream
40-
assert_equal 3, fish([1, 2, 3], [1, 1, 1])
26+
def test_one_fish_upstream
27+
assert_equal 1, fish([1], [0])
4128
end
4229

4330
def test_example_input
44-
assert_equal 2, fish([4, 3, 2, 1, 1], [0, 1, 0, 0, 0])
45-
end
46-
47-
def test_one_big_at_the_end
48-
assert_equal 1, fish([1, 2, 3, 4, 5], [1, 1, 1, 1, 0])
31+
assert_equal 2, fish([4, 3, 2, 1, 5], [0, 1, 0, 0, 0])
4932
end
5033

51-
def test_one_big_at_the_beggining
52-
assert_equal 1, fish([5, 4, 3, 2, 1], [1, 0, 0, 0, 0])
34+
def test_simple
35+
assert_equal 1, fish([8, 6, 5, 3, 2, 4, 7], [1, 1, 1, 1, 1, 0, 0])
5336
end
5437
end

0 commit comments

Comments
 (0)