Created
October 6, 2018 12:02
-
-
Save dramforever/d4c28a0973f0bb8e4942504612e8b601 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
problemStr = | |
"800 000 000 003 600 000 070 090 200 050 007 000 000 045 700 000 \ | |
100 030 001 000 068 008 500 010 090 000 400"; | |
pr = Partition[ToExpression@Characters@StringDelete[problemStr, " "], 9]; | |
blocks = Table[3 Quotient[i, 3] + Quotient[j, 3], {i, 0, 8}, {j, 0, 8}]; | |
rows = Table[i, {i, 0, 8}, {j, 0, 8}]; | |
cols = Table[j, {i, 0, 8}, {j, 0, 8}]; | |
constrain[blk_] := | |
Join @@ Table[Outer[Plus, Range[9], (Position[blk, k] - 1).{81, 9}], {k, Min[blk], Max[blk]}]; | |
numberConstraints = Table[Range[9] + 9 m, {m, 0, 80}]; | |
basicConstraints = | |
Join @@ Thread[Unevaluated@constrain[{blocks, rows, cols}]]; | |
solve[problem_] := | |
Block[{problemConstraints, allConstraints, lpResult}, | |
problemConstraints = | |
Map[List, | |
Join @@ Table[Append[k] /@ Position[problem, k], {k, 9}].{81, 9, 1} - 90]; | |
allConstraints = (Normal@SparseArray[Thread[# -> 1], 729] &) /@ | |
Join[basicConstraints, numberConstraints, problemConstraints]; | |
lpResult = | |
Quiet@LinearProgramming[ConstantArray[0, 729], allConstraints, | |
ConstantArray[{1, 0}, Length@allConstraints], | |
ConstantArray[{0, 1}, 729], Integers]; | |
Partition[FirstPosition[#, 1][[1]] & /@ Partition[lpResult, 9], 9]]; | |
solve[pr] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment