Last active
September 25, 2017 13:22
-
-
Save xremix/c327082683b9e68d379d5d246cf49b5a to your computer and use it in GitHub Desktop.
Find item with most occurrence (JS)
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
// ----------------------------- | |
// ----------------------------- | |
// ----------------------------- | |
// Most Occurence Item in Array | |
// This is just for playing arround. | |
// ----------------------------- | |
// ----------------------------- | |
// ----------------------------- | |
////////// | |
////////// Using Hashmap and Sort afterwards | |
////////// ~1.7s | |
console.time('start') | |
var originalValues = []; | |
for (var i = 0; i < 999999; originalValues.push(++i)) {} | |
originalValues.push(1); | |
var map = new Map(); | |
for (var i = originalValues.length - 1; i >= 0; i--) { | |
var rowName = ''+originalValues[i].toString(); | |
map.set(rowName, map.get(rowName) ? map.get(rowName) +1: 1) | |
} | |
var y = Array | |
.from(map) | |
.sort((a, b) => { | |
return a[0] - b[0]; | |
})[0]; | |
console.log(y); | |
console.log('Biggest number is ' + y[0] + ' with ' +y[1] + ' times'); | |
console.timeEnd('start') | |
////////// | |
////////// Using Hashmap, remember largest one | |
////////// ~29s | |
console.time('start') | |
var originalValues = []; | |
for (var i = 0; i < 100000; originalValues.push(++i)) {} | |
originalValues.push(3); | |
var largestName = ""; | |
var largest = -1; | |
var map = new Map(); | |
for (var i = originalValues.length - 1; i >= 0; i--) { | |
var rowName = ''+originalValues[i].toString(); | |
map.set(rowName, map.get(rowName) ? map.get(rowName) +1: 1) | |
if (map.get(rowName)>largest){ | |
largest = map.get(rowName); | |
largestName = rowName; | |
} | |
} | |
console.log('Largest one is ' + largestName + ' with ' + largest + ' times') | |
console.timeEnd('start') | |
////////// | |
////////// Sort, just remember largest one | |
////////// ~24s | |
console.time('start') | |
var originalValues = []; | |
for (var i = 0; i < 100000; originalValues.push(++i)) {} | |
originalValues.push(3); | |
originalValues.sort(); | |
var maxLength = -1; | |
var maxItem = null; | |
var currentLength = -1; | |
var currentItem = null; | |
for (var i = originalValues.length - 1; i >= 0; i--) { | |
if(currentItem != originalValues[i]){ | |
currentItem = originalValues[i]; | |
currentLength = 1; | |
}else{ | |
currentLength++; | |
} | |
if(maxLength < currentLength){ | |
maxLength = currentLength; | |
maxItem = currentItem; | |
} | |
} | |
console.log('Largest one is ' + maxItem + ' with ' + maxLength + ' times') | |
console.timeEnd('start') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment