TEbogo
TEbogo

Reputation: 229

Compare two string and count letters that are different

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

Answers (4)

Sumit Ramteke
Sumit Ramteke

Reputation: 1496

This is what I would do

Implementation

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

Abito Prakash
Abito Prakash

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

Yosvel Quintero
Yosvel Quintero

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

Vincent
Vincent

Reputation: 4753

In one line:

("ABC"+"DEC").split('').sort().join('').replace(/(.)\1+/g, "").length

Returns

4

Steps of the program:

  1. ("ABC"+"DEC") makes a string with the 2 merged words : ABCDEC

  2. ("ABC"+"DEC").split('').sort().join('') makes the characters sorted in the string: ABCCDE. This will enable us to find duplicates easily with regex

  3. replace(/(.)\1+/g, "") removes all sequences of 2+ characters, then we get ABDE

  4. .length counts the remaining characters, which are the ones with single occurence.

Upvotes: 5

Related Questions