Skip to content

Instantly share code, notes, and snippets.

@lechuhuuha
Created July 15, 2024 05:21
Show Gist options
  • Save lechuhuuha/a8c3f43e6f10bb4e4b69ec5fac174571 to your computer and use it in GitHub Desktop.
Save lechuhuuha/a8c3f43e6f10bb4e4b69ec5fac174571 to your computer and use it in GitHub Desktop.
test
<?php
function createField($H, $W)
{
$field = array();
for ($i = 0; $i < $H; $i++) {
$field[] = array_fill(0, $W, '.');
}
return $field;
}
function dropBlock(&$field, $H, $W, $h, $w, $x)
{
// Find the lowest position the block can land
$lowest_position = $H - $h;
for ($i = 0; $i <= $H - $h; $i++) {
for ($j = 0; $j < $w; $j++) {
if ($field[$i + $h - 1][$x + $j] == '#') {
$lowest_position = min($lowest_position, $i - 1);
break;
}
}
for ($j = 0; $j < $h; $j++) {
if ($field[$i + $j][$x] == '#') {
$lowest_position = min($lowest_position, $i - 1);
break;
}
}
}
// Place the block
for ($i = 0; $i < $h; $i++) {
for ($j = 0; $j < $w; $j++) {
$field[$lowest_position + $i][$x + $j] = '#';
}
}
}
function printField($field, $H, $W)
{
for ($i = 0; $i < $H; $i++) {
echo implode('', $field[$i]) . "\n";
}
}
// Example usage
function runGame($H, $W, $N, $blocks)
{
$field = createField($H, $W);
foreach ($blocks as $block) {
list($h, $w, $x) = $block;
dropBlock($field, $H, $W, $h, $w, $x);
}
printField($field, $H, $W);
}
// Test cases
$tests = [
[
"input" => [
"H" => 7,
"W" => 10,
"N" => 4,
"blocks" => [
[1, 8, 1],
[4, 1, 5],
[1, 6, 2],
[2, 2, 0]
]
],
"expected" => [
"..........",
"..######..",
".....#....",
".....#....",
"##...#....",
"##...#....",
".########."
]
],
[
"input" => [
"H" => 10,
"W" => 10,
"N" => 9,
"blocks" => [
[2, 2, 4],
[2, 2, 3],
[2, 2, 5],
[2, 2, 2],
[2, 2, 6],
[2, 2, 1],
[2, 2, 7],
[2, 2, 0],
[2, 2, 8]
]
],
"expected" => [
"##......##",
"##......##",
".##....##.",
".##....##.",
"..##..##..",
"..##..##..",
"...####...",
"...####...",
"....##....",
"....##...."
]
]
];
foreach ($tests as $index => $test) {
ob_start();
runGame($test["input"]["H"], $test["input"]["W"], $test["input"]["N"], $test["input"]["blocks"]);
$output = explode("\n", trim(ob_get_clean()));
$expected = $test["expected"];
$result = ($output === $expected) ? "Passed" : "Failed";
echo "Test " . ($index + 1) . ": " . $result . "\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment