Search code examples
c#randombacktrackingsudoku

Randomness in Sudoku solving algorithm


I am using this backtracking soduku solving algorithm which is really good and efficient

    private void solve()
    {
        for (var y = 8; y >= 0; y--)
        {
            for (var x = 8; x >= 0; x--)
            {
                var a = grid[y, x];
                if (a == 0)
                {
                    for (var n = 1; n <= 9; n++)
                    {
                        if (possible(y, x, n))
                        {
                            grid[y, x] = n;
                            solve();
                            grid[y, x] = 0;
                        }
                    }
                    return;
                }
            }
        }
        print();
    }

The thing is i want to add a little change which I haven't been able to do and it is that instead of trying numbers 1 to 9 in order i want it to choose a random number from 1 to 9, and then set it in the grid, without repetition of course.


Solution

  • public static class MyRandomGenerator
    {
        private static Random random = new Random();
    
        public static int[] Generate(int inclusiveMinValue, int exclusiveMaxValue)
        {
            if (exclusiveMaxValue <= inclusiveMinValue)
                throw new ArgumentException(nameof(exclusiveMaxValue));
    
            var capacity = exclusiveMaxValue - inclusiveMinValue;
            var result = new HashSet<int>(capacity);
    
            while (result.Count < capacity)
            {
                result.Add(random.Next(inclusiveMinValue, exclusiveMaxValue));
            }
    
            return result.ToArray();
        }            
    }