Add day 1 '22 solution
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2022-12-01 09:48:03 +01:00
parent 64597b0860
commit d91701b50f
5 changed files with 2385 additions and 2 deletions

View File

@ -14,6 +14,11 @@ abstract class Solution
public static int|string|null $part2Result = null;
/**
* @var bool When false, do not apply the `array_filter` function when the data is loaded.
*/
public bool $filterDataOnLoad = true;
/**
* @var string[] The data to use.
*
@ -60,14 +65,14 @@ abstract class Solution
if (file_exists($dataFile)) {
$data = file_get_contents($dataFile);
if ($data !== false) {
$this->data = array_filter(explode(PHP_EOL, $data));
$this->data = $this->filterDataOnLoad ? array_filter(explode(PHP_EOL, $data)) : explode(PHP_EOL, $data);
}
}
if (file_exists($dataExampleFile)) {
$data = file_get_contents($dataExampleFile);
if ($data !== false) {
$this->exampleData = array_filter(explode(PHP_EOL, $data));
$this->exampleData = $this->filterDataOnLoad ? array_filter(explode(PHP_EOL, $data)) : explode(PHP_EOL, $data);
}
}
}

55
src/Y22/Day1.php Normal file
View File

@ -0,0 +1,55 @@
<?php
namespace trizz\AdventOfCode\Y22;
use trizz\AdventOfCode\Solution;
final class Day1 extends Solution
{
public static int|string|null $part1ExampleResult = 24000;
public static int|string|null $part1Result = 72240;
public static int|string|null $part2ExampleResult = 45000;
public static int|string|null $part2Result = 210957;
public bool $filterDataOnLoad = false;
public function part1(array $data): int
{
return $this->calculateCalories($data)[0];
}
public function part2(array $data): int
{
$results = $this->calculateCalories($data);
return $results[0] + $results[1] + $results[2];
}
/**
* @param string[] $data
*
* @return int[]
*/
private function calculateCalories(array $data): array
{
$results = [];
$tmpResult = 0;
foreach ($data as $value) {
if ($value !== '') {
$tmpResult += (int) $value;
continue;
}
$results[] = $tmpResult;
$tmpResult = 0;
}
rsort($results);
return $results;
}
}