Group Abstract Group Abstract

Message Boards Message Boards

Using Meta programming + Compile to speed up Backtracking algorithm

Posted 5 years ago
Attachments:
POSTED BY: Hongyang Cao
sudokuSolve[mat_] := Module[
  {toX, count, symMat, cond, iter, res},

  toX = Symbol["x" <> IntegerString[#, 10, 2]] &;
  count = 1;
  symMat = Partition[
    If[# == 0, toX[count++], #] & /@ Flatten[mat],
    9];

  cond = And @@ Unequal @@@ Join[
      symMat,
      Transpose[symMat],
      Join @@@ Join @@ Partition[symMat, {3, 3}]
      ];
  cond = LogicalExpand[cond];

  iter = Table[{
     toX[i + 1],
     If[Or @@ Cases[Equal @@@ cond, toX[i] == _],
      0,
      Evaluate@If[i < count - 1, 9, 1]]},
    {i, 0, count - 1}];

  res = Reap[Compile[{}, Do[Sow[#], ##2]] &[symMat, Sequence @@ iter][]];
  res[[2, 1]]
  ]

searching for the sudokuSolve code

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard