Last active
September 12, 2024 20:37
-
-
Save fokosun/8f8d08213a3fa63fd268bb3fef31b47c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// This solution does not care for $n <= 1 | |
function displayCheckerBoard($n): string { | |
$gridStartWithX = 'XY'; | |
$gridStartWithY = 'YX'; | |
if ($n === 2) { | |
return $gridStartWithX . PHP_EOL . $gridStartWithY . PHP_EOL; | |
} | |
$intDiv = intdiv($n, 2); | |
$remainder = $n % 2; | |
$rowX = str_repeat($gridStartWithX, $intDiv) . ($remainder > 0 ? 'X' : ''); | |
$rowY = str_repeat($gridStartWithY, $intDiv) . ($remainder > 0 ? 'Y' : ''); | |
// Construct the grid by repeating the rows | |
$output = str_repeat($rowX . PHP_EOL . $rowY . PHP_EOL, $intDiv); | |
if ($remainder > 0) { | |
$output .= $rowX . PHP_EOL; | |
} | |
return $output; | |
} | |
foreach (range(2, 10) as $number) { | |
echo "===============" . PHP_EOL; | |
echo $number . "X" . $number . " Checkerboard:" . PHP_EOL; | |
echo "===============" . PHP_EOL; | |
echo(displayCheckerBoard($number)); | |
echo PHP_EOL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment