Skip to content

Commit a0c2389

Browse files
committed
2023.15
1 parent a0c23bd commit a0c2389

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

php/2023/15/01.php

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
<?php
2+
3+
namespace Year2023\Day15;
4+
5+
$start = microtime(true);
6+
7+
#$in = file_get_contents('example.txt');
8+
$in = file_get_contents('input.txt');
9+
10+
$commands = explode(",", $in);
11+
12+
$boxes = array_fill(0, 256, []);
13+
14+
$part1Sum = 0;
15+
foreach ($commands as $command) {
16+
$part1Sum += hash($command);
17+
18+
if (preg_match('/(\w+)([=-])(\d*)/', $command, $out)) {
19+
[,$label, $operation, $focalLength] = $out;
20+
} else {
21+
die('no match');
22+
}
23+
24+
$boxNumber = hash($label);
25+
26+
if ($operation === '-') {
27+
if (isset($boxes[$boxNumber][$label])) {
28+
unset($boxes[$boxNumber][$label]);
29+
}
30+
} elseif ($operation === '=') {
31+
$boxes[$boxNumber][$label] = $focalLength;
32+
}
33+
}
34+
35+
$part2Sum = 0;
36+
foreach ($boxes as $boxNum => $box) {
37+
foreach (array_values($box) as $lensNum => $focalLength) {
38+
$part2Sum += ($boxNum+1) * ($lensNum+1) * $focalLength;
39+
}
40+
}
41+
42+
43+
44+
45+
46+
echo "\n", $part1Sum, "\n";
47+
echo "\n", $part2Sum, "\n";
48+
49+
50+
echo microtime(true) - $start;
51+
echo "\n";
52+
53+
54+
function hash(string $command): int
55+
{
56+
$val = 0;
57+
for ($i = 0, $iMax = strlen($command); $i < $iMax; $i++) {
58+
$val += ord($command[$i]);
59+
$val *= 17;
60+
$val %= 256;
61+
}
62+
63+
return $val;
64+
}
65+

php/2023/15/example.txt

73 Bytes
Binary file not shown.

php/2023/15/input.txt

22.4 KB
Binary file not shown.

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy