Mean Mode Coderbyte Solution

0

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 more than one mode.



Mean mode coderbyte solution In Java


import java.util.Arrays;
import java.util.Scanner;

public class MeanMode {
String MeanMode(int[] arr) {
int mean = 0, mode = 0;

Arrays.sort(arr);
int prevNum = arr[0], numCount = 0, highestCount = 0;
for (int num : arr) {
mean += num;

if (num == prevNum) {
numCount++;
} else {
prevNum = num;
numCount = 1;
}

if (numCount > highestCount) {
mode = prevNum;
highestCount = numCount;
}
}

mean /= arr.length;
return mean == mode ? "1" : "0";
}

public static void main (String[] args) {

Scanner s = new Scanner(System.in);
MeanMode c = new MeanMode();
System.out.print(c.MeanMode(new int[] {5, 3, 3, 3, 1}));
}
}

Mean mode coderbyte solution In JavaScript

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 more than one mode.  


function MeanMode(arr) {

var myMean, myMode;
myMode = getMode(arr);
myMean = getMean(arr);
if(myMode == myMean) {
return 1;
} else {
return 0;
}
}

function getMean(arr) {
var sum = 0, mean;
for (var i = 0; i < arr.length; i++){
sum = sum + arr[i];
}
mean = sum / arr.length;
return mean;
}


function getMode(arr) {
var ctObj = {}, mode, maxCt = 1;
arr.sort(function(a, b) {return a - b;});
for (var i = 0; i < arr.length; i++){
ctObj[arr[i]] = ctObj[arr[i]] || 0;
ctObj[arr[i]]++;
}
for (var key in ctObj) {
if (ctObj.hasOwnProperty(key)) {
if (ctObj[key] > maxCt) {
maxCt = ctObj[key];
mode = key;
}
}
}
return mode;
}

Explanation

Since it is possible that I will want a function that will calculate the mean or mode in the future, I decided to create separate functions for each. The mean is calculated by the average of all values in the array. The mode is the number that exists the most in the array. My solution is to call my two functions and then compare to see if they are equal and if so return 1 else return 0.  

Disclaimer: The above Problem is generated by Coderbyte but the Solution is provided by ShouterFolk.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.
Post a Comment (0)
Our website uses cookies to enhance your experience. Learn More
Accept !