|
1 |
| -# http://codereview.stackexchange.com/questions/33716/fish-food-chain-on/34081#34081 |
2 | 1 | def fish(a, b)
|
| 2 | + stack = [] |
3 | 3 | survivors = 0
|
4 |
| - flowing_up = [] |
5 | 4 |
|
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 |
24 | 9 | end
|
| 10 | + while stack.any? && a[i] > stack.last |
| 11 | + stack.pop |
| 12 | + end |
| 13 | + survivors += 1 if stack.empty? |
25 | 14 | end
|
26 | 15 |
|
27 |
| - survivors + flowing_up.size |
| 16 | + stack.size + survivors |
28 | 17 | end
|
29 | 18 |
|
30 | 19 | require 'minitest/autorun'
|
31 | 20 |
|
32 |
| -# this test coverage is incomplete |
33 |
| -# you can still write passing code which is wrong |
34 | 21 | 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]) |
37 | 24 | end
|
38 | 25 |
|
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]) |
41 | 28 | end
|
42 | 29 |
|
43 | 30 | 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]) |
49 | 32 | end
|
50 | 33 |
|
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]) |
53 | 36 | end
|
54 | 37 | end
|
0 commit comments