CodeWars 코딩 문제 2021/01/22 - Make the Deadfish swim

이호현·2021년 1월 22일
0

Algorithm

목록 보기
60/138

[문제]

Write a simple parser that will parse and run Deadfish.

Deadfish has 4 commands, each 1 character long:

  • i increments the value (initially 0)
  • d decrements the value
  • s squares the value
  • o outputs the value into the return array

Invalid characters should be ignored.

parse("iiisdoso") => [ 8, 64 ]

(요약) 문자열을 순회하면서 i+1, d-1, s제곱, o면 배열에 push하고, 마지막에 배열을 return

[풀이]

function parse( data )
{
  let num = 0;
  const answer = [];
  const calArr = ['i', 'd', 's', 'o'];
  const cal = {
    0: (n, arr) => n + 1,
    1: (n, arr) => n - 1,
    2: (n, arr) => n * n
  }

  for(let k in data) {
    if(data[k] === 'o') {
      answer.push(num);
    }
    else if(calArr.includes(data[k])) {
      num = cal[calArr.indexOf(data[k])](num);
    }
  }

  return answer;
}

i, d, s, o를 갖고 있는 배열을 하나 만들고, data를 반복문으로 순회하면서 해당 문자가 배열안에 있을 때, cal에서 해당하는 문자의 index의 키값의 함수를 실행하게 함.
o면 정답 배열에 push하게 함.

profile
평생 개발자로 살고싶습니다

0개의 댓글

관련 채용 정보