[21/07/17 KATA NINJA ALGO] 거리두기, 유효한 펠린드롬, 압축

NinjaJuunzzi·2021년 7월 17일
0

코드카타

목록 보기
3/36
post-thumbnail

3일차

거리두기

function getMan(f, s) {
  const row = Math.abs(f.row - s.row);
  const column = Math.abs(f.column - s.column);
  return row + column;
}
function getComb(array, sn) {
  if (sn === 1) {
    return array.map((i) => [i]);
  }
  const result = [];
  array.forEach((item, index) => {
    const target = item;
    const tail = getComb(array.slice(index + 1), sn - 1);
    tail.forEach((tailItem) => {
      result.push([target, ...tailItem]);
    });
  });
  return result;
}
function getTwoCheck(peoples, first, second) {
  if (first.row === second.row) {
    const index = (first.column + second.column) / 2;

    return peoples[first.row][index] === "O";
  }
  if (first.column === second.column) {
    const index = (first.row + second.row) / 2;
    return peoples[index][first.column] === "O";
  }
  const data_1 = peoples[first.row][second.column];
  const data_2 = peoples[second.row][first.column];

  return data_1 === "O" || data_2 === "O";
}
function solution(places) {
  var answer = [];
  places = places.map((place) => place.map((string) => string.split("")));
  places.forEach((place) => {
    const peoples = [];
    let result = 1;
    place.forEach((daegisil, row) => {
      daegisil.forEach((seat, column) => {
        if (seat === "P") peoples.push({ row, column });
      });
    });
    const comb = getComb(
      [...new Array(peoples.length)].map((_, index) => index),
      2
    );
    for (let check = 0; check < comb.length; check++) {
      const [f, s] = comb[check];
      const first = peoples[f];
      const second = peoples[s];
      const menhaton = getMan(first, second);
      if (menhaton === 1) {
        result = 0;
        break;
      }
      if (menhaton === 2) {
        if (getTwoCheck(place, first, second)) {
          result = 0;
          break;
        }
      }
    }

    answer.push(result);
  });
  return answer;
}
getComb([], 2);
solution([
  ["POOOP", "OXXOX", "OPXPX", "OOXOX", "POXXP"],
  ["POOPX", "OXPXP", "PXXXO", "OXXXO", "OOOPP"],
  ["PXOPX", "OXOXP", "OXPOX", "OXXOP", "PXPOX"],
  ["OOOXX", "XOOOX", "OOOXX", "OXOOX", "OOOOO"],
  ["PXPXP", "XPXPX", "PXPXP", "XPXPX", "PXPXP"],
]);

유효한 펠린드롬

function solution(s) {
  const onlyAlphabelString = s.toLowerCase().match(/[a-z]/gi);  
  for (let check = 0; check < onlyAlphabelString.length / 2; check++) {
    if (     
      onlyAlphabelString[check] !==
      onlyAlphabelString[onlyAlphabelString.length - 1 - check]
    ) {
      return false;
    }
  }
	return true;
}

  • 알파벳을 뽑아내거나 match(/[a-z]/g)
  • 알파벳이 아닌걸 지워주거나 replace(/[^a-z]/g,'')
  • reverse는 원본 배열을 바꾼다.
  • 5=> 0 1 vs 3 4
  • 4=> 0 1 vs 2 3

압축

코드는 짧지만, 나에게 매우 강렬했던 문제.

const dict = [
  "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",
];
function getWC(string, current, next, dict) {
  
  // 재귀 형태
  if (next >= string.length)
    // next가 문자열의 길이 이상이라면, 즉, c에 해당하는 문자가 없는 경우라면 바로 w인덱스를 넘긴다.
    return [dict.indexOf(string.slice(current, next)) + 1, next - current - 1];
  
  // 그게 아니라면 w와 c를 받는다.
  const w = string.slice(current, next);
  const c = string.slice(next, next + 1);

  // w+c가 이미 존재한다면 더 길어질 수 있다.
  // 존재하지 않는다면 최대 길이다.
  const index = dict.indexOf(w + c);

  if (index === -1) {
    // 존재하지 않는다면  현재 입력과 일치하는 가장 긴 문자열 w이다.
    dict.push(w + c);
    return [dict.indexOf(w) + 1, next - current - 1];
  } else {
    // 존재한다면 현재 입력과 일치하는 가장 긴 문자열 w가 아니므로 재귀로 한번더.
    return getWC(string, current, next + 1, dict);
  }
}
function solution(msg) {
  var answer = [];
  for (let check = 0; check < msg.length; check++) {
    // 출력할 색인과 문자가 얼마나 길어진 것인지를 나타내는 depth를 반환한다.
    const [print, depth] = getWC(msg, check, check + 1, dict);
    
    
    answer.push(print);
    check += depth;
  }
  return answer;
}

dict를 정적인 배열 말고 동적인 객체로 만들어보자.

profile
Frontend Ninja

0개의 댓글