Day 14 Part 1

Summary

  1. The data is in a grid.
  2. Os can roll, #s can not, .s are empty space.
  3. “tilt” north so all roll-able rocks roll north.
  4. All the “load” value on the north wall. The values of rocks on row 0 are rock_count * (len(grid) - index)
Full challenge: Day 14

Formatting

Stealing from my playbook of Day 13’s Vertical Reflection Points I’m going to rotate the entire grid clockwise. The pros for this to me are:

  1. “Normal” Loop when calculating the roll, left to right.
  2. Value calc will be rock_count * index

In all challenges so far, my default way of importing the data is to read the file and split by \n. This gives me an array, string[], which each element being a row. From that this is how I then rotated it:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
function rotate_raw(data: string[]){
  let rotated_data: string[][] = [];
  let count: number = -1;
  data.forEach((row) => {
    row.split('').forEach((cell, index) => {
      if (count < index){
        rotated_data.push([cell]);
        count++;
      }else{
        rotated_data[index].push(cell);
      }
    });
  });
  rotated_data.forEach((row) => {
    row.reverse();
  });
  return rotated_data;
};

Rolling

Now that the data is in a format I like I need to figure out how to “roll” the rocks. Luckily, data[0][0] (which was the bottom left corner) is now the top left! I can scan left-to-right, picking up Os as I encounter them and once I hit a barrier I can “back up” placing rocks as I go.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function tilt_data(data: string[][]): string[][]{
  for (let i = 0; i < data.length; i++){
    let rollable_count: number = 0
    for (let j = 0; j < data[i].length; j++){
      if (data[i][j] === 'O'){
        // Pick up rocks
        rollable_count++;
        data[i][j] = '.';
      }else if (data[i][j] === '#' && rollable_count !== 0){
        // Back up, drop rocks.
        // Note: we should always have enough room
        for (let k = 0; k < rollable_count; k++){
          data[i][j-(1+k)] = 'O';
        };
        rollable_count = 0;
      }
    };

    if (rollable_count !== 0){
      // hit the end while still holding rocks
      const last_index = data[i].length - 1;
      for (let k = 0; k < rollable_count; k++){
        data[i][last_index-k] = 'O';
      };
    }

  };
  return data;
}

Getting the Sum

Because the data was rotated it’s as easy as looping an adding the index of item in the row to the total.

1
2
3
4
5
6
7
8
9
let sum: number = 0;
for (let i = 0; i < tilted_data.length; i++){
  for (let j = 0; j < tilted_data[i].length; j++){
    if (tilted_data[i][j] == 'O'){
      sum += j+1;
    }
  };
};
console.log(`Sum => ${sum}`);

On to Part 2!

comments powered by Disqus