1+ /* https://coderbyte.com/question/mean-mode
2+
3+ * Have the function MeanMode(arr) take the array of numbers stored in arr and *
4+ * return 1 if the mode equals the mean, 0 if they don't equal each other *
5+ * (ie. [5, 3, 3, 3, 1] should return 1 because the mode (3) equals the mean (3)). *
6+ * The array will not be empty, will only contain positive integers, and will not *
7+ * contain more than one mode. *
8+ * *
9+ * SOLUTION *
10+ * Since it is possible that I will want a function that will calculate the mean or *
11+ * mode in the future, I decided to create separate functions for each. The mean is *
12+ * calculated by the average of all values in the array. The mode is the number that *
13+ * exists the most in the array. My solution is to call my two functions and then *
14+ * compare to see if they are equal and if so return 1 else return 0. *
15+ * *
16+ * Steps for solution *
17+ * 1) Create separate functions for getMean and getMode *
18+ * 2) Compare the values returned from the two functions *
19+ * 3) If values are equal return 1 else return 0
20+ */
21+
22+ mean = arr => ( arr . reduce ( ( a , b ) => a + b ) ) / ( arr . length ) ;
23+
24+ // mode is just the problem of finding the element with greatest no of occurrence
25+ mode = arr => {
26+
27+ let obj = { } , max = 1 , mode ;
28+
29+ for ( let i of arr ) {
30+ obj [ i ] = obj [ i ] || 0 ;
31+ obj [ i ] ++
32+ }
33+
34+ for ( let i in obj ) {
35+ if ( obj . hasOwnProperty ( i ) ) {
36+ if ( obj [ i ] > max ) {
37+ max = obj [ i ]
38+ mode = i ;
39+ }
40+ }
41+ }
42+ return mode ;
43+ }
44+
45+ meanMode = arr => mean ( arr ) == mode ( arr )
46+
47+ let myArr = [ 5 , 3 , 3 , 3 , 1 ]
48+
49+ console . log ( mean ( myArr ) )
50+
51+ console . log ( mode ( myArr ) )
52+
53+ console . log ( meanMode ( myArr ) )
0 commit comments