Created
December 6, 2022 08:33
-
-
Save oberhamsi/bac1d2f2fb976933a3bc0b2698d9a007 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const parse = (inputString) => { | |
const lines = inputString.split('\n'); | |
const crateLines = lines.slice(0,8); | |
const moveLines = lines.slice(10); | |
const crates = []; | |
crateLines.forEach(crateLine => { | |
let columnIdx = 0; | |
for (let i=1;i<crateLine.length-1;i+=4) { | |
let crateChar = crateLine.slice(i, i+1); | |
crates[columnIdx] = crates[columnIdx] || []; | |
if (crateChar != ' ') { | |
crates[columnIdx].push(crateChar); | |
} | |
columnIdx++; | |
} | |
}); | |
const moves = []; | |
moveLines.forEach(move => { | |
let parts = move.split(' '); | |
moves.push({ | |
count: parseInt(parts[1]), | |
from: parseInt(parts[3]) - 1, | |
to: parseInt(parts[5]) - 1 | |
}) | |
}) | |
return {crates, moves}; | |
} | |
const moveCrates = ({crates, moves, sameOrder}) => { | |
moves.forEach(move => { | |
const cratesToMove = crates[move.from].splice(0, move.count); | |
if (!sameOrder) { | |
cratesToMove.reverse(); | |
} | |
Array.prototype.unshift.apply(crates[move.to], cratesToMove); | |
}); | |
return crates; | |
} | |
const mainDayFiveA = (inputString) => { | |
const {crates, moves} = parse(inputString); | |
const movedCrates = moveCrates({crates, moves, sameOrder: false}); | |
return movedCrates.map(column => { | |
return column[0] | |
}).join('') | |
} | |
const mainDayFiveB = (inputString) => { | |
const {crates, moves} = parse(inputString); | |
const movedCrates = moveCrates({crates, moves, sameOrder: true}); | |
return movedCrates.map(column => { | |
return column[0] | |
}).join('') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment