*/ private array $taken = []; public function __construct(public readonly int $w, public readonly int $h) {} /** @param iterable $rects */ public static function with(int $w, int $h, iterable $rects): self { $grid = new self($w, $h); foreach ($rects as $r) { $grid->take($r['x'], $r['y'], $r['w'], $r['h']); } return $grid; } public function take(int $x, int $y, int $w, int $h): void { foreach ($this->cells($x, $y, $w, $h) as $cell) { $this->taken[$cell] = true; } } /** A [0, 0] footprint (the wall) takes no cells and always fits. */ public function fits(int $w, int $h, int $x, int $y): bool { if ($w === 0 || $h === 0) { return true; } if ($x < 0 || $y < 0 || $x + $w > $this->w || $y + $h > $this->h) { return false; } foreach ($this->cells($x, $y, $w, $h) as $cell) { if (isset($this->taken[$cell])) { return false; } } return true; } /** First free position scanning rows top to bottom, or null when it doesn't fit anywhere. */ public function freeSlot(int $w, int $h): ?array { if ($w === 0 || $h === 0) { return ['x' => 0, 'y' => 0]; } for ($y = 0; $y + $h <= $this->h; $y++) { for ($x = 0; $x + $w <= $this->w; $x++) { if ($this->fits($w, $h, $x, $y)) { return ['x' => $x, 'y' => $y]; } } } return null; } /** @return list */ private function cells(int $x, int $y, int $w, int $h): array { $cells = []; for ($dy = 0; $dy < $h; $dy++) { for ($dx = 0; $dx < $w; $dx++) { $cells[] = ($x + $dx).','.($y + $dy); } } return $cells; } }