【问题标题】:Compare/classify equal-length strings in a Wordle-like manner?以类似 Wordle 的方式比较/分类等长字符串?
【发布时间】:2022-06-30 03:47:43
【问题描述】:

我正在制作一个猜词应用程序(例如 Wordle)。
假设我有一个预定义的单词

let predefinedWord = "apple";

我想制作一个函数来与预定义的单词进行比较。

const compare = (word) => {
  // compare the guess with the predefined word apple
}

let myGuess = "alley"
const result = compare(myGuess); // compare apple with alley
// return 
// ["Matched", "Included", "Included", "Included", "Not Matched"]

我怎样才能实现这样的功能?

【问题讨论】:

  • ObjectArrayString 类以及 text formatting 技术是您创建这样一个函数所需的全部内容。你到底卡在哪里了?
  • 请注意,“包含”的匹配项不应重复。 ALLEY 应该为第一个 L 生成“Included”,为第二个 L 生成“Not Matched”。你确定这是你需要的吗?
  • @Sebastian 是对的,还有一个例子,当与apple 进行比较时,用户会提供一个或多个Ps。
  • @Sebastian Simon 我该怎么做这个逻辑?
  • @CCCC 我会通过猜测的字符串两次:第一次列出所有匹配的字母,第二次列出所有包含的字母。每次找到一个字母(匹配或包含)时,从猜测的单词和实际单词中删除该字母。这在使用Array.from 将两个字符串转换为数组然后将索引设置为null 时效果最佳,例如,以保持索引相同。然后最后一次遍历猜测的字符串,但只检查是否在该索引处找到匹配项或是否在该索引处找到包含的字母。

标签: javascript


【解决方案1】:

如果字长和 wordle 一样短,直接的方法效果很好:

let predefinedWord = "apple";
let predefArr = predefinedWord.split('');


const compare = (predef,word) => {
  return word
         .split('')
         .map( (letter,i) => {
           if (predef[i] === letter) return "Matched";
           if (predef.includes(letter)) return "Included";
           return "Not Matched"
         });
  
}

let myGuess = "alley"
const result = compare(predefArr, myGuess); // compare apple with alley
// return 
// ["Matched", "Included", "Included", "Included", "Not Matched"]

console.log(result)

编辑:这回答了原来的问题:

let myGuess = "alley"
const result = compare(myGuess); // compare apple with alley
// return 
// ["Matched", "Included", "Included", "Included", "Not Matched"]

我怎样才能实现这样的功能?

而且它不是游戏wordle的行为

【讨论】:

  • @Arjan 我添加了一个编辑来澄清这一点
【解决方案2】:
const compare = (word) => {
  let result = [];
  for(let i=0;i<word.length;i++){
    if(predefinedWord.includes(word[i])){
      result.push(predefinedWord.indexOf(word[i]) === i?"Matched":"Included")
    }else{
      result.push("Not Matched")
    }
  }
  return result;
}

【讨论】:

  • 虽然这确实符合所要求的,但它仍然不正确。请参阅问题下方的 cmets。
【解决方案3】:

function comparisonhint(secret, guess) {
  try {
    const secretArr = secret.split('');
    const guessArr = guess.split('');
    if (secretArr.length !== guessArr.length) {
      throw 'Secret and Guess must be same length.'
    }
    const hintArr = guessArr.map((letter, i) => {
      return secretArr[i] == letter ? '✅' : secretArr.includes(letter) ? '?' : '❌';
    });
    return hintArr.join('');
  } catch (err) {
    console.error(err);
    return err;
  }
}

const hint = comparisonhint('words', 'guess');

console.log(hint);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-02-04
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 2019-12-18
    • 1970-01-01
    相关资源
    最近更新 更多