-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay7.php
80 lines (63 loc) · 1.97 KB
/
Day7.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2021\Solutions\Day7;
use XonneX\AdventOfCode\Core\AbstractSolution;
use function array_sum;
use function explode;
use function range;
class Day7 extends AbstractSolution
{
public function __construct()
{
parent::__construct(2021, 7);
}
protected function partOne(string $input): string
{
$positions = explode(",", $input);
sort($positions);
$count = count($positions);
$index = floor($count / 2);
if ($count & 1) {
$medianPosition = $positions[$index];
} else {
$medianPosition = ($positions[$index - 1] + $positions[$index]) / 2;
}
$fuel = 0;
foreach ($positions as $position) {
if ($position > $medianPosition) {
$fuel += $position - $medianPosition;
} else {
$fuel += $medianPosition - $position;
}
}
return (string) $fuel;
}
protected function partTwo(string $input): string
{
$positions = explode(",", $input);
$sum = array_sum($positions);
$count = count($positions);
$averageLow = floor($sum / $count);
$averageHigh = ceil($sum / $count);
$fuelLow = 0;
foreach ($positions as $position) {
if ($position > $averageLow) {
$fuelLow += array_sum(range(1, $position - $averageLow));
} else {
$fuelLow += array_sum(range(1, $averageLow - $position));
}
}
$fuelHigh = 0;
foreach ($positions as $position) {
if ($position > $averageHigh) {
$fuelHigh += array_sum(range(1, $position - $averageHigh));
} else {
$fuelHigh += array_sum(range(1, $averageHigh - $position));
}
}
if ($fuelHigh > $fuelLow) {
return (string) $fuelLow;
}
return (string) $fuelHigh;
}
}