我正在Codewars: https://www.codewars.com/kata/635fc0497dadea0030cb7936上解决这个问题这是我的代码:
public static void main(String[] args) {
int[][] ms;
ms = new int[][] {{1, 2, 3, 4},
{3, 1, 4, 2},
{4, 3, 2, 1},
{2, 4, 1, 3}};
System.out.println(count_different_matrices(ms));
}
private static final Set<int[]> registeredM = new HashSet<>();
static public int count_different_matrices(int[][] matrices) {
Arrays.stream(matrices).forEach(m -> {
if(unwrapPossibleMatrices(m).stream().noneMatch(registeredM::contains)) {
registeredM.add(m);
}});
registeredM.forEach(e -> System.out.println(Arrays.toString(e)));
return registeredM.size();
}
static private List<int[]> unwrapPossibleMatrices(int[] m) {
return Arrays.asList(new int[][]{
m,
{m[2], m[0], m[3], m[1]},
{m[3], m[2], m[1], m[0]},
{m[1], m[3], m[0], m[2]}
});
}
控制台收到的输出:
[1, 2, 3, 4]
[2, 4, 1, 3]
[4, 3, 2, 1]
[3, 1, 4, 2]
4
我期望只有[1, 2, 3, 4]
的输出,我的思路是contains()
应该调用a.equals(b)
,其中a
和b
在这个例子中是int[]
类型,当它们将通过等号进行比较时-它将检查数组中的长度和元素是否匹配。相反,发生的事情(我认为)是对象的地址被检查-因此,具有相同元素的数组给出不同的结果。我的问题是:如何修改这段代码来检查数组中传递的实际元素?
好的,我已经改变了我的解决方案,正如@Pshemo指出的(谢谢)
public static void main(String[] args) {
int[][] ms;
ms = new int[][] {{1, 2, 3, 4},
{3, 1, 4, 2},
{4, 3, 2, 1},
{2, 4, 1, 3}};
System.out.println(count_different_matrices(ms));
}
private static final Set<Row> registeredM = new HashSet<>();
static public int count_different_matrices(int[][] matrices) {
registeredM.clear();
Arrays.stream(matrices).forEach(m -> {
if(unwrapPossibleMatrices(m).stream().noneMatch(registeredM::contains)) {
registeredM.add(new Row(m));
}});
registeredM.forEach(e -> System.out.println(Arrays.toString(e.row())));
return registeredM.size();
}
private static List<Row> unwrapPossibleMatrices(int[] m) {
return Arrays.asList(
new Row(m),
new Row(new int[]{m[2], m[0], m[3], m[1]}),
new Row(new int[]{m[3], m[2], m[1], m[0]}),
new Row(new int[]{m[1], m[3], m[0], m[2]})
);
}
record Row(int[] row) {
@Override
public int hashCode() {
return Arrays.hashCode(row);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Row row1 = (Row) o;
return Arrays.equals(row, row1.row);
}
}