Skip to content

Commit a0ce7c4

Browse files
committed
2023.05.1
1 parent a0ccb56 commit a0ce7c4

File tree

3 files changed

+77
-0
lines changed

3 files changed

+77
-0
lines changed

php/2023/05/01.php

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
<?php
2+
3+
namespace Year2023\Day05;
4+
5+
#$input = file_get_contents('example.txt');
6+
$input = file_get_contents('input.txt');
7+
8+
class Map
9+
{
10+
/** @var Range[] */
11+
private array $ranges = [];
12+
public function __construct(string $input)
13+
{
14+
$lines = explode("\n", $input);
15+
array_shift($lines);
16+
foreach ($lines as $line) {
17+
$this->ranges[] = new Range($line);
18+
}
19+
}
20+
21+
public function convert(int $in): int
22+
{
23+
foreach ($this->ranges as $range) {
24+
if (null !== ($result = $range->convert($in))) {
25+
return $result;
26+
}
27+
}
28+
return $in;
29+
}
30+
}
31+
32+
class Range
33+
{
34+
private int $destination;
35+
private int $source;
36+
private int $length;
37+
public function __construct(string $input)
38+
{
39+
[$this->destination, $this->source, $this->length] = explode(" ", $input);
40+
}
41+
42+
public function convert(int $in): ?int
43+
{
44+
if ($in >= $this->source && $in <= $this->source + $this->length) {
45+
return $in - ($this->source - $this->destination);
46+
}
47+
return null;
48+
}
49+
}
50+
51+
52+
53+
$blocks = explode("\n\n", $input);
54+
$seeds = explode(" ", array_shift($blocks));
55+
array_shift($seeds);
56+
57+
$maps = [];
58+
foreach ($blocks as $block) {
59+
$maps[] = new Map($block);
60+
}
61+
62+
$locations = [];
63+
foreach ($seeds as $seed) {
64+
$location = $seed;
65+
foreach ($maps as $map) {
66+
$location = $map->convert($location);
67+
}
68+
69+
$locations[] = $location;
70+
echo $seed, " -> ", $location, "\n";
71+
}
72+
73+
echo "lowest: ", min($locations);
74+
75+
echo "\n";
76+
77+

php/2023/05/example.txt

361 Bytes
Binary file not shown.

php/2023/05/input.txt

7.72 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