Last active
October 5, 2018 17:00
-
-
Save elazar/d91c9571d6334f049708eff5acb00976 to your computer and use it in GitHub Desktop.
Eight Queens Problem
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 | |
/** | |
* 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