Reputation: 229
I have to write a function that takes in two strings and compares them then returns the number of letters in the strings that are different. For example "ABC" and "DEC" should return 4. My function always turns up one short because of how I am comparing them. I've looked but can't seem to find a fix.
I have tried looping through the string without splitting and ended up with the same problem.
function makeAnagram(a, b) {
let result = 0;
let a1 = a.split("").sort();
let b1 = b.split("").sort();
for(let i = 0; i < b1.length; i++){
if(a1.indexOf(b1[i] < 0)){
result += 1;
}
}
return result;
}
Upvotes: 2
Views: 1769
Reputation: 1496
This is what I would do
let makeAnagram = (a,b) => {
let clubStr = ('' + a).concat(b);
let sortedStr = clubStr.trim().split('').sort().join('');
let uncommonStr = sortedStr.replace(/(\w)\1+/gi, '');
return uncommonStr.length;
};
You can do same in one liner.
Caller :
makeAnagram('ABC', 'DCE')
Ouput :
4
Upvotes: 1
Reputation: 4770
An ES6 way to do the same
const makeAnagram = (a, b) => new Set(a + b).size - new Set([...a].filter(x => b.includes(x))).size;
console.log(makeAnagram('ABC', 'DEC')); // prints 4
Upvotes: 2
Reputation: 19070
You can do:
Edited as suggestion by @freefaller
const makeAnagram = (a, b) => {
const arr1 = a.split('')
const arr2 = b.split('')
const diff1 = arr1.filter(letter => !arr2.includes(letter))
const diff2 = arr2.filter(letter => !arr1.includes(letter))
return diff1.length + diff2.length
}
console.log(makeAnagram('ABC', 'DEC'))
Upvotes: 3
Reputation: 4753
In one line:
("ABC"+"DEC").split('').sort().join('').replace(/(.)\1+/g, "").length
Returns
4
Steps of the program:
("ABC"+"DEC")
makes a string with the 2 merged words : ABCDEC
("ABC"+"DEC").split('').sort().join('')
makes the characters sorted in the string: ABCCDE
. This will enable us to find duplicates easily with regex
replace(/(.)\1+/g, "")
removes all sequences of 2+ characters, then we get ABDE
.length
counts the remaining characters, which are the ones with single occurence.
Upvotes: 5