1
0
Fork 0
advent-of-code/2021/day1.php

36 lines
805 B
PHP
Raw Normal View History

2024-02-08 09:55:40 +01:00
<?php
$input_file = '../inputs/day1.txt';
if (file_exists($input_file)) {
$input = file_get_contents($input_file);
if ($input != null) {
$nums = array_map(fn ($str) => (int)$str, array_filter(explode("\n", $input), 'is_numeric'));
print 'Part 1 answer: ' . solve_part_one($nums) . "\n";
print 'Part 2 answer: ' . solve_part_two($nums) . "\n";
}
}
function solve_part_one(array $nums): int
{
$inc = 0;
for ($i = 1; $i < count($nums); $i++) {
if ($nums[$i] > $nums[$i - 1]) {
$inc += 1;
}
}
return $inc;
}
function solve_part_two(array $nums): int
{
$inc = 0;
for ($i = 3; $i < count($nums); $i++) {
$slider1 = $nums[$i] + $nums[$i - 1] + $nums[$i - 2];
$slider2 = $nums[$i - 1] + $nums[$i - 2] + $nums[$i - 3];
if ($slider1 > $slider2) {
$inc += 1;
}
}
return $inc;
}