I need to find non similar rows in matrix and return set of such rows.
A rows is said to be similar if the sets of numbers occurring in these rows coincide.
Example: origin:
1 2 2 4 4
4 2 1 4
3 2 4 1 5 8
expected result:
1 2 2 4 4
3 2 4 1 5 8
My ideas:
Clean duplicates from each row via convert two dimensional array to List>
Create new set of int[] and add row then if row was added its means that row is non similar.then record number of row. return created new set of rows of origin matrix. I know that I can check if element was added via Boolean return value of Add method of Set. But there is problem by forEach, that don't provide index. And I can't use expressions inside forEach. What should I do?
My code:
class NonSimilar {
private int[][] matrix;
private List<Set<Integer>> rows = new ArrayList<>();
public NonSimilar (int[][] matrix) {
this.matrix = matrix;
for (int i = 0; i < matrix.length; i++) {
rows.add(Arrays.stream(matrix[i]).boxed().collect(Collectors.toSet()));
}
}
public Set<int[]> getNonSimilarRows() {
Set<Set<Integer>> nonSimularRows = new HashSet<>();
rows.forEach(item -> nonSimularRows.add(item));
// Now I have to check successfully added rows numbers and construct new Set from Origin matrix
return new HashSet<int[]>();
}
}
Ok. I replaced forEach with for iteration and now all works correctly.
public Set<int[]> getNonSimilarRows() {
Set<Set<Integer>> nonSimularRows = new HashSet<>();
//rows.forEach(item -> nonSimularRows.add(item));
int index = -1;
ArrayList<Integer> indexes = new ArrayList<>();
for (Set<Integer> item : rows) {
index++;
if (nonSimularRows.add(item)) {
indexes.add(index);
}
}
HashSet<int[]> newSet = new HashSet<int[]>();
for (Integer item : indexes) {
newSet.add(matrix[item]);
}
return newSet;
}
Anyway code looks very ugly and I want to get advice how I can refactor code with modern approaches like forEach and Stream API.