Add day 1 '22 solution
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
@ -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
55
src/Y22/Day1.php
Normal 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;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user