Skip to content

Instantly share code, notes, and snippets.

@gogones
Forked from areagray/meanMode.js
Created February 12, 2021 01:35
Show Gist options
  • Save gogones/aedb48fde5abe4e6d3cd4c8eb1ed4fcf to your computer and use it in GitHub Desktop.
Save gogones/aedb48fde5abe4e6d3cd4c8eb1ed4fcf to your computer and use it in GitHub Desktop.
Using the JavaScript language, have the function MeanMode(arr) take the array of numbers stored in arr and return 1 if the mode equals the mean, 0 if they don't equal each other (ie. [5, 3, 3, 3, 1] should return 1 because the mode (3) equals the mean (3)). The array will not be empty, will only contain positive integers, and will not contain m…
//Coderbyte
function MeanMode(arr) {
var sum=0,
mean, mode, midpoint, modeStr, re,
champTotal=0;
//old faithful
arr.sort(function(a, b) {
return a - b;
});
//get mean
for (var i =0; i<arr.length;i++){
sum=sum +arr[i];
}
mean=sum/arr.length;
//get mode
modeStr = arr.join(' ');
for (var j=0; j<arr.length; j++){
re = new RegExp('(' + arr[j] +')', 'g');
if (modeStr.match(re).length > champTotal){
champTotal=modeStr.match(re).length;
mode=arr[j];
}
}
mode=parseInt(mode);
return mode==mean ? 1 : 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment