[php] AOC day 9 both
Viewer
*** This page was generated with the meta tag "noindex, nofollow". This happened because you selected this option before saving or the system detected it as spam. This means that this page will never get into the search engines and the search bot will not crawl it. There is nothing to worry about, you can still share it with anyone.
- <?php
- require __DIR__ . '/vendor/autoload.php';
- use \drupol\phpermutations;
- class XMAS
- {
- private $list = [];
- public function load() : void {
- $this->list = file(__DIR__ . '/input.txt');
- $this->list = array_map('intval', $this->list);
- }
- public function find_error() : int
- {
- for ($i=25; $i < sizeof($this->list); $i++) {
- $offset = $i-25;
- $preamble = array_slice($this->list, $offset, 25);
- $combinations = new phpermutations\Generators\Combinations($preamble, 2);
- $valid = false;
- foreach ($combinations as $comb) {
- if ($comb[0] + $comb[1] == $this->list[$i]) {
- $valid = true;
- break;
- }
- }
- if(!$valid) {
- return $this->list[$i];
- }
- }
- throw new Exception("no error found", 1);
- return 42;
- }
- public function find_weakness(int $error) : int
- {
- for ($length=2; $length <= sizeof($this->list); $length++) {
- for ($offset=0; $offset < sizeof($this->list)-$length; $offset++) {
- $slice = array_slice($this->list, $offset, $length);
- if (array_sum($slice) == $error) {
- return min($slice) + max($slice);
- }
- }
- }
- throw new Exception("no weakness found", 1);
- return 42;
- }
- }
- $xmas = new XMAS();
- $xmas->load();
- echo('Part 1:'.PHP_EOL);
- $error = $xmas->find_error();
- echo ("invalid: $error\n\n");
- echo('Part 2:'.PHP_EOL);
- $weak = $xmas->find_weakness($error);
- echo ("weakness: $weak\n");
Editor
You can edit this paste and save as new:
File Description
- AOC day 9 both
- Paste Code
- 10 Dec-2020
- 1.67 Kb
You can Share it: