N-queens problem: Difference between revisions

Content added Content deleted
Line 803: Line 803:
=={{header|D}}==
=={{header|D}}==
From the C solution.
From the C solution.
<lang d>import std.stdio: write, writeln, writefln;
<lang d>import std.stdio: write, writeln;


enum int SIDE = 8;
enum int SIDE = 8;
int[SIDE] b;
int[SIDE] board;


bool unsafe(int y) {
nothrow bool unsafe(int y) {
int x = b[y];
immutable int x = board[y];
foreach (i; 1 .. y+1) {
foreach (i; 1 .. y+1) {
int t = b[y - i];
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 show_board() {
void showBoard() {
static int s = 0;
static int s = 0;
writefln("\nSolution #%d", ++s);
writeln("\nSolution #", ++s);
foreach (y; 0 .. SIDE) {
foreach (y; 0 .. SIDE) {
foreach (x; 0 .. SIDE)
foreach (x; 0 .. SIDE)
write(b[y] == x ? "|Q" : "|_");
write(board[y] == x ? '*' : '.');
writeln("|");
writeln();
}
}
}
}
Line 831: Line 831:
void main() {
void main() {
int y = 0;
int y = 0;
b[0] = -1;
board[0] = -1;

while (y >= 0) {
while (y >= 0) {
do {
do {
b[y]++;
board[y]++;
} while (b[y] < SIDE && unsafe(y));
} while (board[y] < SIDE && unsafe(y));

if (b[y] < SIDE) {
if (y < (SIDE - 1)) {
if (board[y] < SIDE) {
b[++y] = -1;
if (y < (SIDE - 1))
} else {
board[++y] = -1;
show_board();
else
}
showBoard();
} else {
} else
y--;
y--;
}
}
}
}</lang>
}</lang>
===Brute force version===

Brute force version
<lang d>auto nqueens(int base) {
<lang d>auto nqueens(int base) {
int total = base * base;
int total = base * base;