Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Ensure the translated VB 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
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
Generate a Go translation of this MATLAB snippet without changing its computational steps.
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
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 }
Preserve the algorithm and functionality while converting the code from Nim to C.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
#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 an equivalent C# version of this Nim code.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
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 code in C++ as shown below in Nim.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
#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 Nim.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
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 following code from Nim to Python with equivalent syntax and logic.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
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.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
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
Preserve the algorithm and functionality while converting the code from Nim to Go.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
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 the given OCaml code snippet into C without altering its behavior.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
#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#.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
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 the following code from OCaml to C++, ensuring the logic remains intact.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
#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; }
Keep all operations the same but rewrite the snippet in Java.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
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 OCaml code.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
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.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
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 OCaml code into Go without altering its purpose.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
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 }
Transform the following Pascal implementation into C, maintaining the same output and logic.
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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; }
Can you help me rewrite this code in C# instead of Pascal, keeping it the same logically?
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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(); } }
Produce a language-to-language conversion: from Pascal to C++, same semantics.
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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; }
Port the provided Pascal code into Java while preserving the original functionality.
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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 following code from Pascal to Python with equivalent syntax and logic.
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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()
Maintain the same structure and functionality when rewriting this code in VB.
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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
Can you help me rewrite this code in Go instead of Pascal, keeping it the same logically?
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); 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 }
Preserve the algorithm and functionality while converting the code from Perl to C.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
#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 Perl version.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
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(); } }
Rewrite this program in C++ while keeping its functionality equivalent to the Perl version.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
#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; }
Port the following code from Perl to Java with equivalent syntax and logic.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
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 Perl.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
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()
Transform the following Perl implementation into VB, maintaining the same output and logic.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
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 Perl.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
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 }
Preserve the algorithm and functionality while converting the code from Ruby to C.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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; }
Preserve the algorithm and functionality while converting the code from Ruby to C#.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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(); } }
Please provide an equivalent version of this Ruby code in C++.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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; }
Preserve the algorithm and functionality while converting the code from Ruby to Java.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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 Ruby code into Python without altering its purpose.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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()
Maintain the same structure and functionality when rewriting this code in VB.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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
Change the following Ruby code into Go without altering its purpose.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) 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 the given Scala code snippet into C without altering its behavior.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
#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 Scala implementation.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
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 Scala snippet to C++ and keep its semantics consistent.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
#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; }
Translate the given Scala code snippet into Java without altering its behavior.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
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 Scala, keeping it the same logically?
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
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 code in VB as shown below in Scala.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
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
Generate an equivalent Go version of this Scala code.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
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 Swift.
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
#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; }
Can you help me rewrite this code in C# instead of Swift, keeping it the same logically?
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
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 Swift, keeping it the same logically?
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
#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 a version of this Swift function in Java with identical behavior.
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
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 this program in Python while keeping its functionality equivalent to the Swift version.
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
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 a version of this Swift function in VB with identical behavior.
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
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 programming language of this snippet from Swift to Go without modifying what it does.
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
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 Tcl.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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; }
Translate the given Tcl code snippet into C# without altering its behavior.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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(); } }
Produce a language-to-language conversion: from Tcl to C++, same semantics.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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; }
Transform the following Tcl implementation into Java, maintaining the same output and logic.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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!"); } } }
Port the provided Tcl code into Python while preserving the original functionality.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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()
Rewrite the snippet below in VB so it works the same as the original Tcl code.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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
Ensure the translated Go code behaves exactly like the original Tcl snippet.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 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 }
Write the same algorithm in PHP as shown in this Rust implementation.
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
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();
Translate the given Ada code snippet into PHP without altering its behavior.
with Ada.Text_IO; procedure Sudoku is type sudoku_ar_t is array ( integer range 0..80 ) of integer range 0..9; FINISH_EXCEPTION : exception; procedure prettyprint(sudoku_ar: sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t); procedure solve(sudoku_ar: in out sudoku_ar_t); function checkValidity( val : integer; x : integer; y : integer; sudoku_ar: in sudoku_ar_t) return Boolean is begin for i in 0..8 loop if ( sudoku_ar( y * 9 + i ) = val or sudoku_ar( i * 9 + x ) = val ) then return False; end if; end loop; declare startX : constant integer := ( x / 3 ) * 3; startY : constant integer := ( y / 3 ) * 3; begin for i in startY..startY+2 loop for j in startX..startX+2 loop if ( sudoku_ar( i * 9 +j ) = val ) then return False; end if; end loop; end loop; return True; end; end checkValidity; procedure placeNumber(pos: Integer; sudoku_ar: in out sudoku_ar_t) is begin if ( pos = 81 ) then raise FINISH_EXCEPTION; end if; if ( sudoku_ar(pos) > 0 ) then placeNumber(pos+1, sudoku_ar); return; end if; for n in 1..9 loop if( checkValidity( n, pos mod 9, pos / 9 , sudoku_ar ) ) then sudoku_ar(pos) := n; placeNumber(pos + 1, sudoku_ar ); sudoku_ar(pos) := 0; end if; end loop; end placeNumber; procedure solve(sudoku_ar: in out sudoku_ar_t) is begin placeNumber( 0, sudoku_ar ); Ada.Text_IO.Put_Line("Unresolvable !"); exception when FINISH_EXCEPTION => Ada.Text_IO.Put_Line("Finished !"); prettyprint(sudoku_ar); end solve; procedure prettyprint(sudoku_ar: sudoku_ar_t) is line_sep : constant String := " begin for i in sudoku_ar'Range loop Ada.Text_IO.Put(sudoku_ar(i)'Image); if (i+1) mod 3 = 0 and not((i+1) mod 9 = 0) then Ada.Text_IO.Put("|"); end if; if (i+1) mod 9 = 0 then Ada.Text_IO.Put_Line(""); end if; if (i+1) mod 27 = 0 then Ada.Text_IO.Put_Line(line_sep); end if; end loop; end prettyprint; sudoku_ar : sudoku_ar_t := ( 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 ); begin solve( sudoku_ar ); end 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();
Port the provided AutoHotKey code into PHP while preserving the original functionality.
#SingleInstance, Force SetBatchLines, -1 SetTitleMatchMode, 3 Loop 9 { r := A_Index, y := r*17-8 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Loop 9 { c := A_Index, x := c*17+5 + (A_Index >= 7 ? 4 : A_Index >= 4 ? 2 : 0) Gui, Add, Edit, x%x% y%y% w17 h17 v%r%_%c% Center Number Limit1 gNext } } Gui, Add, Button, vButton gSolve w175 x10 Center, Solve Gui, Add, Text, vMsg r3, Enter Sudoku puzzle and click Solve Gui, Show,, Sudoku Solver Return Solve: Gui, Submit, NoHide Loop 9 { r := A_Index Loop 9 If (%r%_%A_Index% = "") puzzle .= "@" Else puzzle .= %r%_%A_Index% } s := A_TickCount answer := Sudoku(puzzle) iterations := ErrorLevel e := A_TickCount seconds := (e-s)/1000 StringSplit, a, answer, | Loop 9 { r := A_Index Loop 9 { b := (r*9)+A_Index-9 GuiControl,, %r%_%A_Index%, % a%b% GuiControl, +ReadOnly, %r%_%A_Index% } } if answer GuiControl,, Msg, Solved!`nTime: %seconds%s`nIterations: %iterations% else GuiControl,, Msg, Failed! :(`nTime: %seconds%s`nIterations: %iterations% GuiControl,, Button, Again! GuiControl, +gAgain, Button return GuiClose: ExitApp Again: Reload #IfWinActive, Sudoku Solver ~*Enter::GoSub % GetKeyState( "Shift", "P" ) ? "~Up" : "~Down" ~Up:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 1 && f <= 9) ? f+72 : f-9) GuiControl, Focus, Edit%f% return ~Down:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := ((f >= 73 && f <= 81) ? f-72 : f + 9) GuiControl, Focus, Edit%f% return ~Left:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f + 79, 81) + 1 GuiControl, Focus, Edit%f% return Next: ~Right:: GuiControlGet, f, focus StringTrimLeft, f, f, 4 f := Mod(f, 81) + 1 GuiControl, Focus, Edit%f% return #IfWinActive Sudoku( p ) { p := RegExReplace(p, "[^1-9@]"), ErrorLevel := 0 return Sudoku_Display(Sudoku_Solve(p)) } Sudoku_Solve( p, d = 0 ) { If (d >= 81), ErrorLevel++ return p If InStr( "123456789", SubStr(p, d+1, 1) ) return Sudoku_Solve(p, d+1) m := Sudoku_Constraints(p,d)   Loop 9 { If InStr(m, A_Index) Continue NumPut(Asc(A_Index), p, d, "Char") If r := Sudoku_Solve(p, d+1) return r } return 0 } Sudoku_Constraints( ByRef p, d ) { c := Mod(d,9) , r := (d - c) // 9 , b := r//3*27 + c//3*3 + 1 , c++ return ""   . SubStr(p, r * 9 + 1, 9)   . SubStr(p,c ,1) SubStr(p,c+9 ,1) SubStr(p,c+18,1) . SubStr(p,c+27,1) SubStr(p,c+36,1) SubStr(p,c+45,1) . SubStr(p,c+54,1) SubStr(p,c+63,1) SubStr(p,c+72,1) . SubStr(p, b, 3) SubStr(p, b+9, 3) SubStr(p, b+18, 3) } Sudoku_Display( p ) { If StrLen(p) = 81 loop 81 r .= SubStr(p, A_Index, 1) . "|" return r }
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();
Produce a functionally identical PHP code for the snippet given in AWK.
BEGIN { puzzle = "123456789 456789123 789123456 ......... ......... ......... ......... ......... ........." gsub(/ /,"",puzzle) if (length(puzzle) != 81) { error("length of puzzle is not 81") } if (puzzle !~ /^[1-9\.]+$/) { error("only 1-9 and . are valid") } if (gsub(/[1-9]/,"&",puzzle) < 17) { error("too few hints") } if (errors > 0) { exit(1) } plot(puzzle,"unsolved") if (dup_hints_check(puzzle) == 1) { if (solve(puzzle) == 1) { dup_hints_check(sos) plot(sos,"solved") printf("\nbef: %s\naft: %s\n",puzzle,sos) exit(0) } else { error("no solution") } } exit(1) } function dup_hints_check(ss, esf,msg,Rarr,Carr,Barr,i,r_row,r_col,r_pos,r_hint,c_row,c_col,c_pos,c_hint,box) { esf = errors for (i=0; i<81; i++) { r_row = int(i/9) + 1 r_col = i%9 + 1 r_pos = i + 1 r_hint = substr(ss,r_pos,1) Rarr[r_row,r_hint]++ c_row = i%9 + 1 c_col = int(i/9) + 1 c_pos = (c_row-1) * 9 + c_col c_hint = substr(ss,c_pos,1) Carr[c_col,c_hint]++ if ((r_row r_col) ~ /[123][123]/) { box = 1 } else if ((r_row r_col) ~ /[123][456]/) { box = 2 } else if ((r_row r_col) ~ /[123][789]/) { box = 3 } else if ((r_row r_col) ~ /[456][123]/) { box = 4 } else if ((r_row r_col) ~ /[456][456]/) { box = 5 } else if ((r_row r_col) ~ /[456][789]/) { box = 6 } else if ((r_row r_col) ~ /[789][123]/) { box = 7 } else if ((r_row r_col) ~ /[789][456]/) { box = 8 } else if ((r_row r_col) ~ /[789][789]/) { box = 9 } else { box = 0 } Barr[box,r_hint]++ } dup_hints_print(Rarr,"row") dup_hints_print(Carr,"column") dup_hints_print(Barr,"box") return((errors == esf) ? 1 : 0) } function dup_hints_print(arr,rcb, hint,i) { for (i=1; i<=9; i++) { for (hint=1; hint<=9; hint++) { if (arr[i,hint]+0 > 1) { error(sprintf("duplicate hint in %s %d",rcb,i)) } } } } function plot(ss,text1,text2, a,b,c,d,ou) { printf("| - - - + - - - + - - - | %s\n",text1) for (a=0; a<3; a++) { for (b=0; b<3; b++) { ou = "|" for (c=0; c<3; c++) { for (d=0; d<3; d++) { ou = sprintf("%s %1s",ou,substr(ss,1+d+3*c+9*b+27*a,1)) } ou = ou " |" } print(ou) } printf("| - - - + - - - + - - - | %s\n",(a==2)?text2:"") } } function solve(ss, a,b,c,d,e,r,co,ro,bi,bl,nss) { i = 0 do { i++ didit = 0 delete nr delete nc delete nb delete ca for (a=0; a<81; a++) { b = substr(ss,a+1,1) if (b == ".") { c = a % 9 r = int(a/9) ro = substr(ss,r*9+1,9) co = "" for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } bi = int(c/3)*3+(int(r/3)*3)*9+1 bl = "" for (d=0; d<3; d++) { bl = bl substr(ss,bi+d*9,3) } e = 0 for (d=1; d<10; d++) { if (index(ro co bl, d) == 0) { e++ nr[r,d]++ nc[c,d]++ nb[bi,d]++ ca[c,r,d] = bi } } if (e == 0) { return(0) } } } for (crd in ca) { if (ca[crd] != "") { split(crd,spl,SUBSEP) c = spl[1] r = spl[2] d = spl[3] bi = ca[crd] a = c + r * 9 if ((nr[r,d] == 1) || (nc[c,d] == 1) || (nb[bi,d] == 1)) { ss = substr(ss,1,a) d substr(ss,a+2,length(ss)) didit = 1 for (e=0; e<9; e++) { delete ca[c,e,d] delete ca[e,r,d] } for (e=0; e<3; e++) { for (b=0; b<3; b++) { delete ca[int(c/3)*3+b,int(r/3)*3+e,d] } } } } } } while (didit == 1) a = index(ss,".")-1 if (a == -1) { sos = ss return(1) } else { c = a % 9 r = int(a/9) co = substr(ss,r*9+1,9) for (d=0; d<9; d++) { co = co substr(ss,d*9+c+1,1) } c = int(c/3)*3+(int(r/3)*3)*9+1 for (d=0; d<3; d++) { co = co substr(ss,c+d*9,3) } for (b=1; b<10; b++) { if (index(co,b) == 0) { nss = substr(ss,1,a) b substr(ss,a+2,length(ss)) d = solve(nss) if (d == 1) { return(1) } } } } return(0) } function error(message) { printf("error: %s\n",message) ; errors++ }
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();
Transform the following BBC_Basic implementation into PHP, maintaining the same output and logic.
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%
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();
Please provide an equivalent version of this Clojure code in PHP.
(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)))))))
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();
Rewrite the snippet below in PHP so it works the same as the original Common_Lisp code.
(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))))))
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();
Produce a functionally identical PHP code for the snippet given 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; }
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();
Can you help me rewrite this code in PHP 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;
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();
Transform the following Elixir implementation into PHP, maintaining the same output and logic.
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 )
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();
Rewrite the snippet below in PHP so it works the same as the original Erlang code.
-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().
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();
Rewrite the snippet below in PHP so it works the same as the original 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")
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();
Port the provided Forth code into PHP while preserving the original functionality.
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
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();
Write the same algorithm in PHP 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
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();
Write a version of this Groovy function in PHP with identical behavior.
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 }
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();
Change the programming language of this snippet from Julia to PHP without modifying what it does.
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)
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();
Produce a language-to-language conversion: from Lua to PHP, same semantics.
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
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();
Produce a functionally identical PHP code for the snippet given 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] &]
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();
Please provide an equivalent version of this MATLAB code in PHP.
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
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();
Change the programming language of this snippet from Nim to PHP without modifying what it does.
{.this: self.} type Sudoku = ref object grid : array[81, int] solved : bool proc `$`(self: Sudoku): string = var sb: string = "" for i in 0..8: for j in 0..8: sb &= $grid[i * 9 + j] sb &= " " if j == 2 or j == 5: sb &= "| " sb &= "\n" if i == 2 or i == 5: sb &= "------+------+------\n" sb proc init(self: Sudoku, rows: array[9, string]) = for i in 0..8: for j in 0..8: grid[9 * i + j] = rows[i][j].int - '0'.int proc checkValidity(self: Sudoku, v, x, y: int): bool = for i in 0..8: if grid[y * 9 + i] == v or grid[i * 9 + x] == v: return false var startX = (x div 3) * 3 var startY = (y div 3) * 3 for i in startY..startY + 2: for j in startX..startX + 2: if grid[i * 9 + j] == v: return false result = true proc placeNumber(self: Sudoku, pos: int) = if solved: return if pos == 81: solved = true return if grid[pos] > 0: placeNumber(pos + 1) return for n in 1..9: if checkValidity(n, pos mod 9, pos div 9): grid[pos] = n placeNumber(pos + 1) if solved: return grid[pos] = 0 proc solve(self: Sudoku) = echo "Starting grid:\n\n", $self placeNumber(0) if solved: echo "Solution:\n\n", $self else: echo "Unsolvable!" var rows = ["850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040"] var puzzle = Sudoku() puzzle.init(rows) puzzle.solve()
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();
Change the programming language of this snippet from OCaml to PHP without modifying what it does.
open Format open Graph module G = Imperative.Graph.Abstract(struct type t = int * int end) let g = G.create () let nodes = let new_node i j = let v = G.V.create (i, j) in G.add_vertex g v; v in Array.init 9 (fun i -> Array.init 9 (new_node i)) let node i j = nodes.(i).(j) let () = for i = 0 to 8 do for j = 0 to 8 do for k = 0 to 8 do if k <> i then G.add_edge g (node i j) (node k j); if k <> j then G.add_edge g (node i j) (node i k); done; let gi = 3 * (i / 3) and gj = 3 * (j / 3) in for di = 0 to 2 do for dj = 0 to 2 do let i' = gi + di and j' = gj + dj in if i' <> i || j' <> j then G.add_edge g (node i j) (node i' j') done done done done let display () = for i = 0 to 8 do for j = 0 to 8 do printf "%d" (G.Mark.get (node i j)) done; printf "\n"; done; printf "@?" let () = for i = 0 to 8 do let s = read_line () in for j = 0 to 8 do match s.[j] with | '1'..'9' as ch -> G.Mark.set (node i j) (Char.code ch - Char.code '0') | _ -> () done done; display (); printf "---------@." module C = Coloring.Mark(G) let () = C.coloring g 9; display ()
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();
Generate a PHP translation of this Pascal snippet without changing its computational steps.
Program soduko; uses sysutils,crt; const carreeSize = 3; maxCoor = carreeSize*carreeSize; maxValue = maxCoor; maxMask = 1 shl (maxCoor+1)-1; type tLimit = 0..maxCoor-1; tValue = 0..maxCoor; tSteps = 0..maxCoor*maxCoor; tValField = array[tLimit,tLimit] of NativeInt; tBitrepr = 0..maxMask; tcol = array[tLimit] of NativeInt; trow = array[tLimit] of NativeInt; tcar = array[tLimit] of NativeInt; tpValue = ^NativeInt; tpLimit = ^tLimit; tpBitrepr= ^NativeInt; tchgVal = record cvCol, cvRow, cvCar : tpBitrepr; cvVal : tpValue; end; tpChgVal = ^tchgVal; tchgList = array[tSteps] of tchgVal; tField = record fdChgList: tchgList; fdCol : tcol; fdRow : trow; fdcar : tcar; fdVal : tValField; fdChgIdx : tSteps; end; const Expl0:tValField = ((9,0,7,0,0,0,3,0,0), (0,0,0,1,0,0,2,0,0), (6,0,0,0,0,8,0,0,0), (0,0,5,0,3,0,0,0,0), (0,0,0,0,0,0,0,8,4), (0,0,0,0,0,0,0,6,0), (0,0,0,2,7,0,0,0,0), (8,4,0,0,0,0,0,0,0), (0,6,0,0,0,0,0,0,0)); Expl1:tValField=((0,0,0,1,0,0,0,3,8), (2,0,0,0,0,5,0,0,0), (0,0,0,0,0,0,0,0,0), (0,5,0,0,0,0,4,0,0), (4,0,0,0,3,0,0,0,0), (0,0,0,7,0,0,0,0,6), (0,0,1,0,0,0,0,5,0), (0,0,0,0,6,0,2,0,0), (0,6,0,0,0,4,0,0,0)); var F, solF : TField; solCnt, callCnt: NativeUint; solFound : Boolean; procedure OutField(const F:tField); var rw,cl : tLimit; rowS: AnsiString; Begin GotoXy(1,1); For rw := low(tLimit) to High(tLimit) do Begin rowS := ' '; For cl := low(tLimit) to High(tLimit) do RowS :=RowS+IntToStr(F.fdVal[rw,cl]); writeln(RowS); end; end; function CarIdx(rw,cl: NativeInt):NativeInt; begin CarIdx:= (rw DIV carreeSize)*carreeSize +cl DIV carreeSize; end; function InsertTest(const F:tField;rw,cl:tLimit;value:tValue):boolean; var msk: tBitrepr; Begin result := (Value = 0); IF result then EXIT; msk := 1 shl (value-1); with F do Begin result := fdRow[rw] AND msk = 0; result := result AND (fdCol[cl] AND msk = 0); rw :=CarIdx(rw,cl); result := result AND (fdCar[rw] AND msk = 0); end; end; function InitField(var F:tField;const InFd:tValField;DoReverse:boolean):boolean; var TmpchgVal:tchgVal; rw,cl, value, msk : NativeInt; leftSteps:tSteps; Begin Fillchar(F,SizeOf(F),#0); leftSteps := High(tSteps)-1; For rw := low(tLimit) to High(tLimit) do For cl := low(tLimit) to High(tLimit) do Begin value := InFd[rw,cl]; IF InsertTest(F,rw,cl,value) then Begin with F do Begin if value > 0 then Begin msk := 1 shl (value-1); with fdChgList[fdChgIdx] do begin cvCol := @fdCol[cl]; cvCol^ +=Msk; cvRow := @fdRow[rw]; cvRow^ +=Msk; cvCar := @fdCar[CarIdx(rw,cl)]; cvCar^ +=Msk; cvVal := @fdVal[rw,cl]; cvVal^ := value; end; inc(fdChgIdx); end else Begin with fdChgList[leftSteps] do begin cvCol := @fdCol[cl]; cvRow := @fdRow[rw]; cvCar := @fdCar[CarIdx(rw,cl)]; cvVal := @fdVal[rw,cl]; end; dec(leftSteps); end; end end else Begin writeln(rw:10,cl:10,value:10); Writeln(' not solvable SuDoKu '); delay(2000); result := false; EXIT; end; end; IF DoReverse then Begin leftSteps := High(tSteps)-1; rw := F.fdChgIdx; repeat TmpchgVal:= F.fdChgList[leftSteps]; F.fdChgList[leftSteps]:= F.fdChgList[rw]; F.fdChgList[rw] :=TmpchgVal; dec(leftSteps); inc(rw); until rw>=leftSteps; end; solFound := false; result := true; end; procedure SolIsFound; begin solF := F; inc(solCnt); solFound := True; end; procedure TryCell(var ChgVal:tpchgVal); var value :NativeInt; poss,msk: NativeInt; Begin IF solFound then EXIT; with ChgVal^ do poss:= (cvRow^ OR cvCol^ OR cvCar^) XOR maxMask; IF Poss = 0 then EXIT; value := 1; msk := 1; repeat IF Poss AND MSK <>0 then Begin inc(callCnt); with ChgVal^ do Begin cvCol^ := cvCol^ OR msk; cvRow^ := cvRow^ OR msk; cvCar^ := cvCar^ OR msk; cvVAl^ := value; end; inc(ChgVal); IF ChgVal^.cvCol <> NIL then TryCell(ChgVal) else SolIsFound; dec(ChgVal); with ChgVal^ do Begin cvCol^ := cvCol^ XOR msk; cvRow^ := cvRow^ XOR msk; cvCar^ := cvCar^ XOR msk; cvVAl^ := 0; end; end; inc(msk,msk); inc(value); until value> maxValue; end; var ChangeBegin : tpChgVal; k : NativeInt; T1,T0: TDateTime; begin randomize; ClrScr; solCnt := 0; callCnt:= 0; T0 := time; k := 0; repeat InitField(F,Expl1,FALSE); ChangeBegin := @F.fdChgList[F.fdChgIdx]; TryCell(ChangeBegin); inc(k); until k >= 5; T1 := time; Outfield(solF); writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0); end.
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();
Maintain the same structure and functionality when rewriting this code in PHP.
use integer; use strict; my @A = qw( 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 ); sub solve { my $i; foreach $i ( 0 .. 80 ) { next if $A[$i]; my %t = map { $_ / 9 == $i / 9 || $_ % 9 == $i % 9 || $_ / 27 == $i / 27 && $_ % 9 / 3 == $i % 9 / 3 ? $A[$_] : 0, 1; } 0 .. 80; solve( $A[$i] = $_ ) for grep !$t{$_}, 1 .. 9; return $A[$i] = 0; } $i = 0; foreach (@A) { print "-----+-----+-----\n" if !($i%27) && $i; print !($i%9) ? '': $i%3 ? ' ' : '|', $_; print "\n" unless ++$i%9; } } solve();
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();
Ensure the translated PHP code behaves exactly like the original Ruby snippet.
GRID_SIZE = 9 def isNumberInRow(board, number, row) board[row].includes?(number) end def isNumberInColumn(board, number, column) board.any?{|row| row[column] == number } end def isNumberInBox(board, number, row, column) localBoxRow = row - row % 3 localBoxColumn = column - column % 3 (localBoxRow...(localBoxRow+3)).each do |i| (localBoxColumn...(localBoxColumn+3)).each do |j| return true if board[i][j] == number end end false end def isValidPlacement(board, number, row, column) return !isNumberInRow(board, number, row) && !isNumberInColumn(board, number, column) && !isNumberInBox(board, number, row, column) end def solveBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| if(cell == 0) (1..GRID_SIZE).each do |n| if(isValidPlacement(board,n,i,j)) board[i][j]=n if(solveBoard(board)) return true else board[i][j]=0 end end end return false end end end return true end def printBoard(board) board.each_with_index do |row, i| row.each_with_index do |cell, j| print cell print '|' if j == 2 || j == 5 print '\n' if j == 8 end print "-"*11 + '\n' if i == 2 || i == 5 end print '\n' end board = [ [7, 0, 2, 0, 5, 0, 6, 0, 0], [0, 0, 0, 0, 0, 3, 0, 0, 0], [1, 0, 0, 0, 0, 9, 5, 0, 0], [8, 0, 0, 0, 0, 0, 0, 9, 0], [0, 4, 3, 0, 0, 0, 7, 5, 0], [0, 9, 0, 0, 0, 0, 0, 0, 8], [0, 0, 9, 7, 0, 0, 0, 0, 5], [0, 0, 0, 2, 0, 0, 0, 0, 0], [0, 0, 7, 0, 4, 0, 2, 0, 3]] printBoard(board) if(solveBoard(board)) printBoard(board) end
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();
Please provide an equivalent version of this Scala code in PHP.
class Sudoku(rows: List<String>) { private val grid = IntArray(81) private var solved = false init { require(rows.size == 9 && rows.all { it.length == 9 }) { "Grid must be 9 x 9" } for (i in 0..8) { for (j in 0..8 ) grid[9 * i + j] = rows[i][j] - '0' } } fun solve() { println("Starting grid:\n\n$this") placeNumber(0) println(if (solved) "Solution:\n\n$this" else "Unsolvable!") } private fun placeNumber(pos: Int) { if (solved) return if (pos == 81) { solved = true return } if (grid[pos] > 0) { placeNumber(pos + 1) return } for (n in 1..9) { if (checkValidity(n, pos % 9, pos / 9)) { grid[pos] = n placeNumber(pos + 1) if (solved) return grid[pos] = 0 } } } private fun checkValidity(v: Int, x: Int, y: Int): Boolean { for (i in 0..8) { if (grid[y * 9 + i] == v || grid[i * 9 + x] == v) return false } val startX = (x / 3) * 3 val startY = (y / 3) * 3 for (i in startY until startY + 3) { for (j in startX until startX + 3) { if (grid[i * 9 + j] == v) return false } } return true } override fun toString(): String { val sb = StringBuilder() for (i in 0..8) { for (j in 0..8) { sb.append(grid[i * 9 + j]) sb.append(" ") if (j == 2 || j == 5) sb.append("| ") } sb.append("\n") if (i == 2 || i == 5) sb.append("------+-------+------\n") } return sb.toString() } } fun main(args: Array<String>) { val rows = listOf( "850002400", "720000009", "004000000", "000107002", "305000900", "040000000", "000080070", "017000000", "000036040" ) Sudoku(rows).solve() }
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();
Rewrite the snippet below in PHP so it works the same as the original Swift code.
import Foundation typealias SodukuPuzzle = [[Int]] class Soduku { let mBoardSize:Int! let mBoxSize:Int! var mBoard:SodukuPuzzle! var mRowSubset:[[Bool]]! var mColSubset:[[Bool]]! var mBoxSubset:[[Bool]]! init(board:SodukuPuzzle) { mBoard = board mBoardSize = board.count mBoxSize = Int(sqrt(Double(mBoardSize))) mRowSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mColSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) mBoxSubset = [[Bool]](count: mBoardSize, repeatedValue: [Bool](count: mBoardSize, repeatedValue: false)) initSubsets() } func computeBoxNo(i:Int, _ j:Int) -> Int { let boxRow = i / mBoxSize let boxCol = j / mBoxSize return boxRow * mBoxSize + boxCol } func initSubsets() { for i in 0..<mBoard.count { for j in 0..<mBoard.count { let value = mBoard[i][j] if value != 0 { setSubsetValue(i, j, value, true); } } } } func isValid(i:Int, _ j:Int, var _ val:Int) -> Bool { val-- let isPresent = mRowSubset[i][val] || mColSubset[j][val] || mBoxSubset[computeBoxNo(i, j)][val] return !isPresent } func printBoard() { for i in 0..<mBoardSize { if i % mBoxSize == 0 { println(" -----------------------") } for j in 0..<mBoardSize { if j % mBoxSize == 0 { print("| ") } print(mBoard[i][j] != 0 ? String(mBoard[i][j]) : " ") print(" ") } println("|") } println(" -----------------------") } func setSubsetValue(i:Int, _ j:Int, _ value:Int, _ present:Bool) { mRowSubset[i][value - 1] = present mColSubset[j][value - 1] = present mBoxSubset[computeBoxNo(i, j)][value - 1] = present } func solve() { solve(0, 0) } func solve(var i:Int, var _ j:Int) -> Bool { if i == mBoardSize { i = 0 j++ if j == mBoardSize { return true } } if mBoard[i][j] != 0 { return solve(i + 1, j) } for value in 1...mBoardSize { 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 } } let board = [ [4, 0, 0, 0, 0, 0, 0, 6, 0], [5, 0, 0, 0, 8, 0, 9, 0, 0], [3, 0, 0, 0, 0, 1, 0, 0, 0], [0, 2, 0, 7, 0, 0, 0, 0, 1], [0, 9, 0, 0, 0, 0, 0, 4, 0], [8, 0, 0, 0, 0, 3, 0, 5, 0], [0, 0, 0, 2, 0, 0, 0, 0, 7], [0, 0, 6, 0, 5, 0, 0, 0, 8], [0, 1, 0, 0, 0, 0, 0, 0, 6] ] let puzzle = Soduku(board: board) puzzle.solve() puzzle.printBoard()
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();
Generate an equivalent PHP version of this Tcl code.
package require Tcl 8.6 oo::class create Sudoku { variable idata method clear {} { for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { my set $x $y {} } } } method load {data} { set error "data must be a 9-element list, each element also being a\ list of 9 numbers from 1 to 9 or blank or an @ symbol." if {[llength $data] != 9} { error $error } for {set y 0} {$y<9} {incr y} { set row [lindex $data $y] if {[llength $row] != 9} { error $error } for {set x 0} {$x<9} {incr x} { set d [lindex $row $x] if {![regexp {^[@1-9]?$} $d]} { error $d-$error } if {$d eq "@"} {set d ""} my set $x $y $d } } } method dump {} { set rows {} for {set y 0} {$y < 9} {incr y} { lappend rows [my getRow 0 $y] } return $rows } method Log msg { } method set {x y value} { if {[catch {set value [format %d $value]}]} {set value 0} if {$value<1 || $value>9} { set idata(sq$x$y) {} } else { set idata(sq$x$y) $value } } method get {x y} { if {![info exists idata(sq$x$y)]} { return {} } return $idata(sq$x$y) } method getRow {x y} { set row {} for {set x 0} {$x<9} {incr x} { lappend row [my get $x $y] } return $row } method getCol {x y} { set col {} for {set y 0} {$y<9} {incr y} { lappend col [my get $x $y] } return $col } method getRegion {x y} { set xR [expr {($x/3)*3}] set yR [expr {($y/3)*3}] set regn {} for {set x $xR} {$x < $xR+3} {incr x} { for {set y $yR} {$y < $yR+3} {incr y} { lappend regn [my get $x $y] } } return $regn } } oo::class create SudokuSolver { superclass Sudoku method validchoices {x y} { if {[my get $x $y] ne {}} { return [my get $x $y] } set row [my getRow $x $y] set col [my getCol $x $y] set regn [my getRegion $x $y] set eliminate [list {*}$row {*}$col {*}$regn] set eliminate [lsearch -all -inline -not $eliminate {}] set eliminate [lsort -unique $eliminate] set choices {} for {set c 1} {$c < 10} {incr c} { if {$c ni $eliminate} { lappend choices $c } } if {[llength $choices]==0} { error "No choices left for square $x,$y" } return $choices } method completion {} { return [expr { 81-[llength [lsearch -all -inline [join [my dump]] {}]] }] } method solve {} { foreach ruleClass [info class subclass Rule] { lappend rules [$ruleClass new] } while {1} { set begin [my completion] for {set y 0} {$y < 9} {incr y} { for {set x 0} {$x < 9} {incr x} { if {[my get $x $y] eq ""} { foreach rule $rules { set c [$rule solve [self] $x $y] if {$c} { my set $x $y $c my Log "[info object class $rule] solved [self] at $x,$y for $c" break } } } } } set end [my completion] if {$end==81} { my Log "Finished solving!" break } elseif {$begin==$end} { my Log "A round finished without solving any squares, giving up." break } } foreach rule $rules { $rule destroy } } } oo::class create Rule { method solve {hSudoku x y} { if {![info object isa typeof $hSudoku SudokuSolver]} { error "hSudoku must be an instance of class SudokuSolver." } tailcall my Solve $hSudoku $x $y [$hSudoku validchoices $x $y] } } oo::class create RuleOnlyChoice { superclass Rule method Solve {hSudoku x y choices} { if {[llength $choices]==1} { return $choices } else { return 0 } } } oo::class create RuleColumnChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set x2 0} {$x2<9} {incr x2} { if {$x2 != $x && $choice in [$hSudoku validchoices $x2 $y]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRowChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 for {set y2 0} {$y2<9} {incr y2} { if {$y2 != $y && $choice in [$hSudoku validchoices $x $y2]} { set failed 1 break } } if {!$failed} {return $choice} } return 0 } } oo::class create RuleRegionChoice { superclass Rule method Solve {hSudoku x y choices} { foreach choice $choices { set failed 0 set regnX [expr {($x/3)*3}] set regnY [expr {($y/3)*3}] for {set y2 $regnY} {$y2 < $regnY+3} {incr y2} { for {set x2 $regnX} {$x2 < $regnX+3} {incr x2} { if { ($x2!=$x || $y2!=$y) && $choice in [$hSudoku validchoices $x2 $y2] } then { set failed 1 break } } } if {!$failed} {return $choice} } return 0 } }
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();
Translate this program into Rust but keep the logic exactly as in C.
#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; }
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
Convert the following code from C++ to Rust, ensuring the logic remains intact.
#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; }
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
Write a version of this Go function in Rust with identical behavior.
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 }
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
Can you help me rewrite this code in Rust instead of Java, keeping it the same logically?
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!"); } } }
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
Preserve the algorithm and functionality while converting the code from Rust to VB.
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
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 C# block to Rust, preserving its control flow and logic.
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(); } }
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
Port the following code from Rust to Python with equivalent syntax and logic.
type Sudoku = [u8; 81]; fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool { (0..9).all(|i| sudoku_ar[y * 9 + i] != val && sudoku_ar[i * 9 + x] != val) && { let (start_x, start_y) = ((x / 3) * 3, (y / 3) * 3); (start_y..start_y + 3).all(|i| (start_x..start_x + 3).all(|j| sudoku_ar[i * 9 + j] != val)) } } fn place_number(pos: usize, sudoku_ar: &mut Sudoku) -> bool { (pos..81).find(|&p| sudoku_ar[p] == 0).map_or(true, |pos| { let (x, y) = (pos % 9, pos / 9); for n in 1..10 { if is_valid(n, x, y, sudoku_ar) { sudoku_ar[pos] = n; if place_number(pos + 1, sudoku_ar) { return true; } sudoku_ar[pos] = 0; } } false }) } fn pretty_print(sudoku_ar: Sudoku) { let line_sep = "------+-------+------"; println!("{}", line_sep); for (i, e) in sudoku_ar.iter().enumerate() { print!("{} ", e); if (i + 1) % 3 == 0 && (i + 1) % 9 != 0 { print!("| "); } if (i + 1) % 9 == 0 { println!(" "); } if (i + 1) % 27 == 0 { println!("{}", line_sep); } } } fn solve(sudoku_ar: &mut Sudoku) -> bool { place_number(0, sudoku_ar) } fn main() { let mut sudoku_ar: Sudoku = [ 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 ]; if solve(&mut sudoku_ar) { pretty_print(sudoku_ar); } else { println!("Unsolvable"); } }
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 Ada to C# without modifying what it does.
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
using System; class Program { static void Main(string[] args) { Console.WriteLine("Goodbye, World!"); Console.Write("Goodbye, World!"); } }
Convert this Ada block to C, preserving its control flow and logic.
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { (void) printf("Goodbye, World!"); return EXIT_SUCCESS; }
Transform the following Ada implementation into C++, maintaining the same output and logic.
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
#include <iostream> int main() { std::cout << "Goodbye, World!"; return 0; }
Transform the following Ada implementation into Go, maintaining the same output and logic.
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
package main import "fmt" func main() { fmt.Print("Goodbye, World!") }
Generate a Java translation of this Ada snippet without changing its computational steps.
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
public class HelloWorld { public static void main(String[] args) { System.out.print("Goodbye, World!"); } }
Can you help me rewrite this code in Python instead of Ada, keeping it the same logically?
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
import sys sys.stdout.write("Goodbye, World!")
Ensure the translated VB code behaves exactly like the original Ada snippet.
with Ada.Text_IO; procedure Goodbye_World is begin Ada.Text_IO.Put("Goodbye, World!"); end Goodbye_World;
Module Module1 Sub Main() Console.Write("Goodbye, World!") End Sub End Module
Convert this Arturo snippet to C and keep its semantics consistent.
prin "Goodbye, World!"
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { (void) printf("Goodbye, World!"); return EXIT_SUCCESS; }