본문 바로가기
알고리즘/Codewars

[Codewars] Duplicate Encoder (6 kyu) / JavaScript

by fluss 2022. 11. 21.

https://www.codewars.com/kata/54b42f9314d9229fd6000d9c

 

Codewars - Achieve mastery through coding practice and developer mentorship

A coding practice website for all programming levels – Join a community of over 3 million developers and improve your coding skills in over 55 programming languages!

www.codewars.com

 

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"  =>  ")())())"
"(( @"     =>  "))((" 

 

Notes

Assertion messages may be unclear about what they display in some languages. If you read "...It Should encode XXX", the "XXX" is the expected result, not the input!

 


설명:

이 연습의 목표는 문자열을 새 문자열로 변환하는 것입니다. 새로운 문자열의 각 문자는 원래 문자열에서 나타날 경우 "("이고, 원래 문자열에서 두 번 이상 나타나는 경우 ")"입니다. 문자가 중복인지 확인할 때 대문자는 무시하세요.

 

예시

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

 

참고

어설션 메시지는 일부 언어에서는 명확히 표시되지 않을 수 있습니다. 만약 당신이 "... It Should encode XXX"를 읽는다면 "XXX"는 입력이 아니라 예상 결과입니다!

 

풀이

중첩 반복문을 사용해 단어가 문장에서 몇 번 나타나는지 세고 그 수가 1보다 크면 ')'을 그렇지 않다면 '('를 배열에 저장하고 그 배열을 출력했다.

 

코드

function duplicateEncode(word){
  word = word.toLowerCase().split('');
  const len = word.length;
  let result = ''
  for(let i = 0; i < len; i++){
    let count = 0
    for(let j = 0; j < len; j++){
      if(word[i] === word[j]) count++;
    }
    if(count > 1) result += ')';
    else result += '(';
  }
  return result;
}

댓글