I'm creating a kid's learning tool that has a form which matches 4 letters to a word.
I want to count the number of character matches in a word. But it counts duplicates of letters as 2 instead of 1. For example if the word is "loot", and the user submits "flop", the matching letters are 3 instead of 2, because it's counting "o" twice. How do I fix this? Many thanks
function countMatching(str1, str2) {
var c = 0;
for (var i = 0; i < str1.length; i ) {
if (str2.includes(str1[i]))
c = 1;
}
matchingLetters = c;
}
CodePudding user response:
I made an alternative version of @cmgchess' answer, which creates an array of the actual solution of letters to still guess, and removes each letter as it is encountered in the entered solution.
let matchingLetters;
function countMatching(str1, str2) {
var c = 0;
str1Arr = str1.split('');
for (var i = 0; i < str2.length; i ) {
if (str1Arr.includes(str2[i])) {
c = 1;
str1Arr.splice(str1Arr.indexOf(str2[i]), 1);
}
}
matchingLetters = c;
}
countMatching('loot', 'boot')
console.log(matchingLetters)
CodePudding user response:
A possible approach using Sets.
I converted the string into a set and back to an array
so if str1
is loot
then str1Set
will be ['l','o','t']
. The rest is the same
let matchingLetters;
function countMatching(str1, str2) {
var c = 0;
str1Set = [...new Set([...str1])]
str2Set = [...new Set([...str2])]
for (var i = 0; i < str1Set.length; i ) {
if (str2Set.includes(str1Set[i]))
c = 1;
}
matchingLetters = c;
}
countMatching('loot', 'flop')
console.log(matchingLetters)
CodePudding user response:
function countMatching(str1, str2) {
var c = [];
for (var i = 0; i < str1.length; i ) {
if (str2.includes(str1[i]))
if (!c.includes(str1[i])) c.push(str1[i])
}
matchingLetters = c.length;
}
I'm writing on a tab, so there might be mistakes
What I did is that I made c to be a list that contains each character shared between the two strings. And a new character is pushed into c only if the character doesn't exist in it, hence making it a list of unique characters.
Then you can get the length of the list or you can even use the list for other purposes