I was playing around with the "eight queens" problem, just to see how I could use C++ algorithms to write less code.
I figured out a way to find the next unused column using find_if_not
. I am showing both ways of writing it. Assume we are looping over every valid "file" on a given "rank" ( in C++ terms, I am looping over rows and columns in an 8x8 matrix.)
used
is simply a set of column indexes that are currently occupied by a queen.col
is the current index of the column where we will try to place the next queen.
Note for efficiency, the array of column indexes would not be created where it's shown in the code.
Method1:
set<unsigned>::iterator it;
for (; col < 8; ++col)
{
it = used.find(col);
if (it == used.end())
break;
}
if (it != used.end())
return false;
Method2:
array<unsigned, 8> colIdx{ 0, 1, 2, 3, 4, 5, 6, 7 };
auto it = find_if_not(colIdx.begin() + col, colIdx.end(),
[&used](unsigned colIdx) { return used.find(colIdx) != used.end(); });
if (it == colIdx.end())
return false;
else
col = *it;