Codewars 7kyu 문제 Indexed capitalization.
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
문자열과 배열이 하나씩 주어짐. 문자열은 소문자, 배열은 숫자로 이뤄짐. 배열 속 숫자들을 문자열의 인덱스로 둬서 해당 소문자를 대문자로 바꾸는 문제.
1. 최초 시도 (실패)
function capitalize(s,arr){
let string = s.split("");
for (let i = 0; i < arr.length; i++) {
string[arr[i]] = string[arr[i]].toUpperCase();
}
return string.join("");
};
문자열을 쪼갬 -> 배열의 숫자에 해당하는 인덱스를 대문자로 바꿈 -> 글자들을 다시 붙임.
오류 생기는 사례 발생. TypeError: Cannot read property 'toUpperCase' of undefined
들여다보니 입력값이 ("abcdef", [1, 2, 5])일 때는 괜찮은데 ("abcdef", [1, 2, 5, 100])이면 문제가 생김.
string[arr[100]]이 없기 때문에 undefined가 돼버림.
2. 조건 추가 (성공)
function capitalize(s,arr){
let string = s.split("");
for (let i = 0; i < arr.length; i++) {
if (string[arr[i]]) {
string[arr[i]] = string[arr[i]].toUpperCase();
}
}
return string.join("");
};
string[arr[i]]가 있을 때만 대문자로 변환을 하도록 하니 성공.
3. 다른 방법 (성공)
입력값 중에서 숫자 배열이 아니라 문자열을 훑으면서 변환하는 방법도 생각해봄.
function capitalize(s, arr) {
let result = ""
for (let i = 0; i < s.length; i++) {
if (arr.includes(i)) {
result += s[i].toUpperCase();
} else {
result += s[i];
}
}
return result;
};
어제 푼 문제와 비슷함.
Alternate capitalization, toUpperCase() { [native code] } | Codewars [자바스크립트]
Codewars 7kyu 문제 Alternate capitalization. Codewars: Achieve mastery through challenge Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach you..
fennecfox-dev.tistory.com
이 밖에 오늘 푼 문제. 7kyu Array element parity.
Codewars: Achieve mastery through challenge
Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.
www.codewars.com
숫자로 이뤄진 배열에서 -n이 존재하지 않는 n 찾아내기.
function solve(arr){
let i = 0;
while (arr.includes(-arr[i])) i++;
return arr[i];
};
전에 풀면서 공부한 while과 includes를 사용해봄.
Smallest unused ID, includes() has() indexOf() new Set() | Codewars [자바스크립트]
Codewars 8kyu 문제 Smallest unused ID. Codewars: Achieve mastery through challenge Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highe..
fennecfox-dev.tistory.com