#!/usr/local/bin/php adapters = file(__DIR__.'/input.txt'); $this->adapters = array_map('intval', $this->adapters); $this->phone = max($this->adapters) + 3; array_push($this->adapters, $this->phone); sort($this->adapters); } public function part1() : int { $jolts = 0; $three_gaps = 0; $one_gaps = 0; foreach ($this->adapters as $adapter) { if ($adapter - $jolts < 1 || $adapter - $jolts > 3) { throw new Exception("no chain possible between $adapter and $jolts", 1); } if ($adapter - $jolts == 1) { $one_gaps += 1; } elseif ($adapter - $jolts == 3) { $three_gaps += 1; } $jolts = $adapter; } return $three_gaps * $one_gaps; } public function part2() : int { return $this->count_combos(0, $this->phone); } private function count_combos($start, $end) : int { if ($start + 3 == $end) { return 1; } elseif ($start + 3 > $end) { throw new Exception("should be unreachable", 1); } $combos = 0; foreach ([1, 2, 3] as $offset) { if (in_array($start + $offset, $this->adapters)) { if (!isset($this->cache[$start + $offset])) { $this->cache[$start + $offset] = $this->count_combos($start + $offset, $end); } $combos += $this->cache[$start + $offset]; } } return $combos; } } $ja = new JoltageAdapters(); $part1 = $ja->part1(); echo("Part 1 solution: $part1\n"); $part2 = $ja->part2($ja->adapters); echo("Part 2 solution: $part2\n");