Абдулах Хамзиќ Абдулах Хамзиќ - 5 months ago 7
HTML Question

Complex string matching in JavaScript

I am working on a game: http://codepen.io/abdulahhamzic/pen/xVMXQa

The game consists of the player guessing a word and they only have five attempts to guess it correctly. If one of the letters in the player's word is in its appropriate place, then it should become green. And if a letter is in the word, but not in the right place where it should be, it should paint red to give the player a hint that the letter is present, but should be placed somewhere else in the word. I used this part of the code to implement that feature:

if (userWord[i].toUpperCase() == word[i]){
document.getElementsByClassName("letters")[input].children[i].style.background = "green";
else if (word.indexOf(userWord[i].toUpperCase()) > -1){
document.getElementsByClassName("letters")[input].children[i].style.background = "red";

The issue is that when the player inputs a word that contains two or more same letters and the correct word contains less of that letter, only the letter that's in the exact place should be green and the other letters should not be red, because that would imply that the letter is there multiple times. For example:

  • if the word is "ABBBB" and the player enters "AAAAC", only the first "A" of "AAAAC" should remain green and the other "A"'s should remain yellow and not become red.

  • if the word is "ABABB" and the player inputs "ACBAA", the first "A" should remain green and only the second "A" should be red, not both of the last "A"'s to specify that there are only two "A"'s in the word. Also, the "B" should be red of course.

  • if the word is "ABABA" and the player types in "AAAAA", then, only the first, the third and the last "A" should be green, but the other "A"'s should remain yellow and not become red.

So, those were some examples. I think you get the idea by now. I really couldn't figure out how to implement this feature correctly.

  1. Place the guessed word and the desired word in a hash table (object) where frequency of letters are counted


    actualWord = { a: 2, b: 3}
    guessedWord = { a: 3, b: 1, c: 1}
  1. After each guess, iterate through both strings simultaneously

  2. If the letter you are on matches, you highlight it green because it is both the right letter and in the right place.

  3. Decrement both values in the hash table (they match and are no longer considered)

    actualWord = { a: 1, b: 3}
    guessedWord = { a: 2, b: 1, c: 1}
  4. If they do not match, check the hash table. If the guessed letter is in the actualWord's hash table, it exists, but it is in the wrong place. Highlight it red. Decrement both by one

    actualWord = { a: 0, b: 3}
    guessedWord = { a: 1, b: 1, c: 1} 
  5. If the lookup works, but the actual word's hash is 0, you know that the user input too many of the same letter, so you'd color it yellow (I think)