summaryrefslogtreecommitdiff
path: root/php/2024/day_04/Grid.php
diff options
context:
space:
mode:
authorDJ O'Leary <dijitol@proton.me>2026-06-26 18:04:09 +0200
committerDJ O'Leary <dijitol@proton.me>2026-06-26 18:04:09 +0200
commit6d8fb621d1e93b83786890d6d9cb6f0d8defa8ae (patch)
tree17c90d3984c114aa023600cc5bec6f6004b02243 /php/2024/day_04/Grid.php
parentad4ea5ca4bc9f7540ee1d6a4fa2d881709dc6459 (diff)
refactor!: invert repo directory structure
now is language first
Diffstat (limited to 'php/2024/day_04/Grid.php')
-rw-r--r--php/2024/day_04/Grid.php69
1 files changed, 69 insertions, 0 deletions
diff --git a/php/2024/day_04/Grid.php b/php/2024/day_04/Grid.php
new file mode 100644
index 0000000..75d531b
--- /dev/null
+++ b/php/2024/day_04/Grid.php
@@ -0,0 +1,69 @@
+<?php
+
+declare(strict_types=1);
+
+class Grid implements Stringable
+{
+ /**
+ * @param string[][] $data
+ */
+ public function __construct(public array $data)
+ {
+ }
+
+ public function __toString(): string
+ {
+ $rowToLine = fn (array $row): string => array_reduce(
+ array: $row,
+ callback: fn (string $acc, string $character): string => $acc . $character,
+ initial: "",
+ );
+
+ return array_reduce(
+ array: $this->data,
+ callback: fn (string $acc, array $row): string => $acc . $rowToLine($row) . PHP_EOL,
+ initial: "",
+ );
+ }
+
+ public function getCharacterAtPosition(Position $position): string
+ {
+ if ($this->isInBounds($position)) {
+ return $this->data[$position->y][$position->x];
+ }
+
+ return ".";
+ }
+
+ /**
+ * @param Position[] $positions
+ */
+ public function getStringFromPositions(array $positions): string
+ {
+ $characters = array_map(
+ callback: fn (Position $position): string => $this->getCharacterAtPosition($position),
+ array: $positions,
+ );
+
+ $string = array_reduce(
+ array: $characters,
+ callback: fn (string $acc, string $character): string => $acc . $character,
+ initial: "",
+ );
+
+ return $string;
+ }
+
+ public function isInBounds(Position $position): bool
+ {
+ if (!array_key_exists($position->y, $this->data)) {
+ return false;
+ }
+
+ if (!array_key_exists($position->x, $this->data[$position->y])) {
+ return false;
+ }
+
+ return true;
+ }
+}