프로그래머스 Lv.1(JS) - 둘만의 암호
문제
문제 설명
두 문자열 s와 skip, 그리고 자연수 index가 주어질 때, 다음 규칙에 따라 문자열을 만들려 합니다. 암호의 규칙은 다음과 같습니다.
- 문자열 s의 각 알파벳을
index만큼 뒤의 알파벳으로 바꿔줍니다. index만큼의 뒤의 알파벳이z를 넘어갈 경우 다시a로 돌아갑니다.- skip에 있는 알파벳은 제외하고 건너뜁니다.
예를 들어 s = “aukks”, skip = “wbqd”, index = 5일 때, a에서 5만큼 뒤에 있는 알파벳은 f지만 [b, c, d, e, f]에서 ‘b’와 ‘d’는 skip에 포함되므로 세지 않습니다. 따라서 ‘b’, ‘d’를 제외하고 ‘a’에서 5만큼 뒤에 있는 알파벳은 [c, e, f, g, h] 순서에 의해 ‘h’가 됩니다. 나머지 “ukks” 또한 위 규칙대로 바꾸면 “appy”가 되며 결과는 “happy”가 됩니다.
두 문자열 s와 skip, 그리고 자연수 index가 매개변수로 주어질 때 위 규칙대로 s를 변환한 결과를 return하도록 solution 함수를 완성해주세요.
제한사항
- 5 ≤
s의 길이 ≤ 50 - 1 ≤
skip의 길이 ≤ 10 - s“와
skip은 알파벳 소문자로만 이루어져 있습니다.skip에 포함되는 알파벳은s에 포함되지 않습니다.
- 1 ≤
index≤ 20
입출력 예
| s | skip | index | result |
|---|---|---|---|
| ”aukks" | "wbqd” | 5 | ”happy” |
정답
풀이 코드
function solution(s, skip, index) {
let result = '';
const inputNums = s.split('').map((x) => x.charCodeAt(0));
const skipList = skip.split('').map((x) => x.charCodeAt(0));
const convertValue = (value, idx) => {
let start = value;
let end = value + idx;
if (end > 122) end -= 26;
const count = skipList.filter(
(x) => (start < x && x <= start + idx) || (start > end && x <= end),
).length;
return count === 0 ? String.fromCharCode(end) : convertValue(end, count);
};
for (const inputValue of inputNums) {
result += convertValue(inputValue, index);
}
return result;
}
풀이 설명
- ASCII 코드를 활용합니다.
- 변환할 문자의 인덱스만큼 뒤에 있는 문자를 계산한 후, 사이에 건너뛰어야 할 문자가 있다면 해당 개수만큼 추가로 변환합니다.
function solution(s, skip, index) {
let result = '';
const inputNums = s.split('').map((x) => x.charCodeAt(0));
const skipList = skip.split('').map((x) => x.charCodeAt(0));
//...
}
s와 skip의 문자를 분리하여 ASCII 코드로 변환한 배열을 각각 inputNums과 skipList에 저장합니다.
function solution(s, skip, index) {
//...
const convertValue = (value, idx) => {
let start = value;
let end = value + idx;
if (end > 122) end -= 26;
const count = skipList.filter(
(x) => (start < x && x <= start + idx) || (start > end && x <= end),
).length;
return count === 0 ? String.fromCharCode(end) : convertValue(end, count);
};
//...
}
convertValue는 매개변수로 받은 문자를 인덱스만큼 뒤의 알파벳으로 변환하는 함수입니다.
-
start는 변환하려는 문자의 ASCII 값이고end는skip을 고려하지 않고 index만큼 뒤의 위치한 문자의 ASCII값입니다. -
end가 z에 해당하는 ASCII 값인 122를 초과하면 다시 a부터 시작하기 위해 26을 빼줍니다. -
count는start와end사이에 건너뛸 문자의 개수입니다. 건너뛸 문자가 없다면end값을 문자로 변환하여 리턴하고, 있다면count가 0이 될 때까지 재귀적으로 반복합니다.
function solution(s, skip, index) {
//...
for (const inputValue of inputNums) {
result += convertValue(inputValue, index);
}
return result;
}
마지막으로 변환한 문자들을 모두 이어 붙여 리턴합니다.