Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class Matrix
- {
- private const COLORS = [
- '41',
- '42',
- '43',
- '44',
- '46',
- ];
- private $n;
- private $m;
- private $items;
- private $processedMap;
- private $blocks;
- public function __construct(int $n, int $m)
- {
- $this->n = $n;
- $this->m = $m;
- $this->reset();
- }
- public function reset(): void
- {
- $this->items = [];
- $this->processedMap = [];
- $this->blocks = [];
- for ($i = 0; $i < $this->n; $i++) {
- $this->items[$i] = [];
- $this->processedMap[$i] = [];
- for ($j = 0; $j < $this->m; $j++) {
- $this->items[$i][$j] = rand(0, count(self::COLORS) - 1);
- $this->processedMap[$i][$j] = 0;
- }
- }
- foreach (self::COLORS as $color => $_) {
- $this->blocks[$color] = 0;
- }
- }
- public function print(bool $printHeader = false): void
- {
- if ($printHeader) {
- print 'X';
- for ($i = 0; $i < count($this->items[0]); $i++) {
- print ' | ' . $i;
- }
- print PHP_EOL;
- }
- foreach ($this->items as $j => $row) {
- if ($printHeader) {
- print $j;
- }
- $colorizedRow = array_map([$this, 'getColorizedOutput'], $row);
- print implode('', $colorizedRow) . PHP_EOL;
- }
- }
- public function compute(): void
- {
- foreach ($this->items as $i => $row) {
- foreach ($row as $j => $color) {
- if ($this->processedMap[$i][$j]) {
- continue;
- }
- $blockSize = $this->passBlock($i, $j);
- $this->blocks[$color] = max($this->blocks[$color], $blockSize);
- }
- }
- foreach ($this->blocks as $color => $size) {
- print $this->getColorizedOutput($color) . ': ' . $size . PHP_EOL;
- }
- }
- private function passBlock(int $i, int $j): int
- {
- if (!isset($this->items[$i][$j]) || $this->processedMap[$i][$j]) {
- return 0;
- }
- $this->visit($i, $j);
- $possibleNeighbors = [
- [$i + 1, $j],
- [$i - 1, $j],
- [$i, $j + 1],
- [$i, $j - 1],
- ];
- $currentStepResult = 1;
- foreach ($possibleNeighbors as $index) {
- list($nearI, $nearJ) = $index;
- if ($this->items[$i][$j] === $this->items[$nearI][$nearJ]) {
- $currentStepResult += $this->passBlock($nearI, $nearJ);
- }
- }
- return $currentStepResult;
- }
- private function visit(int $i, int $j): void
- {
- $this->processedMap[$i][$j] = 1;
- }
- private function getColorizedOutput(int $color): string
- {
- return "\e[1;37;" . self::COLORS[$color] . "m " . $color . " \e[0m";
- }
- }
- $matrix = new Matrix(40, 50);
- $matrix->print();
- $matrix->compute();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement