Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fs = require('fs');
- const eol = require('os').EOL;
- const startTime = new Date().getTime();
- let part1 = part2 = "";
- let time = 0;
- let [rows, moves] = fs.readFileSync(__dirname + "/data.txt", 'utf8').split(eol + eol);
- rows = rows.split(eol);
- rows.pop();
- let numColl = (rows[0].length + 1) / 4;
- let stacksMaster = new Array(numColl).fill().map(() => []);
- // fill stacks
- for (let row of rows) {
- for (let i = 0; i < numColl; i++) {
- let crate = row[4 * i + 1];
- if (crate !== ' ') {
- stacksMaster[i].push(crate);
- }
- }
- }
- // parse moves
- moves = moves.split(eol).map(val => {
- let temp = val.split('from');
- return {
- amount: temp[0].split('move ')[1],
- from: temp[1].split('to')[0] - 1,
- to: temp[1].split('to')[1] - 1,
- }
- })
- // part1
- let stacks = JSON.parse(JSON.stringify(stacksMaster));
- for (let move of moves) {
- for (let i = 0; i < move.amount; i++) {
- let crate = stacks[move.from].shift();
- stacks[move.to].unshift(crate);
- }
- }
- for (let stack of stacks) {
- if (stack.length > 0) {
- part1 += stack[0];
- }
- }
- // part1
- stacks = JSON.parse(JSON.stringify(stacksMaster));
- for (let move of moves) {
- let stack = stacks[move.from].splice(0, move.amount);
- stacks[move.to].unshift(...stack);
- }
- for (let stack of stacks) {
- if (stack.length > 0) {
- part2 += stack[0];
- }
- }
- time = new Date().getTime() - startTime;
- console.log(`Part 1: ${part1}\nPart 2: ${part2}\nTimer: ${time} ms`);
Advertisement
Add Comment
Please, Sign In to add comment