Get the Element with the Highest Occurrence in an Array

Get the element with the highest occurrence in an array

This is just the mode. Here's a quick, non-optimized solution. It should be O(n).

function mode(array)
{
if(array.length == 0)
return null;
var modeMap = {};
var maxEl = array[0], maxCount = 1;
for(var i = 0; i < array.length; i++)
{
var el = array[i];
if(modeMap[el] == null)
modeMap[el] = 1;
else
modeMap[el]++;
if(modeMap[el] > maxCount)
{
maxEl = el;
maxCount = modeMap[el];
}
}
return maxEl;
}

Get all elements of array with same (highest) occurrence

you can try this

var input = [1,4,3,1,6,5,1,4,4];

var output = {};

for ( var counter = 0; counter < input.length; counter++ )
{
if ( !output[ input[ counter ] ] )
{
output[ input[ counter ] ] = 0;
}
output[ input[ counter ] ]++;
}

var outputArr = [];
for (var key in output)
{
outputArr.push([key, output[key]])
}
outputArr = outputArr.sort(function(a, b) {return b[1] - a[1]})

now initial values of outputArr are the ones with highest frequency

Here is the fiddle

Check this updated fiddle (this will give the output you want)

var input = [1,4,3,1,6,5,1,4,4];

var output = {}; // this object holds the frequency of each value

for ( var counter = 0; counter < input.length; counter++ )
{
if ( !output[ input[ counter ] ] )
{
output[ input[ counter ] ] = 0; //initialized to 0 if value doesn't exists
}
output[ input[ counter ] ]++; //increment the value with each occurence
}
var outputArr = [];
var maxValue = 0;
for (var key in output)
{
if ( output[key] > maxValue )
{
maxValue = output[key]; //find out the max value
}
outputArr.push([key, output[key]])
}
var finalArr = []; //this array holds only those keys whose value is same as the highest value
for ( var counter = 0; counter < outputArr.length; counter++ )
{
if ( outputArr[ counter ][ 1 ] == maxValue )
{
finalArr.push( outputArr[ counter ][ 0 ] )
}
}

console.log( finalArr );

Find the element with highest occurrences in an array [java]

Update:

  • As Maxim pointed out, using HashMap would be a more appropriate choice than Hashtable here.
  • The assumption here is that you are not concerned with concurrency. If synchronized access is needed, use ConcurrentHashMap instead.

You can use a HashMap to count the occurrences of each unique element in your double array, and that would:

  • Run in linear O(n) time, and
  • Require O(n) space

Psuedo code would be something like this:

  • Iterate through all of the elements of your array once: O(n)
    • For each element visited, check to see if its key already exists in the HashMap: O(1), amortized
    • If it does not (first time seeing this element), then add it to your HashMap as [key: this element, value: 1]. O(1)
    • If it does exist, then increment the value corresponding to the key by 1. O(1), amortized
  • Having finished building your HashMap, iterate through the map and find the key with the highest associated value - and that's the element with the highest occurrence. O(n)

A partial code solution to give you an idea how to use HashMap:

import java.util.HashMap;
...

HashMap hm = new HashMap();
for (int i = 0; i < array.length; i++) {
Double key = new Double(array[i]);
if ( hm.containsKey(key) ) {
value = hm.get(key);
hm.put(key, value + 1);
} else {
hm.put(key, 1);
}
}

I'll leave as an exercise for how to iterate through the HashMap afterwards to find the key with the highest value; but if you get stuck, just add another comment and I'll get you more hints =)

Get the item that appears the most times in an array

I would do something like:

var store = ['1','2','2','3','4'];
var frequency = {}; // array of frequency.
var max = 0; // holds the max frequency.
var result; // holds the max frequency element.
for(var v in store) {
frequency[store[v]]=(frequency[store[v]] || 0)+1; // increment frequency.
if(frequency[store[v]] > max) { // is this frequency > max so far ?
max = frequency[store[v]]; // update max.
result = store[v]; // update result.
}
}

Highest occurrence in an array or first selected

You could use something like this:

function mostFrequent(array) {
var map = array.map(function(a) {
return array.filter(function(b) {
return a === b;
}).length;
});

return array[map.indexOf(Math.max.apply(null, map))];
}

First it creates a map of occurrences of all the values. Next just check with Math.max which one is the highest. Check the indexOf for the first value that has that highest occurences and return the value of that index in the original array.

ES2015

If ES2015 is an option, you could use this one. It's less code.

function mostFrequent(array) {
let map = array.map((a) => array.filter((b) => a === b).length);

return array[map.indexOf(Math.max.apply(null, map))];
}

And if you're in a place where even the spread operator is allowed (NodeJS v5 and up, Chrome 54) you could replace Math.max.apply(null, map) for Math.max(...map)!

Find highest frequent element (the smallest one if possible) and its occurrences in integer array

This problem is O(n), but without using structures, it becomes O(n²).

Here's a simple O(n²) solution:

int main(){    
int A[7] = {1, 2, 8, 2, 5, 0, 5};
int value, occurrences;
int maxValue = 99999999, maxOccurrences = 0;
for(int i = 0; i < 7; i++){
value = A[i]; occurrences = 0;
for(int j = 0; j < 7; j++) if(A[j] == value) occurrences++;
if(occurrences > maxOccurrences){
maxValue = value; maxOccurrences = occurrences;
}
else if(occurrences == maxOccurrences){
if(value < maxValue) {
maxValue = value;
maxOccurrences = occurrences;
}
}
}
cout<<maxValue<<" occurs "<<maxOccurrences<<" times"<<endl;
}

We initialize maxValue being a very large number, just to help the fact that if two numbers occur the same number of times, the lowest will be the chosen.

Then we just iterate and count.

A possible optimization is: suppose you are searching for 5 in the array. Always you find a 5, add the occurrence to the amount and set the array value to -1, so when you eventually start from it, you know it is -1 and you can skip that element.



Related Topics



Leave a reply



Submit