anagrams.js

Codewars 알고리즘 풀이


Problem

  • What is an anagram? Well, two words are anagrams of each other if they both contain the same letters.
    • 두 단어가 같은 글자를 포함한다면, 두 단어는 서로의 anagram이다.
  • Write a function that will find all the anagrams of a word from a list.
    • 단어의 모든 anagram을 찾는 함수를 작성한다.
  • 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.
    • anagram이 없는 경우 빈 배열을 반환한다.



Solution 01

function anagrams(word, words) {
  word = word.split('').sort().join('');
  let result = [];
  
  for (let i = 0; i < words.length; i++) {
    if (words[i].split('').sort().join('') === word) {
      result.push(words[i]);
    }
  }
  return result;
}

anagrams('code', ['one', 'two', 'three', 'four']);         // []
anagrams('code', ['deco', 'door', 'eacd', 'code']);        // ['deco', 'code']
anagrams('racer', ['carer', 'crazer', 'caers', 'racer']);  // ['carer', 'racer']


Solution 02

function anagrams(word, words) {
  word = word.split('').sort().join('');
  return words.filter(i => word === i.split('').sort().join(''));
}

anagrams('code', ['one', 'two', 'three', 'four']);         // []
anagrams('code', ['deco', 'door', 'eacd', 'code']);        // ['deco', 'code']
anagrams('racer', ['carer', 'crazer', 'caers', 'racer']);  // ['carer', 'racer']


Solution 03

function anagrams(word, words) {
  return words.filter(i => '' + [...i].sort() === '' + [...word].sort());
}

anagrams('code', ['one', 'two', 'three', 'four']);         // []
anagrams('code', ['deco', 'door', 'eacd', 'code']);        // ['deco', 'code']
anagrams('racer', ['carer', 'crazer', 'caers', 'racer']);  // ['carer', 'racer']