samedi 28 mars 2020

Test word against array for anagrams - Javascript

So far.. I have this:

function anagrams(word, words) {
  for(let i = 0; i <= words.length; i++){
  const aCharMap = buildCharMap(word);
  const bCharMap = buildCharMap(words[i]);

  if(Object.keys(aCharMap).length !== Object.keys(bCharMap).length) {
    words.pop(words[i])
  }
  for (let char in aCharMap) {
    if (aCharMap[char] !== bCharMap[char]) {
    words.pop(words[i]);
    }
  }
  console.log(word);
  console.log(words);
  }
}

  function buildCharMap(str) {
  const charMap = {};
  for (let char of str.replace(/[^\w]/g, '').toLowerCase()) {
  charMap[char] = charMap[char] + 1 || 1;
  }
  return charMap;
}

The question at hand is obvious if you read through the code but here it is

Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none. For example:

anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']

anagrams('racer', ['crazer', 'carer', 'racar', 'caers', 'racer']) => ['carer', 'racer']

anagrams('laser', ['lazing', 'lazy', 'lacer']) => []

Aucun commentaire:

Enregistrer un commentaire