jamaik

Untitled

Dec 9th, 2021
622
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const { readFileSync } = require("fs");
  2. console.time("Test");
  3. const dataSet = readFileSync(`${__dirname}/inputs/day8.txt`, "utf8")
  4.     .replace(/\r\n/g,'\n')
  5.     .split("\n")
  6.     .map((row) => {
  7.         const [signals, outputs] = row.split(" | ");
  8.         return {
  9.             signals: signals.split(" "),
  10.             outputs: outputs.split(" ")
  11.         }
  12.     });
  13.  
  14. const countUniques = () => {
  15.     let sum = 0;
  16.     dataSet.forEach(({ outputs }) => {
  17.         outputs.forEach((output) => {
  18.             if ([2, 3, 4, 7].includes(output.length)) {
  19.                 sum += 1;
  20.             }
  21.         })
  22.     })
  23.     console.log("Sum", sum)
  24. }
  25.  
  26. const keys = ["a", "b", "c", "d", "e", "f", "g"];
  27. const values = ["abcefg", "cf", "acdeg", "acdfg", "bcdf", "abdfg", "abdefg", "acf", "abcdefg", "abcdfg"];
  28.  
  29. const diff = (s1, s2) => {
  30.     const chars = [];
  31.     for (const c of s1) {
  32.         if (s2.indexOf(c) === -1) {
  33.             chars.push(c);
  34.         }
  35.     }
  36.     return chars.join("");
  37. }
  38.  
  39. let sum = 0;
  40. for (const { signals, outputs } of dataSet) {
  41.     const len2 = signals.find(s => s.length === 2)
  42.     const len3 = signals.find(s => s.length === 3)
  43.     const len4 = signals.find(s => s.length === 4)
  44.     const map = {
  45.         a: diff(len3, len2)
  46.     };
  47.  
  48.     const joined = signals.join("");
  49.     for (const key of keys) {
  50.         const occurences = joined.split(key).length - 1;
  51.         if (occurences === 4) {
  52.             map["e"] = key;
  53.         } else if (occurences === 6) {
  54.             map["b"] = key;
  55.         } else if (occurences === 9) {
  56.             map["f"] = key;
  57.         }
  58.     }
  59.  
  60.     map["c"] = diff(len2, map["f"])
  61.     map["d"] = diff(len4, len2 + map["b"])
  62.     map["g"] = diff(keys.join(""), Object.values(map).join(""))
  63.  
  64.     const invertedMap = {};
  65.     for (const key of Object.keys(map)) {
  66.         invertedMap[map[key]] = key;
  67.     }
  68.  
  69.     const decoded = outputs.map((output) => {
  70.         const value = output.split("").map(c => invertedMap[c]).sort().join("");
  71.         return values.indexOf(value);
  72.     });
  73.     sum += parseInt(decoded.join(""));
  74. }
  75. console.log(sum)
  76. console.timeEnd("Test");
  77.  
  78.  
  79.  
  80.  
  81.  
RAW Paste Data