Created
April 9, 2018 20:40
-
-
Save mcraz/0e5282ea3a888095d3b5749b9ed2f76d to your computer and use it in GitHub Desktop.
Shortest ways to find Mode (highest occurring element & it's frequency)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This is most concise I could get without compromising on speed. | |
const arr = [1, 5, 2, 2, 5, 5, 6, 6, 5, 6, 6, 2, 3, 3, 5, 3]; | |
let f = new Map(); | |
for (let i = 0; i < arr.length; i++) | |
f.set(arr[i], f.has(arr[i]) ? f.get(arr[i]) + 1 : 1); | |
let l = arr[0]; | |
for (let i = 1; i < arr.length; i++) | |
if(f.get(l) < f.get(arr[i-1])) l = arr[i]; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This version mutates the input. | |
// I don't know why, but it just felt good not using another array. | |
const arr = [1, 5, 2, 2, 5, 5, 6, 6, 5, 6, 6, 2, 3, 3, 5, 3]; | |
const size = arr.length; | |
for (let i = 0; i < size; i++) { | |
arr[i + size] = arr[arr.indexOf(arr[i]) + size]++ || 1; | |
} | |
const frequencies = arr.splice(size, size*2) | |
const maxFrequency = Math.max(...frequencies); | |
const element = arr[frequencies.indexOf(maxFrequency)]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment