昨天去面试碰到的算法题,笛卡尔积,之前都没接触过。
笛卡尔乘积是指在数学中,两个[集合] X和Y的笛卡尓积(Cartesian product),又称[直积],表示为X* × Y,第一个对象是X的成员而第二个对象是Y的所有可能[有序对]的其中一个成员
例如,A={a,b}, B={0,1,2},则
A×B={(a, 0), (a, 1), (a, 2), (b, 0), (b, 1), (b, 2)}
B×A={(0, a), (0, b), (1, a), (1, b), (2, a), (2, b)}
java 代码:
public class Test {
private static String[] aa = { "aa1", "aa2" };
private static String[] bb = { "bb1", "bb2", "bb3" };
private static String[] cc = { "cc1", "cc2", "cc3", "cc4" };
private static String[][] xyz = { aa, bb, cc };
private static int counterIndex = xyz.length - 1; // 相当于进位 从最后一个数组开始 每次每一个数组循环之后 -1 到上一个数组 。
private static int[] counter = { 0, 0, 0 };
public static void main(String[] args) throws Exception {
for (int i = 0; i < aa.length * bb.length * cc.length; i++) {
System.out.print(aa[counter[0]]);
System.out.print("\t");
System.out.print(bb[counter[1]]);
System.out.print("\t");
System.out.print(cc[counter[2]]);
System.out.println();
handle();
}
}
public static void handle() {
counter[counterIndex]++; //每一个数组从头到尾++
if (counter[counterIndex] >= xyz[counterIndex].length) { //如果一个数组循环完了之后 到上一个数组循环
counter[counterIndex] = 0;
counterIndex--;
if (counterIndex >= 0) {
handle();
}
counterIndex = xyz.length - 1;
}
}
}