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, the array status is an enum of (IN, OK, NOTIN), so the letter and prop status is the guessed word.

Any ideas on how to modify this code to solve my problem

推荐答案

You have to take the number of occurrences into account. So, process the exact matches first, recording the letters not found so far. For each other occurrence in the guess, remove the letter from the recorded letters, so that you will not match it again. E.g.

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

For large data, you’d use something like a Map<Character,Integer> to record the number of occurrences for each element, but since we have at most five elements here, using an ArrayList is simpler while providing reasonable performance. It’s just important to keep in mind that this approach would not scale to other problems.

Java相关问答推荐

具有额外列的Hibert多对多关系在添加关系时返回NonUniqueHealthExcellent

如何审查Java dtos中的自定义注释字段?

使用Java Streams API比较两个不同的Java集合对象和一个公共属性

Jlink选项&-strie-ative-Commands";的作用是什么?

JavaFX Maven Assembly插件一直打包到错误的JDK版本

如何创建同一类的另一个对象,该对象位于变量中?

JavaFX如何在MeshView中修复多个立方体?

如何使用值中包含与号的查询参数创建一个java.net.URI

如何使用Jackson将XML元素与值和属性一起封装

如何在Java记录中设置BigDecimal类型属性的精度?

无法在Java中处理PayPal支付响应

继续收到错误SQLJDBC EXCEPTION执行";org.springframework.dao.InvalidDataAccessResourceUsageException:&

如何在Spring Boot中创建可以将值传递给配置的&Enable&Quot;注释?

Java.lang.invke.LambdaConversionException:实例方法InvokeVirtual的参数数量不正确

如何在Record Java中使用isRecord()和RecordComponent[]?

如何从命令行编译包中的所有类?

字符串的Gzip压缩在java11和java17中给出了不同的结果

如何从指定某些字段的父对象创建子对象

Keycloak + Spring Boot 角色认证不起作用

为什么 JavaFX TextArea 中的 selectRange() 有时不突出显示所选内容?