2
\$\begingroup\$

I'm looking for alternative ways to do it and in general parts that don't look write on this code.

using System.Collections.Generic;

namespace Algorithms 
{ 
    public class SudokuPuzzleValidator 
    { 
        readonly int[,] _board;

        public SudokuPuzzleValidator() 
        { 
            _board = new int[9,9]; 
        }

        public SudokuPuzzleValidator(int[,] board) 
        { 
            _board = board; 
        }

        public bool Validate() 
        { 
            const int integersInGame = 9; 
            var rowSet = new HashSet<int>[integersInGame]; 
            InitializeSet(integersInGame, rowSet); 
            var columnSet = new HashSet<int>[integersInGame]; 
            InitializeSet(integersInGame, columnSet); 
            var subGridSet = new HashSet<int>[integersInGame]; 
            InitializeSet(integersInGame, subGridSet);

            for (var row = 0; row < integersInGame; row++) 
            { 
                for (var column = 0; column < integersInGame; column++) 
                { 
                    var cval = _board[row, column]; 
                    if (rowSet[row].Contains(cval)) 
                    { 
                        return false; 
                    } 
                    rowSet[row].Add(cval); 
                    if (columnSet[column].Contains(cval)) 
                    { 
                        return false; 
                    } 
                    columnSet[column].Add(cval); 
                    var subGridNumber = FigureOutSubGrid(row, column); 
                    if (subGridSet[subGridNumber].Contains(cval)) 
                    { 
                        return false; 
                    } 
                    subGridSet[subGridNumber].Add(cval); 
                } 
            } 
            return true; 
        }

        private static void InitializeSet(int integersInGame, HashSet<int>[] rowSet) 
        { 
            for (var i = 0; i < integersInGame; i++) 
            { 
                rowSet[i] = new HashSet<int>(); 
            } 
        }

        private static int FigureOutSubGrid(int row, int column) 
        { 
            return column/3 + row/3*3; 
        } 
    } 
}

Link to my post: http://alfredoalvarez.com/blog/?p=372

\$\endgroup\$
2
\$\begingroup\$

This looks way overcomplicated. There are a lot of solutions on the web, for example: https://stackoverflow.com/questions/723213/sudoku-algorithm-in-c-sharp

Regarding your code:

  • You have hard-coded numbers everywhere
  • Second ctor accepts arbitrary array and does not check parameter for validity. It can be null or of any size different from 9
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.