fixed
unknown
php
8 months ago
3.2 kB
13
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) {
if ($p1->x === $p2->x && $p1->y < $p2->y) {
foreach ($plusPositions as $p3) {
if ($p1->y === $p3->y && $p1->x < $p3->x) {
$p4 = new Pos($p3->x, $p2->y);
if (in_array($p4, $plusPositions, false) && $this->isValidRectangle($lines, $p1, $p2, $p3, $p4)) {
// Rechteck nur hinzufügen, wenn es die richtige Struktur hat
$rectangles[] = [$p1, $p2, $p3, $p4];
}
}
}
}
}
}
return $rectangles;
}
private function isValidRectangle($lines, $p1, $p2, $p3, $p4): bool
{
// Überprüfen, ob die Mitte des Rechtecks nur aus Leerzeichen besteht
for ($x = $p1->x + 1; $x < $p3->x; $x++) {
for ($y = $p1->y + 1; $y < $p2->y; $y++) {
if ($lines[$x][$y] !== ' ') {
return false;
}
}
}
return true;
}
private function generateRectangle($rectangle): string
{
[$p1, $p2, $p3, $p4] = $rectangle;
$width = $p2->y - $p1->y + 1; // Korrekte Berechnung der Breite
$height = $p3->x - $p1->x + 1; // Korrekte Berechnung der Höhe
$output = "+" . str_repeat("-", $width - 2) . "+\n"; // Formatierung der oberen Grenze
for ($i = 0; $i < $height - 2; $i++) {
$output .= "|" . str_repeat(" ", $width - 2) . "|\n"; // Leere Linien für die Höhe
}
$output .= "+" . str_repeat("-", $width - 2) . "+"; // Formatierung der unteren Grenze
return $output;
}
}
class Pos
{
public int $x, $y;
public function __construct(int $x, int $y) { $this->x = $x; $this->y = $y; }
}
$shape = implode("\n", [
"+------------+",
"| |",
"| |",
"| |",
"| |",
"+-----+------+",
"| | |",
"+-----+------+"
]);
var_dump((new BreakPieces())->process($shape));
$result = [
[
"+------------+",
"| |",
"| |",
"| |",
"| |",
"+------------+"
],
[
"+-----+",
"| |",
"+-----+"
],
[
"+------+",
"| |",
"+------+"
]
];
Editor is loading...
Leave a Comment