Benjamin Kraft 2 weeks ago
parent 7c5c56b581
commit c29d6d937b
  1. 16
      public/Day.php
  2. 46
      public/days/Day1.php
  3. 2
      public/fetch.php
  4. 38
      public/run.php

@ -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);
}
}

@ -8,7 +8,7 @@ foreach (parse_ini_file("../.env") as $key => $value){
for ($i = 1; $i <= 25; $i++){ for ($i = 1; $i <= 25; $i++){
$context = stream_context_create([ $context = stream_context_create([
'http' => [ 'http' => [
'header' => 'Cookie: session=' . $_ENV["SESSION_COOKIE"] . '\r\n' 'header' => 'Cookie: session=' . $_ENV["SESSION_COOKIE"] . "\r\n"
] ]
]); ]);
$contents = file_get_contents("https://adventofcode.com/2024/day/$i/input", context: $context); $contents = file_get_contents("https://adventofcode.com/2024/day/$i/input", context: $context);

@ -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…
Cancel
Save