parent
7c5c56b581
commit
c29d6d937b
4 changed files with 101 additions and 1 deletions
@ -0,0 +1,16 @@ |
||||
<?php |
||||
|
||||
abstract class Day { |
||||
|
||||
/* @var $input array<string> */ |
||||
protected array $input; |
||||
|
||||
public function __construct() { |
||||
$number = explode("Day", get_class($this))[1]; |
||||
|
||||
$this->input = explode("\n", file_get_contents("../input/$number.txt"), -1); |
||||
} |
||||
|
||||
abstract function part1(): string; |
||||
abstract function part2(): string; |
||||
} |
@ -0,0 +1,46 @@ |
||||
<?php |
||||
|
||||
final class Day1 extends Day { |
||||
|
||||
function part1(): string { |
||||
$left = []; |
||||
$right = []; |
||||
|
||||
foreach ($this->input as $line){ |
||||
[$left[], $right[]] = array_map("intval", explode(" ", $line)); |
||||
} |
||||
|
||||
sort($left); |
||||
sort($right); |
||||
|
||||
$sum = 0; |
||||
|
||||
for ($i = 0; $i < count($left); $i++){ |
||||
$sum += abs($left[$i] - $right[$i]); |
||||
} |
||||
|
||||
return strval($sum); |
||||
} |
||||
|
||||
function part2(): string { |
||||
$left = []; |
||||
$rightCounts = []; |
||||
|
||||
foreach ($this->input as $line){ |
||||
[$left[], $right] = array_map("intval", explode(" ", $line)); |
||||
if (array_key_exists($right, $rightCounts)){ |
||||
$rightCounts[$right]++; |
||||
} else { |
||||
$rightCounts[$right] = 1; |
||||
} |
||||
} |
||||
|
||||
$sum = 0; |
||||
|
||||
foreach ($left as $number){ |
||||
$sum += $number * ($rightCounts[$number] ?? 0); |
||||
} |
||||
|
||||
return strval($sum); |
||||
} |
||||
} |
@ -0,0 +1,38 @@ |
||||
<?php |
||||
|
||||
header('Content-Type: application/json'); |
||||
|
||||
require_once 'Day.php'; |
||||
|
||||
$dayNumber = $_GET['day'] ?? null; |
||||
$part = intval($_GET['part'] ?? 1); |
||||
|
||||
if ($dayNumber){ |
||||
$file = "days/Day$dayNumber.php"; |
||||
if (file_exists($file)){ |
||||
require_once $file; |
||||
$class = "Day$dayNumber"; |
||||
|
||||
/* @var $day Day */ |
||||
$day = new $class(); |
||||
|
||||
$method = "part$part"; |
||||
if (method_exists($day, $method)){ |
||||
$t1 = microtime(true); |
||||
$result = $day->$method(); |
||||
$t2 = microtime(true); |
||||
|
||||
$time = $t2 - $t1; |
||||
|
||||
$response = [ |
||||
'result' => $result, |
||||
'time' => $time, |
||||
'data' => null |
||||
]; |
||||
|
||||
|
||||
echo json_encode($response); |
||||
die(); |
||||
} |
||||
} |
||||
} |
Loading…
Reference in new issue