[Codewars/JS] Count the number of Duplicates
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
<code>
function duplicateCount(text) {
let count = 0;
const arr = text.toLowerCase().split(""); //모두 소문자로 바꿔주기,한단어씩 자르기
const uniquArr = [];
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 1; j < arr.length - 1; j++) {
if (arr[i] === arr[j + i]) { //for문을 돌면서 arr[i]랑 arr[i+j]가 같은지 비교하기
count++; //만약 같으면 count 증가 시키기
uniquArr.push(arr[i]); //같은 값을 uniquArr에 넣기
break;
}
}
}
const set = new Set(uniquArr); //넣으면 같은 값들만 들어 있는데 이것을 중복 제거 시키기
return set.size; //중복 제거 시킨 사이즈를 반환
}
duplicateCount("Indivisibility");
힘들게 코드를 하고 다른 사람의 코드를 보니 정말 깔끔하게 코드를 짤 짰다... 남들의 코드를 보면서 비교해보는것이 실력이 늘것 같아서 이참에 비교해 보기로 했다!
<other code>
function duplicateCount(text){
return (text.toLowerCase().split('').sort().join('').match(/([^])\1+/g) || []).length;
}
//문자를 소문자로 변환하고, 배열에 넣고, 정렬 후 , 배열에 있는 문자를 다시 join으로 합쳤다.
//그리고 정규식을 사용하여 중복이 되는 문자만 뽑아 그 값의 legnth를 구한 방법이다.
이 방법이 가장 짧고 깔끔했는데 아쉬운 점은 내가 정규식에 약했다 ..
정규식으로 푸는 문제들이 은근 많아서 시간이 나면 정규식도 따로 공부를 해봐야겠다.
그래도 여기서 join 함수가 어떻게 쓰이는 지 알게되었다.
function duplicateCount(text) {
console.log(
text
.toLowerCase()
.split("")
.filter(function (val, i, arr) {
return arr.indexOf(val) !== i && arr.lastIndexOf(val) === i;
}).length
);
}
duplicateCount("aabbc");
//filter함수는 세개의 매개변수가 있는데 각각, 요소의값, 요소의 인덱스, 사용되는 배열 객체이다.
//배열의 값 중 indexOf()함수를 사용해서 그 값의 인덱스가 필터함수로 구한 인덱스와 같지않으면서,
//lastIndexOf ? 문자열에서 탐색하는 문자열이 마지막으로 등장하는 위치에 대한 index를 반환
//lastIndexOf로 구한 마지막 인덱스 값이 i랑 같으면! 그 값의 length를 구함
- filter()
- indexof()
- lastIndexOf()
이 함수들은 당골이니 꼭 복습해봐야겠다!