DEV Community

Discussion on: Advent of Code 2020 Solution Megathread - Day 11: Seating System

Collapse
 
kudostoy0u profile image
Kudos Beluga • Edited

Part 1 and 2 js solution, toggle part2 to true or false depending on your needs
I'm not sure about others but it took a long 4-5 seconds for it to compute part 1, 5-6 for part 2 and I'm very disappointed :(

const fs = require("fs")
let data = fs.readFileSync("input.txt","utf8").split("\n");
let part2 = true;
const logit = () => {
    let string = data.join(",");
    string = string.split("").map(e => {
    if (e == "#") return "b";
    }).filter(e => e).length
  console.log(string)
}
  let directions = [
    //right
    {x:1,y:0},
    //left
    {x:0,y:1},
    //up
    {x:1,y:1},
    //bottom
    {x:-1,y:-1},
    //topleft
    {x:-1,y:0},
    //topright
    {x:0,y:-1},
    //bottomleft
    {x:1,y:-1},
    //bottomright
    {x:-1,y:1},
    //{x:0,y:0}
  ]
const gethits = (x,y) => {
  let hits = 0;
  let cond;
  if (part2) cond = 59;
  else cond = 1;

  directions.map(({x:ex,y:ey}) => {

let myx = x+ex;
let myy = y+ey
  let i = 0;
  while (i<cond) {
    if (data[myy]) {
      if (data[myy][myx] == "#") {
        hits++
        break;
      }
      else if (data[myy][myx] == "L") {
        break;
        }
    }
   myx += ex;
   myy += ey;
   i++;
  }
  })  
  return hits;
}

const parseinput = (cache="") => {
  let vacants = [];
  let occupants = [];
for (y in data) {
  for (x in data) {
    y = Number(y);
    x = Number(x);

    if (data[y][x] == "L") {
    let hits = gethits(x,y);
    if (!hits) occupants.push({x,y})
    } else if (data[y][x] == "#") {
    let hits = gethits(x,y);
    let tolerance = 4;
    if (part2) tolerance = 5;
    if (hits >= tolerance) vacants.push({x,y})
    }
  }
}
    occupants.forEach(e => {
      let string = [...data[e.y]]
      string[e.x] = "#"
        data[e.y] = string
    })
    vacants.forEach(e => {
      let string = [...data[e.y]]
      string[e.x] = "L";
      data[e.y] = string;
    })
if (cache == data.join(",")) logit()
else parseinput(data.join(","))
}
parseinput();
Enter fullscreen mode Exit fullscreen mode