Skip to content

Instantly share code, notes, and snippets.

@elazar
Last active October 5, 2018 17:00
Show Gist options
  • Save elazar/d91c9571d6334f049708eff5acb00976 to your computer and use it in GitHub Desktop.
Save elazar/d91c9571d6334f049708eff5acb00976 to your computer and use it in GitHub Desktop.
Eight Queens Problem
<?php
/**
* Sample output:
*
* $ time php queens.php
* [ ][ ][ ][ ][ ][X][ ][ ]
* [ ][ ][X][ ][ ][ ][ ][ ]
* [ ][ ][ ][ ][ ][ ][X][ ]
* [ ][X][ ][ ][ ][ ][ ][ ]
* [ ][ ][ ][ ][ ][ ][ ][X]
* [ ][ ][ ][ ][X][ ][ ][ ]
* [X][ ][ ][ ][ ][ ][ ][ ]
* [ ][ ][ ][X][ ][ ][ ][ ]
* php queens.php 0.02s user 0.01s system 66% cpu 0.041 total
*/
function random_queen(): array
{
return ['x' => rand(0, 7), 'y' => rand(0, 7)];
}
function valid($queen1, $queen2): bool
{
return !(
$queen1['x'] == $queen2['x']
|| $queen1['y'] == $queen2['y']
|| abs($queen1['x'] - $queen2['x']) == abs($queen1['y'] - $queen2['y'])
);
}
function coords($queen): string
{
return $queen['x'] . ',' . $queen['y'];
}
$queens = $exclude = [];
while (count($queens) < 8) {
do {
$new_queen = random_queen();
} while (isset($exclude[coords($new_queen)]));
$valid = true;
foreach ($queens as $current_queen) {
if (!valid($new_queen, $current_queen)) {
$valid = false;
break;
}
}
if ($valid) {
$queens[coords($new_queen)] = $new_queen;
}
$exclude[coords($new_queen)] = true;
// All possible positions have been tried, there is no valid solution that
// includes the placed queens, start over
if (count($exclude) == 64) {
$queens = $exclude = [];
}
}
$output = array_fill(0, 8, array_fill(0, 8, ' '));
foreach ($queens as $queen) {
$output[$queen['x']][$queen['y']] = 'X';
}
foreach (range(0, 7) as $x) {
foreach (range(0, 7) as $y) {
echo '[' . $output[$x][$y] . ']';
}
echo PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment