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

39 lines
887 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
{
for ($i = 0; $i < count($nums); $i++) {
for ($j = 0; $j < count($nums); $j++) {
if ($nums[$i] + $nums[$j] == 2020) {
return $nums[$i] * $nums[$j];
}
}
}
return 0;
}
function solve_part_two(array $nums): int
{
for ($i = 0; $i < count($nums); $i++) {
for ($j = 0; $j < count($nums); $j++) {
for ($k = 0; $k < count($nums); $k++) {
if ($nums[$i] + $nums[$j] + $nums[$k] == 2020) {
return $nums[$i] * $nums[$j] * $nums[$k];
}
}
}
}
return 0;
}