N-queens problem: Difference between revisions
Content added Content deleted
(→Alternate Fortran 77 solution: + output) |
|||
Line 803: | Line 803: | ||
=={{header|D}}== |
=={{header|D}}== |
||
From the C solution. |
From the C solution. |
||
<lang d>import std.stdio: write, writeln |
<lang d>import std.stdio: write, writeln; |
||
enum int SIDE = 8; |
enum int SIDE = 8; |
||
int[SIDE] |
int[SIDE] board; |
||
bool unsafe(int y) { |
nothrow bool unsafe(int y) { |
||
int x = |
immutable int x = board[y]; |
||
foreach (i; 1 .. y+1) { |
foreach (i; 1 .. y+1) { |
||
int t = |
int t = board[y - i]; |
||
if ((t == x) || (t == x - i) || (t == x + i)) |
if ((t == x) || (t == x - i) || (t == x + i)) |
||
return true; |
return true; |
||
Line 819: | Line 819: | ||
} |
} |
||
void |
void showBoard() { |
||
static int s = 0; |
static int s = 0; |
||
writeln("\nSolution #", ++s); |
|||
foreach (y; 0 .. SIDE) { |
foreach (y; 0 .. SIDE) { |
||
foreach (x; 0 .. SIDE) |
foreach (x; 0 .. SIDE) |
||
write( |
write(board[y] == x ? '*' : '.'); |
||
writeln( |
writeln(); |
||
} |
} |
||
} |
} |
||
Line 831: | Line 831: | ||
void main() { |
void main() { |
||
int y = 0; |
int y = 0; |
||
board[0] = -1; |
|||
while (y >= 0) { |
while (y >= 0) { |
||
do { |
do { |
||
board[y]++; |
|||
} while ( |
} while (board[y] < SIDE && unsafe(y)); |
||
if (b[y] < SIDE) { |
|||
if (board[y] < SIDE) { |
|||
if (y < (SIDE - 1)) |
|||
board[++y] = -1; |
|||
else |
|||
showBoard(); |
|||
} else |
} else |
||
y--; |
y--; |
||
} |
|||
} |
} |
||
}</lang> |
}</lang> |
||
⚫ | |||
⚫ | |||
<lang d>auto nqueens(int base) { |
<lang d>auto nqueens(int base) { |
||
int total = base * base; |
int total = base * base; |