I’m working on a command for my Discord bot that allows for a game to be played, in which the goal is to post words that either change one letter in the previous word, or add a letter. I’m using this function:
function checkDifferentString(str1, str2) { let diff = 0; if (str1 === str2) return true; let lengthDiff = Math.abs(str1.length - str2.length) if (lengthDiff > 1) return false; for (let i=0; (i<str1.length || i < str2.length);i++) { if (diff > 1) return false; if (str1.charAt(i) !== str2.charAt(i)) diff++ } if (diff <= 1) return true else return false; }
and it works fine if you change a letter, or add a letter to the end of the word (e.g. mat->math). But if you add a letter in the word (e.g. mat->malt), it says that the word doesn’t follow the rules, even though it does. How can I change the function so it also catches for added letters inside the words?
Advertisement
Answer
I think this is more easier to understand.
function isChanged(prev, curr) { return (prev.length + 1 === curr.length && curr.slice(0, prev.length) === prev) || (prev.length === curr.length && Array.from(prev).filter((ch, idx) => ch != curr[idx]).length === 1) }
The first condition is true when add one character. The second conditions is true when there is only one different character.
- Updated (I did misread your question)
To check change one letter, use longest common sequence(https://en.wikipedia.org/wiki/Longest_common_subsequence_problem). If two string has same length N and the length of longest common sequence is N-1, it means one letter is changed. If two string has length N and N+1, and the length of longest common sequesnce is N, it means one letter is added.
function lengtOfLCS(s1, s2) { // LCS algorithm.. return result } function isChanged(prev, curr) { return (prev.length === curr.length && lengtOfLCS(prev, curr) === prev.length - 1) || (prev.length+1 === curr.length && LCSlengtOfLCSprev, curr) === prev.length) }