Skip to content

Instantly share code, notes, and snippets.

@kapitanluffy
Created December 13, 2022 14:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kapitanluffy/3b51ea53cf5380398b304e0ecf716c80 to your computer and use it in GitHub Desktop.
Save kapitanluffy/3b51ea53cf5380398b304e0ecf716c80 to your computer and use it in GitHub Desktop.
I have no idea what a moving median is...
// So I had trouble with Coderbyte's "Moving Median". I have no idea what a "moving median" or a "sliding window" is.
// I can't understand the problem and googling it unfortunately didn't help me at that moment. Maybe I panicked?
// So I burned the remaining 1h50m of a 2 hour test and as I opened a new tab and searched 'moving median "javascript"'
// and I stumbled upon this: https://www.tutorialspoint.com/finding-median-for-every-window-in-javascript
//
// Median turns out was simply the number in the middle of the specified "sliding window".
// I guess I should've listened to my Math professor back in highschool jeez
//
// Below is my take on this problem
function main(arr) {
const [windowSize, ...numList] = arr;
const medians = [];
const preWindow = [];
const getMedian = (w) => {
const mid = w.length / 2
if (w.length % 2 !== 0) return w[Math.floor(mid)]
if (w.length % 2 === 0) return (w[mid - 1] + w[mid]) / 2
}
// the problem requires us to compute medians for windows with lengths smaller than the windowSize
for (let i = 0; i < windowSize - 1 && i < numList.length; i++) {
preWindow.push(numList[i])
medians.push(getMedian(preWindow))
}
for (let i = 0; i < numList.length && windowSize + i <= numList.length; i++) {
const window = numList.slice(i, windowSize+i)
window.sort((a, b) => a < b ? -1 : 1)
medians.push(getMedian(window))
}
return medians.join(",");
}
console.log(main([3, 1, 3, 5, 10, 6, 4, 3, 1])) // 1,2,3,5,6,6,4,3
console.log(main([5, 2, 4, 6])) // 2,3,4
console.log(main([3, 0, 0, -2, 0, 2, 0, -2])) // 0,0,0,0,0,0,0
console.log(main([3, 5, 3, 7, 5, 3, 1, 8, 9, 2, 4, 6, 8])) // 5,4,5,5,5,3,3,8,8,4,4,6
console.log(main([3, 1,2,3,4,2,3,1,4,2])) // 1,1.5,2,3,3,3,2,3,2
console.log(main([3, 1,3,-1,-3,5,3,6,7])) // 1,2,1,-1,-1,3,5,6
console.log(main([3, -1, 5, 13, 8, 2, 3, 3, 1])) // -1,2,5,8,8,3,3,3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment