Scramblies
- Complete the function scramble(str1, str2) that returns true.
- If a portion of str1 characters can be rearranged to match str2,
- otherwise returns false.
Note:
- Only lower case letters will be used (a-z).
- No punctuation or digits will be included.
- Performance needs to be considered.
Example:
scramble('rkqodlw', 'world') ==> True
scramble('cedewaraaossoqqyt', 'codewars') ==> True
scramble('katas', 'steak') ==> False
My solution:
function scramble(str1, str2) {
const stringOne = str1.split('');
const stringTwo = str2.split('');
const charCounts = {};
for (let i = 0; i < stringOne.length; i++) {
const char = stringOne[i];
if (charCounts[char]) { // character already seen
charCounts[char]++;
} else { // first time seeing character
charCounts[char] = 1;
}
};
for (let i = 0; i < stringTwo.length; i++) {
const char = stringTwo[i]
if (!charCounts[char]) {
return false;
}
charCounts[char]--;
};
return true;
};
Code Snapshot:
10 JavaScript Games to learn-Totally Cool & Fun πβ¨π₯
π₯
Top comments (2)
You can simply use for..of loop
function scramble(str1,str2){
for(let x of str2){
if(!str1.includes(x)){
return false
}
}
return true;
}
console.log(scramble('rkqodlw', 'world'))
console.log(scramble('cedewaraaossoqqyt', 'codewars'))
console.log(scramble('katas', 'steak'))
Thank you :)