https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1
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:
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
설명:
중복된 항목 수 계산
입력 문자열에서 한번 이상 나타나는 대소문자를 구분하지 않는 알파벳 문자들의 수와 숫자의 수를 반환하는 함수를 작성하세요. 입력 문자열은 알파벳(대문자와 소문자 모두)과 숫자만 포함한다고 가정할 수 있습니다.
예시
"abcde" -> 0 # 어떤 단어도 한번 이상 반복되지 않습니다.
"aabbcde" -> 2 # 'a'와 'b'.
"aabBcde" -> 2 # 'a'가 두 번, 'b'가 두 번 나타난다(`b`와 `B`).
"indivisibility" -> 1 # 'i'가 6번 나타난다.
"Indivisibilities" -> 2 # 'i'가 7번, 's'가 두 번 나타난다.
"aA11" -> 2 # 'a'와 '1'.
"ABBA" -> 2 # 'A'와 'B'가 각각 두 번 나타난다.
풀이
map을 이용해서 풀었다. 조건을 보면 대소문자를 구분하지 않으므로 문자열을 소문자로 만든다. 그리고 반복문으로 배열의 요소를 하나하나 살피면서 그 문자가 map에 있는지 확인하고 존재한다면 기존에 가지고 있던 값에서 하나 늘려주고 존재하지 않는다면 새로 추가해주었다. 그리고 값이 1보다 큰 요소들을 filter로 걸러서 배열을 만들고 그 배열의 길이를 반환했다.
코드
function duplicateCount(text){
if(text === '') return 0;
text = text.toLowerCase();
let map = new Map();
for(let i = 0; i < text.length; i++){
if(map.has(text[i])){
map.set(text[i], map.get(text[i]) + 1);
} else{
map.set(text[i], 1);
}
}
let dupe = [...map.entries()].filter(el => el[1] > 1);
return dupe.length
}
참고
https://ko.javascript.info/map-set
맵과 셋
ko.javascript.info
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Spread_syntax
전개 구문 - JavaScript | MDN
전개 구문을 사용하면 배열이나 문자열과 같이 반복 가능한 문자를 0개 이상의 인수 (함수로 호출할 경우) 또는 요소 (배열 리터럴의 경우)로 확장하여, 0개 이상의 키-값의 쌍으로 객체로 확장시
developer.mozilla.org
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Array.prototype.filter() - JavaScript | MDN
filter() 메서드는 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환합니다.
developer.mozilla.org
'알고리즘 > Codewars' 카테고리의 다른 글
[Codewars] Duplicate Encoder (6 kyu) / JavaScript (0) | 2022.11.21 |
---|---|
[Codewars] Exes and Ohs (7 kyu) / JavaScript (0) | 2022.11.19 |
[Codewars] Grasshopper - Basic Function Fixer (8 kyu) / JavaScript (0) | 2022.11.17 |
[Codewars] Function 1 - hello world (8 kyu) / JavaScript (0) | 2022.11.16 |
[Codewars] Find The Parity Outlier (6 kyu) / JavaScript (0) | 2022.11.15 |
댓글