Java: finding mode in an array

Discussion in 'Mac Programming' started by canada eh, Oct 19, 2011.

  1. macrumors regular

    Joined:
    Dec 22, 2009
    Location:
    Barrie, Ontario
    #1
    Hi, I am trying to find the mode in an array. Whenever I run the following code the mode only displays 0. The original array is ( mark[] ) it is only configured for a maximum of 10 numbers. Could some one point out to me where I went wrong?

    Thanks :)

    Code:
    // create array of tallies, all initialized to zero
            int[] tally = new int[101];
            for (int i = 0; i < 10; i++) {
                tally[i] = 0;
            }
    
            // for each array entry, increment corresponding tally box
            for (int i = 0; i < 10; i++) {
                int value = (int) mark[i];
                tally[value]++;
            }
    
            // now find the index of the largest tally - this is the mode
            int maxIndex = 0;
            for (int i = 1; i < 10; i++) {
                if (tally[i] > tally[maxIndex]) {
                    maxIndex = i;
                }
            }
            
            System.out.println("Mode is: "+ maxIndex);
     
  2. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #2
    tally has 101 elements. Based on this, I'm guessing mark can only have values from 0-100. In all of your loops, you only initialize, test, etc elements 0-9. Thi is correct for the second loop, but wrong for the first an third. Do you have any marks between 1-10 in that array? More of them than you have 0? If not, you're getting the result you're looking for, the most common element between 0-10.

    -Lee
     
  3. thread starter macrumors regular

    Joined:
    Dec 22, 2009
    Location:
    Barrie, Ontario
    #3
    The whole program is a mark-book sort of deal where you enter in the grade as a percentage for 10 students (the limit of mark[]) and the program will calculate the mode out of the 10 grades entered by the user. the percentage is between 0 and 100%. Which would be the most occurring number between 0 and 100 is what I'm looking for.
     
  4. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #4
    Right, I gathered that. So when you loop over your tally array, 0 to 100. When you loop over your marks array, 0 to 9.

    -Lee
     

Share This Page