Task

Solve a partially filled-in normal   9x9   Sudoku grid   and display the result in a human-readable format.

references

 Algorithmics of Sudoku   may help implement this.
 Python Sudoku Solver Computerphile video.


 
include "ConsoleWindow"
include "NSLog.incl"
include "Util_Containers.incl"
 
begin globals
dim as container gC
end globals
 
BeginCDeclaration
short solve_sudoku(short i);
short check_sudoku(short r, short c);
CFMutableStringRef print_sudoku();
EndC
 
BeginCFunction
short sudoku[9][9] = {
                       {3,0,0,0,0,1,4,0,9},
                       {7,0,0,0,0,4,2,0,0},
                       {0,5,0,2,0,0,0,1,0},
                       {5,7,0,0,4,3,0,6,0},
                       {0,9,0,0,0,0,0,3,0},
                       {0,6,0,7,9,0,0,8,5},
                       {0,8,0,0,0,5,0,4,0},
                       {0,0,6,4,0,0,0,0,7},
                       {9,0,5,6,0,0,0,0,3},
                     };
 
 
short check_sudoku( short r, short c )
{
  short i;
  short rr, cc;
 
  for (i = 0; i < 9; i++)
  {
    if (i != c && sudoku[r][i] == sudoku[r][c]) return 0;
    if (i != r && sudoku[i][c] == sudoku[r][c]) return 0;
    rr = r/3 * 3 + i/3;
    cc = c/3 * 3 + i%3;
    if ((rr != r || cc != c) && sudoku[rr][cc] == sudoku[r][c]) return 0;
  }
  return -1;
}
 
 
short solve_sudoku( short i )
{
  short r, c;
 
  if (i < 0) return 0;
  else if (i >= 81) return -1;
 
  r = i / 9;
  c = i % 9;
 
  if (sudoku[r][c])
    return check_sudoku(r, c) && solve_sudoku(i + 1);
  else
    for (sudoku[r][c] = 9; sudoku[r][c] > 0; sudoku[r][c]--)
    {
      if ( solve_sudoku(i) ) return -1;
    }
  return 0;
}
 
 
CFMutableStringRef print_sudoku()
{
  short i, j;
  CFMutableStringRef mutStr;
 
  mutStr = CFStringCreateMutable( kCFAllocatorDefault, 0 );
 
     for (i = 0; i < 9; i++)
     {
          for (j = 0; j < 9; j++)
          {
             CFStringAppendFormat( mutStr, NULL, (CFStringRef)@" %d", sudoku[i][j] );
          }
       CFStringAppendFormat( mutStr, NULL, (CFStringRef)@"\r" );
     }
  return( mutStr );
}
EndC
 
toolbox fn solve_sudoku( short i ) = short
toolbox fn check_sudoku( short r, short c ) = short
toolbox fn print_sudoku() = CFMutableStringRef
 
dim as short solution
dim as CFMutableStringRef cfRef
 
gC = " "
cfRef = fn print_sudoku()
fn ContainerCreateWithCFString( cfRef, gC )
print : print "Sudoku challenge:" : print : print gC
 
solution = fn solve_sudoku(0)
 
print : print "Sudoku solved:" : print
if ( solution )
gC = " "
cfRef = fn print_sudoku()
fn ContainerCreateWithCFString( cfRef, gC )
print gC
else
print "No solution found"
end if
 