horvathm

Day 19 Part 2

Dec 19th, 2020 (edited)
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2.  
  3. // removed rules 0, 8, 11 from input
  4. // 0: 8 11
  5. // 8: 42 | 42 8
  6. // 11: 42 31 | 42 11 31
  7.  
  8. let [gram, data] = fs.readFileSync('/home/horvathm/aoc/2020/19/part2/input', 'utf8').trim().split('\n\n');
  9.  
  10. gram = gram.split('\n').map(l => {
  11.         const m = l.match(/(\d+): "?([^"]*)"?/);
  12.         return { n: m[1], t: m[2] }
  13.     }, {});
  14.  
  15. //console.log(gram);
  16. gram = gram.sort((a, b) => b.n - a.n);
  17. //console.log(gram);
  18.  
  19. for (const rule of gram) {
  20.     for (const line of gram) {
  21.         line.t = line.t.replace(new RegExp(rule.n, 'g'), `(${rule.t})`);
  22.     }
  23.     // console.log('-----');
  24.     // console.log(gram);
  25. }
  26.  
  27. //console.log(gram);
  28.  
  29. let rule31 = gram.filter(r => r.n === '31')[0].t.replace(/ /g, '');
  30. let rule42 = gram.filter(r => r.n === '42')[0].t.replace(/ /g, '');
  31.  
  32. console.log(rule31);
  33. console.log(rule42);
  34.  
  35. //rule0 = rule0.replace(/\(a\)/g, 'a');
  36. //rule0 = rule0.replace(/\(b\)/g, 'a');
  37.  
  38. const re42 = new RegExp(`^(${rule42})`)
  39. const re31 = new RegExp(`^(${rule31})`)
  40.  
  41. console.log(re31);
  42. console.log(re42);
  43.  
  44. data = data.split('\n');
  45. for (const line of data) {
  46.     //console.log(line);
  47.     let rest = line;
  48.  
  49.     let c42 = 0;
  50.     while (true) {
  51.         const m42 = rest.match(re42);
  52.         if (!m42) break;
  53.         c42++;
  54.         rest = rest.substr(m42[0].length);
  55.         //console.log(42, m42[0], rest);
  56.     }
  57.  
  58.     let c31 = 0;
  59.     while (true) {
  60.         const m31 = rest.match(re31);
  61.         if (!m31) break;
  62.         c31++;
  63.         rest = rest.substr(m31[0].length);
  64.         //console.log(31, m31[0], rest);
  65.     }
  66.  
  67.     if (rest === '' && c42 > 0 && c31 > 0 && c42 > c31) {
  68.         console.log('passed', line);
  69.     } else {
  70.         console.log('failed', line);
  71.     }
  72. }
  73.  
Add Comment
Please, Sign In to add comment