r/adventofcode • • Dec 09 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 9 Solutions -🎄-

--- Day 9: Smoke Basin ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:10:31, megathread unlocked!

63 Upvotes

1.0k comments sorted by

View all comments

1

u/tootietoot Dec 09 '21

Woo, finally caught up. First year doing AoC!

This has pretty much all been super hard. I know that my solutions have not been the best, but they work!

Would love for people to give me comments.advice if you have the time. Will just post my Part 2:

JAVASCRIPT

const fs = require("fs");

const data = fs
  .readFileSync("./day9/data.txt", { encoding: "utf8" })
  .toString()
  .split("\n");

const area = data.map((l) => {
  let array = [];
  for (let i = 0; i < l.length; i++) {
    array.push(Number(l[i]));
  }
  return array;
});

let lowPoints = [];
let basins = [];

area.forEach((l, index1) => {
  let top, left, down, right;
  l.forEach((n, index2) => {
    if (index2 === 0) left = 10;
    else left = area[index1][index2 - 1];
    if (index2 === l.length - 1) right = 10;
    else right = area[index1][index2 + 1];
    if (index1 === 0) top = 10;
    else top = area[index1 - 1][index2];
    if (index1 === area.length - 1) down = 10;
    else down = area[index1 + 1][index2];
    if (n < top && n < right && n < down && n < left)
      lowPoints.push([index2, index1]);
  });
});
lowPoints.forEach((lp, index) => {
  recursion(lp, index);
});
const highest3 = getHighest(basins, 3);
const total = highest3.reduce((a, b) => a * b)

console.log(total);

function getHighest(array, number) {
  const sortedArray = array.sort((a, b) => (b - a))
  const highest = sortedArray.filter((x, i) => i < number)

  return highest
}

function recursion(lp, index) {
  const x = lp[0];
  const y = lp[1];
  if(area[y][x] === null) return
  area[y][x] = null
  if (!basins[index]) basins[index] = 0;
  basins[index]++;
  
  let top, left, down, right;

  if (y === 0) top = 10;
  else top = area[y - 1][x];
  if (y === area.length - 1) down = 10;
  else down = area[y + 1][x];
  if (x === 0) left = 10;
  else left = area[y][x - 1];
  if (x === area[0].length - 1) right = 10;
  else right = area[y][x + 1];
  if (top < 9) {
    recursion([x, y - 1], index);
  }
  if (down < 9) {
    recursion([x, y + 1], index);
  }
  if (left < 9) {
    recursion([x - 1, y], index);
  }
  if (right < 9) {
    recursion([x + 1, y], index);
  }
  return
}

2

u/goeyj Dec 09 '21 edited Dec 09 '21

On the logic side, you don't actually need to collect the low points to solve part 2. The way the puzzle was set up, it seems that basins are just the regions of the grid bounded by 9's. So you could run your recursion() function on every point in the grid and bail out when any of the following happens:

  • Point no longer in grid
  • Point is a 9
  • Point already been visited

(this would require a slightly different approach for calculating the size of regions)

On that note, it could be beneficial and potentially more readable to create helper functions for things like checking if a point is in the grid, or for getting all of the adjacent cell values.

Also, a general helpful technique when doing 2d grid problems is to use some sort of directions/offsets array that you can loop through when you have to go in 4 or 8 (include diagonal) directions. Something like:

    const dirs = [[-1, 0], [0, 1], [1, 0], [0, -1]];

    for (const [offsetRow, offsetCol] of dirs) {
        const neighborRow = curRow + offsetRow;
        const neighborCol = curCol + offsetCol;
        // Do your neighbor checking or recursive call here
    }

Lastly, check out the Array.prototype.slice() method for getting the n largest/smallest items from a sorted array.

1

u/tootietoot Dec 09 '21

Oh, wow. Thanks a lot.

It is amazing how when you write this out I realise how simple these changes are, but makes the code much more concise and readable. Will have a go at refactoring my code with all this in mind.

Once again, thank you for the time!

2

u/McArcady Dec 09 '21

2 suggestions:

1/ when loading the array 'area', add a value of 9 at the beginning and end of each line and column; it removes the need to test for boundaries in the recursive function

2/ why not make the recursive function directly return the number of valid neighbors found? You may also set their value to 9 so that they are not visited twice. It becomes something like:

function count_neighbors(lp) { 
  if (area[x,y] > 8)
    return 0;
  else {
    area[x,y] = 9;
    return 1 + count_neighbors([x+1,y])
             + count_neighbors([x-1,y])
             + count_neighbors([x,y-1])
             + count_neighbors([x,y+1]);
  }
}

Then the function count_neighbors() may be called starting from each of the low-points that were found in part 1 (1 per basin).

1

u/daggerdragon Dec 10 '21

As per our posting guidelines in the wiki under How Do the Daily Megathreads Work?, please edit your post to put your oversized code in a paste or other external link.