From 39b53dc09ebcc051475e8fb26b504b27cda4e9a0 Mon Sep 17 00:00:00 2001 From: Elis Hirwing Date: Sat, 1 Dec 2018 08:50:11 +0100 Subject: [PATCH] [2018-12-01] Add second challange samples and solution --- day1/main.php | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/day1/main.php b/day1/main.php index 384efa4..ea2d515 100644 --- a/day1/main.php +++ b/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;