Assume I have an array of doubles that looks like the following:
Array[10] = {10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10}
I need a function th
Sort the array first w/ quick sort and then scan and count for a majority - O(n ln n). If the range of elements is known ahead of time, say between {1,k}, then a counting sort can be used which will run in O(n+k).
As a slight improvement, as you are scanning the sorted array, if you find value that has more that n/2 occurrences you are done.
I just created such a beautiful and small solution with the new Java 8:
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
public class MostCommonObject {
public static void main(String[] args) {
System.out.println(mostCommonObject(new Integer[] { -4, 1, -2, 3, 1, -2, 3, 1 }));
}
public static <T> T mostCommonObject(T[] array) {
return mostCommonObject(Arrays.asList(array));
}
public static <T> T mostCommonObject(Collection<T> collection) {
Map<T, Integer> map = new HashMap<>();
collection.forEach(t -> map.compute(t, (k, i) -> i == null ? 1 : i + 1));
return map.entrySet().stream().max((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue())).get().getKey();
}
}
Your first problem is that you have an "array of doubles", because equality is problematic with floating point data (identical numerical values can be represented by different bit patters, among other things). If your doubles are in fact (as in the example) integers, use int
instead. Otherweise, think long and hard about how you define what values are equal for the purpose of representing the same vote.
As for determining the majority vote, use a Map
with the "vote id" as key and the number of votes as value - then in the end iterate through the map to find the maximal value.
What you really want to do is to count the occurrences of certain items in given set. In fact this was previously asked less than a day ago, you might want to look into this very relevant question.
Using a Map<Integer, Integer>
should be simple as:
int mostFrequent(int... ary) {
Map<Integer, Integer> m = new HashMap<Integer, Integer>();
for (int a : ary) {
Integer freq = m.get(a);
m.put(a, (freq == null) ? 1 : freq + 1);
}
int max = -1;
int mostFrequent = -1;
for (Map.Entry<Integer, Integer> e : m.entrySet()) {
if (e.getValue() > max) {
mostFrequent = e.getKey();
max = e.getValue();
}
}
return mostFrequent;
}
Try This one,
Integer[] array=new Integer[]{10, 10, 10, 3, 10, 10, 6, 10, 10, 9, 10};
List<Integer> demoList=new ArrayList<Integer>(Arrays.asList(array));
Set<Integer> set=new HashSet<Integer>(demoList);
Map<Integer,Integer> myMap=new HashMap<Integer, Integer>();
for (Integer integer : set)
{
int count=Collections.frequency(demoList, integer);
myMap.put(count, integer);
}
int maxOccurance=myMap.get(Collections.max(myMap.keySet()));