Untitled
unknown
php
21 days ago
4.0 kB
2
Indexable
<?php class BreakPieces { public function process($shape): array { $lines = explode("\n", $shape); $plusPositions = $this->findPlusPositions($lines); $rectangles = $this->findRectangles($plusPositions, $lines); return array_map([$this, 'generateRectangle'], $rectangles); } private function findPlusPositions($lines): array { $positions = []; foreach ($lines as $x => $line) { foreach (str_split($line) as $y => $char) { if ($char === '+') { $positions[] = new Pos($x, $y); } } } return $positions; } private function findRectangles($plusPositions, $lines): array { $rectangles = []; foreach ($plusPositions as $p1) { foreach ($plusPositions as $p2) { // Rechteck muss zwei Pluszeichen auf derselben Spalte und in vertikaler Ausrichtung haben if ($p1->x === $p2->x && $p1->y < $p2->y) { foreach ($plusPositions as $p3) { // Das dritte Pluszeichen muss sich auf derselben Reihe wie das erste befinden if ($p1->y === $p3->y && $p1->x < $p3->x) { // Berechnung der vierten Ecke $p4 = new Pos($p3->x, $p2->y); // Überprüfen, ob alle vier Ecken ein gültiges Rechteck bilden if (in_array($p4, $plusPositions, false) && $this->isValidRectangle($lines, $p1, $p2, $p3, $p4)) { $rectangles[] = [$p1, $p2, $p3, $p4]; } } } } } } return $rectangles; } private function isValidRectangle($lines, $p1, $p2, $p3, $p4): bool { // Überprüfen, ob der Bereich zwischen den Pluszeichen leer ist for ($x = $p1->x + 1; $x < $p3->x; $x++) { for ($y = $p1->y + 1; $y < $p2->y; $y++) { // Sicherstellen, dass der Index gültig ist, bevor auf das Zeichen zugegriffen wird if (isset($lines[$x][$y]) && $lines[$x][$y] !== ' ') { return false; } } } return true; } private function generateRectangle($rectangle): string { [$p1, $p2, $p3, $p4] = $rectangle; $width = $p2->y - $p1->y + 1; $height = $p3->x - $p1->x + 1; $output = "+" . str_repeat("-", $width - 2) . "+\n"; for ($i = 0; $i < $height - 2; $i++) { $output .= "|" . str_repeat(" ", $width - 2) . "|\n"; } $output .= "+" . str_repeat("-", $width - 2) . "+"; return $output; } } class Pos { public int $x, $y; public function __construct(int $x, int $y) { $this->x = $x; $this->y = $y; } } // Diese Formen gehen alle nciht $shape = implode("\n", [ "+-------------------+--+", "| | |", "| | |", "| +----------------+ |", "| | |", "| | |", "+--+-------------------+", ]); $shape3 = implode("\n", [ "+------------+", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "| |", "+---+ |", "| | |", "| | |", "| | |", "| | |", "+---+--------+" ]); $shape2 = implode("\n", [ "+-----------------+", "| |", "| +-------------+", "| |", "| |", "| |", "| +-------------+", "| |", "| |", "+-----------------+" ]); // Test der Form var_dump((new BreakPieces())->process($shape));
Editor is loading...
Leave a Comment