比较两个字符串的重复项和字符串位置

时间:2018-10-08 03:21:28

标签: javascript string-comparison

我正在编写一个函数,比较两个始终相同长度的字母数组,以检查两个条件。

  1. array1是否包含与array2相同的值(逐个键)
  2. 在相同的索引位置中是否存在相同的值?

如果array1多次包含相同的字母,但是array2不包含相同的字母,则我的函数会产生一个副作用。

这是我到目前为止的内容:

const compareWords = (array1, array2) => {
    let guess = []

    array1.forEach((letter, i) => {
        let guessMap = { letter }

        // Does the word contain the correct letter
        if (array2.includes(letter)) {
            guessMap.includes = true

            // Is the correct letter in the same position?
            if (array1[i] === array2[i]) {
                guessMap.samePos = true
            } else {
                guessMap.samePos = false
            }
        } else {
            guessMap.includes = false
            guessMap.samePos = false
        }
        guess.push(guessMap)
    })
    console.log(guess)
}
compareWords( ['M', 'O', 'M'], ['M', 'A', 'P'] )

具有当前功能的输入/输出:

compareWords( ['M', 'O', 'M'], ['M', 'A', 'P'] )

[ { letter: 'M', includes: true, samePos: true },
  { letter: 'O', includes: false, samePos: false },
  { letter: 'M', includes: true, samePos: false } ]

所需的示例输入/输出

compareWords( ['M', 'O', 'M'], ['M', 'A', 'P'] )

[ { letter: 'M', includes: true, samePos: true },
  { letter: 'O', includes: false, samePos: false },
  { letter: 'M', includes: false, samePos: false } ]

compareWords( ['M', 'O', 'M'], ['M', 'A', 'M'] )

[ { letter: 'M', includes: true, samePos: true },
  { letter: 'O', includes: false, samePos: false },
  { letter: 'M', includes: true, samePos: true } ]

compareWords( ['M', 'O', 'M'], ['H', 'M', 'M'] )

[ { letter: 'M', includes: true, samePos: false },
  { letter: 'O', includes: false, samePos: false },
  { letter: 'M', includes: true, samePos: true } ]

6 个答案:

答案 0 :(得分:0)

您可以做的是从array2创建一个对象。它的属性将作为array2中的元素,其值作为它们在array2中的次数。之后,您应该遍历array1并查看元素当前元素是否在array2中以及count> 0。如果为true,则必须减少该元素的计数,并且您将知道该元素在array2中。 为了在遍历array1时保持位置,您还必须像在代码中所做的那样遍历array2。

const currentGuess = ['M', 'O', 'M']
const currentWord = ['M', 'A', 'P']
let guess = new Object()
let ans = []

currentWord.forEach((item, index) => {
    if( quess.hasOwnProperty(item) {
        guess[item]++
    }
    else{
        guess[item] = 1
    }
})

for(let index = 0; index < currentGuess.length; index++){
    if(guess.hasOwnProperty(currentGuess[index]) and 
    guess[currentGuess[index]]>0 and 
    currentGuess[index]===currentWord[index]){
        guess[currentGuess[index]]--
        console.log("{ letter: '"+currentGuess[index]+"', includes: true, 
        samePos: true },")        
    }
    else if(currentGuess[index]]>0 and 
    currentGuess[index]!=currentWord[index] ){
        console.log("{ letter: '"+currentGuess[index]+"', includes: true, 
        samePos: false},")
    }
    else{
       console.log("{ letter: '"+currentGuess[index]+"', includes: false, 
        samePos: false},")
    }


}

答案 1 :(得分:0)

尝试一下,这不是一种优雅的方法,但它可能会达到您的预期目的:

const compareWords = () => {
    const currentGuess = ['M', 'O', 'M', 'E', 'P']
    const currentWord = ['M', 'A', 'P', 'E', 'R']
    let guess = [];

    for (let i in currentGuess) {
        const letter = currentGuess[i];
        // Check if this letter was previously stated 
        const previousGuess = guess.find(g => g.letter === letter);
        const guessMap = { letter };
        const currentWordSubset = !!previousGuess ? currentWord.filter((v, i) => i > previousGuess.foundAt) : currentWord;
        if (currentWordSubset.includes(letter)) {
            guessMap.includes = true;
            guessMap.foundAt = currentWord.indexOf(letter);
            if (currentWord[i] === currentGuess[i]) {
                guessMap.samePos = true
            } else {
                guessMap.samePos = false
            }
        } else {
            guessMap.includes = false;
            guessMap.samePos = false;
        }
        guess.push(guessMap);
    }
    console.log(`Comparing: ${currentGuess.join('')} vs ${currentWord.join('')}`);
    guess.forEach(g => { 
        if (!!g.foundAt || g.foundAt === 0) { delete g.foundAt}
        return g; 
    })
    console.log(guess);
}

compareWords();

输出

Comparing: MOMEP vs MAPER
[ { letter: 'M', includes: true, samePos: true },
  { letter: 'O', includes: false, samePos: false },
  { letter: 'M', includes: false, samePos: false },
  { letter: 'E', includes: true, samePos: true },
  { letter: 'P', includes: true, samePos: false } ]

答案 2 :(得分:0)

您可以使用数组映射将其写得更短:

const compareWords = () => {
    const currentGuess = ['M', 'O', 'M'];
    const currentWord = ['M', 'A', 'P'];
    let guess = currentGuess.map((current,index)=>{
      let obj = {};
      obj["letter"] = current;
      obj["includes"] = currentWord.includes(current);
      obj["samePos"] = current === currentWord[index];
      return obj;
    });
    console.log(guess);
}
compareWords();

答案 3 :(得分:0)

您需要再检查一件事。如果array1包含相同的字母不止一次,则可以在第一次检查时将其推入数组,然后将检查数组中是否存在该字母。

const compareWords = () => {
const currentGuess = ['M', 'O', 'M'];
const currentWord = ['M', 'A', 'P'];
let guess = [];
const exist = [];

currentGuess.forEach((letter, i) => {
    let guessMap = { letter };

    // Does the word contain the correct letter and if it is not compared previously
    if (currentWord.includes(letter) && !exist.includes(letter)) {
        guessMap.includes = true;
        exist.push(letter);

        // Is the correct letter in the same position?
        if (currentWord[i] === currentGuess[i]) {
            guessMap.samePos = true;
        } else {
            guessMap.samePos = false;
        }
    } else {
        guessMap.includes = false;
        guessMap.samePos = false;
    }
    guess.push(guessMap);
})
console.log(guess);

}

答案 4 :(得分:0)

我的解决方案使用reduce,例如:

const compareWords = () => {
  const currentGuess = ['M', 'O', 'M']
  const currentWord = ['M', 'A', 'P']
  
  const result = currentGuess.reduce((result, currentGuessCharacter, currentGuessIndex) => {
    const currentWordIndexFound = currentWord.findIndex(currentWordCharacter => currentWordCharacter === currentGuessCharacter);    

    return [
      ...result,
      { 
        letter: currentGuessCharacter, 
        includes: currentWordIndexFound > -1, 
        samePos: currentGuessIndex === currentWordIndexFound 
      }
    ]
  }, []);

  console.log(result);
}

compareWords();

答案 5 :(得分:0)

我使用@protoproto和@ monil-bansal的示例来提出以下解决方案。

const compareWords = (word1, word2) => {
    let wordLetterCount = word2.reduce((result, letter) => {
        result[letter] = (result[letter] || 0) + 1
        return result
    }, {})

    const checkIncludes = (letter) => {
        if (word2.includes(letter) && wordLetterCount[letter] > 0) {
            wordLetterCount[letter]--
            return true
        } else {
            return false
        }
    }

    const guess = word1.map((letter, i) => {
        return {
            letter,
            includes: checkIncludes(letter),
            samePos: letter === word2[i]
        }
    });

    console.log(guess)
}
compareWords( ['M', 'O', 'M'], ['M', 'A', 'P'] )
compareWords( ['M', 'O', 'M'], ['M', 'A', 'M'] )
compareWords( ['M', 'O', 'M'], ['H', 'M', 'M'] )