Reputation: 107
I have an array of int type, I want check that if all elements of this array are equal to the elements of i-th row of m×n matrix. For example:
array={5,0,2,3};
and
matrix={{1,3,2,2}{5,0,2,3}{2,1,2,9}};
so if
array[j] = matrix[i][j];
for all j=0,1,2
then
print("the wanted i is: "+i);
I have written this code:
public static void main(String[] args){
int i, j, m=3, n=4;
int[][] A0 = {{0,2,2,5},{2,0,3,1},{0,2,0,5}};
int[] A={0,2,0,5};
int seq = 0;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(A[j] != A0[i][j]){
break;
}
seq= i;
}
}
System.out.print(seq);
}
But its not work well because it always continue checking until final row.
Is there is any other better idea? Many thanks.
Upvotes: 1
Views: 417
Reputation: 59
public static void main(String[] args){
int i, j, m=3, n=4;int ct=0;
int[][] A0 = {{0,2,2,5},{2,0,3,1},{0,2,0,5}};
int[] A={0,2,0,5};
int seq = 0;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
if(A[j] == A0[i][j]){
ct++;
}
else
{
break;
}
}
if(ct==4)
{
seq=i;
break;
}
ct=0;
}
System.out.print(seq);
}
Upvotes: 1
Reputation: 11
private int[][] myArray;
public boolean equalsRow(int[] row, int x)
{
return Arrays.equals(row, myArray[x]);
}
simpler
Upvotes: 1
Reputation: 124804
First of all,
if any value is different in a row,
then you want to skip to the next iteration of the outer loop.
You can do that by giving the outer loop a label,
and the continue
statement.
Secondly, as soon as you found a row where all values match, you can break out of the outer loop.
OUT: for (i = 0; i < m; i++) {
for (j = 0; j < n; j++) {
if (A[j] != A0[i][j]) {
continue OUT;
}
}
seq = i;
break;
}
By using Arrays.equals
you can simplify by quite a lot,
by eliminating the inner loop,
and with it all the label + continue black magic:
for (i = 0; i < m; i++) {
if (Arrays.equals(A, A0[i])) {
seq = i;
break;
}
}
Upvotes: 2
Reputation: 20885
You can simply use Arrays.equals()
private int[][] matrix;
public boolean equalsRow(int[] row, int index) {
return Arrays.equals(row, matrix[index]);
}
Upvotes: 1
Reputation: 7199
You have two for
conditions. So when you reach
if(A[j] != A0[i][j]) {
break;
}
You will break the only this for loop, so you will continue the other loop:
for(i=0;i<m;i++) {
So you have to break this one too, here is a solution
boolean canBreak = false;
for(i=0;i<m;i++) {
for(j=0;j<n;j++) {
if(A[j] != A0[i][j]) {
canBreak = true;
break;
}
if (canBreak) break;
seq= i;
}
}
Upvotes: 1