Skip to content

[구현] 주사위굴리기 #93

Description

@ericagong

⭐ 성찰

  1. 방향 동서남북 잘 구분해 디버깅 이슈 만들지 않기
  2. 복잡해보이는 내용도 항상 규칙을 찾기 OR 하드코딩

❓ 문제 상황

주사위 굴리기

👨‍💻 문제 해결: 풀이 방식

✅ 1차 풀이: 키워드

  1. 주어진 방향 값에 따라 이동 여부 결정(범위 밖이면 이동 X)
  2. 이동 가능 시, 주어진 방향에 따라 주사위 칸의 위치를 변경
  3. 도달한 위치의 값에 따라 주사위 바닥 값 복제/피복제 여부 결정
  4. 이동 수행
const fs = require("fs");
const inputs = fs.readFileSync("/dev/stdin").toString().split("\n");

const [N, M, x, y, K] = inputs.shift().split(" ").map(Number);
const g = [];
for (let i = 0; i < N; i++) {
  g[i] = inputs.shift().split(" ").map(Number);
}
const moves = inputs.shift().split(" ").map(Number);

function getNewDice(d, dice) {
  // 위 아래 앞 뒤 좌 우
  const [x0, x1, x2, x3, x4, x5] = dice;
  // 동 서 북 남 1 2 3 4
  switch (d) {
    case 1:
      return [x4, x5, x2, x3, x1, x0];
    case 2:
      return [x5, x4, x2, x3, x0, x1];
    case 3:
      return [x2, x3, x1, x0, x4, x5];
    case 4:
      return [x3, x2, x0, x1, x4, x5];
  }
}

function changeBottom(to, dice) {
  const [top, bottom, ...rest] = dice;
  return [top, to, ...rest];
}

// 동 서 북 남 0123
const dx = [0, 0, -1, 1];
const dy = [1, -1, 0, 0];
let dice = [0, 0, 0, 0, 0, 0];
let cx = x;
let cy = y;
for (let i = 0; i < moves.length; i++) {
  const d = moves[i];

  // 동서남북 1234
  const nx = cx + dx[d - 1];
  const ny = cy + dy[d - 1];

  if (nx < 0 || nx > N - 1 || ny < 0 || ny > M - 1) continue;

  // 주사위 현재 위치 변경
  cx = nx;
  cy = ny;

  // 주사위 굴림
  dice = getNewDice(d, dice);

  // 주사위 맨 아래 값이나 지도 값 변경
  if (g[nx][ny] === 0) g[nx][ny] = dice[1];
  else {
    dice = changeBottom(g[nx][ny], dice);
    g[nx][ny] = 0;
  }

  // 주사위 맨 위 출력
  console.log(dice[0]);
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions