如何从字母表中猜出来信?因此,如果第一个猜测是AABB,我需要从字母表字母表中获取A和B,以便在没有字母A和B的情况下进行新的随机猜测。
randomCode.clear();//Clears the random code ArrayList to put a new one in it
Random r = new Random();
String alphabet = "ABCDEF";
StringBuilder result = new StringBuilder(randomCode.size());
if(turn == 0){
guess = "AABB";
}else{
if(blackPin == 0 && whitePin ==0){
for (int c = 0; c < 4; c++) {
if(alphabet.charAt(c) == guess.charAt(c)){
}
randomCode.add(alphabet.charAt(r.nextInt(alphabet.length())));//generate 4 random letters with the letters ABCDEF and put in arrayList
}
for (Character c : randomCode){//Converts Char[] randomCode to a String
result.append(c);
}
guess = result.toString();//Gives the String guess 4 random letters.
答案 0 :(得分:0)
为什么要在可以避免的情况下循环:
String abd = "ABCDEF";
String guess = "AABB";
System.out.println(abd.replaceAll(String.join("|", guess.split("")), ""));
打印:
CDEF
答案 1 :(得分:0)
如果您有ArrayList
,例如:
ArrayList<Character> alphabet = new ArrayList<>(Arrays.asList('A', 'B', 'C', 'D'));
和String
:
String guess = "AABB";
您可以从猜测中的字母中删除字母,如下所示:
for (int i = 0; i < guess.length(); i++)
alphabet.remove(new Character(guess.charAt(i)));
现在,如果打印出字母:
for (int i = 0; i < alphabet.size(); i++)
System.out.print(alphabet.get(i));
输出结果为:"CD"
。
你可以一起使用:
ArrayList<Character> alphabet = new ArrayList<>(Arrays.asList('A', 'B', 'C', 'D'));
Random random = new Random();
String guess = "";
while (true) {
/* init a guess */
guess = "";
for (int j = 0; j < 4; j++)
guess += alphabet.get(random.nextInt(alphabet.size()));
System.out.println("The guess is: " + guess);
/* remove letters */
for (int j = 0; j < guess.length(); j++)
alphabet.remove(new Character(guess.charAt(j)));
/* the alphabet is empty */
if (alphabet.isEmpty()) {
System.out.println("The alphabet is empty");
break;
}
}
答案 2 :(得分:0)
最有效的方法是利用字母的ASCII码是26个连续的整数,并从char转换为int。代码65-68是ABCD。