0

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;
    }
Scott Pendleton
  • 1,021
  • 3
  • 16
  • 32

1 Answers1

0

Yes you can, using some arithmetic on the number let's say n = 4,732

To get the thousands digit you can do (int) n/1000.

To get the hundreds digit you do: ((int) n/100) % 10

The tens digit (3) you do: ((int) n/10) %10

and so on... and place each value in a block of the array of ints

Can be done in a loop