8000 Day1 · FailedCode/adventofcode-2022-php@bbd577c · GitHub
[go: up one dir, main page]

Skip to content

Commit bbd577c

Browse files
committed
Day1
1 parent 28e7f6a commit bbd577c

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

src/Days/AbstractDay.php

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,8 +2,17 @@
22

33
namespace Failedcode\Aoc2022\Days;
44

5+
use Failedcode\Aoc2022\Utils;
6+
57
abstract class AbstractDay
68
{
9+
protected Utils $util;
10+
11+
public function __construct()
12+
{
13+
$this->util = new Utils();
14+
}
15+
716
public function solve_part_1(): string
817
{
918
return "TODO";

src/Days/Day1.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,4 +5,38 @@
55
class Day1 extends AbstractDay
66
{
77

8+
public function solve_part_1(): string
9+
{
10+
$calories = $this->getCalories();
11+
return max($calories);
12+
}
13+
14+
public function solve_part_2(): string
15+
{
16+
$calories = $this->getCalories();
17+
$caloriesMax = 0;
18+
for ($i = 0; $i < 3; $i += 1) {
19+
$maxVal = max($calories);
20+
$position = array_search($maxVal, $calories);
21+
unset($calories[$position]);
22+
$caloriesMax += (int)$maxVal;
23+
}
24+
return $caloriesMax;
25+
}
26+
27+
public function getCalories(): array
28+
{
29+
$list = $this->util->loadInput(1);
30+
$calories = [];
31+
$currentSum = 0;
32+
foreach ($list as $row) {
33+
if (trim($row) === '') {
34+
$calories[] = $currentSum;
35+
$currentSum = 0;
36+
continue;
37+
}
38+
$currentSum += (int)$row;
39+
}
40+
return $calories;
41+
}
842
}

src/Utils.php

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<?php
2+
3+
namespace Failedcode\Aoc2022;
4+
5+
class Utils
6+
{
7+
public function loadInput($day, $type="day"): array
8+
{
9+
$filePath = "input/{$type}{$day}.txt";
10+
if (!file_exists($filePath)) {
11+
// TODO: download input
12+
throw new \Exception("Input missing: '$filePath'", 1670457206416);
13+
}
14+
$content = file_get_contents($filePath);
15+
return explode("\n", $content);
16+
}
17+
}

0 commit comments

Comments
 (0)
0