To traverse an array you need a for
within a for
, So a possible solution is to go through the matrix and compare each element by going through the matrix again. So you’ll have 4 for
nested s, the outer two of which are traversing the matrix for the first time, and the inner two are taking the element of the matrix’s external iteration and comparing the element of the internal iteration.
To increase the performance of your comparison, the two for
More internal s do not need to start from the element [0][0]
, iteration can start from the current element of the most external iteration. By finding a repeated element you store this value in a ArrayList
and continues the most external iteration.
Thus:
import java.util.ArrayList;
import java.util.List;
public class Matriz {
public static void main(String[] args) {
int[][] matriz = new int[][]{
{1,2,3,4},
{3,4,5,6},
{6,7,8,9}};
List<Integer> repetidos = new ArrayList<Integer>();
//percorre a matriz, elemento por elemento
for(int i=0; i<matriz.length; i++) {
proximoElemento:
for(int j=0; j<matriz[i].length; j++) {
//caso elemento já foi marcado como repetido
//continua para a próxima iteração
if(repetidos.contains(matriz[i][j])) continue proximoElemento;
//percorre novamente a matriz, elemento por elemento
//começando do elemento atual da iteração mais externa
for(int i2=i; i2<matriz.length; i2++) {
for(int j2=0; j2<matriz[i2].length; j2++) {
//não se compara com ele mesmo
if(i==i2 && j==j2) break;
//achamos um repetido, armazena e
//continua para a próxima iteração
if(matriz[i][j] == matriz[i2][j2]) {
repetidos.add(matriz[i][j]);
continue proximoElemento;
}
}
}
}
}
//exibe os elementos encontrados repetidos ao menos uma vez
for(int r: repetidos) {
System.out.println(r);
}
}
}
Upshot:
3
4
6
Example in Ideone
Do you already have some code of your attempts? If yes, could you share with us?
– Math
I don’t. I couldn’t think of any way for each element to be compared with everyone else in the matrix. The only thing I thought was to order the rows and columns in ascending order, then if you have repeated element they will be in consecutive positions and then you could do a check of type x == x+1. But I couldn’t implement it like that and I thought there was some simpler way.
– Chittolina
Some of these answers answered him?
– Ricardo