Reputation: 3
thanks in advance for your help. I'm new to java and I've been having difficulty processing the rows of a 2D array of ints. I've searched through this forum and other resourceful places, but nothing was helpful enough.
Here are the array elements:
1 2 3 4
4 9 17 26
2 4 6 8
1 3 5 7
9 12 32 33
4 8 10 16
3 7 9 21
10 11 12 13
here is my incorect code:
for (int row=0; row<list.length; row++) {
for (int col=0; col<list[row].length; col++) {
if (list[row][0] + 1 != list[row][1] &&
list[row][1] + 1 != list[row][2] &&
list[row][2] + 1 != list[row][3]) {
System.out.print(list[row][col] + " ");
}
}
System.out.println()
I need a code that can test and print the rows of the array whose elements are NOT consecutively incremented by 1, such as 1 2 3 4 and 10 11 12 13, assuming you do not know the values of the elements of the array.
Upvotes: 0
Views: 50
Reputation: 3331
You can iterate through the whole column, compare each value, and use a boolean to keep track if they're consecutively incremented or not. Something like this:
boolean rowIsConsecutive;
int previousValue;
for (int row = 0; row<list.length; row++)
{
rowIsConsecutive = true;
previousValue = list[row][0]; // This will blow up with a 1D array. Just wrote it like this for readability.
for (int col = 1; col<list[row].length && rowIsConsecutive; col++)
{
if (list[row][col] == previousValue + 1)
{
previousValue = list[row][col];
}
else
{
rowIsConsecutive = false;
}
}
if (rowIsConsecutive)
{
System.out.println(Arrays.toString(list[row]));
}
}
Disclaimer: I didn't test this, but something along these lines should work. And I leave it to you to come up with a more performant way to do it :)
Upvotes: 1