Skip to content

Instantly share code, notes, and snippets.

@germanescobar
Created February 20, 2021 01:05
Show Gist options
  • Save germanescobar/0766cf33d230460d68aac5bbb530e0aa to your computer and use it in GitHub Desktop.
Save germanescobar/0766cf33d230460d68aac5bbb530e0aa to your computer and use it in GitHub Desktop.
function escape(carpark){
let instructions = []
const floors = carpark.length
const cells = carpark[0].length
let [posX, posY] = findOurPosition(carpark)
while (posX != floors - 1 || posY != cells - 1) {
const stairY = findStair(carpark[posX])
const newInstructions = generateInstructions(carpark, posX, posY, stairY)
instructions = instructions.concat(newInstructions)
console.log(instructions, newInstructions)
const [x, y] = calculateNewPosition(carpark, posX, posY, stairY)
posX += x
posY += y
}
return instructions
}
function findOurPosition(carpark) {
for (let i=0; i < carpark.length; i++) {
for (let j=0; j < carpark[i].length; j++) {
if (carpark[i][j] === 2) return [i, j]
}
}
}
function findStair(floor) {
for (let i=0; i < floor.length; i++) {
if (floor[i] == 1) return i
}
return -1
}
function generateInstructions(carpark, posX, posY, stairY) {
if (stairY == -1) { // no hay escalera, estamos en el piso de abajo
const spaces = carpark[0].length - 1 - posY
return [`R${spaces}`]
} else {
const spaces = stairY - posY
const direction = spaces < 0 ? "L" : "R"
const instructions = [direction + Math.abs(spaces)]
const floorsDown = calculateFloorsDown(carpark, posX, stairY)
instructions.push(`D${floorsDown}`)
return instructions
}
}
function calculateNewPosition(carpark, posX, posY, stairY) {
let spaces = 0, floors = 0
if (stairY == -1) { // no hay escalera, estamos en el piso de abajo
spaces = carpark[0].length - 1 - posY
} else {
spaces = stairY - posY
floors = calculateFloorsDown(carpark, posX, stairY)
}
return [floors, spaces]
}
function calculateFloorsDown(carpark, posX, stairY) {
let floorsDown = 0
for (let i=posX; i < carpark.length && carpark[i][stairY] == 1; i++) {
floorsDown++
}
return floorsDown
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment