Skip to content

Instantly share code, notes, and snippets.

@thewhodidthis
Last active August 8, 2021 16:23
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 thewhodidthis/6f5162b6f115be4778a372f24a5e2502 to your computer and use it in GitHub Desktop.
Save thewhodidthis/6f5162b6f115be4778a372f24a5e2502 to your computer and use it in GitHub Desktop.
Find the median value in array of numbers
const assert = require('assert')
// I'm trusting R's built in helper for calculating expected values
// https://repl.it/repls/IroncladLightpinkBookmark
const samples = [
{
input: [187],
expected: 187,
},
{
input: [378, 329, 445],
expected: 378,
},
{
input: [102, 152, 441, 200, 256, 216, 440, 234, 392, 358, 270, 506],
expected: 263,
},
{
input: [135, 60, 66, 85, 101, 68, 80],
expected: 80,
},
{
input: [36, 222, 56, 86, 87, 95],
expected: 86.5,
},
{
input: [1611, 144, 136, 149, 168, 169, 144, 712, 183, 148, 157, 143],
expected: 153,
},
{
input: [794,267,404,219],
expected: 335.5,
},
{
input: [207],
expected: 207,
},
{
input: [128,218,239,272,277,219,372,208,211,471,319,385,350],
expected: 272,
},
{
input: [89,80,48,144,437,86,72,99,66],
expected: 86,
},
{
input: [59,137,99],
expected: 99,
},
{
input: [73,126,133,110,140,131,141,137,156,174,163],
expected: 137,
},
]
for (const sample of samples) {
const result = findMedian(sample.input)
assert.equal(result, sample.expected)
}
function findMedian(inputMaybe = []) {
// Sort in ascending order assuming data sanitized for e.g., `Infinity` and `NaN` values,
// but get a copy first, because sorting happens in place
const input = [...inputMaybe].sort((a, b) => a - b)
// https://en.wikipedia.org/wiki/Median#Finite_data_set_of_numbers
const i = 0.5 * (input.length + 1)
const a = Math.floor(i) - 1
const b = Math.ceil(i) - 1
return 0.5 * (input[a] + input[b])
}
@thewhodidthis
Copy link
Author

# Tested with Node.js 12.18.4, clean exit means tests are passing
git clone https://gist.github.com/6f5162b6f115be4778a372f24a5e2502.git find-median
cd find-median
node index.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment