Skip to content

Commit 6d404a4

Browse files
committed
Lesson 3 - MinAvgTwoSlice (from scratch)
1 parent 69a492d commit 6d404a4

File tree

1 file changed

+20
-24
lines changed

1 file changed

+20
-24
lines changed

min_avg_two_slice.rb

Lines changed: 20 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,22 @@
11
def min_avg_two_slice(a)
2-
prefix_sums = Array.new(a.size + 1, 0)
3-
a.each_with_index do |value, i|
4-
prefix_sums[i+1] = value + prefix_sums[i]
2+
min_avg = 1 / 0.0
3+
min_index = 0
4+
5+
a.each_cons(2).each_with_index do |double, i|
6+
avg = double.inject(:+) / 2.0
7+
8+
if avg < min_avg
9+
min_index = i
10+
min_avg = avg
11+
end
512
end
613

7-
min_index = 0
8-
min_average = nil
9-
prefix_sums.each_with_index do |prefix_sum, index|
10-
[2, 3].each do |slice_size|
11-
next if index < slice_size
12-
13-
slice_average = (prefix_sum - prefix_sums[index-slice_size])/slice_size.to_f
14-
min_average = slice_average if min_average.nil?
15-
16-
if slice_average < min_average
17-
min_index = index - slice_size
18-
min_average = slice_average
19-
end
14+
a.each_cons(3).each_with_index do |triple, i|
15+
avg = triple.inject(:+) / 3.0
16+
17+
if avg < min_avg
18+
min_index = i
19+
min_avg = avg
2020
end
2121
end
2222

@@ -30,15 +30,11 @@ def test_example_input
3030
assert_equal 1, min_avg_two_slice([4, 2, 2, 5, 1, 5, 8])
3131
end
3232

33-
def test_first_index
34-
assert_equal 0, min_avg_two_slice([1, 1])
35-
end
36-
37-
def test_first_minimal_index
38-
assert_equal 1, min_avg_two_slice([2, 1, 1, 1])
33+
def test_slice_of_three
34+
assert_equal 1, min_avg_two_slice([2, 1, 2, 1])
3935
end
4036

41-
def test_slice_length_3
42-
assert_equal 1, min_avg_two_slice([2, 1, 2, 1])
37+
def test_negative
38+
assert_equal 4, min_avg_two_slice([1, 1, 0, 0, -5, -5, 1, 1])
4339
end
4440
end

0 commit comments

Comments
 (0)