Instruction stringlengths 45 106 | input_code stringlengths 1 13.7k | output_code stringlengths 1 13.7k |
|---|---|---|
Change the programming language of this snippet from BBC_Basic to C++ without modifying what it does. | VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
DIM Board%(8,8)
Board%() = %111111111
FOR L% = 0 TO 9:P% = L%*100
LINE 2,P%+2,902,P%+2
IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4
LINE P%+2,2,P%+2,902
IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902
NEXT
DATA " 4 5 6 "
DATA " 6 1 8 9"
DATA "3 7 "
DATA " 8 5 "
DATA " 4 3 "
DATA " 6 7 "
DATA " 2 6"
DATA "1 5 4 3 "
DATA " 2 7 1 "
FOR R% = 8 TO 0 STEP -1
READ A$
FOR C% = 0 TO 8
A% = ASCMID$(A$,C%+1) AND 15
IF A% Board%(R%,C%) = 1 << (A%-1)
NEXT
NEXT R%
GCOL 4
PROCshow
WAIT 200
dummy% = FNsolve(Board%(), TRUE)
GCOL 2
PROCshow
REPEAT WAIT 1 : UNTIL FALSE
END
DEF PROCshow
LOCAL C%,P%,R%
FOR C% = 0 TO 8
FOR R% = 0 TO 8
P% = Board%(R%,C%)
IF (P% AND (P%-1)) = 0 THEN
IF P% P% = LOGP%/LOG2+1.5
MOVE C%*100+30,R%*100+90
VDU 5,P%+48,4
ENDIF
NEXT
NEXT
ENDPROC
DEF FNsolve(P%(),F%)
LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%()
DIM Q%(8,8)
REPEAT
Q%() = P%()
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF (D% AND (D%-1))=0 THEN
M% = NOT D%
FOR X% = 0 TO 8
IF X%<>C% P%(R%,X%) AND= M%
IF X%<>R% P%(X%,C%) AND= M%
NEXT
FOR X% = C%DIV3*3 TO C%DIV3*3+2
FOR Y% = R%DIV3*3 TO R%DIV3*3+2
IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M%
NEXT
NEXT
ENDIF
NEXT
NEXT
Q%() -= P%()
UNTIL SUMQ%()=0
M% = 10
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF D%=0 M% = 0
IF D% AND (D%-1) THEN
N% = 0
REPEAT N% += D% AND 1
D% DIV= 2
UNTIL D% = 0
IF N%<M% M% = N% : X% = C% : Y% = R%
ENDIF
NEXT
NEXT
IF M%=0 THEN = 0
IF M%=10 THEN = 1
D% = 0
FOR M% = 0 TO 8
IF P%(Y%,X%) AND (2^M%) THEN
Q%() = P%()
Q%(Y%,X%) = 2^M%
C% = FNsolve(Q%(),F%)
D% += C%
IF C% IF F% P%() = Q%() : = D%
ENDIF
NEXT
= D%
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Write the same algorithm in Java as shown in this BBC_Basic implementation. | VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
DIM Board%(8,8)
Board%() = %111111111
FOR L% = 0 TO 9:P% = L%*100
LINE 2,P%+2,902,P%+2
IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4
LINE P%+2,2,P%+2,902
IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902
NEXT
DATA " 4 5 6 "
DATA " 6 1 8 9"
DATA "3 7 "
DATA " 8 5 "
DATA " 4 3 "
DATA " 6 7 "
DATA " 2 6"
DATA "1 5 4 3 "
DATA " 2 7 1 "
FOR R% = 8 TO 0 STEP -1
READ A$
FOR C% = 0 TO 8
A% = ASCMID$(A$,C%+1) AND 15
IF A% Board%(R%,C%) = 1 << (A%-1)
NEXT
NEXT R%
GCOL 4
PROCshow
WAIT 200
dummy% = FNsolve(Board%(), TRUE)
GCOL 2
PROCshow
REPEAT WAIT 1 : UNTIL FALSE
END
DEF PROCshow
LOCAL C%,P%,R%
FOR C% = 0 TO 8
FOR R% = 0 TO 8
P% = Board%(R%,C%)
IF (P% AND (P%-1)) = 0 THEN
IF P% P% = LOGP%/LOG2+1.5
MOVE C%*100+30,R%*100+90
VDU 5,P%+48,4
ENDIF
NEXT
NEXT
ENDPROC
DEF FNsolve(P%(),F%)
LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%()
DIM Q%(8,8)
REPEAT
Q%() = P%()
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF (D% AND (D%-1))=0 THEN
M% = NOT D%
FOR X% = 0 TO 8
IF X%<>C% P%(R%,X%) AND= M%
IF X%<>R% P%(X%,C%) AND= M%
NEXT
FOR X% = C%DIV3*3 TO C%DIV3*3+2
FOR Y% = R%DIV3*3 TO R%DIV3*3+2
IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M%
NEXT
NEXT
ENDIF
NEXT
NEXT
Q%() -= P%()
UNTIL SUMQ%()=0
M% = 10
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF D%=0 M% = 0
IF D% AND (D%-1) THEN
N% = 0
REPEAT N% += D% AND 1
D% DIV= 2
UNTIL D% = 0
IF N%<M% M% = N% : X% = C% : Y% = R%
ENDIF
NEXT
NEXT
IF M%=0 THEN = 0
IF M%=10 THEN = 1
D% = 0
FOR M% = 0 TO 8
IF P%(Y%,X%) AND (2^M%) THEN
Q%() = P%()
Q%(Y%,X%) = 2^M%
C% = FNsolve(Q%(),F%)
D% += C%
IF C% IF F% P%() = Q%() : = D%
ENDIF
NEXT
= D%
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Please provide an equivalent version of this BBC_Basic code in Python. | VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
DIM Board%(8,8)
Board%() = %111111111
FOR L% = 0 TO 9:P% = L%*100
LINE 2,P%+2,902,P%+2
IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4
LINE P%+2,2,P%+2,902
IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902
NEXT
DATA " 4 5 6 "
DATA " 6 1 8 9"
DATA "3 7 "
DATA " 8 5 "
DATA " 4 3 "
DATA " 6 7 "
DATA " 2 6"
DATA "1 5 4 3 "
DATA " 2 7 1 "
FOR R% = 8 TO 0 STEP -1
READ A$
FOR C% = 0 TO 8
A% = ASCMID$(A$,C%+1) AND 15
IF A% Board%(R%,C%) = 1 << (A%-1)
NEXT
NEXT R%
GCOL 4
PROCshow
WAIT 200
dummy% = FNsolve(Board%(), TRUE)
GCOL 2
PROCshow
REPEAT WAIT 1 : UNTIL FALSE
END
DEF PROCshow
LOCAL C%,P%,R%
FOR C% = 0 TO 8
FOR R% = 0 TO 8
P% = Board%(R%,C%)
IF (P% AND (P%-1)) = 0 THEN
IF P% P% = LOGP%/LOG2+1.5
MOVE C%*100+30,R%*100+90
VDU 5,P%+48,4
ENDIF
NEXT
NEXT
ENDPROC
DEF FNsolve(P%(),F%)
LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%()
DIM Q%(8,8)
REPEAT
Q%() = P%()
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF (D% AND (D%-1))=0 THEN
M% = NOT D%
FOR X% = 0 TO 8
IF X%<>C% P%(R%,X%) AND= M%
IF X%<>R% P%(X%,C%) AND= M%
NEXT
FOR X% = C%DIV3*3 TO C%DIV3*3+2
FOR Y% = R%DIV3*3 TO R%DIV3*3+2
IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M%
NEXT
NEXT
ENDIF
NEXT
NEXT
Q%() -= P%()
UNTIL SUMQ%()=0
M% = 10
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF D%=0 M% = 0
IF D% AND (D%-1) THEN
N% = 0
REPEAT N% += D% AND 1
D% DIV= 2
UNTIL D% = 0
IF N%<M% M% = N% : X% = C% : Y% = R%
ENDIF
NEXT
NEXT
IF M%=0 THEN = 0
IF M%=10 THEN = 1
D% = 0
FOR M% = 0 TO 8
IF P%(Y%,X%) AND (2^M%) THEN
Q%() = P%()
Q%(Y%,X%) = 2^M%
C% = FNsolve(Q%(),F%)
D% += C%
IF C% IF F% P%() = Q%() : = D%
ENDIF
NEXT
= D%
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Convert the following code from BBC_Basic to VB, ensuring the logic remains intact. | VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
DIM Board%(8,8)
Board%() = %111111111
FOR L% = 0 TO 9:P% = L%*100
LINE 2,P%+2,902,P%+2
IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4
LINE P%+2,2,P%+2,902
IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902
NEXT
DATA " 4 5 6 "
DATA " 6 1 8 9"
DATA "3 7 "
DATA " 8 5 "
DATA " 4 3 "
DATA " 6 7 "
DATA " 2 6"
DATA "1 5 4 3 "
DATA " 2 7 1 "
FOR R% = 8 TO 0 STEP -1
READ A$
FOR C% = 0 TO 8
A% = ASCMID$(A$,C%+1) AND 15
IF A% Board%(R%,C%) = 1 << (A%-1)
NEXT
NEXT R%
GCOL 4
PROCshow
WAIT 200
dummy% = FNsolve(Board%(), TRUE)
GCOL 2
PROCshow
REPEAT WAIT 1 : UNTIL FALSE
END
DEF PROCshow
LOCAL C%,P%,R%
FOR C% = 0 TO 8
FOR R% = 0 TO 8
P% = Board%(R%,C%)
IF (P% AND (P%-1)) = 0 THEN
IF P% P% = LOGP%/LOG2+1.5
MOVE C%*100+30,R%*100+90
VDU 5,P%+48,4
ENDIF
NEXT
NEXT
ENDPROC
DEF FNsolve(P%(),F%)
LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%()
DIM Q%(8,8)
REPEAT
Q%() = P%()
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF (D% AND (D%-1))=0 THEN
M% = NOT D%
FOR X% = 0 TO 8
IF X%<>C% P%(R%,X%) AND= M%
IF X%<>R% P%(X%,C%) AND= M%
NEXT
FOR X% = C%DIV3*3 TO C%DIV3*3+2
FOR Y% = R%DIV3*3 TO R%DIV3*3+2
IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M%
NEXT
NEXT
ENDIF
NEXT
NEXT
Q%() -= P%()
UNTIL SUMQ%()=0
M% = 10
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF D%=0 M% = 0
IF D% AND (D%-1) THEN
N% = 0
REPEAT N% += D% AND 1
D% DIV= 2
UNTIL D% = 0
IF N%<M% M% = N% : X% = C% : Y% = R%
ENDIF
NEXT
NEXT
IF M%=0 THEN = 0
IF M%=10 THEN = 1
D% = 0
FOR M% = 0 TO 8
IF P%(Y%,X%) AND (2^M%) THEN
Q%() = P%()
Q%(Y%,X%) = 2^M%
C% = FNsolve(Q%(),F%)
D% += C%
IF C% IF F% P%() = Q%() : = D%
ENDIF
NEXT
= D%
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Change the following BBC_Basic code into Go without altering its purpose. | VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
DIM Board%(8,8)
Board%() = %111111111
FOR L% = 0 TO 9:P% = L%*100
LINE 2,P%+2,902,P%+2
IF (L% MOD 3)=0 LINE 2,P%,902,P% : LINE 2,P%+4,902,P%+4
LINE P%+2,2,P%+2,902
IF (L% MOD 3)=0 LINE P%,2,P%,902 : LINE P%+4,2,P%+4,902
NEXT
DATA " 4 5 6 "
DATA " 6 1 8 9"
DATA "3 7 "
DATA " 8 5 "
DATA " 4 3 "
DATA " 6 7 "
DATA " 2 6"
DATA "1 5 4 3 "
DATA " 2 7 1 "
FOR R% = 8 TO 0 STEP -1
READ A$
FOR C% = 0 TO 8
A% = ASCMID$(A$,C%+1) AND 15
IF A% Board%(R%,C%) = 1 << (A%-1)
NEXT
NEXT R%
GCOL 4
PROCshow
WAIT 200
dummy% = FNsolve(Board%(), TRUE)
GCOL 2
PROCshow
REPEAT WAIT 1 : UNTIL FALSE
END
DEF PROCshow
LOCAL C%,P%,R%
FOR C% = 0 TO 8
FOR R% = 0 TO 8
P% = Board%(R%,C%)
IF (P% AND (P%-1)) = 0 THEN
IF P% P% = LOGP%/LOG2+1.5
MOVE C%*100+30,R%*100+90
VDU 5,P%+48,4
ENDIF
NEXT
NEXT
ENDPROC
DEF FNsolve(P%(),F%)
LOCAL C%,D%,M%,N%,R%,X%,Y%,Q%()
DIM Q%(8,8)
REPEAT
Q%() = P%()
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF (D% AND (D%-1))=0 THEN
M% = NOT D%
FOR X% = 0 TO 8
IF X%<>C% P%(R%,X%) AND= M%
IF X%<>R% P%(X%,C%) AND= M%
NEXT
FOR X% = C%DIV3*3 TO C%DIV3*3+2
FOR Y% = R%DIV3*3 TO R%DIV3*3+2
IF X%<>C% IF Y%<>R% P%(Y%,X%) AND= M%
NEXT
NEXT
ENDIF
NEXT
NEXT
Q%() -= P%()
UNTIL SUMQ%()=0
M% = 10
FOR R% = 0 TO 8
FOR C% = 0 TO 8
D% = P%(R%,C%)
IF D%=0 M% = 0
IF D% AND (D%-1) THEN
N% = 0
REPEAT N% += D% AND 1
D% DIV= 2
UNTIL D% = 0
IF N%<M% M% = N% : X% = C% : Y% = R%
ENDIF
NEXT
NEXT
IF M%=0 THEN = 0
IF M%=10 THEN = 1
D% = 0
FOR M% = 0 TO 8
IF P%(Y%,X%) AND (2^M%) THEN
Q%() = P%()
Q%(Y%,X%) = 2^M%
C% = FNsolve(Q%(),F%)
D% += C%
IF C% IF F% P%() = Q%() : = D%
ENDIF
NEXT
= D%
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Convert this Clojure snippet to C and keep its semantics consistent. | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Change the programming language of this snippet from Clojure to C# without modifying what it does. | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Port the following code from Clojure to C++ with equivalent syntax and logic. | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Ensure the translated Java code behaves exactly like the original Clojure snippet. | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Can you help me rewrite this code in Python instead of Clojure, keeping it the same logically? | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Change the following Clojure code into VB without altering its purpose. | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Rewrite the snippet below in Go so it works the same as the original Clojure code. | (ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
(defn- compatible? [m x y n]
(let [n= #(= n (get-in m [%1 %2]))]
(or (n= y x)
(let [c (count m)]
(and (zero? (get-in m [y x]))
(not-any? #(or (n= y %) (n= % x)) (range c))
(let [zx (* c (quot x c)), zy (* c (quot y c))]
(every? false?
(map n= (range zy (+ zy c)) (range zx (+ zx c))))))))))
(defn solve [m]
(let [c (count m)]
(loop [m m, x 0, y 0]
(if (= y c) m
(let [ng (->> (range 1 c)
(filter #(compatible? m x y %))
first
(assoc-in m [y x]))]
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Please provide an equivalent version of this Common_Lisp code in C. | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Write the same algorithm in C# as shown in this Common_Lisp implementation. | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Can you help me rewrite this code in C++ instead of Common_Lisp, keeping it the same logically? | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Write the same algorithm in Java as shown in this Common_Lisp implementation. | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Change the following Common_Lisp code into Python without altering its purpose. | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Change the programming language of this snippet from Common_Lisp to VB without modifying what it does. | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Maintain the same structure and functionality when rewriting this code in Go. | (defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
(unless (or (eq '_ x) (= i column))
(push x neighbors)))))
(defun column-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid i column)))
(unless (or (eq x '_) (= i row))
(push x neighbors)))))
(defun square-neighbors (row column grid &aux (neighbors '()))
(let* ((rmin (* 3 (floor row 3))) (rmax (+ rmin 3))
(cmin (* 3 (floor column 3))) (cmax (+ cmin 3)))
(do ((r rmin (1+ r))) ((= r rmax) neighbors)
(do ((c cmin (1+ c))) ((= c cmax))
(let ((x (aref grid r c)))
(unless (or (eq x '_) (= r row) (= c column))
(push x neighbors)))))))
(defun choices (row column grid)
(nset-difference
(list 1 2 3 4 5 6 7 8 9)
(nconc (row-neighbors row column grid)
(column-neighbors row column grid)
(square-neighbors row column grid))))
(defun solve (grid &optional (row 0) (column 0))
(cond
((= row 9)
grid)
((= column 9)
(solve grid (1+ row) 0))
((not (eq '_ (aref grid row column)))
(solve grid row (1+ column)))
(t (dolist (choice (choices row column grid) (setf (aref grid row column) '_))
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Port the provided D code into C while preserving the original functionality. | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Convert this D snippet to C# and keep its semantics consistent. | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Preserve the algorithm and functionality while converting the code from D to C++. | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Rewrite the snippet below in Java so it works the same as the original D code. | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Translate this program into Python but keep the logic exactly as in D. | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Port the following code from D to VB with equivalent syntax and logic. | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Can you help me rewrite this code in Go instead of D, keeping it the same logically? | import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
struct Digit {
immutable char d;
this(in char d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = d_; }
this(in int d_) pure nothrow @safe @nogc
in { assert(d_ >= '0' && d_ <= '9'); }
body { this.d = cast(char)d_; }
alias d this;
}
enum size_t sudokuUnitSide = 3;
enum size_t sudokuSide = sudokuUnitSide ^^ 2;
alias SudokuTable = Digit[sudokuSide ^^ 2];
Nullable!SudokuTable sudokuSolver(in ref SudokuTable problem)
pure nothrow {
alias Tgrid = uint;
Tgrid[SudokuTable.length] grid = void;
problem[].map!(c => c - '0').copy(grid[]);
Tgrid access(in size_t x, in size_t y) nothrow @safe @nogc {
return grid[y * sudokuSide + x];
}
bool checkValidity(in Tgrid val, in size_t x, in size_t y)
pure nothrow @safe @nogc {
foreach (immutable i; staticIota!(0, sudokuSide))
if (access(i, y) == val || access(x, i) == val)
return false;
immutable startX = (x / sudokuUnitSide) * sudokuUnitSide;
immutable startY = (y / sudokuUnitSide) * sudokuUnitSide;
foreach (immutable i; staticIota!(0, sudokuUnitSide))
foreach (immutable j; staticIota!(0, sudokuUnitSide))
if (access(startX + j, startY + i) == val)
return false;
return true;
}
bool canPlaceNumbers(in size_t pos=0) nothrow @safe @nogc {
if (pos == SudokuTable.length)
return true;
if (grid[pos] > 0)
return canPlaceNumbers(pos + 1);
foreach (immutable n; 1 .. sudokuSide + 1)
if (checkValidity(n, pos % sudokuSide, pos / sudokuSide)) {
grid[pos] = n;
if (canPlaceNumbers(pos + 1))
return true;
grid[pos] = 0;
}
return false;
}
if (canPlaceNumbers) {
immutable SudokuTable result = grid[]
.map!(c => Digit(c + '0'))
.array;
return typeof(return)(result);
} else
return typeof(return)();
}
string representSudoku(in ref SudokuTable sudo)
pure nothrow @safe out(result) {
assert(result.countchars("1-9") == sudo[].count!q{a != '0'});
assert(result.countchars(".") == sudo[].count!q{a == '0'});
} body {
static assert(sudo.length == 81,
"representSudoku works only with a 9x9 Sudoku.");
string result;
foreach (immutable i; 0 .. sudokuSide) {
foreach (immutable j; 0 .. sudokuSide) {
result ~= sudo[i * sudokuSide + j];
result ~= ' ';
if (j == 2 || j == 5)
result ~= "| ";
}
result ~= "\n";
if (i == 2 || i == 5)
result ~= "------+-------+------\n";
}
return result.replace("0", ".");
}
void main() {
enum ValidateCells(string s) = s.map!Digit.array;
immutable SudokuTable problem = ValidateCells!("
850002400
720000009
004000000
000107002
305000900
040000000
000080070
017000000
000036040".removechars(whitespace));
problem.representSudoku.writeln;
immutable solution = problem.sudokuSolver;
if (solution.isNull)
writeln("Unsolvable!");
else
solution.get.representSudoku.writeln;
}
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Please provide an equivalent version of this Delphi code in C. | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Keep all operations the same but rewrite the snippet in C#. | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Convert this Delphi snippet to C++ and keep its semantics consistent. | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Change the following Delphi code into Java without altering its purpose. | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Can you help me rewrite this code in Python instead of Delphi, keeping it the same logically? | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Convert this Delphi block to VB, preserving its control flow and logic. | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Convert this Delphi block to Go, preserving its control flow and logic. | type
TIntArray = array of Integer;
TSudokuSolver = class
private
FGrid: TIntArray;
function CheckValidity(val: Integer; x: Integer; y: Integer): Boolean;
function ToString: string; reintroduce;
function PlaceNumber(pos: Integer): Boolean;
public
constructor Create(s: string);
procedure Solve;
end;
implementation
uses
Dialogs;
function TSudokuSolver.CheckValidity(val: Integer; x: Integer; y: Integer
): Boolean;
var
i: Integer;
j: Integer;
StartX: Integer;
StartY: Integer;
begin
for i := 0 to 8 do
begin
if (FGrid[y * 9 + i] = val) or
(FGrid[i * 9 + x] = val) then
begin
Result := False;
Exit;
end;
end;
StartX := (x div 3) * 3;
StartY := (y div 3) * 3;
for i := StartY to Pred(StartY + 3) do
begin
for j := StartX to Pred(StartX + 3) do
begin
if FGrid[i * 9 + j] = val then
begin
Result := False;
Exit;
end;
end;
end;
Result := True;
end;
function TSudokuSolver.ToString: string;
var
sb: string;
i: Integer;
j: Integer;
c: char;
begin
sb := '';
for i := 0 to 8 do
begin
for j := 0 to 8 do
begin
c := (IntToStr(FGrid[i * 9 + j]) + '0')[1];
sb := sb + c + ' ';
if (j = 2) or (j = 5) then sb := sb + '| ';
end;
sb := sb + #13#10;
if (i = 2) or (i = 5) then
sb := sb + '-----+-----+-----' + #13#10;
end;
Result := sb;
end;
function TSudokuSolver.PlaceNumber(pos: Integer): Boolean;
var
n: Integer;
begin
Result := False;
if Pos = 81 then
begin
Result := True;
Exit;
end;
if FGrid[pos] > 0 then
begin
Result := PlaceNumber(Succ(pos));
Exit;
end;
for n := 1 to 9 do
begin
if CheckValidity(n, pos mod 9, pos div 9) then
begin
FGrid[pos] := n;
Result := PlaceNumber(Succ(pos));
if not Result then
FGrid[pos] := 0;
end;
end;
end;
constructor TSudokuSolver.Create(s: string);
var
lcv: Cardinal;
begin
SetLength(FGrid, 81);
for lcv := 0 to Pred(Length(s)) do
FGrid[lcv] := StrToInt(s[Succ(lcv)]);
end;
procedure TSudokuSolver.Solve;
begin
if not PlaceNumber(0) then
ShowMessage('Unsolvable')
else
ShowMessage('Solved!');
end;
end;
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Translate this program into C but keep the logic exactly as in Elixir. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Generate a C# translation of this Elixir snippet without changing its computational steps. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Translate the given Elixir code snippet into C++ without altering its behavior. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Convert this Elixir snippet to Java and keep its semantics consistent. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Ensure the translated VB code behaves exactly like the original Elixir snippet. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Produce a functionally identical Go code for the snippet given in Elixir. | defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
def start( knowns ), do: Enum.into( knowns, Map.new )
def solve( grid ) do
sure = solve_all_sure( grid )
solve_unsure( potentials(sure), sure )
end
def task( knowns ) do
IO.puts "start"
start = start( knowns )
display( start )
IO.puts "solved"
solved = solve( start )
display( solved )
IO.puts ""
end
defp bt( grid ), do: bt_reject( is_not_allowed(grid), grid )
defp bt_accept( true, board ), do: throw( {:ok, board} )
defp bt_accept( false, grid ), do: bt_loop( potentials_one_position(grid), grid )
defp bt_loop( {position, values}, grid ), do: ( for x <- values, do: bt( Map.put(grid, position, x) ) )
defp bt_reject( true, _grid ), do: :backtrack
defp bt_reject( false, grid ), do: bt_accept( is_all_correct(grid), grid )
defp display_row( row, grid ) do
for x <- [1, 4, 7], do: display_row_group( x, row, grid )
display_row_nl( row )
end
defp display_row_group( start, row, grid ) do
Enum.each(start..start+2, &IO.write "
IO.write " "
end
defp display_row_nl( n ) when n in [3,6,9], do: IO.puts "\n"
defp display_row_nl( _n ), do: IO.puts ""
defp is_all_correct( grid ), do: map_size( grid ) == 81
defp is_not_allowed( grid ) do
is_not_allowed_rows( grid ) or is_not_allowed_columns( grid ) or is_not_allowed_groups( grid )
end
defp is_not_allowed_columns( grid ), do: values_all_columns(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_groups( grid ), do: values_all_groups(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_rows( grid ), do: values_all_rows(grid) |> Enum.any?(&is_not_allowed_values/1)
defp is_not_allowed_values( values ), do: length( values ) != length( Enum.uniq(values) )
defp group_positions( {x, y} ) do
for colum <- group_positions_close(x), row <- group_positions_close(y), do: {colum, row}
end
defp group_positions_close( n ) when n < 4, do: [1,2,3]
defp group_positions_close( n ) when n < 7, do: [4,5,6]
defp group_positions_close( _n ) , do: [7,8,9]
defp positions_not_in_grid( grid ) do
keys = Map.keys( grid )
for x <- 1..9, y <- 1..9, not {x, y} in keys, do: {x, y}
end
defp potentials_one_position( grid ) do
Enum.min_by( potentials( grid ), fn {_position, values} -> length(values) end )
end
defp potentials( grid ), do: List.flatten( for x <- positions_not_in_grid(grid), do: potentials(x, grid) )
defp potentials( position, grid ) do
useds = potentials_used_values( position, grid )
{position, Enum.to_list(1..9) -- useds }
end
defp potentials_used_values( {x, y}, grid ) do
row_values = (for row <- 1..9, row != x, do: {row, y}) |> potentials_values( grid )
column_values = (for column <- 1..9, column != y, do: {x, column}) |> potentials_values( grid )
group_values = group_positions({x, y}) -- [ {x, y} ] |> potentials_values( grid )
row_values ++ column_values ++ group_values
end
defp potentials_values( keys, grid ) do
for x <- keys, val = grid[x], do: val
end
defp values_all_columns( grid ) do
for x <- 1..9, do:
( for y <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp values_all_groups( grid ) do
[[g1,g2,g3], [g4,g5,g6], [g7,g8,g9]] = for x <- [1,4,7], do: values_all_groups(x, grid)
[g1,g2,g3,g4,g5,g6,g7,g8,g9]
end
defp values_all_groups( x, grid ) do
for x_offset <- x..x+2, do: values_all_groups(x, x_offset, grid)
end
defp values_all_groups( _x, x_offset, grid ) do
( for y_offset <- group_positions_close(x_offset), do: {x_offset, y_offset} )
|> potentials_values( grid )
end
defp values_all_rows( grid ) do
for y <- 1..9, do:
( for x <- 1..9, do: {x, y} ) |> potentials_values( grid )
end
defp solve_all_sure( grid ), do: solve_all_sure( solve_all_sure_values(grid), grid )
defp solve_all_sure( [], grid ), do: grid
defp solve_all_sure( sures, grid ) do
solve_all_sure( Enum.reduce(sures, grid, &solve_all_sure_store/2) )
end
defp solve_all_sure_values( grid ), do: (for{position, [value]} <- potentials(grid), do: {position, value} )
defp solve_all_sure_store( {position, value}, acc ), do: Map.put( acc, position, value )
defp solve_unsure( [], grid ), do: grid
defp solve_unsure( _potentials, grid ) do
try do
bt( grid )
catch
{:ok, board} -> board
end
end
end
simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}]
Sudoku.task( simple )
difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Port the provided Erlang code into C while preserving the original functionality. | -module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Convert the following code from Erlang to C#, ensuring the logic remains intact. | -module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Port the following code from Erlang to C++ with equivalent syntax and logic. | -module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Write the same code in Java as shown below in Erlang. | -module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Please provide an equivalent version of this Erlang code in Python. | -module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Maintain the same structure and functionality when rewriting this code in VB. | -module( sudoku ).
-export( [display/1, start/1, solve/1, task/0] ).
display( Grid ) -> [display_row(Y, Grid) || Y <- lists:seq(1, 9)].
start( Knowns ) -> dict:from_list( Knowns ).
solve( Grid ) ->
Sure = solve_all_sure( Grid ),
solve_unsure( potentials(Sure), Sure ).
task() ->
Simple = [{{1, 1}, 3}, {{2, 1}, 9}, {{3, 1},4}, {{6, 1}, 2}, {{7, 1}, 6}, {{8, 1}, 7},
{{4, 2}, 3}, {{7, 2}, 4},
{{1, 3}, 5}, {{4, 3}, 6}, {{5, 3}, 9}, {{8, 3}, 2},
{{2, 4}, 4}, {{3, 4}, 5}, {{7, 4}, 9},
{{1, 5}, 6}, {{9, 5}, 7},
{{3, 6}, 7}, {{7, 6}, 5}, {{8, 6}, 8},
{{2, 7}, 1}, {{5, 7}, 6}, {{6, 7}, 7}, {{9, 7}, 8},
{{3, 8}, 9}, {{6, 8}, 8},
{{2, 9}, 2}, {{3, 9}, 6}, {{4, 9}, 4}, {{7, 9}, 7}, {{8, 9}, 3}, {{9, 9}, 5}],
task( Simple ),
Difficult = [{{6, 2}, 3}, {{8, 2}, 8}, {{9, 2}, 5},
{{3, 3}, 1}, {{5, 3}, 2},
{{4, 4}, 5}, {{6, 4}, 7},
{{3, 5}, 4}, {{7, 5}, 1},
{{2, 6}, 9},
{{1, 7}, 5}, {{8, 7}, 7}, {{9, 7}, 3},
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}],
task( Difficult ).
bt( Grid ) -> bt_reject( is_not_allowed(Grid), Grid ).
bt_accept( true, Board ) -> erlang:throw( {ok, Board} );
bt_accept( false, Grid ) -> bt_loop( potentials_one_position(Grid), Grid ).
bt_loop( {Position, Values}, Grid ) -> [bt( dict:store(Position, X, Grid) ) || X <- Values].
bt_reject( true, _Grid ) -> backtrack;
bt_reject( false, Grid ) -> bt_accept( is_all_correct(Grid), Grid ).
display_row( Row, Grid ) ->
[display_row_group( X, Row, Grid ) || X <- [1, 4, 7]],
display_row_nl( Row ).
display_row_group( Start, Row, Grid ) ->
[io:fwrite(" ~c", [display_value(X, Row, Grid)]) || X <- [Start, Start+1, Start+2]],
io:fwrite( " " ).
display_row_nl( N ) when N =:= 3; N =:= 6; N =:= 9 -> io:nl(), io:nl();
display_row_nl( _N ) -> io:nl().
display_value( X, Y, Grid ) -> display_value( dict:find({X, Y}, Grid) ).
display_value( error ) -> $.;
display_value( {ok, Value} ) -> Value + $0.
is_all_correct( Grid ) -> dict:size( Grid ) =:= 81.
is_not_allowed( Grid ) ->
is_not_allowed_rows( Grid )
orelse is_not_allowed_columns( Grid )
orelse is_not_allowed_groups( Grid ).
is_not_allowed_columns( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_columns(Grid) ).
is_not_allowed_groups( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_groups(Grid) ).
is_not_allowed_rows( Grid ) -> lists:any( fun is_not_allowed_values/1, values_all_rows(Grid) ).
is_not_allowed_values( Values ) -> erlang:length( Values ) =/= erlang:length( lists:usort(Values) ).
group_positions( {X, Y} ) -> [{Colum, Row} || Colum <- group_positions_close(X), Row <- group_positions_close(Y)].
group_positions_close( N ) when N < 4 -> [1,2,3];
group_positions_close( N ) when N < 7 -> [4,5,6];
group_positions_close( _N ) -> [7,8,9].
positions_not_in_grid( Grid ) ->
Keys = dict:fetch_keys( Grid ),
[{X, Y} || X <- lists:seq(1, 9), Y <- lists:seq(1, 9), not lists:member({X, Y}, Keys)].
potentials_one_position( Grid ) ->
[{_Shortest, Position, Values} | _T] = lists:sort( [{erlang:length(Values), Position, Values} || {Position, Values} <- potentials( Grid )] ),
{Position, Values}.
potentials( Grid ) -> lists:flatten( [potentials(X, Grid) || X <- positions_not_in_grid(Grid)] ).
potentials( Position, Grid ) ->
Useds = potentials_used_values( Position, Grid ),
{Position, [Value || Value <- lists:seq(1, 9) -- Useds]}.
potentials_used_values( {X, Y}, Grid ) ->
Row_positions = [{Row, Y} || Row <- lists:seq(1, 9), Row =/= X],
Row_values = potentials_values( Row_positions, Grid ),
Column_positions = [{X, Column} || Column <- lists:seq(1, 9), Column =/= Y],
Column_values = potentials_values( Column_positions, Grid ),
Group_positions = lists:delete( {X, Y}, group_positions({X, Y}) ),
Group_values = potentials_values( Group_positions, Grid ),
Row_values ++ Column_values ++ Group_values.
potentials_values( Keys, Grid ) ->
Row_values_unfiltered = [dict:find(X, Grid) || X <- Keys],
[Value || {ok, Value} <- Row_values_unfiltered].
values_all_columns( Grid ) -> [values_all_columns(X, Grid) || X <- lists:seq(1, 9)].
values_all_columns( X, Grid ) ->
Positions = [{X, Y} || Y <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
values_all_groups( Grid ) ->
[G123, G456, G789] = [values_all_groups(X, Grid) || X <- [1, 4, 7]],
[G1,G2,G3] = G123,
[G4,G5,G6] = G456,
[G7,G8,G9] = G789,
[G1,G2,G3,G4,G5,G6,G7,G8,G9].
values_all_groups( X, Grid ) ->[values_all_groups(X, X_offset, Grid) || X_offset <- [X, X+1, X+2]].
values_all_groups( _X, X_offset, Grid ) ->
Positions = [{X_offset, Y_offset} || Y_offset <- group_positions_close(X_offset)],
potentials_values( Positions, Grid ).
values_all_rows( Grid ) ->[values_all_rows(Y, Grid) || Y <- lists:seq(1, 9)].
values_all_rows( Y, Grid ) ->
Positions = [{X, Y} || X <- lists:seq(1, 9)],
potentials_values( Positions, Grid ).
solve_all_sure( Grid ) -> solve_all_sure( solve_all_sure_values(Grid), Grid ).
solve_all_sure( [], Grid ) -> Grid;
solve_all_sure( Sures, Grid ) -> solve_all_sure( lists:foldl(fun solve_all_sure_store/2, Grid, Sures) ).
solve_all_sure_values( Grid ) -> [{Position, Value} || {Position, [Value]} <- potentials(Grid)].
solve_all_sure_store( {Position, Value}, Acc ) -> dict:store( Position, Value, Acc ).
solve_unsure( [], Grid ) -> Grid;
solve_unsure( _Potentials, Grid ) ->
try
bt( Grid )
catch
_:{ok, Board} -> Board
end.
task( Knowns ) ->
io:fwrite( "Start~n" ),
Start = start( Knowns ),
display( Start ),
io:fwrite( "Solved~n" ),
Solved = solve( Start ),
display( Solved ),
io:nl().
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Rewrite this program in C while keeping its functionality equivalent to the F# version. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Preserve the algorithm and functionality while converting the code from F# to C#. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Please provide an equivalent version of this F# code in C++. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Generate an equivalent Java version of this F# code. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Maintain the same structure and functionality when rewriting this code in Python. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Please provide an equivalent version of this F# code in VB. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Produce a language-to-language conversion: from F# to Go, same semantics. | module SudokuBacktrack
let tuple2 a b = a,b
let flip f a b = f b a
let (>>=) f g = Option.bind g f
let key a b = $"{a}{b}"
let cross ax bx = [| for a in ax do for b in bx do key a b |]
let valid = "1234567890.,"
let rows = "ABCDEFGHI"
let cols = "123456789"
let squares = cross rows cols
let unitList =
[for c in cols do cross rows (string c) ]@
[for r in rows do cross (string r) cols ]@
[for rs in ["ABC";"DEF";"GHI"] do for cs in ["123";"456";"789"] do cross rs cs ]
let units =
[for s in squares do s, [| for u in unitList do if u |> Array.contains s then u |] ] |> Map.ofSeq
let peers =
[for s in squares do units[s] |> Array.concat |> Array.distinct |> Array.except [s] |> tuple2 s] |> Map.ofSeq
let parseGrid grid =
let ints = [for c in grid do if valid |> Seq.contains c then if ",." |> Seq.contains c then 0 else (c |> string |> int)]
if Seq.length ints = 81 then ints |> Seq.zip squares |> Map.ofSeq |> Some else None
let asString = function
| Some values -> values |> Map.toSeq |> Seq.map (snd>>string) |> String.concat ""
| _ -> "No solution or Parse Failure"
let prettyPrint = function
| Some (values:Map<_,_>) ->
[for r in rows do [for c in cols do (values[key r c] |> string) ] |> String.concat " " ] |> String.concat "\n"
| _ -> "No solution or Parse Failure"
let constraints (values:Map<_,_>) s d = peers[s] |> Seq.map (fun p -> values[p]) |> Seq.exists ((=) d) |> not
let next s = squares |> Array.tryFindIndex ((=)s) |> function Some i when i + 1 < 81 -> Some squares[i + 1] | _ -> None
let rec backtracker (values:Map<_,_>) = function
| None -> Some values
| Some s when values[s] > 0 -> backtracker values (next s)
| Some s ->
let rec tracker = function
| [] -> None
| d::dx ->
values
|> Map.change s (Option.map (fun _ -> d))
|> flip backtracker (next s)
|> function
| None -> tracker dx
| success -> success
[for d in 1..9 do if constraints values s d then d] |> tracker
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Ensure the translated C code behaves exactly like the original Forth snippet. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Write the same code in C# as shown below in Forth. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Translate the given Forth code snippet into C++ without altering its behavior. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Transform the following Forth implementation into Java, maintaining the same output and logic. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Write the same code in Python as shown below in Forth. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Generate a VB translation of this Forth snippet without changing its computational steps. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Write a version of this Forth function in Go with identical behavior. | include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
81 string sudokugrid
9 array sudoku_row
9 array sudoku_col
9 array sudoku_box
: >grid
rot dup >r 9 chars * sudokugrid + dup >r swap
0 do
over i chars + c@ dup is-digit
if [char] 0 - over c! char+ else drop then
loop
nip r> - 9 / r> +
;
0
s" 090004007" >grid
s" 000007900" >grid
s" 800000000" >grid
s" 405800000" >grid
s" 300000002" >grid
s" 000009706" >grid
s" 000000004" >grid
s" 003500000" >grid
s" 200600080" >grid
drop
: xy 9 * + ;
: getrow 9 / ;
: getcol 9 mod ;
: getbox dup getrow 3 / 3 * swap getcol 3 / + ;
: setnumber sudokugrid + c! ;
: getnumber sudokugrid + c@ ;
: cleargrid sudokugrid 81 bounds do 0 i c! loop ;
: addbits_row cells sudoku_row + dup @ rot 1 swap lshift or swap ! ;
: addbits_col cells sudoku_col + dup @ rot 1 swap lshift or swap ! ;
: addbits_box cells sudoku_box + dup @ rot 1 swap lshift or swap ! ;
: removebits_row cells sudoku_row + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_col cells sudoku_col + dup @ rot 1 swap lshift invert and swap ! ;
: removebits_box cells sudoku_box + dup @ rot 1 swap lshift invert and swap ! ;
: clearbitmaps 9 0 do i cells
0 over sudoku_row + !
0 over sudoku_col + !
0 swap sudoku_box + !
loop ;
: addnumber
2dup setnumber
2dup getrow addbits_row
2dup getcol addbits_col
getbox addbits_box
;
: removenumber
dup getnumber swap
2dup getrow removebits_row
2dup getcol removebits_col
2dup getbox removebits_box
nip 0 swap setnumber
;
: getrow_bits getrow cells sudoku_row + @ ;
: getcol_bits getcol cells sudoku_col + @ ;
: getbox_bits getbox cells sudoku_box + @ ;
: getbits
dup getrow_bits
over getcol_bits
rot getbox_bits or or
;
: countbits
[HEX] DUP 55555555 AND SWAP 1 RSHIFT 55555555 AND +
DUP 33333333 AND SWAP 2 RSHIFT 33333333 AND +
DUP 0F0F0F0F AND SWAP 4 RSHIFT 0F0F0F0F AND +
[DECIMAL] 255 MOD
;
: try
getbits 1 rot lshift and 0=
;
: parsegrid
sudokugrid
81 0 do
dup i + c@
dup if
dup i try if
i addnumber
else
unloop drop drop FALSE exit
then
else
drop
then
loop
drop
TRUE
;
: morespaces?
0 sudokugrid 81 bounds do i c@ 0= if 1+ then loop ;
: findnextmove
-1 10
81 0 do
i sudokugrid + c@ 0= IF
i getbits countbits 9 swap -
2dup > if
nip nip i swap
else
drop
then
THEN
loop
drop
;
: solver
findnextmove
dup 0< if
morespaces? if
drop false exit
else
drop true exit
then
then
10 1 do
i over try if
i over addnumber
recurse if
drop unloop TRUE EXIT
else
dup removenumber
then
then
loop
drop FALSE
;
: startsolving
clearbitmaps
parsegrid
solver
AND
;
: .sudokugrid
CR CR
sudokugrid
81 0 do
dup i + c@ .
i 1+
dup 3 mod 0= if
dup 9 mod 0= if
CR
dup 27 mod 0= if
dup 81 < if ." ------+-------+------" CR then
then
else
." | "
then
then
drop
loop
drop
CR
;
: checkifoccupied
sudokugrid + c@
;
: add
xy 2dup
dup checkifoccupied if
dup removenumber
then
try if
addnumber
.sudokugrid
else
CR ." Not a valid move. " CR
2drop
then
;
: rm
xy removenumber
.sudokugrid
;
: clearit
cleargrid
clearbitmaps
.sudokugrid
;
: solveit
CR
startsolving
if
." Solution found!" CR .sudokugrid
else
." No solution found!" CR CR
then
;
: showit .sudokugrid ;
: help
CR
." Type clearit ; to clear grid " CR
." 1-9 x y add ; to add 1-9 to grid at x y " CR
." x y rm ; to remove number at x y " CR
." showit ; redisplay grid " CR
." solveit ; to solve " CR
." help ; for help " CR
CR
;
: godoit
clearbitmaps
parsegrid if
CR ." Grid valid!"
else
CR ." Warning: grid invalid!"
then
.sudokugrid
help
;
: read-sudoku
input 1 arg-open 0
begin dup 9 < while refill while 0 parse >grid repeat
drop close
;
: bye quit ;
create wordlist
," clearit" ' clearit ,
," add" ' add ,
," rm" ' rm ,
," showit" ' showit ,
," solveit" ' solveit ,
," quit" ' bye ,
," exit" ' bye ,
," bye" ' bye ,
," q" ' bye ,
," help" ' help ,
NULL ,
wordlist to dictionary
:noname ." Unknown command '" type ." '" cr ; is NotFound
: sudoku
argn 1 > if read-sudoku then
godoit
begin
." OK" cr
refill drop ['] interpret
catch if ." Error" cr then
again
;
sudoku
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Write the same code in C# as shown below in Fortran. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Write the same algorithm in C++ as shown in this Fortran implementation. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Produce a functionally identical C code for the snippet given in Fortran. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Preserve the algorithm and functionality while converting the code from Fortran to Java. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Keep all operations the same but rewrite the snippet in Python. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Write the same algorithm in VB as shown in this Fortran implementation. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Rewrite the snippet below in PHP so it works the same as the original Fortran code. | program sudoku
implicit none
integer, dimension (9, 9) :: grid
integer, dimension (9, 9) :: grid_solved
grid = reshape ((/ &
& 0, 0, 3, 0, 2, 0, 6, 0, 0, &
& 9, 0, 0, 3, 0, 5, 0, 0, 1, &
& 0, 0, 1, 8, 0, 6, 4, 0, 0, &
& 0, 0, 8, 1, 0, 2, 9, 0, 0, &
& 7, 0, 0, 0, 0, 0, 0, 0, 8, &
& 0, 0, 6, 7, 0, 8, 2, 0, 0, &
& 0, 0, 2, 6, 0, 9, 5, 0, 0, &
& 8, 0, 0, 2, 0, 3, 0, 0, 9, &
& 0, 0, 5, 0, 1, 0, 3, 0, 0/), &
& shape = (/9, 9/), &
& order = (/2, 1/))
call pretty_print (grid)
call solve (1, 1)
write (*, *)
call pretty_print (grid_solved)
contains
recursive subroutine solve (i, j)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer :: n
integer :: n_tmp
if (i > 9) then
grid_solved = grid
else
do n = 1, 9
if (is_safe (i, j, n)) then
n_tmp = grid (i, j)
grid (i, j) = n
if (j == 9) then
call solve (i + 1, 1)
else
call solve (i, j + 1)
end if
grid (i, j) = n_tmp
end if
end do
end if
end subroutine solve
function is_safe (i, j, n) result (res)
implicit none
integer, intent (in) :: i
integer, intent (in) :: j
integer, intent (in) :: n
logical :: res
integer :: i_min
integer :: j_min
if (grid (i, j) == n) then
res = .true.
return
end if
if (grid (i, j) /= 0) then
res = .false.
return
end if
if (any (grid (i, :) == n)) then
res = .false.
return
end if
if (any (grid (:, j) == n)) then
res = .false.
return
end if
i_min = 1 + 3 * ((i - 1) / 3)
j_min = 1 + 3 * ((j - 1) / 3)
if (any (grid (i_min : i_min + 2, j_min : j_min + 2) == n)) then
res = .false.
return
end if
res = .true.
end function is_safe
subroutine pretty_print (grid)
implicit none
integer, dimension (9, 9), intent (in) :: grid
integer :: i
integer :: j
character (*), parameter :: bar = '+-----+-----+-----+'
character (*), parameter :: fmt = '(3 ("|", i0, 1x, i0, 1x, i0), "|")'
write (*, '(a)') bar
do j = 0, 6, 3
do i = j + 1, j + 3
write (*, fmt) grid (i, :)
end do
write (*, '(a)') bar
end do
end subroutine pretty_print
end program sudoku
| class SudokuSolver {
protected $grid = [];
protected $emptySymbol;
public static function parseString($str, $emptySymbol = '0')
{
$grid = str_split($str);
foreach($grid as &$v)
{
if($v == $emptySymbol)
{
$v = 0;
}
else
{
$v = (int)$v;
}
}
return $grid;
}
public function __construct($str, $emptySymbol = '0') {
if(strlen($str) !== 81)
{
throw new \Exception('Error sudoku');
}
$this->grid = static::parseString($str, $emptySymbol);
$this->emptySymbol = $emptySymbol;
}
public function solve()
{
try
{
$this->placeNumber(0);
return false;
}
catch(\Exception $e)
{
return true;
}
}
protected function placeNumber($pos)
{
if($pos == 81)
{
throw new \Exception('Finish');
}
if($this->grid[$pos] > 0)
{
$this->placeNumber($pos+1);
return;
}
for($n = 1; $n <= 9; $n++)
{
if($this->checkValidity($n, $pos%9, floor($pos/9)))
{
$this->grid[$pos] = $n;
$this->placeNumber($pos+1);
$this->grid[$pos] = 0;
}
}
}
protected function checkValidity($val, $x, $y)
{
for($i = 0; $i < 9; $i++)
{
if(($this->grid[$y*9+$i] == $val) || ($this->grid[$i*9+$x] == $val))
{
return false;
}
}
$startX = (int) ((int)($x/3)*3);
$startY = (int) ((int)($y/3)*3);
for($i = $startY; $i<$startY+3;$i++)
{
for($j = $startX; $j<$startX+3;$j++)
{
if($this->grid[$i*9+$j] == $val)
{
return false;
}
}
}
return true;
}
public function display() {
$str = '';
for($i = 0; $i<9; $i++)
{
for($j = 0; $j<9;$j++)
{
$str .= $this->grid[$i*9+$j];
$str .= " ";
if($j == 2 || $j == 5)
{
$str .= "| ";
}
}
$str .= PHP_EOL;
if($i == 2 || $i == 5)
{
$str .= "------+-------+------".PHP_EOL;
}
}
echo $str;
}
public function __toString() {
foreach ($this->grid as &$item)
{
if($item == 0)
{
$item = $this->emptySymbol;
}
}
return implode('', $this->grid);
}
}
$solver = new SudokuSolver('009170000020600001800200000200006053000051009005040080040000700006000320700003900');
$solver->solve();
$solver->display();
|
Convert this Groovy block to C, preserving its control flow and logic. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Maintain the same structure and functionality when rewriting this code in C#. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Transform the following Groovy implementation into C++, maintaining the same output and logic. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Write the same code in Python as shown below in Groovy. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Produce a functionally identical VB code for the snippet given in Groovy. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Port the provided Groovy code into Go while preserving the original functionality. | final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
GridException(String message) { super(message) }
}
def string2grid = { string ->
assert string.size() == 81
(0..8).collect { i -> (0..8).collect { j -> string[9*i+j] } }
}
def gridRow = { grid, slot -> grid[slot.i] as Set }
def gridCol = { grid, slot -> grid.collect { it[slot.j] } as Set }
def gridBox = { grid, slot ->
def t, l; (t, l) = [slot.i.intdiv(3)*3, slot.j.intdiv(3)*3]
(0..2).collect { row -> (0..2).collect { col -> grid[t+row][l+col] } }.flatten() as Set
}
def slotList = { grid ->
def slots = (0..8).collect { i -> (0..8).findAll { j -> grid[i][j] == '.' } \
.collect {j -> [i: i, j: j] } }.flatten()
}
def assignCandidates = { grid, slots = slotList(grid) ->
slots.each { slot ->
def unavailable = [gridRow, gridCol, gridBox].collect { it(grid, slot) }.sum() as Set
slot.candidates = CELL_VALUES - unavailable
}
slots.sort { - it.candidates.size() }
if (slots && ! slots[-1].candidates) {
throw new GridException('Invalid Sudoku Grid, overdetermined slot: ' + slots[-1])
}
slots
}
def isSolved = { grid -> ! (grid.flatten().find { it == '.' }) }
def solve
solve = { grid ->
def slots = assignCandidates(grid)
if (! slots) { return grid }
while (slots[-1].candidates.size() == 1) {
def slot = slots.pop()
grid[slot.i][slot.j] = slot.candidates[0]
if (! slots) { return grid }
slots = assignCandidates(grid, slots)
}
if (! slots) { return grid }
def slot = slots.pop()
slot.candidates.each {
if (! isSolved(grid)) {
try {
def sGrid = grid.collect { row -> row.collect { cell -> cell } }
sGrid[slot.i][slot.j] = it
grid = solve(sGrid)
} catch (GridException ge) {
grid[slot.i][slot.j] = '.'
}
}
}
if (!isSolved(grid)) {
slots = assignCandidates(grid)
throw new GridException('Invalid Sudoku Grid, underdetermined slots: ' + slots)
}
grid
}
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Convert the following code from Julia to C, ensuring the logic remains intact. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Translate the given Julia code snippet into C# without altering its behavior. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Preserve the algorithm and functionality while converting the code from Julia to C++. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Maintain the same structure and functionality when rewriting this code in Java. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Rewrite the snippet below in Python so it works the same as the original Julia code. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Keep all operations the same but rewrite the snippet in VB. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Write a version of this Julia function in Go with identical behavior. | function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
jd == id && return true
jm == im && return true
div(id, 3) == div(jd, 3) &&
div(jm, 3) == div(im, 3)
end
const lookup = zeros(Bool, 81, 81)
for i in 1:81
for j in 1:81
lookup[i,j] = check(i-1, j-1)
end
end
function solve_sudoku(callback::Function, grid::Array{Int64})
(function solve()
for i in 1:81
if grid[i] == 0
t = Dict{Int64, Nothing}()
for j in 1:81
if lookup[i,j]
t[grid[j]] = nothing
end
end
for k in 1:9
if !haskey(t, k)
grid[i] = k
solve()
end
end
grid[i] = 0
return
end
end
callback(grid)
end)()
end
function display(grid)
for i in 1:length(grid)
print(grid[i], " ")
i % 3 == 0 && print(" ")
i % 9 == 0 && print("\n")
i % 27 == 0 && print("\n")
end
end
grid = Int64[5, 3, 0, 0, 2, 4, 7, 0, 0,
0, 0, 2, 0, 0, 0, 8, 0, 0,
1, 0, 0, 7, 0, 3, 9, 0, 2,
0, 0, 8, 0, 7, 2, 0, 4, 9,
0, 2, 0, 9, 8, 0, 0, 7, 0,
7, 9, 0, 0, 0, 0, 0, 8, 0,
0, 0, 0, 0, 3, 0, 5, 0, 6,
9, 6, 0, 0, 1, 0, 3, 0, 0,
0, 5, 0, 6, 9, 0, 0, 1, 0]
solve_sudoku(display, grid)
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Please provide an equivalent version of this Lua code in C. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Convert the following code from Lua to C#, ensuring the logic remains intact. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Translate the given Lua code snippet into C++ without altering its behavior. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Ensure the translated Java code behaves exactly like the original Lua snippet. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Change the following Lua code into Python without altering its purpose. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Rewrite the snippet below in VB so it works the same as the original Lua code. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Please provide an equivalent version of this Lua code in Go. |
concat=table.concat
insert=table.insert
constraints = { }
columns = { }
rows = { }
blocks = { }
for f = 1, 81 do
constraints[f] = { }
end
all_constraints = { }
for i = 1, 9 do
columns[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, columns[i])
rows[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, rows[i])
blocks[i] = {
unknown = 9,
unknowns = { }
}
insert(all_constraints, blocks[i])
end
constraints_by_unknown = { }
for i = 0, 9 do
constraints_by_unknown[i] = {
count = 0
}
end
for r = 1, 9 do
for c = 1, 9 do
local f = (r - 1) * 9 + c
insert(rows[r], f)
insert(constraints[f], rows[r])
insert(columns[c], f)
insert(constraints[f], columns[c])
end
end
for i = 1, 3 do
for j = 1, 3 do
local r = (i - 1) * 3 + j
for k = 1, 3 do
for l = 1, 3 do
local c = (k - 1) * 3 + l
local f = (r - 1) * 9 + c
local b = (i - 1) * 3 + k
insert(blocks[b], f)
insert(constraints[f], blocks[b])
end
end
end
end
working = { }
function read()
local f = 1
local l = io.read("*a")
for d in l:gmatch("(%d)") do
local n = tonumber(d)
if n > 0 then
working[f] = n
for _,cons in pairs(constraints[f]) do
cons.unknown = cons.unknown - 1
end
else
for _,cons in pairs(constraints[f]) do
cons.unknowns[f] = f
end
end
f = f + 1
end
assert((f == 82), "Wrong number of digits")
end
read()
function printer(t)
local pattern = {1,2,3,false,4,5,6,false,7,8,9}
for _,r in pairs(pattern) do
if r then
local function p(c)
return c and t[(r - 1) * 9 + c] or "|"
end
local line={}
for k,v in pairs(pattern) do
line[k]=p(v)
end
print(concat(line))
else
print("
end
end
end
order = { }
for _,cons in pairs(all_constraints) do
local level = constraints_by_unknown[cons.unknown]
level[cons] = cons
level.count = level.count + 1
end
function first(t)
for k, v in pairs(t) do
if k == v then
return k
end
end
end
function establish_order()
local solved = constraints_by_unknown[0].count
while solved < 27 do
local i = 1
while constraints_by_unknown[i].count == 0 do
i = i + 1
end
local cons = first(constraints_by_unknown[i])
local f = first(cons.unknowns)
insert(order, f)
for _,c in pairs(constraints[f]) do
c.unknowns[f] = nil
local level = constraints_by_unknown[c.unknown]
level[c] = nil
level.count = level.count - 1
c.unknown = c.unknown - 1
level = constraints_by_unknown[c.unknown]
level[c] = c
level.count = level.count + 1
constraints_by_unknown[c.unknown][c] = c
end
solved = constraints_by_unknown[0].count
end
end
establish_order()
max = #order
function bound(f,i)
for _,c in pairs(constraints[f]) do
for _,x in pairs(c) do
if i == working[x] then
return false
end
end
end
return true
end
function branch(n)
local f = order[n]
if n > max then
return working
else
for i = 1, 9 do
if bound(f, i) then
working[f] = i
local res = branch(n + 1)
if res then
return res
else
working[f] = nil
end
else
working[f] = nil
end
end
return false
end
end
x = branch(1)
if x then
return printer(x)
end
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Please provide an equivalent version of this Mathematica code in C. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Convert the following code from Mathematica to C#, ensuring the logic remains intact. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Convert this Mathematica block to C++, preserving its control flow and logic. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Generate a Java translation of this Mathematica snippet without changing its computational steps. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Write the same algorithm in Python as shown in this Mathematica implementation. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Convert this Mathematica snippet to VB and keep its semantics consistent. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| Dim grid(9, 9)
Dim gridSolved(9, 9)
Public Sub Solve(i, j)
If i > 9 Then
For r = 1 To 9
For c = 1 To 9
gridSolved(r, c) = grid(r, c)
Next c
Next r
Exit Sub
End If
For n = 1 To 9
If isSafe(i, j, n) Then
nTmp = grid(i, j)
grid(i, j) = n
If j = 9 Then
Solve i + 1, 1
Else
Solve i, j + 1
End If
grid(i, j) = nTmp
End If
Next n
End Sub
Public Function isSafe(i, j, n) As Boolean
Dim iMin As Integer
Dim jMin As Integer
If grid(i, j) <> 0 Then
isSafe = (grid(i, j) = n)
Exit Function
End If
For c = 1 To 9
If grid(i, c) = n Then
isSafe = False
Exit Function
End If
Next c
For r = 1 To 9
If grid(r, j) = n Then
isSafe = False
Exit Function
End If
Next r
iMin = 1 + 3 * Int((i - 1) / 3)
jMin = 1 + 3 * Int((j - 1) / 3)
For r = iMin To iMin + 2
For c = jMin To jMin + 2
If grid(r, c) = n Then
isSafe = False
Exit Function
End If
Next c
Next r
isSafe = True
End Function
Public Sub Sudoku()
Dim s(9) As String
s(1) = "001005070"
s(2) = "920600000"
s(3) = "008000600"
s(4) = "090020401"
s(5) = "000000000"
s(6) = "304080090"
s(7) = "007000300"
s(8) = "000007069"
s(9) = "010800700"
For i = 1 To 9
For j = 1 To 9
grid(i, j) = Int(Val(Mid$(s(i), j, 1)))
Next j
Next i
Solve 1, 1
Debug.Print "Solution:"
For i = 1 To 9
For j = 1 To 9
Debug.Print Format$(gridSolved(i, j)); " ";
Next j
Debug.Print
Next i
End Sub
|
Write the same code in Go as shown below in Mathematica. | solve[sudoku_] :=
NestWhile[
Join @@ Table[
Table[ReplacePart[s, #1 -> n], {n, #2}] & @@
First@SortBy[{#,
Complement[Range@9, s[[First@#]], s[[;; , Last@#]],
Catenate@
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]
| package main
import "fmt"
var puzzle = "" +
"394 267 " +
" 3 4 " +
"5 69 2 " +
" 45 9 " +
"6 7" +
" 7 58 " +
" 1 67 8" +
" 9 8 " +
" 264 735"
func main() {
printGrid("puzzle:", puzzle)
if s := solve(puzzle); s == "" {
fmt.Println("no solution")
} else {
printGrid("solved:", s)
}
}
func printGrid(title, s string) {
fmt.Println(title)
for r, i := 0, 0; r < 9; r, i = r+1, i+9 {
fmt.Printf("%c %c %c | %c %c %c | %c %c %c\n", s[i], s[i+1], s[i+2],
s[i+3], s[i+4], s[i+5], s[i+6], s[i+7], s[i+8])
if r == 2 || r == 5 {
fmt.Println("------+-------+------")
}
}
}
func solve(u string) string {
d := newDlxObject(324)
for r, i := 0, 0; r < 9; r++ {
for c := 0; c < 9; c, i = c+1, i+1 {
b := r/3*3 + c/3
n := int(u[i] - '1')
if n >= 0 && n < 9 {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
} else {
for n = 0; n < 9; n++ {
d.addRow([]int{i, 81 + r*9 + n, 162 + c*9 + n,
243 + b*9 + n})
}
}
}
}
d.search()
return d.text()
}
type x struct {
c *y
u, d, l, r *x
x0 *x
}
type y struct {
x
s int
n int
}
type dlx struct {
ch []y
h *y
o []*x
}
func newDlxObject(nCols int) *dlx {
ch := make([]y, nCols+1)
h := &ch[0]
d := &dlx{ch, h, nil}
h.c = h
h.l = &ch[nCols].x
ch[nCols].r = &h.x
nh := ch[1:]
for i := range ch[1:] {
hi := &nh[i]
ix := &hi.x
hi.n = i
hi.c = hi
hi.u = ix
hi.d = ix
hi.l = &h.x
h.r = ix
h = hi
}
return d
}
func (d *dlx) addRow(nr []int) {
if len(nr) == 0 {
return
}
r := make([]x, len(nr))
x0 := &r[0]
for x, j := range nr {
ch := &d.ch[j+1]
ch.s++
np := &r[x]
np.c = ch
np.u = ch.u
np.d = &ch.x
np.l = &r[(x+len(r)-1)%len(r)]
np.r = &r[(x+1)%len(r)]
np.u.d, np.d.u, np.l.r, np.r.l = np, np, np, np
np.x0 = x0
}
}
func (d *dlx) text() string {
b := make([]byte, len(d.o))
for _, r := range d.o {
x0 := r.x0
b[x0.c.n] = byte(x0.r.c.n%9) + '1'
}
return string(b)
}
func (d *dlx) search() bool {
h := d.h
j := h.r.c
if j == h {
return true
}
c := j
for minS := j.s; ; {
j = j.r.c
if j == h {
break
}
if j.s < minS {
c, minS = j, j.s
}
}
cover(c)
k := len(d.o)
d.o = append(d.o, nil)
for r := c.d; r != &c.x; r = r.d {
d.o[k] = r
for j := r.r; j != r; j = j.r {
cover(j.c)
}
if d.search() {
return true
}
r = d.o[k]
c = r.c
for j := r.l; j != r; j = j.l {
uncover(j.c)
}
}
d.o = d.o[:len(d.o)-1]
uncover(c)
return false
}
func cover(c *y) {
c.r.l, c.l.r = c.l, c.r
for i := c.d; i != &c.x; i = i.d {
for j := i.r; j != i; j = j.r {
j.d.u, j.u.d = j.u, j.d
j.c.s--
}
}
}
func uncover(c *y) {
for i := c.u; i != &c.x; i = i.u {
for j := i.l; j != i; j = j.l {
j.c.s++
j.d.u, j.u.d = j, j
}
}
c.r.l, c.l.r = &c.x, &c.x
}
|
Rewrite this program in C while keeping its functionality equivalent to the MATLAB version. | function solution = sudokuSolver(sudokuGrid)
subBoxes(1:9,1:9) = {{(1:3),(1:3)}};
subBoxes(4:6,:)= {{(4:6),(1:3)}};
subBoxes(7:9,:)= {{(7:9),(1:3)}};
for column = (4:6)
for row = (1:9)
subBoxes{row,column}(2)= {4:6};
end
end
for column = (7:9)
for row = (1:9)
subBoxes{row,column}(2)= {7:9};
end
end
possibleValues(1:9,1:9) = { (1:9) };
possibleValues( ~isnan(sudokuGrid) )={[]};
solution = sudokuGrid;
memory = 0;
dontStop = true;
while( dontStop )
while( ~isequal(possibleValues,memory) )
memory = possibleValues;
for row = (1:9)
for column = (1:9)
if isnan( solution(row,column) )
removableValues = solution( ~isnan(solution(:,column)),column );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
removableValues = solution( row,~isnan(solution(row,:)) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
currentBoxBoundaries=subBoxes{row,column};
box = solution(currentBoxBoundaries{:});
removableValues = box( ~isnan(box) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
end
end
end
if ~isempty( find( histc( solution,(1:9),1 )>1 ) )
solution = false;
return
end
if ~isempty( find( histc( solution,(1:9),2 )>1 ) )
solution = false;
return
end
subBoxBins = zeros(9,9);
counter = 0;
for row = [2 5 8]
for column = [2 5 8]
counter = counter +1;
subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 );
end
end
if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) )
solution = false;
return
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
for counter = (1:numel(rowStack))
if isempty(possibleValues{rowStack(counter),columnStack(counter)})
solution = false;
return
end
end
elseif (numel(rowStack) == 0)
return
end
keepGoing = true;
dontStop = false;
[rowStack,columnStack] = find(isnan(solution));
counter = 0;
while( keepGoing && (counter < numel(rowStack)) )
counter = counter + 1;
row = rowStack(counter);
column = columnStack(counter);
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(column) = [];
rowPossibles = [possibleValues{row,coords}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(row) = [];
columnPossibles = [possibleValues{coords,column}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
currentBoxBoundaries = subBoxes{row,column};
subBoxPossibles = [];
for m = currentBoxBoundaries{1}
for n = currentBoxBoundaries{2}
if ~((m == row) && (n == column))
subBoxPossibles = [subBoxPossibles possibleValues{m,n}];
end
end
end
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
end
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
searchTreeNodes = possibleValues{rowStack(1),columnStack(1)};
keepSearching = true;
counter = 0;
tempSolution = solution;
while( keepSearching && (counter < numel(searchTreeNodes)) )
counter = counter + 1;
tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter);
tempSolution = sudokuSolver(tempSolution);
if ~islogical(tempSolution)
keepSearching = false;
solution = tempSolution;
elseif counter == numel(searchTreeNodes)
solution = false;
else
tempSolution = solution;
end
end
end
end
| #include <stdio.h>
void show(int *x)
{
int i, j;
for (i = 0; i < 9; i++) {
if (!(i % 3)) putchar('\n');
for (j = 0; j < 9; j++)
printf(j % 3 ? "%2d" : "%3d", *x++);
putchar('\n');
}
}
int trycell(int *x, int pos)
{
int row = pos / 9;
int col = pos % 9;
int i, j, used = 0;
if (pos == 81) return 1;
if (x[pos]) return trycell(x, pos + 1);
for (i = 0; i < 9; i++)
used |= 1 << (x[i * 9 + col] - 1);
for (j = 0; j < 9; j++)
used |= 1 << (x[row * 9 + j] - 1);
row = row / 3 * 3;
col = col / 3 * 3;
for (i = row; i < row + 3; i++)
for (j = col; j < col + 3; j++)
used |= 1 << (x[i * 9 + j] - 1);
for (x[pos] = 1; x[pos] <= 9; x[pos]++, used >>= 1)
if (!(used & 1) && trycell(x, pos + 1)) return 1;
x[pos] = 0;
return 0;
}
void solve(const char *s)
{
int i, x[81];
for (i = 0; i < 81; i++)
x[i] = s[i] >= '1' && s[i] <= '9' ? s[i] - '0' : 0;
if (trycell(x, 0))
show(x);
else
puts("no solution");
}
int main(void)
{
solve( "5x..7...."
"6..195..."
".98....6."
"8...6...3"
"4..8.3..1"
"7...2...6"
".6....28."
"...419..5"
"....8..79" );
return 0;
}
|
Rewrite this program in C# while keeping its functionality equivalent to the MATLAB version. | function solution = sudokuSolver(sudokuGrid)
subBoxes(1:9,1:9) = {{(1:3),(1:3)}};
subBoxes(4:6,:)= {{(4:6),(1:3)}};
subBoxes(7:9,:)= {{(7:9),(1:3)}};
for column = (4:6)
for row = (1:9)
subBoxes{row,column}(2)= {4:6};
end
end
for column = (7:9)
for row = (1:9)
subBoxes{row,column}(2)= {7:9};
end
end
possibleValues(1:9,1:9) = { (1:9) };
possibleValues( ~isnan(sudokuGrid) )={[]};
solution = sudokuGrid;
memory = 0;
dontStop = true;
while( dontStop )
while( ~isequal(possibleValues,memory) )
memory = possibleValues;
for row = (1:9)
for column = (1:9)
if isnan( solution(row,column) )
removableValues = solution( ~isnan(solution(:,column)),column );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
removableValues = solution( row,~isnan(solution(row,:)) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
currentBoxBoundaries=subBoxes{row,column};
box = solution(currentBoxBoundaries{:});
removableValues = box( ~isnan(box) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
end
end
end
if ~isempty( find( histc( solution,(1:9),1 )>1 ) )
solution = false;
return
end
if ~isempty( find( histc( solution,(1:9),2 )>1 ) )
solution = false;
return
end
subBoxBins = zeros(9,9);
counter = 0;
for row = [2 5 8]
for column = [2 5 8]
counter = counter +1;
subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 );
end
end
if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) )
solution = false;
return
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
for counter = (1:numel(rowStack))
if isempty(possibleValues{rowStack(counter),columnStack(counter)})
solution = false;
return
end
end
elseif (numel(rowStack) == 0)
return
end
keepGoing = true;
dontStop = false;
[rowStack,columnStack] = find(isnan(solution));
counter = 0;
while( keepGoing && (counter < numel(rowStack)) )
counter = counter + 1;
row = rowStack(counter);
column = columnStack(counter);
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(column) = [];
rowPossibles = [possibleValues{row,coords}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(row) = [];
columnPossibles = [possibleValues{coords,column}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
currentBoxBoundaries = subBoxes{row,column};
subBoxPossibles = [];
for m = currentBoxBoundaries{1}
for n = currentBoxBoundaries{2}
if ~((m == row) && (n == column))
subBoxPossibles = [subBoxPossibles possibleValues{m,n}];
end
end
end
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
end
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
searchTreeNodes = possibleValues{rowStack(1),columnStack(1)};
keepSearching = true;
counter = 0;
tempSolution = solution;
while( keepSearching && (counter < numel(searchTreeNodes)) )
counter = counter + 1;
tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter);
tempSolution = sudokuSolver(tempSolution);
if ~islogical(tempSolution)
keepSearching = false;
solution = tempSolution;
elseif counter == numel(searchTreeNodes)
solution = false;
else
tempSolution = solution;
end
end
end
end
| using System;
class SudokuSolver
{
private int[] grid;
public SudokuSolver(String s)
{
grid = new int[81];
for (int i = 0; i < s.Length; i++)
{
grid[i] = int.Parse(s[i].ToString());
}
}
public void solve()
{
try
{
placeNumber(0);
Console.WriteLine("Unsolvable!");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine(this);
}
}
public void placeNumber(int pos)
{
if (pos == 81)
{
throw new Exception("Finished!");
}
if (grid[pos] > 0)
{
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++)
{
if (checkValidity(n, pos % 9, pos / 9))
{
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
public bool checkValidity(int val, int x, int y)
{
for (int i = 0; i < 9; i++)
{
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++)
{
for (int j = startX; j < startX + 3; j++)
{
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
public override string ToString()
{
string sb = "";
for (int i = 0; i < 9; i++)
{
for (int j = 0; j < 9; j++)
{
sb += (grid[i * 9 + j] + " ");
if (j == 2 || j == 5)
sb += ("| ");
}
sb += ('\n');
if (i == 2 || i == 5)
sb += ("------+-------+------\n");
}
return sb;
}
public static void Main(String[] args)
{
new SudokuSolver("850002400" +
"720000009" +
"004000000" +
"000107002" +
"305000900" +
"040000000" +
"000080070" +
"017000000" +
"000036040").solve();
Console.Read();
}
}
|
Write a version of this MATLAB function in C++ with identical behavior. | function solution = sudokuSolver(sudokuGrid)
subBoxes(1:9,1:9) = {{(1:3),(1:3)}};
subBoxes(4:6,:)= {{(4:6),(1:3)}};
subBoxes(7:9,:)= {{(7:9),(1:3)}};
for column = (4:6)
for row = (1:9)
subBoxes{row,column}(2)= {4:6};
end
end
for column = (7:9)
for row = (1:9)
subBoxes{row,column}(2)= {7:9};
end
end
possibleValues(1:9,1:9) = { (1:9) };
possibleValues( ~isnan(sudokuGrid) )={[]};
solution = sudokuGrid;
memory = 0;
dontStop = true;
while( dontStop )
while( ~isequal(possibleValues,memory) )
memory = possibleValues;
for row = (1:9)
for column = (1:9)
if isnan( solution(row,column) )
removableValues = solution( ~isnan(solution(:,column)),column );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
removableValues = solution( row,~isnan(solution(row,:)) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
currentBoxBoundaries=subBoxes{row,column};
box = solution(currentBoxBoundaries{:});
removableValues = box( ~isnan(box) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
end
end
end
if ~isempty( find( histc( solution,(1:9),1 )>1 ) )
solution = false;
return
end
if ~isempty( find( histc( solution,(1:9),2 )>1 ) )
solution = false;
return
end
subBoxBins = zeros(9,9);
counter = 0;
for row = [2 5 8]
for column = [2 5 8]
counter = counter +1;
subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 );
end
end
if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) )
solution = false;
return
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
for counter = (1:numel(rowStack))
if isempty(possibleValues{rowStack(counter),columnStack(counter)})
solution = false;
return
end
end
elseif (numel(rowStack) == 0)
return
end
keepGoing = true;
dontStop = false;
[rowStack,columnStack] = find(isnan(solution));
counter = 0;
while( keepGoing && (counter < numel(rowStack)) )
counter = counter + 1;
row = rowStack(counter);
column = columnStack(counter);
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(column) = [];
rowPossibles = [possibleValues{row,coords}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(row) = [];
columnPossibles = [possibleValues{coords,column}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
currentBoxBoundaries = subBoxes{row,column};
subBoxPossibles = [];
for m = currentBoxBoundaries{1}
for n = currentBoxBoundaries{2}
if ~((m == row) && (n == column))
subBoxPossibles = [subBoxPossibles possibleValues{m,n}];
end
end
end
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
end
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
searchTreeNodes = possibleValues{rowStack(1),columnStack(1)};
keepSearching = true;
counter = 0;
tempSolution = solution;
while( keepSearching && (counter < numel(searchTreeNodes)) )
counter = counter + 1;
tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter);
tempSolution = sudokuSolver(tempSolution);
if ~islogical(tempSolution)
keepSearching = false;
solution = tempSolution;
elseif counter == numel(searchTreeNodes)
solution = false;
else
tempSolution = solution;
end
end
end
end
| #include <iostream>
using namespace std;
class SudokuSolver {
private:
int grid[81];
public:
SudokuSolver(string s) {
for (unsigned int i = 0; i < s.length(); i++) {
grid[i] = (int) (s[i] - '0');
}
}
void solve() {
try {
placeNumber(0);
cout << "Unsolvable!" << endl;
} catch (char* ex) {
cout << ex << endl;
cout << this->toString() << endl;
}
}
void placeNumber(int pos) {
if (pos == 81) {
throw (char*) "Finished!";
}
if (grid[pos] > 0) {
placeNumber(pos + 1);
return;
}
for (int n = 1; n <= 9; n++) {
if (checkValidity(n, pos % 9, pos / 9)) {
grid[pos] = n;
placeNumber(pos + 1);
grid[pos] = 0;
}
}
}
bool checkValidity(int val, int x, int y) {
for (int i = 0; i < 9; i++) {
if (grid[y * 9 + i] == val || grid[i * 9 + x] == val)
return false;
}
int startX = (x / 3) * 3;
int startY = (y / 3) * 3;
for (int i = startY; i < startY + 3; i++) {
for (int j = startX; j < startX + 3; j++) {
if (grid[i * 9 + j] == val)
return false;
}
}
return true;
}
string toString() {
string sb;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
char c[2];
c[0] = grid[i * 9 + j] + '0';
c[1] = '\0';
sb.append(c);
sb.append(" ");
if (j == 2 || j == 5)
sb.append("| ");
}
sb.append("\n");
if (i == 2 || i == 5)
sb.append("------+-------+------\n");
}
return sb;
}
};
int main() {
SudokuSolver ss("850002400"
"720000009"
"004000000"
"000107002"
"305000900"
"040000000"
"000080070"
"017000000"
"000036040");
ss.solve();
return EXIT_SUCCESS;
}
|
Ensure the translated Java code behaves exactly like the original MATLAB snippet. | function solution = sudokuSolver(sudokuGrid)
subBoxes(1:9,1:9) = {{(1:3),(1:3)}};
subBoxes(4:6,:)= {{(4:6),(1:3)}};
subBoxes(7:9,:)= {{(7:9),(1:3)}};
for column = (4:6)
for row = (1:9)
subBoxes{row,column}(2)= {4:6};
end
end
for column = (7:9)
for row = (1:9)
subBoxes{row,column}(2)= {7:9};
end
end
possibleValues(1:9,1:9) = { (1:9) };
possibleValues( ~isnan(sudokuGrid) )={[]};
solution = sudokuGrid;
memory = 0;
dontStop = true;
while( dontStop )
while( ~isequal(possibleValues,memory) )
memory = possibleValues;
for row = (1:9)
for column = (1:9)
if isnan( solution(row,column) )
removableValues = solution( ~isnan(solution(:,column)),column );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
removableValues = solution( row,~isnan(solution(row,:)) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
currentBoxBoundaries=subBoxes{row,column};
box = solution(currentBoxBoundaries{:});
removableValues = box( ~isnan(box) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
end
end
end
if ~isempty( find( histc( solution,(1:9),1 )>1 ) )
solution = false;
return
end
if ~isempty( find( histc( solution,(1:9),2 )>1 ) )
solution = false;
return
end
subBoxBins = zeros(9,9);
counter = 0;
for row = [2 5 8]
for column = [2 5 8]
counter = counter +1;
subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 );
end
end
if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) )
solution = false;
return
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
for counter = (1:numel(rowStack))
if isempty(possibleValues{rowStack(counter),columnStack(counter)})
solution = false;
return
end
end
elseif (numel(rowStack) == 0)
return
end
keepGoing = true;
dontStop = false;
[rowStack,columnStack] = find(isnan(solution));
counter = 0;
while( keepGoing && (counter < numel(rowStack)) )
counter = counter + 1;
row = rowStack(counter);
column = columnStack(counter);
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(column) = [];
rowPossibles = [possibleValues{row,coords}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(row) = [];
columnPossibles = [possibleValues{coords,column}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
currentBoxBoundaries = subBoxes{row,column};
subBoxPossibles = [];
for m = currentBoxBoundaries{1}
for n = currentBoxBoundaries{2}
if ~((m == row) && (n == column))
subBoxPossibles = [subBoxPossibles possibleValues{m,n}];
end
end
end
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
end
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
searchTreeNodes = possibleValues{rowStack(1),columnStack(1)};
keepSearching = true;
counter = 0;
tempSolution = solution;
while( keepSearching && (counter < numel(searchTreeNodes)) )
counter = counter + 1;
tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter);
tempSolution = sudokuSolver(tempSolution);
if ~islogical(tempSolution)
keepSearching = false;
solution = tempSolution;
elseif counter == numel(searchTreeNodes)
solution = false;
else
tempSolution = solution;
end
end
end
end
| public class Sudoku
{
private int mBoard[][];
private int mBoardSize;
private int mBoxSize;
private boolean mRowSubset[][];
private boolean mColSubset[][];
private boolean mBoxSubset[][];
public Sudoku(int board[][]) {
mBoard = board;
mBoardSize = mBoard.length;
mBoxSize = (int)Math.sqrt(mBoardSize);
initSubsets();
}
public void initSubsets() {
mRowSubset = new boolean[mBoardSize][mBoardSize];
mColSubset = new boolean[mBoardSize][mBoardSize];
mBoxSubset = new boolean[mBoardSize][mBoardSize];
for(int i = 0; i < mBoard.length; i++) {
for(int j = 0; j < mBoard.length; j++) {
int value = mBoard[i][j];
if(value != 0) {
setSubsetValue(i, j, value, true);
}
}
}
}
private void setSubsetValue(int i, int j, int value, boolean present) {
mRowSubset[i][value - 1] = present;
mColSubset[j][value - 1] = present;
mBoxSubset[computeBoxNo(i, j)][value - 1] = present;
}
public boolean solve() {
return solve(0, 0);
}
public boolean solve(int i, int j) {
if(i == mBoardSize) {
i = 0;
if(++j == mBoardSize) {
return true;
}
}
if(mBoard[i][j] != 0) {
return solve(i + 1, j);
}
for(int value = 1; value <= mBoardSize; value++) {
if(isValid(i, j, value)) {
mBoard[i][j] = value;
setSubsetValue(i, j, value, true);
if(solve(i + 1, j)) {
return true;
}
setSubsetValue(i, j, value, false);
}
}
mBoard[i][j] = 0;
return false;
}
private boolean isValid(int i, int j, int val) {
val--;
boolean isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val];
return !isPresent;
}
private int computeBoxNo(int i, int j) {
int boxRow = i / mBoxSize;
int boxCol = j / mBoxSize;
return boxRow * mBoxSize + boxCol;
}
public void print() {
for(int i = 0; i < mBoardSize; i++) {
if(i % mBoxSize == 0) {
System.out.println(" -----------------------");
}
for(int j = 0; j < mBoardSize; j++) {
if(j % mBoxSize == 0) {
System.out.print("| ");
}
System.out.print(mBoard[i][j] != 0 ? ((Object) (Integer.valueOf(mBoard[i][j]))) : "-");
System.out.print(' ');
}
System.out.println("|");
}
System.out.println(" -----------------------");
}
public static void main(String[] args) {
int[][] board = {
{8, 5, 0, 0, 0, 2, 4, 0, 0},
{7, 2, 0, 0, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 1, 0, 7, 0, 0, 2},
{3, 0, 5, 0, 0, 0, 9, 0, 0},
{0, 4, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 8, 0, 0, 7, 0},
{0, 1, 7, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 3, 6, 0, 4, 0}
};
Sudoku s = new Sudoku(board);
System.out.print("Starting grid:\n");
s.print();
if (s.solve()) {
System.out.print("\nSolution:\n");
s.print();
} else {
System.out.println("\nUnsolvable!");
}
}
}
|
Port the provided MATLAB code into Python while preserving the original functionality. | function solution = sudokuSolver(sudokuGrid)
subBoxes(1:9,1:9) = {{(1:3),(1:3)}};
subBoxes(4:6,:)= {{(4:6),(1:3)}};
subBoxes(7:9,:)= {{(7:9),(1:3)}};
for column = (4:6)
for row = (1:9)
subBoxes{row,column}(2)= {4:6};
end
end
for column = (7:9)
for row = (1:9)
subBoxes{row,column}(2)= {7:9};
end
end
possibleValues(1:9,1:9) = { (1:9) };
possibleValues( ~isnan(sudokuGrid) )={[]};
solution = sudokuGrid;
memory = 0;
dontStop = true;
while( dontStop )
while( ~isequal(possibleValues,memory) )
memory = possibleValues;
for row = (1:9)
for column = (1:9)
if isnan( solution(row,column) )
removableValues = solution( ~isnan(solution(:,column)),column );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
removableValues = solution( row,~isnan(solution(row,:)) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
if isnan( solution(row,column) )
currentBoxBoundaries=subBoxes{row,column};
box = solution(currentBoxBoundaries{:});
removableValues = box( ~isnan(box) );
if ~isempty(removableValues)
for m = ( 1:numel(removableValues) )
possibleValues{row,column}( possibleValues{row,column}==removableValues(m) )=[];
end
end
if numel( possibleValues{row,column} ) == 1
solution(row,column) = possibleValues{row,column};
possibleValues(row,column)={[]};
end
end
end
end
end
if ~isempty( find( histc( solution,(1:9),1 )>1 ) )
solution = false;
return
end
if ~isempty( find( histc( solution,(1:9),2 )>1 ) )
solution = false;
return
end
subBoxBins = zeros(9,9);
counter = 0;
for row = [2 5 8]
for column = [2 5 8]
counter = counter +1;
subBoxBins(counter,:) = reshape( solution(subBoxes{row,column}{:}),1,9 );
end
end
if ~isempty( find( histc( subBoxBins,(1:9),2 )>1 ) )
solution = false;
return
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
for counter = (1:numel(rowStack))
if isempty(possibleValues{rowStack(counter),columnStack(counter)})
solution = false;
return
end
end
elseif (numel(rowStack) == 0)
return
end
keepGoing = true;
dontStop = false;
[rowStack,columnStack] = find(isnan(solution));
counter = 0;
while( keepGoing && (counter < numel(rowStack)) )
counter = counter + 1;
row = rowStack(counter);
column = columnStack(counter);
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(column) = [];
rowPossibles = [possibleValues{row,coords}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (rowPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
coords = (1:9);
coords(row) = [];
columnPossibles = [possibleValues{coords,column}];
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (columnPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
if(keepGoing)
gridPossibles = [possibleValues{row,column}];
currentBoxBoundaries = subBoxes{row,column};
subBoxPossibles = [];
for m = currentBoxBoundaries{1}
for n = currentBoxBoundaries{2}
if ~((m == row) && (n == column))
subBoxPossibles = [subBoxPossibles possibleValues{m,n}];
end
end
end
totalMatches = zeros( numel(gridPossibles),1 );
for n = ( 1:numel(gridPossibles) )
totalMatches(n) = sum( (subBoxPossibles == gridPossibles(n)) );
end
gridPossibles = gridPossibles(totalMatches==0);
if numel(gridPossibles) == 1
solution(row,column) = gridPossibles;
possibleValues(row,column)={[]};
keepGoing = false;
dontStop = true;
end
end
end
end
[rowStack,columnStack] = find(isnan(solution));
if (numel(rowStack) > 0)
searchTreeNodes = possibleValues{rowStack(1),columnStack(1)};
keepSearching = true;
counter = 0;
tempSolution = solution;
while( keepSearching && (counter < numel(searchTreeNodes)) )
counter = counter + 1;
tempSolution(rowStack(1),columnStack(1)) = searchTreeNodes(counter);
tempSolution = sudokuSolver(tempSolution);
if ~islogical(tempSolution)
keepSearching = false;
solution = tempSolution;
elseif counter == numel(searchTreeNodes)
solution = false;
else
tempSolution = solution;
end
end
end
end
| def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
box.append([3, 4, 5, 12, 13, 14, 21, 22, 23])
box.append([6, 7, 8, 15, 16, 17, 24, 25, 26])
box.append([27, 28, 29, 36, 37, 38, 45, 46, 47])
box.append([30, 31, 32, 39, 40, 41, 48, 49, 50])
box.append([33, 34, 35, 42, 43, 44, 51, 52, 53])
box.append([54, 55, 56, 63, 64, 65, 72, 73, 74])
box.append([57, 58, 59, 66, 67, 68, 75, 76, 77])
box.append([60, 61, 62, 69, 70, 71, 78, 79, 80])
for i in range(0, 81, 9):
row.append(range(i, i+9))
for i in range(9):
column.append(range(i, 80+i, 9))
def valid(n, pos):
current_row = pos/9
current_col = pos%9
current_box = (current_row/3)*3 + (current_col/3)
for i in row[current_row]:
if (grid[i] == n):
return False
for i in column[current_col]:
if (grid[i] == n):
return False
for i in box[current_box]:
if (grid[i] == n):
return False
return True
def solve():
i = 0
proceed = 1
while(i < 81):
if given[i]:
if proceed:
i += 1
else:
i -= 1
else:
n = grid[i]
prev = grid[i]
while(n < 9):
if (n < 9):
n += 1
if valid(n, i):
grid[i] = n
proceed = 1
break
if (grid[i] == prev):
grid[i] = 0
proceed = 0
if proceed:
i += 1
else:
i -=1
def inputs():
nextt = 'T'
number = 0
pos = 0
while(not(nextt == 'N' or nextt == 'n')):
print "Enter the position:",
pos = int(raw_input())
given[pos - 1] = True
print "Enter the numerical:",
number = int(raw_input())
grid[pos - 1] = number
print "Do you want to enter another given?(Y, for yes: N, for no)"
nextt = raw_input()
grid = [0]*81
given = [False]*81
box = []
row = []
column = []
initiate()
inputs()
solve()
for i in range(9):
print grid[i*9:i*9+9]
raw_input()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.