Sunday, September 23, 2007

Add consecutive equal values in array

I don't know how to explain this snippet so people can find it if they search for it, but it would be something like add consecutive equal values in array.

I thought this would help you when you have a ResultSet and you need to add together two rows if they equal each other and then print it out. But it didn't, I'm going to end up doing it on the query. There might be another way to do this, but this is what I came up with... If someone knows a better way, please let me know :)

public class ConsecutiveArrayValues{

public static void main(String[] args) {
int a[]={1, 2, 4, 4};
int previousValue = a[0];
int output = a[0];

for (int i = 1; i<= a.length-1; i++) { if (a[i] == previousValue) {
output += a[i];
previousValue = a[i];
}
else {
System.out.println(output);
previousValue = a[i];
output = a[i];
}
}

System.out.println(output);

}
}

/* This will output 1 2 8.
If the array is {1, 1, 1, 1} the output will be 4.
If the array is {1, 2, 2, 3} the output will be 1 4 3

It adds consecutive values together, so in array
A = {1, 2, 2, 3}
A[1] and A[2] are equal (i.e. 2), then it adds the values up.
*/

Hope this is useful to someone, I had a fun time trying to get this working :)

No comments: