Skip to content

Instantly share code, notes, and snippets.

@kubo39
Created February 17, 2015 15:14
Show Gist options
  • Select an option

  • Save kubo39/b286718cd8c1ddf056a8 to your computer and use it in GitHub Desktop.

Select an option

Save kubo39/b286718cd8c1ddf056a8 to your computer and use it in GitHub Desktop.
uint inner_nqueen(int all_bits, int left, int depth, int right) pure nothrow @safe @nogc
{
int results, bitmap = ~(left | depth | right) & all_bits;
while (bitmap != 0) {
int last_bit = -bitmap & bitmap;
bitmap ^= last_bit;
results += inner_nqueen(all_bits, (left | last_bit) << 1, depth | last_bit, (right | last_bit) >> 1);
}
return results + (depth == all_bits ? 1 : 0);
}
uint nqueen(uint n) pure nothrow @safe @nogc { return inner_nqueen((1 << n) - 1, 0, 0, 0); }
unittest {
import std.conv : to; foreach (i, elem; [1, 1, 0, 0, 2, 10, 4, 40, 92]) assert( nqueen(i.to!uint) == elem );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment