Question:给出任意一个二维数组,要求输出数组元素的所有排列组合
例如:
String[][] array = {{"a", "b", "c"}, {"d", "e", "f", "g"}, {"h", "i"}};
**输出**:
adh,aeh,afh,agh,adi,aei,afi,agi
bdh,beh,bfh,bgh,bdi,bei,bfi,bgi
cdh,ceh,cfh,cgh,cdi,cei,cfi,cgi
二维数组矩阵
/**
* @param array 目标数组
* @return 矩阵结果
* @description: 根据给定二维数组,输出排列组合矩阵
*/
public String[][] generateMatrix(String[][] array) {
ArrayList<Integer> lengthArr = new ArrayList<>();
ArrayList<Integer> productArr = new ArrayList<>();
int length = 1;
for (int i = 0; i < array.length; i++) {
int len = array[i].length;
lengthArr.add(len);
int product = i == 0 ? 1 : array[i - 1].length * productArr.get(i - 1);
productArr.add(product);
length *= len;
}
String[][] result = new String[array.length][length / array.length];
for (int i = 0; i < length; i++) {
StringBuilder item = new StringBuilder();
for (int j = 0; j < array.length; j++) {
item.append(array[j][(int) (Math.floor(i / productArr.get(j)) % lengthArr.get(j))]);
}
int index1 = i % array.length;
int index2 = i / array.length;
result[index1][index2] = item.toString();
}
return result;
}
二维数组集合
/**
* @param array 目标数组
* @return 排列组合结果
* @description: 根据给定二维数组,输出排列组合结果
*/
public ArrayList<String> generateList(String[][] array) {
ArrayList<Integer> lengthArr = new ArrayList<>();
ArrayList<Integer> productArr = new ArrayList<>();
ArrayList<String> result = new ArrayList<>();
int length = 1;
for (int i = 0; i < array.length; i++) {
int len = array[i].length;
lengthArr.add(len);
int product = i == 0 ? 1 : array[i - 1].length * productArr.get(i - 1);
productArr.add(product);
length *= len;
}
for (int i = 0; i < length; i++) {
StringBuilder item = new StringBuilder();
for (int j = 0; j < array.length; j++) {
item.append(array[j][(int) (Math.floor(i / productArr.get(j)) % lengthArr.get(j))]);
}
result.add(item.toString());
}
return result;
}
@Test
public void testJava() {
String[] row1 = new String[]{"a", "b", "c"};
String[] row2 = new String[]{"d", "e", "f", "g"};
String[] row3 = new String[]{"h", "i"};
String[][] array = {row1, row2, row3};
//获取矩阵结果
String[][] matrix = generateMatrix(array);
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + ",");
}
System.out.println();
}
System.out.println("**********************************************************");
//获取集合
ArrayList<String> list = generateList(array);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
adh,aeh,afh,agh,adi,aei,afi,agi,
bdh,beh,bfh,bgh,bdi,bei,bfi,bgi,
cdh,ceh,cfh,cgh,cdi,cei,cfi,cgi,
**********************************************************
adh
bdh
cdh
aeh
beh
ceh
afh
bfh
cfh
agh
bgh
cgh
adi
bdi
cdi
aei
bei
cei
afi
bfi
cfi
agi
bgi
cgi
如果对你有帮助,请点击左下角一键三连 /理直气壮.jpg