CodeWars符号化問題2021/01/29-Snail


[質問]


Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

For better understanding, please follow the numbers of the next array consecutively:

This image will illustrate things more clearly:

NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
NOTE 2: The 0x0 (empty matrix) is represented as en empty array inside an array [[]].
(要約)時計回りに回転するカタツムリの数字を配列に入れ、return/

[回答]

snail = function(array) {
  const answer = [];
  const length = array.length * array[0].length;
  let direction = 'r';
  let row = 0;
  let col = 0;
  array.push(new Array(array[0].length).fill('#'));

  for(let i = 0; i < length; i++) {
    answer.push(array[row][col]);
    array[row][col] = '#';

    const [tempRow, tempCol] = nextP(row, col, direction);

    if(array[tempRow][tempCol] === '#' || !array[tempRow][tempCol]) {
      direction = setDir(direction);
      [row, col] = nextP(row, col, direction);
    }
    else {
      row = tempRow;
      col = tempCol;
    }
  }

  return answer;
}

// 한 칸씩 움직이는 함수
function nextP(r, c, dir) {
  if(dir === 'r') {
    return [r, ++c];
  }
  else if(dir === 'd') {
    return [++r, c];
  }
  else if(dir === 'l') {
    return [r, --c];
  }
  else {
    return [--r, c];
  }
}

// 방향 바꾸는 함수
function setDir(dir) {
  const directionArr = ['r', 'd', 'l', 'u'];
  let dirIndex = directionArr.indexOf(dir);

  if(dirIndex < 3) {
    return directionArr[++dirIndex];
  }
  else {
    return directionArr[0];
  }
}
まず、指向性のあるセルごとに移動する関数と、方向を変える関数を定義します.
繰り返し文を使用してセルを1つずつ移動し、最後に達すると方向を変える関数を呼び出します.
会った数字はanswerpushで、その場で#で覆われています.arrayの最後の1つを#に充填する理由は、arrayの最後の配列の次の要素で検索すると、エラーが発生して暗闇に入るからです.
したがって、カタツムリの形で回転して数字を収集し、結果値はreturnであった.