Search code examples
javaarrayssortingsummarization

Array summary ( working code), not grasping a line of code


Learning arrays atm (self-thought noob) Can somebody explain what does this part of the code mean here?

for (int answer = 0; answer < responses.length; answer++ )
 ++frequency[ responses[ answer ] ];

I can't grasp the logic of it. Obviously "answer" is my counter.frequency is increasing by 1 until it reaches array #11 ( which is number 10), but what happens inside the brackets is what baffles me. But if it reaches the maximum number of 10, results (which are right) give actual frequency. My guess is this piece of code is what manipulates big part of this class.
I have built on this code, but I am using this part of the code by default (because it's given in the book per se).

Thank you.

Here's the full code

public class StudentPoll
{
  public static void main( String[] args)
  {
   int[] responses = {1, 2, 6, 4, 8, 5, 9, 7, 8, 10, 1, 6, 3, 8, 6,
       10, 3, 8, 2, 7, 6, 5, 7, 6, 8, 6, 7, 5, 6, 6, 5, 6, 7, 5, 6,
       4, 8, 6, 8, 10};
   int[] frequency = new int[ 11 ];

   for (int answer = 0; answer < responses.length; answer++ )
     ++frequency[ responses[ answer ] ];

   System.out.printf( "%s%10s\n", "Rating", "Frequency" );

   for ( int rating = 1; rating < frequency.length; rating++ )
    System.out.printf( "%d%10d\n", rating, frequency[ rating ] );

   }
 }

Solution

  • The indices of frequency correspond to the number being counted, and the value at one of those indices is the frequency of that number. It works because the maximum number in responses is 10, and the length of frequency is 11, meaning that 10 is a valid index into frequency (the maximum index of an array is always array length - 1).

               two 1's   seven 2's
                    |    |
                    v    v
    values:  [ 0 ][ 2 ][ 7 ] ... and so on
    indices:   0    1    2
    

    You can think of ++frequency[ responses[ answer ] ]; as "increase the frequency corresponding to this response by one".

    I would find this to be more readable, as it removes the unnecessary responses[answer] noise:

    for (int response : responses)
        frequency[response]++;
    

    "For each response, increment the response's frequency by one"