-
[알고리즘/자바스크립트] 아나그램 모두 찾기 (Where my anagrams at?)Algorithm 2019. 8. 4. 22:22
-해당 문제는 codewars사이트의 level5 문제입니다. (1~8단계 중 8단계가 가장 쉬운 레벨)-
Where my anagrams at?
What is an anagram? Well, two words are anagrams of each other if they both contain the same letters. For
example:
'abba' & 'baab' == true 'abba' & 'bbaa' == true 'abba' & 'abbba' == false 'abba' & 'abca' == false
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']) => []
예전에 푼 아나그램 문제와 비슷한데 이번에는 배열에 들어있는 단어들 중 아나그램인 단어를 모두 찾아서 배열로 리턴하는 문제이다.
저번에 푼 문제:
https://im-developer.tistory.com/131
[알고리즘/자바스크립트] 아나그램 판별하기 (is Anagram)
문제: Modify the String prototype to add a new method `isAnagram`. `isAnagram` takes a single string argument. It returns true if that string is an anagram of the string it was called on, and false..
im-developer.tistory.com
function anagrams (word, words) { const sortWord = word => word.split('').sort().join(''); const sortedWord = sortWord(word); return words.filter(anagram => sortedWord === sortWord(anagram)); }
풀이는 매우 간단하다.
문자열을 split('')으로 쪼개서 배열로 만들고 sort() 메소드로 정렬한 후 join('')을 한 후,
문자열끼리 === 으로 비교하여 true이면 아나그램이고 false이면 아나그램이 아닌 것으로 판별한다.
filter() 메소드를 사용하면 조건이 true가 되는 요소만 모아서 배열로 리턴해주기 때문에
위 문제에 사용하면 편리하다.
반응형'Algorithm' 카테고리의 다른 글
[알고리즘/자바스크립트] 문자열 카운터 (String incrementer) (609) 2019.08.04 [알고리즘/자바스크립트] Pig Latin 게임 (Simple Pig Latin) (609) 2019.08.04 [알고리즘/자바스크립트] 반복되지 않는 첫 알파벳 찾기 (First non-repeating character) (609) 2019.08.04 [알고리즘/자바스크립트] 알파벳 스크램블 (Scramblies) (484) 2019.08.03 [알고리즘/자바스크립트] 한 자리수가 될 때까지 곱하기 (Persistent Bugger) (609) 2019.08.03 COMMENT