Unable to load image

Advent of Code 2022: Day 8

Post solutions here :marseysad: :marseyill:

25
Jump in the discussion.

No email address required.

would've been easier if i wasn't so damn dyslexic

// build grid
import * as fs from 'fs'
const g: number[][] = [];
fs.readFileSync(process.argv[2], 'utf-8').split('\n')
  .map((l, i) => g[i] = l.split('').map(s => Number(s)));

// PART 1 - O(n)
const v: {[key: string]: 1}= {};
const lft = {r:0, c:0, h:-1};
const rht = {...lft}, top = {...lft}, bot = {...lft};
for (let i = 0; i < g.length; i++) {
  for (let j = 0; j < g.length; j++) {
    lft.r = rht.r = top.c = bot.c = i;
    lft.c =         top.r         = j;
            rht.c         = bot.r = g.length-j-1;
    const check = (dir: typeof lft) => {
      const h = g[dir.r][dir.c];
      if (h > dir.h) {
        v[`${dir.r}-${dir.c}`] = 1;
        dir.h = h;
      }
    };
    check(lft); check(rht); check(top); check(bot);
  }
  lft.h = rht.h = top.h = bot.h = -1;
}
console.log(Object.keys(v).length);

// PART 2 - O(n^2)
const score = (r: number, c: number) => {
  const h = g[r][c];
  let sTop=0, sLft=0, sRht=0, sBot=0;
  for (let iR=r; iR > 0 && ++sTop && (g[iR-1][c] < h); iR--);
  for (let iC=c; iC > 0 && ++sLft && ((g[r][iC-1] < h)); iC--);
  for (let iC=c; (iC < g.length-1) && ++sRht && (g[r][iC+1] < h); iC++);
  for (let iR=r; (iR < g.length-1) && ++sBot && (g[iR+1][c] < h); iR++);
  return sLft * sRht * sTop * sBot;
}
let maxScr = 0;
g.map((row, r) => row.map((_, c) => {
  const scr = score(r, c);
  if (scr > maxScr) maxScr = scr;
}))
console.log(maxScr);

now that i think of it, there's probably a O(n) solution for PART 2, i'm just a bit lazy on figuring it out.

Jump in the discussion.

No email address required.

Some people are able to display their intelligence by going on at length on a subject and never actually saying anything. This ability is most common in trades such as politics, public relations, and law. You have impressed me by being able to best them all, while still coming off as an absolute idiot.

Jump in the discussion.

No email address required.

Link copied to clipboard
Action successful!
Error, please refresh the page and try again.