Sudoku algorithm in C#

前端 未结 9 965
南方客
南方客 2021-02-03 15:24

I need one liner (or close to it) that verifies that given array of 9 elements doesn\'t contain repeating numbers 1,2,3,...,9. Repeating zeroes do not count (they represent empt

相关标签:
9条回答
  • 2021-02-03 16:09

    The following is simple and fast.

    if a.Select(i => Math.Pow(2, i - 1)).ToArray().Sum()==511 ...
    
    0 讨论(0)
  • 2021-02-03 16:12

    Why do you want a convoluted line of Linq code, rather than wrapping up an efficient implementation of the test in an extension method and calling that?

    var a = new int[9] {1,2,3,4,5,6,7,8,9};
    var itIsOk = a.HasNoNonZeroRepeats();
    

    One implementation of NoNonZeroRepeats could be to use the 9 lowest bits of a short to indicate presence of a value in the array, giving an O(length(a)) test with no dynamic memory use. Linq is cute, but unless you're only using it for aesthetic reasons (you don't specifically say that you're writing a sudoku solver using only Linq as an exercise) it seems to be just adding complexity here.

    0 讨论(0)
  • This is about 50-250 times faster than a LINQ solution (depending on how early the duplicate is found):

    public static bool IsValid(int[] values) {
        int flag = 0;
        foreach (int value in values) {
            if (value != 0) {
                int bit = 1 << value;
                if ((flag & bit) != 0) return false;
                flag |= bit;
            }
        }
        return true;
    }
    
    0 讨论(0)
提交回复
热议问题