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

Skip to content

Commit 1e9009c

Browse files
committed
Day3
1 parent 72cf0eb commit 1e9009c

File tree

1 file changed

+83
-0
lines changed

1 file changed

+83
-0
lines changed

src/Days/Day3.php

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
<?php
2+
3+
namespace Failedcode\Aoc2022\Days;
4+
5+
class Day3 extends AbstractDay
6+
{
7+
public function solve_part_1(): string
8+
{
9+
$inputList = $this->util->loadInput(3);
10+
$prioritySum = 0;
11+
foreach ($inputList as $row) {
12+
if (empty($row)) {
13+
continue;
14+
}
15+
$len = strlen($row)/2;
16+
$left = $this->charMap(substr($row, 0, $len));
17+
$right = str_split(substr($row, $len));
18+
foreach ($right as $char) {
19+
if (isset($left[$char])) {
20+
$prioritySum += $this->charValue($char);
21+
break;
22+
}
23+
}
24+
}
25+
return $prioritySum;
26+
}
27+
28+
public function solve_part_2(): string
29+
{
30+
$inputList = $this->util->loadInput(3);
31+
$chunkedList = $this->chunkArray($inputList, 3);
32+
$prioritySum = 0;
33+
foreach ($chunkedList as $team) {
34+
$charMap = [];
35+
foreach ($team as $row) {
36+
$chars = array_unique(str_split($row));
37+
foreach ($chars as $char) {
38+
if (!isset($charMap[$char])) {
39+
$charMap[$char] = 0;
40+
}
41+
$charMap[$char] += 1;
42+
if ($charMap[$char] === 3) {
43+
$prioritySum += $this->charValue($char);
44+
break 2;
45+
}
46+
}
47+
}
48+
}
49+
return $prioritySum;
50+
}
51+
52+
protected function chunkArray($array, $chunkSize)
53+
{
54+
$result = [];
55+
$currentChunk = [];
56+
foreach ($array as $element) {
57+
$currentChunk[] = $element;
58+
if (count($currentChunk) === $chunkSize) {
59+
$result[] = $currentChunk;
60+
$currentChunk = [];
61+
}
62+
}
63+
return $result;
64+
}
65+
66+
protected function charMap($string)
67+
{
68+
$chars = str_split($string);
69+
$charMap = [];
70+
foreach ($chars as $char) {
71+
$charMap[$char] = 0;
72+
}
73+
return $charMap;
74+
}
75+
76+
protected function charValue($char)
77+
{
78+
if ($char === strtolower($char)) {
79+
return ord($char) - ord('a') + 1;
80+
}
81+
return ord($char) - ord('A') + 1 + 26;
82+
}
83+
}

0 commit comments

Comments
 (0)
0