summaryrefslogtreecommitdiff
path: root/2024/PHP/day_04/Grid.php
blob: c0382df69bc62a79a45d519d436ff79038116904 (plain)
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
62
63
64
65
66
67
<?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;
	}
}