mosredna

AoC 2021 day 18 Node.js

Dec 18th, 2021 (edited)
664
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var fs = require("fs");
  2. const internal = require("stream");
  3.  
  4. var fileName =__filename.slice(__dirname.length + 1, -3)+ ".txt";
  5.  
  6. let input = fs.readFileSync(fileName, 'utf8').toString();
  7. let data = input.split('\n').map(s => s.split(',').join("").trim());
  8.  
  9. data = data.map(s => {
  10.     return s.split('').map(s =>isNaN(s)?s:Number(s));
  11. });
  12.  
  13. function add(a,b){
  14.     let c =  ["[",...a,...b,"]"];
  15.     while(explode(c) || split(c));
  16.     return c;
  17. }
  18.  
  19. function explode(a){
  20.     let open = 0;
  21.     for (let i = 0; i < a.length; i++) {
  22.         const e = a[i];
  23.         if(e == "[")open++;
  24.         if(e == "]")open--;
  25.         if(open == 5){
  26.             let buf = a.splice(i, 4);
  27.             let up=i-1;
  28.             let down=i;
  29.             while(down--){
  30.                 if(!isNaN(a[down])){
  31.                     a[down]+= buf[1];
  32.                     break;
  33.                 }
  34.             }
  35.             while(up++<a.length){
  36.                 if(!isNaN(a[up])){
  37.                     a[up]+= buf[2];
  38.                     break;
  39.                 }
  40.             }
  41.             a.splice(i, 0,0);
  42.             explode(a);
  43.             return true;
  44.         }
  45.     }
  46.     return false;
  47. }
  48.  
  49. function split(a){
  50.     for (let i = 0; i < a.length; i++) {
  51.         const e = a[i];
  52.         if(!isNaN(e) && e>9){
  53.             let l = Math.floor(e/2);
  54.             let h = Math.ceil(e/2);
  55.             let s = ['[',l,h,']'];
  56.             a.splice(i,1,...s);
  57.             return true;
  58.         }
  59.     }
  60.     return false;
  61. }
  62.  
  63. function magnitude (a){
  64.     for (let i = 0; i < a.length; i++) {
  65.         const e = a[i];
  66.         if(e == "]"){
  67.             let buf = a.splice(i-3, 4);
  68.             let sum = buf[1]*3 + buf[2]*2;
  69.             a.splice(i-3,0,sum);
  70.             i-=3;
  71.         }
  72.     }
  73.     return a;
  74. }
  75.  
  76. let sum =  data[0];
  77. for (let i = 0; i < data.length-1; i++) {
  78.     sum = add(sum,data[i+1]);
  79. }
  80. let mag = magnitude(sum);
  81. console.log(1,mag[0]);
  82.  
  83. let max = 0;
  84. for (let i = 0; i < data.length-1; i++) {
  85.     for (let j = 0; j < data.length; j++) {
  86.         if(i != j){
  87.             max = Math.max( max, magnitude( add(data[i],data[j])));
  88.             max = Math.max( max, magnitude( add(data[j],data[i])))
  89.         }
  90.     }
  91. }
  92. console.log(2,max);
Advertisement
Add Comment
Please, Sign In to add comment