-
Notifications
You must be signed in to change notification settings - Fork 0
/
Puzzle06.php
60 lines (47 loc) · 1.42 KB
/
Puzzle06.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
<?php declare(strict_types=1);
namespace AdventOfCode2020;
echo sprintf('Puzzle 6 part 1: %d'.PHP_EOL, (new Puzzle06())->part1());
echo sprintf('Puzzle 6 part 2: %d'.PHP_EOL, (new Puzzle06())->part2());
final class Puzzle06
{
public function part1(): int
{
$totalCount = 0;
foreach ($this->getGroups() as $group) {
$groupString = implode('', $group);
$totalCount += strlen(count_chars($groupString, 3));
}
return $totalCount;
}
public function part2(): int
{
$totalCount = 0;
foreach ($this->getGroups() as $group) {
$groupCount = count($group);
$groupString = implode('', $group);
$questionsAnswered = count_chars($groupString, 1);
foreach ($questionsAnswered as $questionAnswered) {
if ($questionAnswered === $groupCount) {
$totalCount++;
}
}
}
return $totalCount;
}
private function getGroups(): array
{
$fp = @fopen('Input06.txt', 'rb');
$groups = [];
$i = 0;
if ($fp) {
while (($line = fgets($fp, 4096)) !== false) {
if ("\n" !== $line) {
$groups[$i][] = trim(preg_replace('/\s+/', ' ', $line));
} else {
$i++;
}
}
}
return $groups;
}
}