Skip to content

Commit

Permalink
finish 11
Browse files Browse the repository at this point in the history
  • Loading branch information
amazingandyyy committed Nov 21, 2017
1 parent b55ac45 commit e78486c
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 0 deletions.
41 changes: 41 additions & 0 deletions 11-mean-median-mode.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
function getMean(arr) {
return arr.reduce((sum, curr) => sum += curr, 0) / arr.length;
}

function getMedian(arr) {
arr.sort((a, b) => a > b);
if ((arr.length % 2) === 0) {
return (arr[arr.length / 2] + arr[arr.length / 2 - 1]) / 2
} else {
return arr[Math.floor(arr.length / 2)];
}
}

function getMode(arr) {
var obj = {};
var modes = [];
var maxCount = 0;
arr.forEach(e => {
obj[e] ? obj[e]++ : obj[e] = 1;
if (obj[e] > maxCount) {
modes = [e];
maxCount = obj[e];
}
if (obj[e] === maxCount && modes.indexOf(e) == -1) {
modes.push(e);
}
});
if (modes.length === Object.keys(obj).length) modes = [];
return modes;
}

function meanMedianMode(arr) {
return {
mean: getMean(arr),
median: getMedian(arr),
mode: getMode(arr)
}
}


console.log(meanMedianMode([1, 1, 3, 3, 4, 4, 5, 5, 6]))
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@ When it comes to data stucture, people firstly think about python or Java which
- 02 Recursion
- 03 Binary Search Tree
- 04 Hash Table
- 05 Fizz Buzz
- 06 Harmless Ransom Note
- 07 Palindrome
- 08 Caesar Cipher
- 09 Eeverse Words
- 10 Reverse Array In Place

## Author
Andy Chen ([amazingandyyy](github.com/amazingandyyy))
Expand Down

0 comments on commit e78486c

Please sign in to comment.