Skip to content

Instantly share code, notes, and snippets.

@zacwasielewski
Last active July 11, 2017 13:22
Show Gist options
  • Save zacwasielewski/cf4d5fc4b5e48c95ef95abe98065a770 to your computer and use it in GitHub Desktop.
Save zacwasielewski/cf4d5fc4b5e48c95ef95abe98065a770 to your computer and use it in GitHub Desktop.
Solution to CodeFights `secretArchivesLock` challenge
const secretArchivesLock = (lock, actions) =>
optimizeActions([...actions]).reduce((lock, direction) => move(lock, direction), lock)
const move = (lock, direction) => {
return {
'L': moveLeft(lock),
'R': moveRight(lock),
'U': moveUp(lock),
'D': moveDown(lock)
}[direction] || lock
}
const optimizeActions = actions => removeConsecutiveDuplicates(actions)
const moveLeft = lock =>
lock.map(row => row.replace(/\./g, '').padEnd(lock[0].length, '.'))
const moveRight = lock =>
lock.map(row => row.replace(/\./g, '').padStart(lock[0].length, '.'))
const moveUp = lock => transpose(moveLeft(transpose(lock)))
const moveDown = lock => transpose(moveRight(transpose(lock)))
const transpose = lock => {
const columnRange = Array(lock[0].length).fill()
return columnRange.map((_, col) => lock.map(row => row.charAt(col)).join(''))
}
const removeConsecutiveDuplicates = actions => {
return actions
.map((action, i) => (action === actions[i-1]) ? NULL : action)
.filter(action => !NULL)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment