-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDay2.php
61 lines (44 loc) · 1.74 KB
/
Day2.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
<?php
declare(strict_types=1);
namespace XonneX\AdventOfCode\Y2020\Solutions\Day2;
use XonneX\AdventOfCode\Core\AbstractSolution;
class Day2 extends AbstractSolution
{
public function __construct()
{
parent::__construct(2020, 2);
}
protected function partOne(string $input): string
{
$lines = explode("\n", $input);
$validPasswordCounter = 0;
foreach ($lines as $line) {
preg_match('/(\d*)-(\d*) (\w): (\w*)/', $line, $matches);
[1 => $minOccurrences, 2 => $maxOccurrences, 3 => $letter, 4 => $subject] = $matches;
$occurrences = substr_count($subject, $letter);
if ($occurrences >= (int) $minOccurrences && $occurrences <= (int) $maxOccurrences) {
$validPasswordCounter++;
}
}
return (string) $validPasswordCounter;
}
// TODO: Performance rewrite low priority
protected function partTwo(string $input): string
{
$lines = explode("\n", $input);
$validPasswordCounter = 0;
foreach ($lines as $line) {
preg_match('/(\d*)-(\d*) (\w): (\w*)/', $line, $matches);
[1 => $positionOne, 2 => $positionTwo, 3 => $letter, 4 => $subject] = $matches;
$letterPositionOne = substr($subject, (int) $positionOne - 1, 1);
$letterPositionTwo = substr($subject, (int) $positionTwo - 1, 1);
if ($letterPositionOne === $letter && $letterPositionTwo === $letter) {
continue;
}
if ($letterPositionOne === $letter || $letterPositionTwo === $letter) {
$validPasswordCounter++;
}
}
return (string) $validPasswordCounter;
}
}