Created
November 11, 2022 18:39
-
-
Save flacial/2d0fbf18b400949d30a0a6fcbe3ccea0 to your computer and use it in GitHub Desktop.
Sliding Window: find averages of subarrays
This file contains 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
function find_averages_of_subarrays(K, arr) { | |
const result = [] | |
let windowSum = 0 | |
let windowStart = 0 | |
for (let windowEnd = 0; windowEnd < arr.length; windowEnd++) { | |
// Push the last element back, slide new element as the last one | |
windowSum += arr[windowEnd] | |
// We reached a window with 5 elements | |
if (windowEnd >= K - 1) { | |
result.push(windowSum / 5) | |
// Slide the first element out | |
windowSum -= arr[windowStart] | |
// Replace the first element with the second one | |
windowStart += 1 | |
} | |
} | |
return result | |
} | |
const result = find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2]); | |
console.log(`Averages of subarrays of size K: ${result}`); | |
/* | |
K = 5 | |
K - 1 = 4 | |
windowStart = 0 | |
// i = 0 | |
WindowSum = 1 | |
// i = 1 | |
windowSum = 1 + 3 | |
// i = 2 | |
windowSum = 1 + 3 + 2 | |
// i = 3 | |
windowSum = 1 + 3 + 2 + 6 | |
// i = 4 | |
windowSum = 1 + 3 + 2 + 6 + -1 | |
windowSum -= arr[windowStart] | |
windowStart += 1 | |
windowSum = 3 + 2 + 6 + -1 | |
// i = 5 | |
windowSum = 3 + 2 + 6 + -1 + 4 | |
windowSum -= arr[windowStart] | |
windowStart += 1 | |
windowSum = 2 + 6 + -1 + 4 | |
// i = 6 | |
windowSum = 2 + 6 + -1 + 4 + 1 | |
windowSum -= arr[windowStart] | |
windowStart += 1 | |
windowSum = 6 + -1 + 4 + 1 | |
// i = 7 | |
windowSum = 6 + -1 + 4 + 1 + 8 | |
windowSum -= arr[windowStart] | |
windowStart += 1 | |
windowSum = -1 + 4 + 1 + 8 | |
// i = 7 | |
windowSum = -1 + 4 + 1 + 8 + 2 | |
windowSum -= arr[windowStart] | |
windowStart += 1 | |
windowSum = 4 + 1 + 8 + 2 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment