Skip to content

Instantly share code, notes, and snippets.

@myf
Last active June 21, 2019 01:34
Show Gist options
  • Save myf/267594ed8afed151ceace3f13cc1a99e to your computer and use it in GitHub Desktop.
Save myf/267594ed8afed151ceace3f13cc1a99e to your computer and use it in GitHub Desktop.
const Med = function() {
// assuming from 10 to 60 is the possibility
this.range = Array(50).fill(0);
};
Med.prototype.next = function(num) {
const num_index = num - 10; // from 10 ot 60 but using 0 - 50 as template
this.range[num_index] += 1;
}
;
Med.prototype.median = function() {
const count = this.range.reduce((acc, cur) => acc + cur, 0);
const mid_index = count / 2;
// even or odd
if (mid_index % 1.0 === 0) {
return (conv_num(mid_index, this.range) +
conv_num(mid_index + 1, this.range)) / 2;
}
return conv_num(Math.ceil(mid_index), this.range);
};
const conv_num = function(num, range) {
// count from the beginning of the range until it reaches mid_index
let acc = 0;
for (let i = 0; i < range.length; i++) {
//console.log(acc, num, acc + range[i]);
if (acc < num && num <= acc + range[i]) {
return i + 10;
}
acc = acc + range[i];
}
};
module.exports = Med;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment