본문 바로가기
코테연습

28.Duplicate Encoder

by hxunz 2022. 4. 4.

Description:

The goal of this exercise is to convert a string to a new string where each character in the new string is "(" if that character appears only once in the original string, or ")" if that character appears more than once in the original string. Ignore capitalization when determining if a character is a duplicate.

Examples

"din"      =>  "((("
"recede"   =>  "()()()"
"Success"  =>  ")())())"
"(( @"     =>  "))((" 

function duplicateEncode(word){
  const arrWord = [...word.toLowerCase()];
  
  const newWord = arrWord.reduce(function(accumulator, currentValue, currentIndex, arrWord) {
    const text = arrWord.filter(x => x === currentValue)
    const newText = text.length === 1 ? '(' : ')'
    return accumulator + newText;
  }, '');
  return newWord;
};

우선, 주어진 string을 삼항연산자로 알파벳 하나씩 쪼개고 toLowerCase()를 사용해서 소문자로 바꿔서 arrWord라는 새로운 배열로 만들어줬다.

const arrWord = [...word.toLowerCase()];
 

그리고 reduce를 사용했는데 reduce 안에서 text를 따로 선언해줬다.

text는 arrWord의 요소들을 비교해주는 역할이다.

filter()를 사용해서 arrWord에 있는 요소와 currentValue와 같은 모든 요소를 모아 새로운 배열로 반환한다.

여기서 currentValue는 arrWord의 요소 하나하나이다.

예를 들어서 arrWord = ['r', 'e', 'c', 'e', 'd', 'e']에서 순서대로 비교해주는거다. 'r'은 중복되는 요소가 없으니 ['r']반환. 'e'는 중복 되는 요소가 뒤에 더 나오기 때문에 ['e', 'e', 'e'] 반환. 'c'도 중복 요소가 없으니 ['c']반환 ... 

const text = arrWord.filter(x => x === currentValue)
 

이렇게 순서대로 반환된 배열을 이용해서 알파벳이 한번만 사용되었다면 배열의 길이는 1이기 때문에 '('을 반환하고 그렇지 않은 경우에는 ')'을 반환했다. 

const newText = text.length === 1 ? '(' : ')'
 

이렇게 누적된 값이랑 새롭게 생성되는 newText 값이랑 더한 값을 리턴해주는 reducer 함수가 완성되었다.

const newWord = arrWord.reduce(function(accumulator, currentValue, currentIndex, arrWord) {
const text = arrWord.filter(x => x === currentValue)
const newText = text.length === 1 ? '(' : ')'
return accumulator + newText;
}, '');
 

이 함수를 리턴해주면서 코드를 완성시켰다.

 

'코테연습' 카테고리의 다른 글

30.Persistent Bugger.  (0) 2022.04.04
29.Take a Ten Minutes Walk  (0) 2022.04.04
27.Counting Duplicates  (0) 2022.04.03
26.Find The Parity Outlier  (0) 2022.04.02
25.Create Phone Number  (0) 2022.04.02

댓글