Skip to content

Commit

Permalink
Day 2 Part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
marshall-davis committed Dec 2, 2024
1 parent a5d6cdc commit e4446c0
Showing 1 changed file with 44 additions and 15 deletions.
59 changes: 44 additions & 15 deletions 2024/02/puzzle.php
Original file line number Diff line number Diff line change
@@ -1,30 +1,59 @@
<?php

$input = fopen('input.txt', 'r+');
$safe = 0 ;
$safe = 0;
$unsafe = 0;
while (!feof($input)) {
$readings = fgetcsv($input, separator: ' ');
$line = 0;

for($i = 0; $i < count($readings); $i++) {
if (array_key_exists($i+1, $readings) && abs($readings[$i] - $readings[$i+1]) > 3) {
echo "Difference is too great. {$readings[$i]} and " . $readings[$i+1] . PHP_EOL;
continue 2;
}
// This worked for Part 1, so assuming it checks out.
function checkReading(array $readings): ?int
{
for ($i = 0; $i < count($readings); $i++) {
if (array_key_exists($i + 1, $readings) && abs($readings[$i] - $readings[$i + 1]) > 3) {
return $i;

if (array_key_exists($i+1, $readings) && array_key_exists($i-1, $readings) && (($readings[$i-1] <=> $readings[$i]) !== ($readings[$i] <=> $readings[$i+1]))) {
echo 'Trend change. ' . join(', ', [$readings[$i-1], $readings[$i], $readings[$i+1]]) . PHP_EOL;
continue 2;
}

if (array_key_exists($i+1, $readings) && $readings[$i] == $readings[$i+1]) {
echo "No change! {$readings[$i]} {$readings[$i+1]}" . PHP_EOL;
if (array_key_exists($i + 1, $readings) && array_key_exists($i - 1,
$readings) && (($readings[$i - 1] <=> $readings[$i]) !== ($readings[$i] <=> $readings[$i + 1]))) {
return $i;
}

if (array_key_exists($i + 1, $readings) && $readings[$i] == $readings[$i + 1]) {
return $i;
}
}
return null;
}

function duplicateValues(array $readings): array
{
return array_keys(array_filter(array_count_values($readings), fn (int $count) => $count > 1));
}

++$safe;
while (!feof($input)) {
++$line;
$readings = fgetcsv($input, separator: ' ');

// Does the simple check work?
if (checkReading($readings) === null) {
// Great, easy!
++$safe;
continue;
}

for ($i = 0; $i < count($readings); $i++) {
$test = $readings;
array_splice($test, $i, 1);
if (checkReading($test) === null) {
// Great, easy!
++$safe;
continue 2; // Safe version found, next reading!
}
}
}

echo $safe . PHP_EOL;
if ($safe <= 488 || $safe >= 538) {
echo 'WRONG'.PHP_EOL;
}
echo $safe.PHP_EOL;

0 comments on commit e4446c0

Please sign in to comment.