Advertisement
jamaik

Untitled

Dec 3rd, 2021
725
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require("fs");
  2. const dataSet = fs.readFileSync("inputs/day3.txt", "utf8").replace(/\r\n/g,'\n').split("\n")
  3.  
  4. const mostCommonValue = (data, position) => {
  5.     let sum = 0;
  6.     for (let i = 0; i < data.length; i += 1) {
  7.         sum += +data[i][position];
  8.     }
  9.     return 2 * sum >= data.length ? 1 : 0;
  10. }
  11.  
  12. const findGammaAndEpsilon = (data) => {
  13.     let [gamma, epsilon] = ["0B", "0B"];
  14.     for (let i = 0; i < data[0].length; i += 1) {
  15.         const x = mostCommonValue(data, i);
  16.         gamma += x; epsilon += 1-x;
  17.     }
  18.     console.log("Gamma", +gamma)
  19.     console.log("Epsilon", +epsilon)
  20.     console.log("Product", gamma*epsilon, "\n")
  21. }
  22.  
  23. const filterByCriteria = (most, data, i = 0) => {
  24.     if (data.length === 1 || i === data[0].length) {
  25.         return "0B"+data[0];
  26.     }
  27.     const x = mostCommonValue(data, i);
  28.     return filterByCriteria(most, data.filter(d => d[i] == most ? x : 1-x), i + 1);
  29. }
  30.  
  31. const findOxygenAndCO2 = (dataSet) => {
  32.     const oxygen = filterByCriteria(true, dataSet);
  33.     const co2 = filterByCriteria(false, dataSet);
  34.     console.log("Oxygen", +oxygen)
  35.     console.log("co2", +co2)
  36.     console.log("Product", oxygen*co2)
  37. }
  38.  
  39. findGammaAndEpsilon(dataSet)
  40. findOxygenAndCO2(dataSet)
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement