Beispiel #1
0
        /// <summary>
        /// Populates a matrix such that each 3x3 grid is valid.
        /// </summary>
        /// <param name="matrix">partially populated matrix</param>
        /// <returns>a fully populated matrix where all 3x3 cells are in a valid state</returns>
        public static int[][] RandomMatrix(int[][] matrix)
        {
            var result = CopyMatrix(matrix);

            for (int block = 0; block < 9; ++block)
            {
                var valuesInBlock = result.GetBlock(block).Where(x => x != 0).ToArray();

                // Create a shuffled list missing values for block
                var list =
                    new Queue <int>(
                        Enumerable.Range(1, 9)
                        .Except(valuesInBlock)
                        .OrderBy(x => Guid.NewGuid()));

                // walk through each cell in the current block
                foreach (var index in SudokuExtensions.GetBlockIndexes(block))
                {
                    //if cell is empty add a value from list
                    if (result[index[0]][index[1]] == 0)
                    {
                        result[index[0]][index[1]] = list.Dequeue();
                    }
                }
            }

            return(result);
        }
Beispiel #2
0
        public static int[][] NeighborMatrix(int[][] problem, int[][] matrix)
        {
            var result  = CopyMatrix(matrix);
            var indexes = SudokuExtensions.GetBlockIndexes(rnd.Next(0, 9));

            // determine two cells in the same block that don't contain a fixed value
            int[][] swaps = indexes
                            .Where(coord => problem.ValueForIndex(coord) == 0)
                            .OrderBy(_ => Guid.NewGuid())
                            .Take(2)
                            .ToArray();

            // pick two of those cells: (r1, c1) (r2,c2)
            int r1 = swaps[0][0],
                c1 = swaps[0][1],
                r2 = swaps[1][0],
                c2 = swaps[1][1];

            int tmp = result[r1][c1];

            result[r1][c1] = result[r2][c2];
            result[r2][c2] = tmp;

            return(result);
        }
Beispiel #3
0
        public static int[][] MergeMatrices(int[][] m1, int[][] m2)
        {
            var result = CopyMatrix(m1);

            for (var i = 0; i < 9; ++i)
            {
                if (rnd.NextDouble() > 0.5)
                {
                    var indexes = SudokuExtensions.GetBlockIndexes(i);
                    foreach (var index in indexes)
                    {
                        result[index[0]][index[1]] = m2[index[0]][index[1]];
                    }
                }
            }

            return(result);
        }