Skip to content

Commit 185b686

Browse files
committed
Create MeanMode
1 parent 22ddec2 commit 185b686

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

MeanMode

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
/***************************************************************************************
2+
* *
3+
* CODERBYTE BEGINNER CHALLENGE *
4+
* *
5+
* MeanMode *
6+
* Have the function MeanMode(arr) take the array of numbers stored in arr and *
7+
* return 1 if the mode equals the mean, 0 if they don't equal each other *
8+
* (ie. [5, 3, 3, 3, 1] should return 1 because the mode (3) equals the mean (3)). *
9+
* The array will not be empty, will only contain positive integers, and will not *
10+
* contain more than one mode. *
11+
* *
12+
* SOLUTION *
13+
* Since it is possible that I will want a function that will calculate the mean or *
14+
* mode in the future, I decided to create separate functions for each. The mean is *
15+
* calculated by the average of all values in the array. The mode is the number that *
16+
* exists the most in the array. My solution is to call my two functions and then *
17+
* compare to see if they are equal and if so return 1 else return 0. *
18+
* *
19+
* Steps for solution *
20+
* 1) Create separate functions for getMean and getMode *
21+
* 2) Compare the values returned from the two functions *
22+
* 3) If values are equal return 1 else return 0 *
23+
* *
24+
***************************************************************************************/
25+
function MeanMode(arr) {
26+
27+
var myMean, myMode;
28+
29+
myMode = getMode(arr);
30+
myMean = getMean(arr);
31+
32+
if(myMode == myMean) {
33+
return 1;
34+
} else {
35+
return 0;
36+
}
37+
38+
}
39+
40+
function getMean(arr) {
41+
var sum = 0, mean;
42+
43+
for (var i = 0; i < arr.length; i++){
44+
sum = sum + arr[i];
45+
}
46+
mean = sum / arr.length;
47+
48+
return mean;
49+
}
50+
51+
52+
function getMode(arr) {
53+
var ctObj = {}, mode, maxCt = 1;
54+
55+
arr.sort(function(a, b) {return a - b;});
56+
57+
for (var i = 0; i < arr.length; i++){
58+
ctObj[arr[i]] = ctObj[arr[i]] || 0;
59+
ctObj[arr[i]]++;
60+
}
61+
62+
for (var key in ctObj) {
63+
if (ctObj.hasOwnProperty(key)) {
64+
if (ctObj[key] > maxCt) {
65+
maxCt = ctObj[key];
66+
mode = key;
67+
}
68+
}
69+
}
70+
71+
return mode;
72+
}

0 commit comments

Comments
 (0)