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

55 lines
1.4 KiB

<?php
// https://adventofcode.com/2018/day/1
function puzzle1(array $changes) : int
{
$frequency = 0;
foreach ($changes as $change) {
$frequency += $change;
}
return $frequency;
}
function puzzle2(array $changes) : int
{
$frequency = 0;
// Start building the frequency history with the current one
$history = [
$frequency => 1,
];
while (true) {
foreach ($changes as $change) {
$frequency += $change;
$history[$frequency]++;
if ($history[$frequency] == 2) {
return $frequency;
}
}
}
return $frequency;
}
echo 'First challange samples:'.PHP_EOL;
echo puzzle1(['+1','+1','+1']).PHP_EOL; // 3
echo puzzle1(['+1','+1','-2']).PHP_EOL; // 0
echo puzzle1(['-1','-2','-3']).PHP_EOL; // -6
echo 'First challange solution:'.PHP_EOL;
echo puzzle1(explode(PHP_EOL, trim(file_get_contents(dirname(__FILE__).'/input.txt')))).PHP_EOL.PHP_EOL;
echo 'Second challange samples:'.PHP_EOL;
echo puzzle2(['+1','-1']).PHP_EOL; // 0
echo puzzle2(['+3','+3','+4','-2','-4']).PHP_EOL; // 10
echo puzzle2(['-6','+3','+8','+5','-6']).PHP_EOL; // 5
echo puzzle2(['+7','+7','-2','-7','-4']).PHP_EOL; // 14
echo 'Second challange solution:'.PHP_EOL;
echo puzzle2(explode(PHP_EOL, trim(file_get_contents(dirname(__FILE__).'/input.txt')))).PHP_EOL.PHP_EOL;