Darron Martinez
Darron Martinez

Reputation: 49

Determining the most common value in an array

Let's say I have an array of 10 randomly generated numbers. Then these numbers go into a list. Such as:

int[] fams = new int[4];

System.out.println("Number of families with 2 children: " + fams[0]);

System.out.println("Number of families with 3 children: " + fams[1]);

System.out.println("Number of families with 4 children: " + fams[2]);

System.out.println("Number of families with 5 or more children: " + fams[3]);

Then I must say:

System.out.println("The most common number of children was " + common + ".");

I tried the code

int common = 0;
for(int i = 0; i < fams.length; i++) {
    if(common < fams[i]) {
            common = fams[i];

However, this outputs what the most common fams number is (obviously so). What i need is the most common number of children. For instance, if 2 had 5 families (with an input of 10), I need the number 2 to be the output, not 5. Thanks for the help!

Upvotes: 0

Views: 79

Answers (2)

eckes
eckes

Reputation: 10423

If you don't want to keep the count for each number (for example in a map-reduce scenario with a log of different values) you can sort the collection, and then linearly scan through the list. Every time the value changes, you reset your counter. If your counter reaches max you remeber the number and the index.

Upvotes: 0

Eran
Eran

Reputation: 393771

You need to keep track of both the highest element in fams array and the index of that element. The index is what you are looking for.

int common = 0;
int commonIndex = -1;
for(int i = 0; i < fams.length; i++) {
    if(common < fams[i]) {
        common = fams[i];
        commonIndex = i;
    }
}

At the end of the loop, commonIndex would hold what you need.

Upvotes: 4

Related Questions