Hello, I am comparing a vector with each one of the rows of a matrix. I have created a variable so that it indicates when it has reached the end of the vector so that it does not continue comparing. Said variable (called coincidence) I increase it every time I find a match but its value does not increase and I do not understand why. By not increasing, I don't get into the if that compares it with the length of the vector and keeps comparing me. Could someone point me to my mistake or give me a clue about the solution? Thanks in advance.
int[][] matriz = {{2, 4, 6}, {1, 2, 4, 5, 5}, {1, 8, 9}};
int[] vector = {2, 4, 5};
int coincidencia = 0;
for (int i = 0; i < matriz.length; i++) {
for (int j = 0; j < matriz[i].length; j++) {
if (vector.length <= matriz[i].length ) {
for (int k = 0; k < vector.length; k++) {
if (vector[k] == matriz[i][j]) {
System.out.println("Coincidencia en " + "[" + i + "]" + "[" + j + "]");
coincidencia++;
System.out.println(coincidencia);
} else {
coincidencia = 0;
}
}
if(coincidencia == vector.length) {
break;
}
} else{
break;
}
}
}
Once again you have a logic problem in your algorithm...
You're looking for matches, and you're doing it wrong...
Let's analyze your code (again, we've already done this several times):
Your solution should be something like this:
First, the problem of why it's not working for you:
If you look, you have 3
for
nested, and where you make the comparison is in the innermost one, that is, you are comparing each of the elements of the vector with the first of the elements of the row of the matrix. Then all the elements of the vector with the second in the row of the matrix, and so on. The problem is that there is an iterator left over. You must iterate through the i-th row comparing the j-th elements of the vector and of that row.I think this code should solve the problem.
The other problem I see in the code you're using is that you have the
if
nested inside the secondfor
, so it makes row size comparisons that are unnecessary.And finally, the condition of the
if
actually is that the row of the matrix is exactly equal to the size of the vector you are looking for. This will speed up and simplify the code a lot.I hope I have helped.
Excuse me, by coincidence you mean that the right vector is found in the matrix? If that is the case, it is much easier this way: