Skip to content

Commit 9af899c

Browse files
committed
Lesson 2 - MaxCounters (from scratch)
Hmm, I've checked old solution after writing new one and now I don't like any of them ;) Maybe next time I will write some hybrid ;).
1 parent 1dfc9dc commit 9af899c

File tree

1 file changed

+19
-11
lines changed

1 file changed

+19
-11
lines changed

max_counters.rb

+19-11
Original file line numberDiff line numberDiff line change
@@ -1,20 +1,24 @@
11
def max_counters(n, a)
22
counters = Array.new(n, 0)
3-
43
max = 0
5-
last_set_max = 0
4+
min = 0
65

7-
a.each do |counter|
8-
if counter <= n
9-
current_counter = counters[counter-1] += 1
10-
max = max < current_counter ? current_counter : max
11-
else
12-
if last_set_max < max
13-
counters = Array.new(n, max)
14-
last_set_max = max
6+
a.each do |v|
7+
if v <= n
8+
if counters[v - 1] < min + 1
9+
counters[v - 1] = min + 1
10+
else
11+
counters[v - 1] += 1
1512
end
13+
max = [max, counters[v - 1]].max
14+
else
15+
min = max
1616
end
1717
end
18+
19+
counters.each_index do |i|
20+
counters[i] = min if counters[i] < min
21+
end
1822
counters
1923
end
2024

@@ -26,6 +30,10 @@ def test_example_input
2630
end
2731

2832
def test_only_max_counter
29-
assert_equal [0, 0, 0, 0, 0], max_counters(5, [6, 6, 6])
33+
assert_equal [0, 0, 0], max_counters(3, [4, 4, 4, 4, 4])
34+
end
35+
36+
def test_max_at_the_end
37+
assert_equal [4, 4, 4], max_counters(3, [1, 1, 1, 1, 4])
3038
end
3139
end

0 commit comments

Comments
 (0)