Advertisement
TheFastFish

array tally

Jan 15th, 2016
496
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.01 KB | None | 0 0
  1. /*
  2.  * count how many numbers in the array are between 1 - 10, 11 - 20, etc.
  3.  * kind-of like making a histogram
  4.  */
  5. public static void tally(int[] array) {
  6.     int i;
  7.     int[] tally = new int[10]; //table to hold range counts
  8.    
  9.     /*
  10.      * the for loop iterates over the entire array, testing every element for its range
  11.      * the value of the element is subtracted by 1, and then integer-divided by 10
  12.      * (remember, integer division floors)
  13.      * this obtains the index of the total table to increment
  14.      * total 1-10 is index 0, 11-20 is index 1, etc.
  15.      * ---
  16.      * some example math problems (remember, integer division)
  17.      * (10 - 1) / 10 = 0
  18.      * (22 - 1) / 10 = 2
  19.      * ---
  20.      * and kids say they'll never use math :)
  21.      */
  22.     for(i = 0; i < array.length; i++) {
  23.         tally[(array[i] - 1) / 10]++;
  24.     }
  25.    
  26.     /*
  27.      * iterate over the total table and print the values
  28.      * range numbers are calculated based on i
  29.      */
  30.     for(i = 0; i < 10; i++) {
  31.         System.out.printf("%3d - %3d: %3d\n", (i * 10) + 1, (i + 1) * 10, tally[i]);
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement