Skip to content

Instantly share code, notes, and snippets.

@Nditah
Last active March 25, 2018 12:48
Show Gist options
  • Save Nditah/c8f906d3cf2a3ab5ba205d0fe2838acc to your computer and use it in GitHub Desktop.
Save Nditah/c8f906d3cf2a3ab5ba205d0fe2838acc to your computer and use it in GitHub Desktop.
Measure of Central Tendencies, mean-median-mode with NodeJs
/*
* Input
* The first line contains an integer, N, denoting the number of elements in the array.
* The second line contains N space-separated integers describing the array's elements.
* The should print mean, median and mode
*/
function processData(input) {
let lines = input.split("\n");
const n = parseInt(lines[0]);
let a = lines[1].split(" ");
a.sort(function (a, b) { return a - b; });
//mean
let mean = 0, sum = 0;
for( let i=0; i<n; i++){
sum += parseInt(a[i]);
}
mean = sum / n ;
//median
let median = 0;
if(n % 2 === 0) {
median = ( parseInt(a[n/2]) + parseInt(a[n/2 - 1]) )/2;
} else {
median = a[Math.floor(n/2)];
}
//mode
let set = new Set(a);
let setsize = set.size ;
let arrset = Array.from(set);
let mode = a[0];
if( n !== setsize) {
let freq = []; // Array(count)
for(let i=0; i < setsize ; i++){
let count = 0;
for(let j=0; j<n ; j++) {
if(arrset[i] === a[j]){
count++
}
freq[i] = count;
}
}
//mode = elt whose freq[index] is max
freq.sort(function (a, b) { return a - b; });
let max = freq[setsize-1];
mode = indexof(max);
}else{
mode = a[0];
}
console.log(mean);
console.log(median);
console.log(mode);
return 0;
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment