[Lv.1]크레인 인형뽑기 게임

Jihyun-Jeon·2022년 3월 3일
0

https://programmers.co.kr/learn/courses/30/lessons/64061

🔶내가 한 방법
1. moves배열을 forEach로 순회하면서, board에서 활용할 인덱스값을 moveNum으로 지정함.
2. board배열을 for문으로 순회하면서 picked = board[ i ][moveNum] 값을 찾는다.
3. 그 값이 0이면 if문 실행없이 다음 for문 순회로 넘어가고
4. 그 값이 0이 아니면 if문 실행한다.
5. 그 값이 result배열의 마지막 값과 같으면, 그 마지막 값을 pop으로 지우고, cnt를 +2한다.
6. result배열의 마지막 값과 겹치지 않으면 result배열에 picked를 넣은다.
7. 그리고 picked 값을 0으로 만들고
8. break를 통해 다음 for문을 실행시키지 않도록 끝내버린다.
9. forEach문이 다 실행된 후, cnt값을 리턴한다.

function solution(board, moves) {
  const result = [];
  let cnt = 0;
  
  moves.forEach((el) => {
    const moveNum = el - 1;     // 0,4,2,4,0,1,0,3

    for (let i = 0; i < board.length; i += 1) {
      const picked = board[i][moveNum];

      if (picked) {
        if (result[result.length - 1] === picked) {
          cnt += 2;
          result.pop(result[result.length - 1]);
        } else {
          result.push(picked);
        }

        board[i][moveNum] = 0;
        break;
      }
    }
  });
  return cnt;
}
// 실행
console.log(
  solution(
    [
      [0, 0, 0, 0, 0],
      [0, 0, 1, 0, 3],
      [0, 2, 5, 0, 1],
      [4, 2, 4, 4, 2],
      [3, 5, 1, 3, 1],
    ],
    [1, 5, 3, 5, 1, 2, 1, 4],
  ),
);
// 4,3,1,1,3,2,4 -> 결과 4

🔶다른사람 풀이

코드를 입력하세요

🔶피드백

profile
~23.05 (🚌 이사갔어요👉👉https://journey-dev.tistory.com)

0개의 댓글

관련 채용 정보