본문 바로가기
코테연습

27.Counting Duplicates

by hxunz 2022. 4. 3.

Count the number of Duplicates

Write a function that will return the count of distinct case-insensitive alphabetic characters and numeric digits that occur more than once in the input string. The input string can be assumed to contain only alphabets (both uppercase and lowercase) and numeric digits.

Example

"abcde" -> 0 # no characters repeats more than once
"aabbcde" -> 2 # 'a' and 'b'
"aabBcde" -> 2 # 'a' occurs twice and 'b' twice (`b` and `B`)
"indivisibility" -> 1 # 'i' occurs six times
"Indivisibilities" -> 2 # 'i' occurs seven times and 's' occurs twice
"aA11" -> 2 # 'a' and '1'
"ABBA" -> 2 # 'A' and 'B' each occur twice

 


function duplicateCount(text){
  const arrText = [...text];
  const lowerText = arrText.map(str => str.toLowerCase());
  
  let countNum = lowerText.reduce(function (allNumbers, number) {
    if (number in allNumbers) {
      allNumbers[number]++;
    } else {
      allNumbers[number] = 1;
    }
    return allNumbers;
  }, {});
  
  const result = Object.values(countNum).filter(num => num > 1);
  
  return result.length === 0 ? 0 : result.length;
}

먼저 주어진 typeof가 string인 text를 단어 하나씩 쪼개서 배열로 만들어줬다. (펼침연산자 사용)

-> const arrText = [...text];

 

그 다음에는 대문자들을 소문자로 변경해주었다. (array.toLowerCase() 사용)

-> const lowerText = arrText.map(str => str.toLowerCase());

 

그리고 mdn 문서를 참고해서 reduce를 사용해서 객체 내의 값 인스턴스 개수를 세어주었다.

그래서 알파벳 별로 몇개가 사용되었는지 알 수 있었다. 

->

let countNum = lowerText.reduce(function (allNumbers, number) {
if (number in allNumbers) {
allNumbers[number]++;
} else {
allNumbers[number] = 1;
}
return allNumbers;
}, {});

그렇게 return 된 object에서 values(알파벳 사용 개수)만 따로 뺀 다음에(Object.values() 사용) 각 요소들의 크기가 1 초과인 것들만(중복 사용되었거나 그 이상 사용된 알파벳들) filter()를 사용해서 분리해주었다.

-> const result = Object.values(countNum).filter(num => num > 1);

 

마지막으로 삼항연산자를 사용해서 result의 길이가 0이면(빈 배열이거나 요소가 전부 1인경우에는 result의 길이가 0이다) 0을 리턴하고 그렇지 않은경우에는 result의 길이(여러번 사용된 알파벳이 총 몇개인지)를 리턴해주었다.

-> return result.length === 0 ? 0 : result.length;

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

29.Take a Ten Minutes Walk  (0) 2022.04.04
28.Duplicate Encoder  (0) 2022.04.04
26.Find The Parity Outlier  (0) 2022.04.02
25.Create Phone Number  (0) 2022.04.02
24.Bit Counting  (0) 2022.04.01

댓글