Last active
February 10, 2019 13:14
-
-
Save Morriz/abeeff463f810b8f50bc23051c53ac1b to your computer and use it in GitHub Desktop.
My solution to codility test MinAvgTwoSlice: https://app.codility.com/programmers/lessons/5-prefix_sums/min_avg_two_slice/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given: | |
* | |
* A non-empty array A consisting of N integers is given. A pair of integers (P, Q), | |
* such that 0 ≤ P < Q < N, is called a slice of array A (notice that the slice contains | |
* at least two elements). The average of a slice (P, Q) is the sum of | |
* A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, | |
* the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q − P + 1). | |
* | |
* Implied assumption: | |
* - a slice will never be longer than 3 items, as any slice longer will contain | |
* a slice of 2 or 3 items which has a lower average. | |
* | |
* Chosen approach: | |
* - iterate over index of items | |
* - keep index of lowest average double | |
* - keep index -1 of lowest average triple if lower than double | |
* | |
*/ | |
const summer = (val, sum) => (sum += val) | |
const sumSlice = slice => slice.reduce(summer, 0) | |
function solution(A) { | |
let minAvg | |
let minIndex | |
for (let i = 0; i <= A.length - 2; i++) { | |
const slice2 = A.slice(i, i + 2) | |
const sum2 = sumSlice(slice2) | |
const avg2 = sum2 === 0 ? sum2 : sum2 / slice2.length | |
if (minAvg === undefined || avg2 < minAvg) { | |
minIndex = i | |
minAvg = avg2 | |
} | |
if (i > 0) { | |
const slice3 = A.slice(i - 1, i + 2) | |
const sum3 = sumSlice(slice3) | |
const avg3 = sum3 === 0 ? sum3 : sum3 / slice3.length | |
if (avg3 < minAvg) { | |
minIndex = i - 1 | |
minAvg = avg3 | |
} | |
} | |
} | |
return minIndex | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment