Skip to content

Instantly share code, notes, and snippets.

@oberhamsi
Created December 6, 2022 08:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oberhamsi/bac1d2f2fb976933a3bc0b2698d9a007 to your computer and use it in GitHub Desktop.
Save oberhamsi/bac1d2f2fb976933a3bc0b2698d9a007 to your computer and use it in GitHub Desktop.
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