[Lv.1] 시저 암호(☆☆☆)

Jihyun-Jeon·2022년 4월 29일
0

https://programmers.co.kr/learn/courses/30/lessons/12926/solution_groups?language=javascript
체감 난이도 : ☆☆☆

🔶 내가 한 방법

  • 2.소문자일 경우와 3.대문자일 경우 코드에 중복되는게 있는데, 어떻게 정리해야 리팩토링 할 수 있는지 잘 모르겠음.
    일단 오류는 안나니까 이대로 해봄.
function solution(str, num) {
  const alpha = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',];
  let result = '';

  for (let i = 0; i < str.length; i += 1) {
    // 1.공백이면 그냥 공백으로 리턴
    if (str[i] === ' ') {
      result += ' ';
      continue;
    }

    let idx = alpha.findIndex((el) => el === str[i]);

    if (idx >= 0) {
      // 2.소문자인 경우
      let position = idx + num; // 26
      if (position > alpha.length - 1) {
        // 26 > 25
        position -= alpha.length;
      }
      result += alpha[position];
      continue;
    } else {
      // 3.대문자인 경우
      idx = alpha.findIndex((el) => el === str[i].toLowerCase());
      let position = idx + num;
      if (position > alpha.length - 1) {
        position -= alpha.length;
      }
      result += alpha[position].toUpperCase();
    }
  }

  return result;
}

// 실행코드
console.log(solution('Ab', 1)); /// BC
console.log(solution('z', 1)); // a
console.log(solution('a B', 1)); // b C
console.log(solution('a B z', 4)); // e F d

🔶 다른 사람 방법

  • 방법1. 알파벳 배열을 소문자, 대문자 각각 만듦.
function solution(str, num) {
  const lower = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',];
  const upper = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',];

  let result = '';

  for (let i = 0; i < str.length; i += 1) {
    // 1. 공백이면 공백을 더함
    if (str[i] === ' ') {
      result += ' ';
      continue;
    }
    
    // 2.대문자인지 소문자인지 구별
    const arr = lower.includes(str[i]) ? lower : upper;
    
    // 3.인덱스 값을 찾아 num을 더한 인덱스 값을 찾음
    let index = arr.indexOf(str[i]) + num;
    if (index > arr.length - 1) {
      index -= arr.length;
    }
    result += arr[index];
  }
  return result;
}
  • 방법2. 소문자,대문자,공백을 한 변수에 다 담아 indexOf()로 찾음.
// 1.split으로 str을 배열로 만든 후
// 2.map을 돌면서 해당 인덱스+num 인 요소를 찾아 반환함.
// 3.map의 결과를 join하여 문자열로 반환.
function solution(str, n) {
  const alpha = 'abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXY                          ';
  return str
    .split('')
    .map((el) => alpha[alpha.indexOf(el) + n])
    .join('');
}

🔶피드백

<indexOf 과 findIndex 차이>

indexOf()는 매개변수에 "찾으려는 값"이 들어감,
findIndex()는 매개변수에 "콜백함수"가 들어감

1. Array.prototype.indexOf()

  • 정의 : 배열에서 지정된 요소를 찾을 수 있는 첫 번째 인덱스를 반환하고 존재하지 않으면 -1을 반환합니다.
  • 형태 : arr.indexOf(searchElement, Index);
    Index :문자열에서 찾기 시작하는 위치를 나타내는 인덱스 값입니다.

1-2. String.prototype.indexOf()

  • string에서도 쓸 수 있음!
  • 예제
const str = 'abcdefg hijk lmnop';
console.log(str.indexOf('cde')); // 2
console.log(str.indexOf('a', 3)); // -1 // 3번째 인덱스인 d부터 찾기 시작하라는 뜻

2. Array.prototype.findIndex()

  • 정의 : 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.
  • 형태 : arr. findIndex(callback(element[, index[, array]])[, thisArg])
const array1 = [5, 12, 8, 130, 44];
console.log(array1.findIndex((el) => el > 13)); // 3 (요소 130의 인덱스값이 나옴)

0개의 댓글