|
Accumulator Arrays
A Programming Pattern |
|
Prof. David Bernstein |
| Computer Science Department |
| bernstdh@jmu.edu |
Given what you know, you might proceed as follows:
int ones, tens, twentys, thirtys, fortys, fiftys, sixtys,
seventys, eightys, ninetys, hundreds;
ones = tens = twentys = thirtys = fortys = fiftys
= sixtys = seventys = eightys = ninetys = hundreds = 0;
int n = Array.getLength(data);
for (int i = 0; i < n; i++) {
if (data[i] < 10) ones++;
else if (data[i] < 20) tens++;
else if (data[i] < 30) twentys++;
else if (data[i] < 40) thirtys++;
else if (data[i] < 50) fortys++;
else if (data[i] < 60) fiftys++;
else if (data[i] < 70) sixtys++;
else if (data[i] < 80) seventys++;
else if (data[i] < 90) eightys++;
else if (data[i] < 100) ninetys++;
else hundreds++;
}
if statement that is used to update
the appropriate accumulator is both awkward and error-prone
/**
* Create a frequency histogram by centile for an array
* of numeric grades (in the range [0, 100]).
*
* @param data The array of grades
* @return The frequencies
*/
public static int[] gradeHistogram(int[] data) {
int centile, n;
int[] count = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
n = Array.getLength(data);
for (int i = 0; i < n; i++) {
centile = data[i] / 10;
count[centile] += 1;
}
return count;
}
/**
* Count the number of odd and even elements
* in an array. Element 0 contains the number of even values,
* element 1 contains the number of odd values.
*
* @param data The data
* @return An array containing the counts
*/
public static int[] oddsAndEvens(int[] data) {
int[] count = {0, 0};
int n = Array.getLength(data);
for (int i = 0; i < n; i++) {
count[data[i] % 2] += 1;
}
return count;
}
/**
* Count the number of negative, zero, and positive elements
* in an array. Element 0 contains the number of negative values,
* element 1 contains the number of 0s, and element 2 contains the
* number of positive values.
*
* @param data The data
* @return An array containing the counts
*/
public static int[] signs(int[] data) {
int[] count = {0, 0, 0};
int n = Array.getLength(data);
for (int i = 0; i < n; i++) {
if (data[i] < 0) count[0]++;
else if (data[i] == 0) count[1]++;
else count[2]++;
}
return count;
}