Using the method I talked about in the previous post, I get a solved sudoku in 0.000015 seconds using 120 lines of code, most of which is initializing the 12 basic 3x3 Latin Squares. Here's the code:
static int[] arRowSwap = new int[] { 0, 3, 6, 1, 4, 7, 2, 5, 8 };
static int[, ,] LatinSquares3X3 = new int[12, 3, 3]
#region 3x3 Latin Square Enumeration
{
{
{0,1,2},
{1,2,0},
{2,0,1}
},
{
{0,1,2},
{2,0,1},
{1,2,0}
},
{
{1,2,0},
{0,1,2},
{2,0,1}
},
{
{2,0,1},
{0,1,2},
{1,2,0}
},
{
{1,2,0},
{2,0,1},
{0,1,2}
},
{
{2,0,1},
{1,2,0},
{0,1,2}
},
{
{0,2,1},
{2,1,0},
{1,0,2}
},
{
{0,2,1},
{1,0,2},
{2,1,0}
},
{
{2,1,0},
{0,2,1},
{1,0,2}
},
{
{1,0,2},
{0,2,1},
{2,1,0}
},
{
{2,1,0},
{1,0,2},
{0,2,1}
},
{
{1,0,2},
{2,1,0},
{0,2,1}
}
};
#endregion
static int[] RandomPermutation(int n, Random rnd)
{
int[] intRet = new int[n];
for (int i = 0; i < n; i++)
{
intRet[i] = i;
}
for (int i = 0; i < n; i++)
{
int iSwap = rnd.Next(i, n);
int iSwapVal = intRet[iSwap];
intRet[iSwap] = intRet[i];
intRet[i] = iSwapVal;
}
return intRet;
}
static int[] RandomPermutation(int n)
{
return RandomPermutation(n, new Random());
}
public static int[,] SolutionGenerator()
{
Random rnd = new Random();
int[,] ls = new int[9, 9];
int i3x3Outer = rnd.Next(12);
int[] arPermute = RandomPermutation(9);
for (int iRowMajor = 0; iRowMajor < 3; iRowMajor++)
{
for (int iColMajor = 0; iColMajor < 3; iColMajor++)
{
int iRowBase = iRowMajor * 3;
int iColBase = iColMajor * 3;
int i3x3 = rnd.Next(12);
int upperDigitVal = LatinSquares3X3[i3x3Outer, iRowMajor, iColMajor] * 3;
for (int iRowMinor = 0; iRowMinor < 3; iRowMinor++)
{
for (int iColMinor = 0; iColMinor < 3; iColMinor++)
{
ls[arRowSwap[iRowBase + iRowMinor], iColBase + iColMinor] =
arPermute[LatinSquares3X3[i3x3, iRowMinor, iColMinor] + upperDigitVal] + 1;
}
}
}
}
return ls;
}
|