Java无限期地生成交替字符序列

时间:2013-08-01 22:33:15

标签: java string recursion generator

有人可以帮我解决这个问题吗?我试图递归地做这件事,我真的只是头疼。我想在需要时生成一个字符串形式的字符串。实施例

a A b B ... z Z aa aA Aa AA bb bB Bb BB ...

我正在尝试这个

static int count;//a = 97, z = 122...A = 65, Z = 90
static int length = 1;
static boolean upper;

public static void main(String args[]){
    for (int i = 0; i < 10; i++){
        System.out.println(nextString(length));
    }
}

static String nextString(int len){
    char ch = (char) ((len == length ? count++ : count) / 26 + 97);
    if (upper)
        ch -= 32;
    upper = !upper;
    String s0 = String.valueOf(ch);
    if (len != 1)
        s0 = s0.concat(nextString(len - 1));
    return s0;
}

1 个答案:

答案 0 :(得分:2)

我不确定,如果我理解了这个问题,但这里有一段代码,应该生成所需的模式。

public class CharPatternGenerator {

private int length; //length of current "word"
private char letter;//letter used in current "word"
private int number; //number converted to binary and replaced with letters
                    //for example: 5 in binary is 101, in letters: AaA

public CharPatternGenerator() {
    this.length = 1;    
    this.letter = 'a';  
    this.number = 0;    
}

public String nextString(int len){
    StringBuilder result = new StringBuilder();

    for (int i = 0; i < len; i++)
        result.append(nextWord()).append(' ');

    return result.substring(0, result.length() - 1);

}

private String nextWord() {
    StringBuilder word = new StringBuilder();
    int numberCopy = number;

    /*following loop converts number to binary representation
     * with all 1s replaced with capital case 
     * and 0s - with lower case 
     */
    for (int i = 0; i < length; i++) {
        if (numberCopy % 2 == 0)
            word.append(letter);
        else
            word.append((char) (letter - 32));
        numberCopy /= 2;
    }
    String result = word.reverse().toString();

    number++;
    if (number >= Math.pow(2, length)) {
        number = 0;
        letter++;
        if (letter > 'z') {
            letter = 'a';
            length++;
        }
    }

    return result;

}

/*
 * example of use
 */
public static void main(String[] args) {
    CharPatternGenerator generator = new CharPatternGenerator();
    System.out.println(generator.nextString(100));
    System.out.println(generator.nextString(100));
}
}