實現電商的分類屬性排序,利用笛卡爾積實現

(1)循環內,每次只有一列向下移一個單元格,就是CounterIndex指向的那列。 java

(2)若是該列到尾部了,則這列index重置爲0,而CounterIndex則指向前一列,至關於進位,把前列的index加1。 
(3)最後,由生成的行數來控制退出循環。 spa

   貼代碼code

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;  
    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;  
        }  
    }  
  
}

輸出共2*3*4=24行: 
aa1 bb1 cc1 
aa1 bb1 cc2 
aa1 bb1 cc3 
aa1 bb1 cc4 
aa1 bb2 cc1 
aa1 bb2 cc2 
aa1 bb2 cc3 
aa1 bb2 cc4 
aa1 bb3 cc1 
aa1 bb3 cc2 
aa1 bb3 cc3 
aa1 bb3 cc4 
aa2 bb1 cc1 
aa2 bb1 cc2 
aa2 bb1 cc3 
aa2 bb1 cc4 
aa2 bb2 cc1 
aa2 bb2 cc2 
aa2 bb2 cc3 
aa2 bb2 cc4 
aa2 bb3 cc1 
aa2 bb3 cc2 
aa2 bb3 cc3 
aa2 bb3 cc4io

相關文章
相關標籤/搜索