printSudoku static method

void printSudoku(
  1. List<List<int>> sudoku
)

Prints the sudoku in a readable format to the console. Zeroes are represented as -.

InvalidSudokuConfigurationException is thrown if the configuration of the sudoku is not valid. Example Format:

9  -  3   1  2  5   -  8  7
1  8  -   4  -  6   -  5  -
5  -  7   8  9  3   1  4  2

3  5  4   9  -  2   7  1  8
7  -  8   3  -  4   5  2  6
6  2  -   5  8  7   9  -  -

4  1  9   6  5  8   -  7  3
2  -  5   7  4  9   8  -  1
8  7  -   2  3  1   -  9  5

Implementation

static void printSudoku(List<List<int>> sudoku) {
  if (!isValidConfiguration(sudoku)) {
    throw InvalidSudokuConfigurationException();
  }
  var bufferToPrint = StringBuffer();
  for (var i = 0; i < 9; i++) {
    for (var j = 0; j < 9; j++) {
      if (sudoku[i][j] == 0) {
        bufferToPrint.write(j == 8 ? '-' : '-  ');
      } else {
        bufferToPrint.write('${sudoku[i][j]}${j == 8 ? '' : '  '}');
      }
      if (((j + 1) % 3 == 0) && !(j == 8)) {
        bufferToPrint.write(' ');
      }
      if (j == 8) {
        print(bufferToPrint); // ignore: avoid_print
        bufferToPrint.clear();
      }
    }
    if ((i + 1) % 3 == 0) {
      print(''); // ignore: avoid_print
    }
  }
}