Anagram -- Attempt 1
//Attempt 1
const countChar = (str) => {
let map = new Map();
for (let i of str) {
map.set(i, map.get(i) ? map.get(i) + 1 : 1);
}
return map;
};
const isPermutation = (str1, str2) => {
if (str1.length === str2.length) {
let mappedChar1 = countChar(str1);
//Map(3)Â {'a' => 2, 'n' => 1, 'u' => 1}
let mappedChar2 = countChar(str2);
//Map(3)Â {'u' => 1, 'n' => 1, 'a' => 2}
let output = true;
for (const key of mappedChar1.keys()) {
if (mappedChar2.get(key) !== mappedChar1.get(key)) {
output = false;
}
}
return output;
}
return false;
};
console.log(isPermutation("anua", "unaa"));
Anagram - Attempt 2
//Attempt-->2
const isPermutation = (str1, str2) => {
//convert string to array
let str1Array1 = str1.split("");
let str1Array2 = str2.split("");
let map = new Map();
if (str1.length === str2.length) {
for (let y of str1) {
//dont loop for already looped character...
if (map.get(y)) {
continue;
} else map.set(y, true);
//count of character length in that array1 and array2...
//if count mismatches - return...
let str1CountChar = str1Array1.filter((x) => x === y).length;
let str2CountChar = str1Array2.filter((x) => x === y).length;
if (str1CountChar !== str2CountChar) return false;
}
return true;
}
return false;
};
console.log(isPermutation("pnuragaaga", "garunaaaag")); //false
console.log(isPermutation("anurag", "garuna")); //true
Anagram - attempt 3
//attempt3
const isPermutation = (str1, str2) => {
return str1.split("").sort().join("") === str2.split("").sort().join("");
};
console.log(isPermutation("anurag", "garuna"));
console.log(isPermutation("ppnurag", "garuna"));