1

我正在尝试以角度从头开始创建自己的 wordle 实现,并且一直试图解决其中一种边缘情况。假设要对以下所有情况进行猜测的单词是“ CLOSE ”。

案例 1 - 两个重复的字母都在错误的位置。

如果我的猜测是“ CHEER ”,则两个“ E ”都在错误的位置,但“ CLOSE ”只有一个“ E ”,因此只有一个应该得到黄色突出显示。我的代码正在根据需要处理这个

情况1

案例 2 - 位置正确的字母先出现,然后是位置错误的相同字母

如果我的猜测是“ COCKS ”,那么第一个“ C ”在正确的位置并且应该得到一个黄色高亮,而“ C ”应该得到一个灰色高亮,因为“ CLOSE ”只有一个“ C ”。我的代码也在处理这个问题

案例2

案例 3 - 位置不正确的字母先出现,然后是正确位置的相同字母

如果我的猜测是“ LEAVE ”,那么第一个“ E ”的位置不正确,但是因为第二个“ E ”的位置正确,而“ CLOSE ”只有一个“ E ”,它应该会得到一个灰色的高光并且第二个' E '应该得到绿色突出显示。这是我要修复的边缘情况

我的实施结果:

案例3

本案的预期结果:

期望的结果

我目前使用的逻辑:

let remainingLettersInWord: string = this.chosenWord;

  for (let i = 0; i < 5; i++) {
    if (this.currentGuess[i] === this.chosenWord[i]) {
      remainingLettersInWord = remainingLettersInWord.replace(this.currentGuess[i], '');
      this.setAttributeStyle(i, COLOR.Green);
    } else if (remainingLettersInWord.includes(this.currentGuess[i])) {
      remainingLettersInWord = remainingLettersInWord.replace(this.currentGuess[i], '');
      this.setAttributeStyle(i, COLOR.Yellow);
    } else {
      this.setAttributeStyle(i, COLOR.Gray);
    }
  }

在这里,selectedWord = "CLOSE",currentGuess = "CHEER" 用于案例 1,"COCKS" 用于案例 2,"LEAVE" 用于案例 3

4

2 回答 2

1

通过计算所需单词的字母的不同方法。

const
    getColors = ([...word], [...input]) => {
        const
            count = {},
            result = Array(5).fill('-'); // only to show the result.

        for (let i = 0; i < input.length; i++) {
            if (word[i] === input[i]) result[i] = 'green';
            else count[word[i]] = (count[word[i]] || 0) + 1;
        }
        for (let i = 0; i < input.length; i++) {
            if (word[i] === input[i] || !count[input[i]]) continue;
            count[input[i]]--;
            result[i] = 'yellow';
        }
        return result;
    };

console.log(...getColors("CLOSE", "CHEER"));
console.log(...getColors("CLOSE", "COCKS"));
console.log(...getColors("CLOSE", "LEAVE"));

于 2022-03-02T17:12:58.140 回答
0

我最终在我的一位高级开发人员的帮助和@Chris G 的评论下解决了这个问题

这是我使用的解决方案:

let remainingLettersInWord: string = this.chosenWord;

  for (let i = 0; i < 5; i++) {
    if (this.currentGuess[i] === this.chosenWord[i]) {
      remainingLettersInWord = remainingLettersInWord.replace(this.currentGuess[i], '');
      this.setAttributeStyle(i, COLOR.Green);
    } else {
      this.setAttributeStyle(i, COLOR.Gray);
    }
  }

  for (let i = 0; i < 5; i++) {
    if (remainingLettersInWord.includes(this.currentGuess[i]) && this.currentGuess[i] !== this.chosenWord[i]) {
      remainingLettersInWord = remainingLettersInWord.replace(this.currentGuess[i], '');
      this.setAttributeStyle(i, COLOR.Yellow);
    }
  }

我将黄色检查的逻辑拆分为一个单独的循环,并在检查黄色列表之前从列表中删除绿色单词。现在符合我所有的边缘情况

于 2022-03-02T16:25:03.553 回答