I have to write a function that takes in two strings and pares 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 paring 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;
}
I have to write a function that takes in two strings and pares 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 paring 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;
}
a1.indexOf(b1[i] < 0)
should be a1.indexOf(b1[i]) < 0
. Also, there's no need to do the .sort()
– freefaller
Commented
Nov 6, 2019 at 9:25
C
in mon, so the difference is ABDE
, which is 4 long.
– Matt Ellen
Commented
Nov 6, 2019 at 9:26
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.
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'))
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
This is what I would do
let makeAnagram = (a,b) => {
let clubStr = ('' + a).concat(b);
let sortedStr = clubStr.trim().split('').sort().join('');
let unmonStr = sortedStr.replace(/(\w)\1+/gi, '');
return unmonStr.length;
};
You can do same in one liner.
Caller :
makeAnagram('ABC', 'DCE')
Ouput :
4