2017-08-31 168 views
-2

我輸入了char[][]。我需要生成可能的組合,其中每個char數組爲對應位置提供符號。例如:如何生成符號組合?

char[][] symbols = new char[][] { 
      {'M', 'm'}, 
      {'o', '0'}, 
      {'i', 'l', '|', 'e'}, 
      {'s', '$'} 
    }; 

使用此輸入數據應該產生:

Mois 
Moi$ 
Mols 
Mol$ 
MoLs 
... 
m0e$ 

我有麻煩如何在陣列狀態更新從正確排列正確的符號,並建立不是字符串。

+0

尋找「笛卡爾積」 – MBo

回答

3

很澀,但工作液:然後你就可以稱之爲如下打印組合

public static void main(String... args) throws ParseException { 
    char[][] symbols = new char[][] { { 'M', 'm' }, { 'o', '0' }, { 'i', 'l', '|', 'e' }, { 's', '$' } }; 
    String s = "1234"; 
    for (int i = 0; i < symbols[0].length; i++) { 
     s = s.replace(s.charAt(0), symbols[0][i]); 
     for (int j = 0; j < symbols[1].length; j++) { 
      s = s.replace(s.charAt(1), symbols[1][j]); 
      for (int k = 0; k < symbols[2].length; k++) { 
       s = s.replace(s.charAt(2), symbols[2][k]); 
       for (int l = 0; l < symbols[3].length; l++) { 
        s = s.replace(s.charAt(3), symbols[3][l]); 
        System.out.println(s); 
       } 
      } 
     } 
    } 

} 

,你可以看到,這將快速增長取決於你多久字符串將在最後。因此其他解決方案更適合它。我會強烈建議使用@alirabiee答案

3

您可以通過如下定義計算機功能做到這一點:

void compute(String combo, Integer i) { 
    if (i == symbols.length) { 
     System.out.println(combo); 
    } 
    else { 
     for (int j = 0; j < symbols[ i ].length; j++) { 
      compute(combo + symbols[ i ][ j ], i + 1); 
     } 
    } 
} 

請注意,您的符號陣列也需要一流的領域,否則,你需要改變它一下。使用循環

this.compute("", 0);