Skip to main content
🎄 Advent of Code Day 09
  1. Posts/

🎄 Advent of Code Day 09

·382 words·2 mins·
AdventOfCode
May Meow
Author
May Meow
MayMeow is a developer and cybersecurity enthusiast with a passion for cryptography, DevSecOps, and open-source contributions. They enjoy creating tools that strengthen digital security, blending creativity and technology to innovate in fields like PHP and .NET. Always exploring new frontiers in tech, MayMeow is dedicated to safeguarding the digital landscape through their work.

Today’s problem contains a prediction of the next values for the Oasis and Sand instability sensors. You are looking at the report that contains the history. This report looks like this and you need to predict next values.

0 3 6 9 12 15
1 3 6 10 15 21
10 13 16 21 30 45

To do this, you must create a new sequence by doing the difference at each step of your history. If the new sequence is not all zeros, you have to repeat the process with the sequence you just created. At the end you will have a bunch of sequences that look like this.

0   3   6   9  12  15
  3   3   3   3   3
    0   0   0   0

I created these sequences by iterating over all the rows and creating a difference for each element in the row.

foreach ($histories as $index => $history) {
    $rows[$index][] = $history;
    $row = $history;

    while (array_sum($row) != 0) {
        $row = calculateNexRow($row);
        $rows[$index][] = $row;
    }
}

function calculateNexRow($row)
{
    $values = [];
    for ($i = 0; $i <= count($row) -2; $i++) {
        $s = $row[$i + 1] - $row[$i];
        $values[] = $s;
    }

    return $values;
}

This returned me multiple arrays

Row: 0
Step 0.0 -> 0 3 6 9 12 15
Step 0.1 -> 3 3 3 3 3
Step 0.2 -> 0 0 0 0
Row: 1
Step 1.0 -> 1 3 6 10 15 21
Step 1.1 -> 2 3 4 5 6
Step 1.2 -> 1 1 1 1
Step 1.3 -> 0 0 0
Row: 2
Step 2.0 -> 10 13 16 21 30 45
Step 2.1 -> 3 3 5 9 15
Step 2.2 -> 0 2 4 6
Step 2.3 -> 2 2 2
Step 2.4 -> 0 0

I get the next values by summing the last number from each row by iterating over them. Here is example for the first row 0 + 3 +15 = 18. Next rows get 28, and 68 which on total gives me 114.

$sum = 0;
foreach ($rows as $index => $row) {
    $nextValue = 0;
    foreach ($row as $rowIndex => $rowValue) {
        $nextValue += $rowValue[array_key_last($rowValue)];
    }
    $sum += $nextValue;
}

That was it! Part 1 for me today.

MayMeow/advent-of-code

PHP
0
0
Reply by Email

Related

🎄 Advent of Code Day 08
·916 words·5 mins
AdventOfCode
65738938e130b
·5 words·1 min
6572356209197
·24 words·1 min