實現邏輯: 1、接受一個2維數組,按一維數組的長度進行排序 2、一維數組中長度最大的2個數組進行全量匹配,後續的數組根據匹配次數均勻匹配 3、匹配完成後,按之前傳入的順序 重新排序 匹配好的數組 public Object[][] Orthogonal(Object[][] data) { List<JSONArray> newData = new LinkedList<>(); ArrayList<ArrayList<JSONObject>> arrayLists = new ArrayList<>(); //將二維數組轉化爲鏈表 並加入step int num=0; for (Object[] datum : data) { JSONArray jsonArray = new JSONArray(); for (int j = 0, size1 = datum.length; j < size1; j++) { jsonArray.put(j, new JSONObject() .put("value", datum[j]) .put("num", num) .put("step", 0)); } num++; newData.add(jsonArray); }
if (newData.size() < 2) throw new RuntimeException("二維數組長度必須>=2"); //將linkedList按jsonarray 長度排序 for (int i = 0, size = newData.size() - 1; i < size; i++) { for (int j = i + 1; j <= size; j++) { JSONArray jsonArray = newData.get(i); JSONArray jsonArray1 = newData.get(j); if (jsonArray.length() < jsonArray1.length()) { newData.set(i, jsonArray1); newData.set(j, jsonArray); } } } JSONArray jsonArray = newData.get(0); JSONArray jsonArray1 = newData.get(1); newData.remove(0); newData.remove(0); for (int i = 0, size = jsonArray.length(); i < size; i++) { for (int k = 0, s = jsonArray1.length(); k < s; k++) { ArrayList<JSONObject> arrayList = new ArrayList<>(); arrayList.add(jsonArray.optJSONObject(i)); arrayList.add(minValue(jsonArray1)); if (!newData.isEmpty()) newData.forEach(array -> arrayList.add(minValue(array))); arrayLists.add(arrayList); } } Object[][] objects=new Object[arrayLists.size()][arrayLists.get(0).size()]; for (int i=0,size=arrayLists.size();i<size;i++){ JSONArray arr=new JSONArray(arrayLists.get(i)); //按最開始的數組順序組合二維數組 for (int k=0,sizes=arr.length();k<sizes;k++){ objects[i][k]=new GetJsonValue().getValue(new GetJsonValue() .getJSONObjectOfKV(arr.toString(),"num",k+""),"value"); } } return objects; } private JSONObject minValue(JSONArray jsonArray) { for (int i = 1, size = jsonArray.length(); i < size; i++) { JSONObject jsonObject = jsonArray.optJSONObject(0); JSONObject jsonObject1 = jsonArray.getJSONObject(i); if (jsonObject.getInt("step") >= jsonObject1.getInt("step")) { jsonArray.put(0, jsonObject1); jsonArray.put(i, jsonObject); } } return jsonArray.getJSONObject(0); }