You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.5 KiB
PHP

<?php
// https://adventofcode.com/2017/day/2
function puzzle1(string $input) : int
{
$rows = array_filter(explode(PHP_EOL, $input));
$sum = 0;
foreach ($rows as $row) {
$columns = explode("\t", $row);
sort($columns);
$small = array_shift($columns);
$big = array_pop($columns);
$sum += ($big - $small);
}
return $sum;
}
function puzzle2(string $input) : int
{
$rows = array_filter(explode(PHP_EOL, $input));
$sum = 0;
foreach ($rows as $row) {
$columns = explode("\t", $row);
foreach ($columns as $key1 => $value1) {
foreach ($columns as $key2 => $value2) {
if ($key1 === $key2) {
continue;
}
if ($value1 < $value2) {
continue;
}
// Do the actual division
$div = $value1 / $value2;
if (intval($div) === $div) {
$sum += $div;
}
}
}
}
return $sum;
}
echo 'First challange sample:'.PHP_EOL;
echo puzzle1('5 1 9 5
7 5 3
2 4 6 8').PHP_EOL.PHP_EOL;
echo 'First challange solution:'.PHP_EOL;
echo puzzle1(file_get_contents(dirname(__FILE__).'/input.txt')).PHP_EOL.PHP_EOL;
echo 'Second challenge sample:'.PHP_EOL;
echo puzzle2('5 9 2 8
9 4 7 3
3 8 6 5').PHP_EOL.PHP_EOL;
echo 'Second challange solution:'.PHP_EOL;
echo puzzle2(file_get_contents(dirname(__FILE__).'/input.txt')).PHP_EOL.PHP_EOL;