gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 06:51:14 25 4
gpt4 key购买 nike

有人可以帮我实现这个目标吗?我正在尝试递归地执行此操作,但我真的很头疼。我想在需要时生成一个模式形式的字符串。例如。

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

最佳答案

我不确定我是否理解这个问题,但这是一段代码,应该生成所需的模式。

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

关于Java 无限期地生成交替字符序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18005779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com