2012-03-08 47 views
0

編輯注意:我沒有很清楚。我試圖從一個單一的字符猜測開始,比如0到00到000 ...一直到zzzzzz。基本上,所有可能的迭代從0到zzzzzz。對不起,我不是很清楚!增加一個字符串/字符數組

我目前正在嘗試循環訪問一組字符。該數組包含0-9和a-z(小寫)。誠然,這是作業 - 我是一個無用的編碼器(請參閱前一篇文章),我可以做一些幫助。

我要的是通過字符數組的所有可能的結果進行迭代,並列出結果...

aaa    aba 
aab > through to > aca 
aac    ada 

如果只是基於信我讀過,我可以將它基於base26數字系統,但這包括數字。

到目前爲止,我已設法循環訪問數組,在循環訪問下一個位置之前將答案分配給「猜測」數組。之後,我很難過。

任何建議,作爲最後一次,非常感謝。這項工作基於Brute Force,但如果我的真實目的是非法的,那麼我可以使用大量的工作示例,但事實並非如此。

這是我到目前爲止。

/** 
* 
* @author Aaron 
*/ 
public class Test { 

    /** 
    * @param args the command line arguments 
    */ 
    int current = 0; 
    char[] guess = new char[6]; 

    public static void main(String[] args) { 
     Test test = new Test(); 
     int maxLength = 6; 
     char c = '0'; 

     while (maxLength != 0) { 
      maxLength--; 
      test.iterateAll(c); 
      test.increment(c);    
     } 
    } 

    public void iterateAll(char c) { 
     char[] charset = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 
          'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 
          'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 
          'u', 'v', 'w', 'x', 'y', 'z'}; 
     for (int i = 0; i < charset.length; i++) { 
      //c = charset[i]; 
      guess[current] = charset[i]; 
      System.out.println(guess); 
     } 
    } 

    public void increment(char c) { 
     current++; 
    } 
} 
+0

你的想法使用基地26是好的,事實上,你也有數字只是意味着你應該去基地36代替。 FauxFaux的答案似乎使用了這個事實。 – ARRG 2012-03-08 23:39:49

回答

1

您能使用Integer.toString()嗎?如果是這樣,它願意爲你做大部分工作。以下內容打印aaa,aab,aac等。

final int start = 36*36*10 + (36*10) + 10; 
for (int i = start; i < 36*36*36; ++i) { 
    final String base36 = Integer.toString(i, 36); 
    final String padded = String.format("%3s", base36).replace(' ', '0'); 
    System.out.println(padded); 
} 
+0

我沒有想過基地36,但這是一個很好的答案!你能解釋一下這個例子的數學嗎?爲什麼啓動變量129970?爲什麼我們需要36 * 36 * 36?我希望能夠增加到六個字符,所以我會將它改爲36 * 36 * 36 * 36 * 36 * 36?謝謝! – Rookie 2012-03-09 10:15:46

+0

起始號碼是aaa,'10'表示'a','36'是字母表的大小;在base-'10'中得到一系列'3','333',我們會做(10 * 10 * 3 + 10 * 3 + 3)? – FauxFaux 2012-03-09 13:01:26

0

我會使用StringBuilder作爲「操縱」字符級別的字符串。這裏它剛剛起來,在pos「寄存器」中從左到右帶有值,它們只是索引字符序列。還要注意字符只是一種數字,所以可以在循環中用作文字。

char[] seq = new char[36]; 
int i = 0; 
for (char c = '0'; c <= '9'; c++) { 
    seq[i++] = c; 
} 
for (char c = 'a'; c <= 'z'; c++) { 
    seq[i++] = c; 
} 

int length = 3; 
StringBuilder builder = new StringBuilder(" "); 

int[] pos = new int[length]; 
int total = (int) Math.pow(seq.length, length); 
for (int count = 0; count < total; count++) { 
    for (int x = 0; x < length; x++) { 
     if (pos[x] == seq.length) { 
      pos[x] = 0; 
      if (x + 1 < length) { 
       pos[x + 1]++; 
      } 
     } 
     builder.setCharAt(x, seq[pos[x]]); 
    } 
    pos[0]++; 

    System.out.println(builder.toString()); 
} 
相關問題