[프로그래머스] 시저 암호

개발잘하기프로젝트·2020년 11월 13일
0
post-thumbnail

🤔 문제

프로그래머스 - 시저 암호

어떤 문장의 각 알파벳을 일정한 거리만큼 밀어서 다른 알파벳으로 바꾸는 암호화 방식을 시저 암호라고 합니다. 예를 들어 AB는 1만큼 밀면 BC가 되고, 3만큼 밀면 DE가 됩니다. z는 1만큼 밀면 a가 됩니다. 문자열 s와 거리 n을 입력받아 s를 n만큼 민 암호문을 만드는 함수, solution을 완성해 보세요.

❗️ 제한

  • 공백은 아무리 밀어도 공백입니다.
  • s는 알파벳 소문자, 대문자, 공백으로만 이루어져 있습니다.
  • s의 길이는 8000이하입니다.
  • n은 1 이상, 25이하인 자연수입니다.

💡 접근

암호화할 문자열 s는 대문자 혹은 소문자로 이루어져 있기 때문에 largesmall이라는 알파벳 문자열을 만들었다. s의 각 알파벳 str에 대해서 공백문자일 경우와 대, 소문자일 경우로 나누어 암호화해 리턴하기로 했다. str이 공백 문자이면 그대로 두고, 대문자와 소문자일 경우를 구분해서 large, small 문자열에서 n만큼 움직여서 나온 값을 찾아 리턴하도록 했다. Z, z 이상으로 움직일 경우 다시 처음으로 돌아가 이어서 나머지 움직여야 하는 만큼 세야 하기 때문에 %연산자를 이용했다.

solution 1은 주어진 문제에 대한 풀이이고, solution 2는 암호화된 문자열을 다시 원래 문장으로 만드는 코드이다. 기존 코드에서 n = 26 - n; 코드 한줄만 추가해주었다.

🧑🏻‍💻 코드

// 암호화
// solution 1
function solution(s, n) {
  const large = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const small = 'abcdefghijklmnopqrstuvwxyz';
  const largeLen = large.length;
  const smallLen = small.length;
  
  const cipher = [...s]
    .map(str => {
      if (str === ' ') return str;
      if (str === str.toUpperCase())
        return large[(large.indexOf(str) + n) % largeLen];
      if (str === str.toLowerCase())
        return small[(small.indexOf(str) + n) % smallLen];
    })
    .join('');

  return cipher;
}

solution('This is Caesar Cipher', 10); // 'Drsc sc Mkockb Mszrob'

// 복호화
// solution 2
function solution2(s, n) {
  n = 26 - n; // solution1에서 추가된 코드
  const large = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
  const small = 'abcdefghijklmnopqrstuvwxyz';
  const largeLen = large.length;
  const smallLen = small.length;
  
  const cipher = [...s]
    .map(str => {
      if (str === ' ') return str;
      if (str === str.toUpperCase())
        return large[(large.indexOf(str) + n) % largeLen];
      if (str === str.toLowerCase())
        return small[(small.indexOf(str) + n) % smallLen];
    })
    .join('');

  return cipher;
}

solution2('Drsc sc Mkockb Mszrob', 10); // 'This is Caesar Cipher'

📝 참고

MDN - String.prototype.toUpperCase()
MDN - String.prototype.toLowerCase()
wikipedia - 카이사르 암호

profile
🏠 ☕️ 🎞 🌿 + 🧑🏻‍💻

0개의 댓글