In my algorithm to compare the secret word with the guessed word, I need to manage the duplicated letters. For example,
if the secret word is newly and the guessed word is newer, the output of this should be "GGGWW" (G = green(Correct Place), W = White(The Letter isn't in the secret word)),
but instead my algorithm down below outputs "GGGYW" (Y = Yellow(Letter is in the word but not the right place)).

        for (int i = 0; i < 5; i++) {
            if (secret.charAt(i) == prop.charAt(i)) {
                status[i] = LetterStatus.IN;
            } else if (secret.contains(Character.toString(prop.charAt(i)))) {
                status[i] = LetterStatus.OK;
            } else {
                status[i] = LetterStatus.NOTIN;
            }
        }
        return status;

secret=secretword,数组状态是(IN, OK, NOTIN)的枚举,因此字母和props 状态是猜测的单词.

关于如何修改这个代码来解决我的问题有什么 idea 吗

推荐答案

你必须考虑到发生的次数.因此,首先处理精确匹配,记录到目前为止尚未找到的字母.对于猜测中的每一次出现,请从记录的字母中删除该字母,以便不再匹配它.例如.

ArrayList<Character> missing = new ArrayList<>();
for(int i = 0; i < 5; i++) {
    if(secret.charAt(i) == prop.charAt(i)) {
        status[i] = LetterStatus.IN;
    }
    else missing.add(secret.charAt(i));
}
if(!missing.isEmpty()) {
  for(int i = 0; i < 5; i++) {
      if(secret.charAt(i) != prop.charAt(i)) {
        Object ch = prop.charAt(i); // ensure to use remove(Object) not remove(int)
        status[i] = missing.remove(ch)? LetterStatus.OK: LetterStatus.NOTIN;
      }
  }
}

对于 Big Data ,您可以使用Map<Character,Integer>之类的数字来记录每个元素的出现次数,但由于我们这里最多有五个元素,因此使用ArrayList在提供合理性能的同时更简单.重要的是要记住,这种方法不会扩展到其他问题.

Java相关问答推荐

将linkedHashMap扩展到Java中的POJO类

Cucumber TestNG Assert失败,出现java. lang. Numbercycle异常

Java中后期绑定的替代概念

无法处理批处理侦听器中的反序列化异常

在运行MVN测试时,为什么构建失败,并显示了java.lang.ClassNotFoundException:java.net.http.HttpResponse?

使用REST客户端和对象映射器从字符串反序列化Json

Jakarta CDI强制bean构造/注册遗留事件侦听器

Com.google.firebase.database.DatabaseException:无法将类型为java.lang.Boolean的值转换为字符串.这是关于什么的?

如何集成语义发布和BitBucket(Java项目)

使用正则表达式从字符串中提取多个值

Java页面筛选器问题

舰队运行配置Maven版本

为什么在下面的Java泛型方法中没有类型限制?

Quarkus:运行时出现EnumConstantNotPresentException

为什么这种递归会有这样的行为?

将BlockingQueue+守护程序线程替换为执行器

为什么创建Java动态代理需要接口参数

";home/runner/work/中没有文件...匹配到[**/pom.xml];Maven项目的构建过程中出现错误

如何在JSP中从select中获取值并将其放入另一个select

如何使用java区分以下结果