[php] AOC day 9 both

Viewer

copydownloadembedprintName: AOC day 9 both
  1. <?php
  2. require __DIR__ . '/vendor/autoload.php';
  3.  
  4. use \drupol\phpermutations;
  5.  
  6. class XMAS
  7. {
  8.     private $list = [];
  9.  
  10.     public function load() : void {
  11.         $this->list = file(__DIR__ . '/input.txt');
  12.         $this->list = array_map('intval', $this->list);
  13.     }
  14.  
  15.     public function find_error() : int
  16.     {
  17.         for ($i=25; $i < sizeof($this->list); $i++) {
  18.             $offset = $i-25;
  19.             $preamble = array_slice($this->list, $offset, 25);
  20.             $combinations = new phpermutations\Generators\Combinations($preamble, 2);
  21.             $valid = false;
  22.             foreach ($combinations as $comb) {
  23.                 if ($comb[0] + $comb[1] == $this->list[$i]) {
  24.                     $valid = true;
  25.                     break;
  26.                 }
  27.             }
  28.             if(!$valid) {
  29.                 return $this->list[$i];
  30.             }
  31.         }
  32.         throw new Exception("no error found", 1);
  33.         return 42;
  34.     }
  35.  
  36.     public function find_weakness(int $error) : int
  37.     {
  38.         for ($length=2; $length <= sizeof($this->list); $length++) {
  39.             for ($offset=0; $offset < sizeof($this->list)-$length; $offset++) {
  40.                 $slice = array_slice($this->list, $offset, $length);
  41.                 if (array_sum($slice) == $error) {
  42.                     return min($slice) + max($slice);
  43.                 }
  44.             }
  45.         }
  46.         throw new Exception("no weakness found", 1);
  47.         return 42;
  48.     }
  49. }
  50.  
  51. $xmas = new XMAS();
  52. $xmas->load();
  53. echo('Part 1:'.PHP_EOL);
  54. $error = $xmas->find_error();
  55. echo ("invalid: $error\n\n");
  56.  
  57. echo('Part 2:'.PHP_EOL);
  58. $weak = $xmas->find_weakness($error);
  59. echo ("weakness: $weak\n");

Editor

You can edit this paste and save as new: