Advertisement
Era37

Untitled

Dec 2nd, 2023
1,115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require("fs");
  2.  
  3. function part1() {
  4.   const bag = { red: 12, green: 13, blue: 14 };
  5.   const isValid = (colour) => {
  6.     let flag = true;
  7.     Object.keys(bag).forEach((key) => {
  8.       if (colour.endsWith(key) && Number(colour.replace(key, "")) > bag[key])
  9.         flag = false;
  10.     });
  11.     return flag;
  12.   };
  13.   let total = 0;
  14.   fs.readFileSync("./input.txt")
  15.     .toString()
  16.     .split("\n")
  17.     .forEach((line) => {
  18.       line = line.replaceAll(/\s+/g, "").slice(4).split(":");
  19.       let id = Number(line[0]);
  20.       let validFlag = true;
  21.       line[1].split(";").forEach((game) => {
  22.         game.split(",").forEach((colour) => {
  23.           if (!isValid(colour)) {
  24.             validFlag = false;
  25.             return;
  26.           }
  27.         });
  28.         if (!validFlag) return;
  29.       });
  30.       total += validFlag ? id : 0;
  31.     });
  32.   console.log(`Part 1: ${total}`);
  33. }
  34.  
  35. function part2() {
  36.   let sum = 0;
  37.   fs.readFileSync("./input.txt")
  38.     .toString()
  39.     .split("\n")
  40.     .forEach((line) => {
  41.       const minColours = { red: 0, green: 0, blue: 0 };
  42.       line
  43.         .replaceAll(/\s+/g, "")
  44.         .split(":")[1]
  45.         .split(";")
  46.         .forEach((game) => {
  47.           game.split(",").forEach((colour) => {
  48.             const [colourMatched, amount] = [
  49.               colour.match(/[a-z]+/g)[0],
  50.               Number(colour.match(/[0-9]+/g)[0]),
  51.             ];
  52.             if (minColours[colourMatched] < amount)
  53.               minColours[colourMatched] = amount;
  54.           });
  55.         });
  56.       sum += Object.values(minColours).reduce((acc, curr) => acc * curr);
  57.     });
  58.   console.log(`Part 2: ${sum}`);
  59. }
  60.  
  61. part1();
  62. part2();
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement