# Scala algorithm: Find the contiguous slice with the minimum average

Published

## Algorithm goal

In an array, find the contiguous slice that has the minimum average.

For example, $$[3, 1, 9, 1, 2]$$ has slices:

1. $$[3, 1]$$, average $$2$$.
2. $$[3, 1, 9]$$, average $$4.33$$.
3. $$[3, 1, 9, 1]$$, average $$3.5$$.
4. $$[3, 1, 9, 1, 2]$$, average $$3.2$$.
5. $$[1, 9]$$, average $$5$$.
6. $$[1, 9, 1]$$, average $$3.67$$.
7. $$[1, 9, 1, 2]$$, average $$3.25$$.
8. $$[9, 1]$$, average $$5$$.
9. $$[9, 1, 2]$$, average $$4$$.
10. $$[1, 2]$$, average $$1.5$$.

The slice with the minimum average is $$[1, 2]$$ because it has minimum average of $$1.5$$.

This is similar to Codility's MinAvgTwoSlice problem.

## Test cases in Scala

assert(findMinAvgSlice() == None)
assert(findMinAvgSlice(1) == None)
assert(findMinAvgSlice(1, 2) == Some(SubSlice(startIndex = 0, List(1, 2))))
assert(
findMinAvgSlice(3, 1, 2) == Some(SubSlice(startIndex = 1, List(1, 2)))
)
assert(
findMinAvgSlice(3, 1, 1, 2) == Some(SubSlice(startIndex = 1, List(1, 1)))
)
assert(
findMinAvgSlice(3, 1, 2, 1, 2) ==
Some(SubSlice(startIndex = 1, List(1, 2, 1)))
)
assert(
findMinAvgSlice(3, 1, 9, 1, 2) ==
Some(SubSlice(startIndex = 3, List(1, 2)))
)
assert(
findMinAvgSlice(Int.MaxValue, Int.MaxValue, 1, 2) ==
Some(SubSlice(startIndex = 2, List(1, 2)))
)
assert(
findMinAvgSlice(3, 4, Int.MinValue, Int.MinValue, 1, 2) ==
Some(SubSlice(startIndex = 2, List(Int.MinValue, Int.MinValue)))
)


## Algorithm in Scala

28 lines of Scala (compatible versions 2.13 & 3.0), showing how concise Scala can be!