0

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!

3
  • Where's the array of 10 numbers, and where's the list? Your question doesn't sufficiently explain the task. Commented Sep 10, 2014 at 2:16
  • Here is your solution friend :) ideone.com/CSAx3Y @Eran also has it right Commented Sep 10, 2014 at 2:17
  • @user2357112 it says that they are 10 randomly generated numbers, put into a list of either 2, 3, 4, or 5+ Commented Sep 10, 2014 at 2:22

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I might be misreading the question, but this will return the "maximum" value entered, not the most "common" value entered...
@MadProgrammer it is a continuation of a previous question he asked. The fams array at index 0 contains the number of families with 2 children, the fams array at index 1 contains the number of families with 3 children, etc.... so he finds the largest number of children between families with 2 children, 3 children etc... This largest number is, in this context, the most common number of children :)
Ah, I guess context helps them :P
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.