如果行中的數據是相同的,但是洗牌並不重要,我們可以將數組中的所有數字存儲在單獨的列表中,然後進行比較。
int[][] a1 = { { 1, 2 }, { 3, 4 } };
int[][] a2 = { { 4, 3 }, { 2, 1 } };
//lists to store arrays data
List<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
//lest place data from arrays to lists
for (int[] tmp:a1)
for (int i:tmp)
list1.add(i);
for (int[] tmp:a2)
for (int i:tmp)
list2.add(i);
//now we need to sort lists
Collections.sort(list1);
Collections.sort(list2);
//now we can compare lists on few ways
//1 by Arrays.equals using list.toArray()
System.out.println(Arrays.equals(list1.toArray(), list2.toArray()));
//2 using String representation of List
System.out.println(list1.toString().equals(list2.toString()));
//3 using containsAll from List object
if (list1.containsAll(list2) && list2.containsAll(list1))
System.out.println(true);
else
System.out.println(false);
//and many other probably better ways
如果行也必須包含相同的數字(但可以進行改組等[1,2] [2,1],但不喜歡[1,2] [1,3]),則可以做這樣的事情
// lets say i a1 and a2 are copies or original arrays
int[][] a1 = { { 1, 2 }, { 3, 4 } };
int[][] a2 = { { 4, 3 }, { 2, 1 } };
System.out.println(Arrays.deepToString(a1));// [[1, 2], [3, 4]]
System.out.println(Arrays.deepToString(a2));// [[3, 4], [1, 2]]
// lets sort data in each row
for (int[] tmp : a1)
Arrays.sort(tmp);
for (int[] tmp : a2)
Arrays.sort(tmp);
System.out.println("========");
System.out.println(Arrays.deepToString(a1));// [[1, 2], [3, 4]]
System.out.println(Arrays.deepToString(a2));// [[3, 4], [1, 2]]
// Now I want to order rows by first stored number.
// To do that I will use Array.sort with this Comparator
Comparator<int[]> orderByFirsNumber = new Comparator<int[]>() {
public int compare(int[] o1, int[] o2) {
if (o1[0] > o2[0]) return 1;
if (o1[0] < o2[0]) return -1;
return 0;
}
};
// lets sort rows by its first stored number
Arrays.sort(a1, orderByFirsNumber);
Arrays.sort(a2, orderByFirsNumber);
// i wonder how arrays look
System.out.println("========");
System.out.println(Arrays.deepToString(a1));// [[1, 2], [3, 4]]
System.out.println(Arrays.deepToString(a2));// [[1, 2], [3, 4]]
System.out.println("Arrays.deepEquals(a1, a2)="
+ Arrays.deepEquals(a1, a2));
輸出
[[1, 2], [3, 4]]
[[4, 3], [2, 1]]
========
[[1, 2], [3, 4]]
[[3, 4], [1, 2]]
========
[[1, 2], [3, 4]]
[[1, 2], [3, 4]]
Arrays.deepEquals(a1, a2)=true
查看API,特別是有用的方法的java.util.Arrays類。 –
有多種方法可以做到這一點。您正在尋找效率嗎?因爲我會循環訪問一個數組,並檢查每個數值與其他數值。如果存在,繼續前進。如果沒有,打破循環,並拋出一個錯誤/消息 – n0pe
這不是家庭工作...我試圖做到這一點,但我沒有成功...而我嘗試了API,我沒有找到可以幫助的東西我... – whiteberryapps