To sort through 16 million combinations in the 8 Queens problem, I use an 8-digit number in which each digit represents a column, and the value of the digit is the row. No digit may repeat. My function accepts a number, converts it to a string, then to a char array, and then to an int array. Is there a simpler way to arrive at an int array?
Also, are any optimizations available in this code:
private bool IsValidSolution(int MyInt)
{
string sNum = MyInt.ToString();
int iVal = 0;
int i, k, j;
// Eliminate row and column conflicts.
char[] aChars = sNum.ToCharArray();
int[] aInt = Array.ConvertAll(aChars, c => (int)Char.GetNumericValue(c));
// The first false in the array is just a placeholder. Of interest are positions 1 - 8).
bool[] aCheck = new bool[] { false, false, false, false, false, false, false, false, false, false };
for (i = 0; i < 8; i++)
{
iVal = aInt[i];
if (iVal == 0 || iVal == 9) return false;
if (aCheck[iVal] == false)
{
aCheck[iVal] = true;
} else {
return false;
}
}
// Eliminate diagonal conflicts.
for (k = 0; k < 7; k++)
{
j = k + 1;
for (i = j; i < 8; i++)
{
if (Math.Abs(aInt[k] - aInt[i]) == Math.Abs(k - i)) return false;
}
}
return true;
}