코딩공부/코딩문제 풀이들

2022-01-15 코드워즈 문제풀이.

지구야 사랑해 2022. 1. 15. 16:36

Q1. 

https://www.codewars.com/kata/54bf1c2cd5b56cc47f0007a1/train/javascript

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

 

My sol)

function duplicateCount(text){
  //lowercase
  let lowText = text.toLowerCase(); 
  let obj = {};
  for (let i = 0; i < lowText.length; i++) {
    if (lowText.indexOf(lowText[i]) !== i) {
      obj[lowText[i]] = 1;      
    }
  }
  const count = Object.keys(obj).length;
  return count;
}

- 계속 겹쳐서 있는 문자열은 카운트를 1번만 해야되니 그냥 count 보다

 

객체에서 계속 키의 값을 갱신해주는게 낫다고 판단함.

 

 

another sol)

 

function duplicateCount(text){
  return text.toLowerCase().split('').filter(function(val, i, arr){
    return arr.indexOf(val) !== i && arr.lastIndexOf(val) === i;
  }).length;
}

- 1. 우선 다루기 쉬운 배열로 만듦

 

  2. filter함수로 거르는데 첫인덱스가 자기자신이 아니고(두번 이상 중복이고)  다 카운트 하면 안되니

last 인덱스가 자기인것만 카운트...와................

 

 

- 새로 배운 정보 :

 

arr.lastInexOf : 역순으로 서칭하여 제일 처음 마주치는 문자열 인덱스 반환하는것 

 

- 느낀점 : 

 

새로 배운 정보를 모르니 아이디어의 한계를 느낀것 같다. 그래도 배웠으니 ok입니다