Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.7 kB
1
Indexable
Never
const DIRECTION = {
	LEFT: "LEFT",
	RIGHT: "RIGHT",
	UP: "UP",
	DOWN: "DOWN"
}
const arr = [[1,2,3,4], [5,6,7,8], [9,10,11,12], [13,14,15,16]]
const arr1 = [[1,2,3], [4,5,6], [7,8,9]]
const lenX = arr.length
const lenY = arr[0].length
let boundX = lenX
let boundY = lenY
let isContinue = true
let direction = DIRECTION.RIGHT
let i = 0
let j = 0

let res = [arr[0][0]]

const checkCollision = (i, j) => {
  if(i >= boundX || j >= boundY || i <= lenX - boundX - 1 || j <= lenY - boundY - 1) {
    if (direction === DIRECTION.LEFT) {
      boundX--
    }
    if (direction === DIRECTION.UP) {
      boundY--
    }
    return true
  }
  return false;
}

const goToRight = () => {
  i += 0
  j += 1
}

const goToLeft = () => {
  i += 0
  j += -1
}

const goUp = () => {
  i += -1
  j += 0
}

const goDown = () => {
  i += 1
  j += 0
}


while (isContinue) {
  switch (direction) {
    case DIRECTION.LEFT:
    	goToLeft()
        if(checkCollision(i, j)) {
          goToRight()
          direction = DIRECTION.UP
          continue
        }
        break
    case DIRECTION.RIGHT:
    	goToRight()
        if(checkCollision(i, j)) {
          goToLeft()
          direction = DIRECTION.DOWN
          continue
        }
        break
    case DIRECTION.UP:
    	goUp()
        if(checkCollision(i, j)) {
          goDown()
          direction = DIRECTION.RIGHT
          continue
        }
        break
    case DIRECTION.DOWN:
    	goDown()
        if(checkCollision(i, j)) {
          goUp()
          direction = DIRECTION.LEFT
          continue
        }
        break
    default: return
  }

  res.push(arr[i][j])
  if(res.length == lenX * lenY) {
    isContinue = false
  }
}

console.log(res)