mosredna

AoC 2022 day 5

Dec 5th, 2022
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
JavaScript 1.54 KB | Source Code | 0 0
  1. const fs = require('fs');
  2. const eol = require('os').EOL;
  3.  
  4. const startTime = new Date().getTime();
  5. let part1 = part2 = "";
  6. let time = 0;
  7. let [rows, moves] = fs.readFileSync(__dirname + "/data.txt", 'utf8').split(eol + eol);
  8.  
  9. rows = rows.split(eol);
  10. rows.pop();
  11.  
  12. let numColl = (rows[0].length + 1) / 4;
  13. let stacksMaster = new Array(numColl).fill().map(() => []);
  14.  
  15. // fill stacks
  16. for (let row of rows) {
  17.     for (let i = 0; i < numColl; i++) {
  18.         let crate = row[4 * i + 1];
  19.         if (crate !== ' ') {
  20.             stacksMaster[i].push(crate);
  21.         }
  22.     }
  23. }
  24.  
  25. // parse moves
  26. moves = moves.split(eol).map(val => {
  27.     let temp = val.split('from');
  28.     return {
  29.         amount: temp[0].split('move ')[1],
  30.         from: temp[1].split('to')[0] - 1,
  31.         to: temp[1].split('to')[1] - 1,
  32.     }
  33. })
  34.  
  35. // part1
  36. let stacks = JSON.parse(JSON.stringify(stacksMaster));
  37. for (let move of moves) {
  38.     for (let i = 0; i < move.amount; i++) {
  39.         let crate = stacks[move.from].shift();
  40.         stacks[move.to].unshift(crate);
  41.     }
  42. }
  43.  
  44. for (let stack of stacks) {
  45.     if (stack.length > 0) {
  46.         part1 += stack[0];
  47.     }
  48. }
  49.  
  50. // part1
  51. stacks = JSON.parse(JSON.stringify(stacksMaster));
  52. for (let move of moves) {
  53.     let stack = stacks[move.from].splice(0, move.amount);
  54.     stacks[move.to].unshift(...stack);
  55. }
  56.  
  57. for (let stack of stacks) {
  58.     if (stack.length > 0) {
  59.         part2 += stack[0];
  60.     }
  61. }
  62.  
  63. time = new Date().getTime() - startTime;
  64.  
  65. console.log(`Part 1: ${part1}\nPart 2: ${part2}\nTimer: ${time} ms`);
Advertisement
Add Comment
Please, Sign In to add comment