Browse Source

[2018-12-01] Add second challange samples and solution

master
Elis Hirwing 3 years ago
parent
commit
39b53dc09e
Signed by: etu GPG Key ID: D57EFA625C9A925F
  1. 34
      day1/main.php

34
day1/main.php

@ -12,6 +12,30 @@ function puzzle1(array $changes) : int
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
@ -19,3 +43,13 @@ 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;

Loading…
Cancel
Save