Skip to content

Commit

Permalink
Add v2 solution challenge 09
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsi15 committed Dec 12, 2024
1 parent 2962045 commit de8cf05
Showing 1 changed file with 25 additions and 38 deletions.
63 changes: 25 additions & 38 deletions challenges-2024/challenge-09/moveTrain.js
Original file line number Diff line number Diff line change
@@ -1,49 +1,36 @@
const board = ['·····', '*····', '@····', 'o····', 'o····']

export function moveTrain(board, mov) {
for (let i = 0; i < board.length; i++) {
const row = board[i]

for (let j = 0; j < row.length; j++) {
const cell = row[j]

if (cell === '@') {
const nextRow = board[i + 1] || []
const prevRow = board[i - 1] || []

const nextCell = nextRow[j]
const prevCell = prevRow[j]
const nextCellRight = row[j + 1]
const prevCellRight = row[j - 1]

if (mov === 'U') {
if (prevCell === '*') return 'eat'
if (!prevCell || prevCell === 'o') return 'crash'
if (prevCell === '.') return 'none'
}
const directions = {
U: [-1, 0], // Arriba
D: [1, 0], // Abajo
L: [0, -1], // Izquierda
R: [0, 1], // Derecha
}

if (mov === 'D') {
if (nextCell === '*') return 'eat'
if (!nextCell || nextCell === 'o') return 'crash'
if (nextCell === '.') return 'none'
}
let startRow, startCol
for (let i = 0; i < board.length; i++) {
const col = board[i].indexOf('@')
if (col !== -1) {
startRow = i
startCol = col
break
}
}

if (mov === 'L') {
if (prevCellRight === '*') return 'eat'
if (!prevCellRight || prevCellRight === 'o') return 'crash'
if (prevCellRight === '.') return 'none'
}
const [rowOffset, colOffset] = directions[mov]
const newRow = startRow + rowOffset
const newCol = startCol + colOffset

if (mov === 'R') {
if (nextCellRight === '*') return 'eat'
if (!nextCellRight || nextCellRight === 'o') return 'crash'
if (nextCellRight === '.') return 'none'
}
break
}
}
if (newRow < 0 || newRow >= board.length) {
return 'crash'
}

const targetCell = board[newRow][newCol]
if (targetCell === '*') return 'eat'
if (targetCell === 'o') return 'crash'
if (targetCell === '.') return 'none'

return 'none'
}

Expand Down

0 comments on commit de8cf05

Please sign in to comment.