Sudoku: Difference between revisions

3,126 bytes added ,  1 year ago
m
syntax highlighting fixup automation
m (→‎{{header|Tailspin}}: typed array indices)
m (syntax highlighting fixup automation)
Line 12:
{{trans|Kotlin}}
 
<langsyntaxhighlight lang="11l">T Sudoku
solved = 0B
grid = [0] * 81
Line 83:
‘000036040’]
 
Sudoku(rows).solve()</langsyntaxhighlight>
 
{{out}}
Line 118:
 
=={{header|8th}}==
<langsyntaxhighlight lang="8th">
\
\ Simple iterative backtracking Sudoku solver for 8th
Line 265:
"No solution!\n" .
then ;
</syntaxhighlight>
</lang>
 
=={{header|Ada}}==
{{trans|C++}}
<langsyntaxhighlight lang="ada">
with Ada.Text_IO;
 
Line 378:
solve( sudoku_ar );
end Sudoku;
</syntaxhighlight>
</lang>
 
{{out}}
Line 401:
{{works with|ALGOL 68G|Any - tested with release [http://sourceforge.net/projects/algol68/files/algol68g/algol68g-1.18.0/algol68g-1.18.0-9h.tiny.el5.centos.fc11.i386.rpm/download 1.18.0-9h.tiny].}}
{{wont work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release [http://sourceforge.net/projects/algol68/files/algol68toc/algol68toc-1.8.8d/algol68toc-1.8-8d.fc9.i386.rpm/download 1.8-8d] - due to extensive use of '''format'''[ted] ''transput''.}}
<langsyntaxhighlight lang="algol68">MODE AVAIL = [9]BOOL;
MODE BOX = [3, 3]CHAR;
 
Line 495:
"__1__6__9"))
END CO
)</langsyntaxhighlight>
{{out}}
<pre>
Line 515:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">#SingleInstance, Force
SetBatchLines, -1
SetTitleMatchMode, 3
Line 658:
r .= SubStr(p, A_Index, 1) . "|"
return r
}</langsyntaxhighlight>
 
=={{header|AWK}}==
<syntaxhighlight lang="awk">
<lang AWK>
# syntax: GAWK -f SUDOKU_RC.AWK
BEGIN {
Line 849:
}
function error(message) { printf("error: %s\n",message) ; errors++ }
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 886:
{{works with|BBC BASIC for Windows}}
[[Image:sudoku_bbc.gif|right]]
<langsyntaxhighlight lang="bbcbasic"> VDU 23,22,453;453;8,20,16,128
*FONT Arial,28
Line 990:
ENDIF
NEXT
= D%</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight BCPLlang="bcpl">// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10.
// Implemented by Martin Richards.
 
Line 1,388:
{ count := count + 1
prboard()
}</langsyntaxhighlight>
 
=={{header|Befunge}}==
Line 1,394:
Input should be provided as a sequence of 81 digits (optionally separated by whitespace), with zero representing an unknown value.
 
<langsyntaxhighlight lang="befunge">99*>1-:0>:#$"0"\# #~`#$_"0"-\::9%:9+00p3/\9/:99++10p3vv%2g\g01<
2%v|:p+9/9\%9:\p\g02\1p\g01\1:p\g00\1:+8:\p02+*93+*3/<>\20g\g#:
v<+>:0\`>v >\::9%:9+00p3/\9/:99++10p3/3*+39*+20p\:8+::00g\g2%\^
Line 1,401:
p|<$0.0^!g+:#9/9<^@ ^,>#+5<5_>#!<>#$0"------+-------+-----":#<^
<>v$v1:::0<>"P"`!^>0g#0v#p+9/9\%9:p04:\pg03g021pg03g011pg03g001
::>^_:#<0#!:p#-\#1:#g0<>30g010g30g020g30g040g:9%\:9/9+\01-\1+0:</langsyntaxhighlight>
 
{{in}}
Line 1,431:
=={{header|Bracmat}}==
The program:
<langsyntaxhighlight lang="bracmat">{sudokuSolver.bra
 
Solves any 9x9 sudoku, using backtracking.
Line 1,619:
. new$((its.sudoku),!arg):?puzzle
& (puzzle..Display)$
);</langsyntaxhighlight>
Solve a sudoku that is hard for a brute force solver:
<langsyntaxhighlight lang="bracmat">new'( sudokuSolver
, (.- - - - - - - - -)
(.- - - - - 3 - 8 5)
Line 1,631:
(.- - 2 - 1 - - - -)
(.- - - - 4 - - - 9)
);</langsyntaxhighlight>
Solution:
<pre>|~~~|~~~|~~~|
Line 1,651:
 
The following code is really only good for size 3 puzzles. A longer, even less readable version [[Sudoku/C|here]] could handle size 4s.
<langsyntaxhighlight lang="c">#include <stdio.h>
 
void show(int *x)
Line 1,717:
 
return 0;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
===Backtracking===
{{trans|Java}}
<langsyntaxhighlight lang="csharp">using System;
 
class SudokuSolver
Line 1,824:
Console.Read();
}
}</langsyntaxhighlight>
 
=== Best First Search===
<!-- By Martin Freedman, 20/11/2021 -->
<langsyntaxhighlight lang="csharp">using System.Linq;
using static System.Linq.Enumerable;
using System.Collections.Generic;
Line 1,904:
}
}
}</langsyntaxhighlight>
Usage
<langsyntaxhighlight lang="csharp">using System.Linq;
using static System.Linq.Enumerable;
using static System.Console;
Line 1,941:
}
}
}</langsyntaxhighlight>
Output
<pre>693784512
Line 1,960:
{{libheader|Microsoft Solver Foundation}}
<!-- By Nigel Galloway, Jan 29, 2012 -->
<langsyntaxhighlight lang="csharp">using Microsoft.SolverFoundation.Solvers;
 
namespace Sudoku
Line 2,032:
}
}
}</langsyntaxhighlight>
Produces:
<pre>
Line 2,049:
 
==="Dancing Links"/Algorithm X===
<langsyntaxhighlight lang="csharp">using System;
using System.Collections.Generic;
using System.Text;
Line 2,327:
 
public static string DelimitWith<T>(this IEnumerable<T> source, string separator) => string.Join(separator, source);
}</langsyntaxhighlight>
{{out}}
<pre>
Line 2,352:
=={{header|C++}}==
{{trans|Java}}
<langsyntaxhighlight lang="cpp">#include <iostream>
using namespace std;
 
Line 2,443:
ss.solve();
return EXIT_SUCCESS;
}</langsyntaxhighlight>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="clojure">(ns rosettacode.sudoku
(:use [clojure.pprint :only (cl-format)]))
 
Line 2,469:
(if (= x (dec c))
(recur ng 0 (inc y))
(recur ng (inc x) y)))))))</langsyntaxhighlight>
 
<langsyntaxhighlight lang="clojure">sudoku>(cl-format true "~{~{~a~^ ~}~%~}"
(solve [[3 9 4 0 0 2 6 7 0]
[0 0 0 3 0 0 4 0 0]
Line 2,491:
8 2 6 4 1 9 7 3 5
 
nil</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
A simple solver without optimizations (except for pre-computing the possible entries of a cell).
<langsyntaxhighlight lang="lisp">(defun row-neighbors (row column grid &aux (neighbors '()))
(dotimes (i 9 neighbors)
(let ((x (aref grid row i)))
Line 2,534:
(setf (aref grid row column) choice)
(when (eq grid (solve grid row (1+ column)))
(return grid))))))</langsyntaxhighlight>
Example:
<pre>> (defparameter *puzzle*
Line 2,564:
Based on the Java implementation presented in the video "[https://www.youtube.com/watch?v=mcXc8Mva2bA Create a Sudoku Solver In Java...]".
 
<langsyntaxhighlight lang="ruby">GRID_SIZE = 9
 
def isNumberInRow(board, number, row)
Line 2,637:
printBoard(board)
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 2,666:
=={{header|Curry}}==
Copied from [http://www.informatik.uni-kiel.de/~curry/examples/ Curry: Example Programs].
<langsyntaxhighlight lang="curry">-----------------------------------------------------------------------------
--- Solving Su Doku puzzles in Curry with FD constraints
---
Line 2,728:
" 5 7 921 ",
" 64 9 ",
" 2 438"]</langsyntaxhighlight>
 
 
Line 2,734:
{{Works with|PAKCS}}
Minimal w/o read or show utilities.
<langsyntaxhighlight lang="curry">import CLPFD
import Constraint (allC)
import List (transpose)
Line 2,767:
, [7,_,_,6,_,_,5,_,_]
]
main | sudoku xs = xs where xs = test</langsyntaxhighlight>
{{Out}}
<pre>Execution time: 0 msec. / elapsed: 10 msec.
Line 2,775:
{{trans|C++}}
A little over-engineered solution, that shows some strong static typing useful in larger programs.
<langsyntaxhighlight lang="d">import std.stdio, std.range, std.string, std.algorithm, std.array,
std.ascii, std.typecons;
 
Line 2,901:
else
solution.get.representSudoku.writeln;
}</langsyntaxhighlight>
{{out}}
<pre>8 5 . | . . 2 | 4 . .
Line 2,929:
===Short Version===
Adapted from: http://code.activestate.com/recipes/576725-brute-force-sudoku-solver/
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range;
 
const(int)[] solve(immutable int[] s) pure nothrow @safe {
Line 2,962:
0, 0, 0, 0, 3, 6, 0, 4, 0];
writefln("%(%s\n%)", problem.solve.chunks(9));
}</langsyntaxhighlight>
{{out}}
<pre>[8, 5, 9, 6, 1, 2, 4, 3, 7]
Line 2,976:
===No-Heap Version===
This version is similar to the precedent one, but it shows idioms to avoid memory allocations on the heap. This is enforced by the use of the @nogc attribute.
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm, std.range, std.typecons;
 
Nullable!(const ubyte[81]) solve(in ubyte[81] s) pure nothrow @safe @nogc {
Line 3,017:
0, 0, 0, 0, 3, 6, 0, 4, 0];
writefln("%(%s\n%)", problem.solve.get[].chunks(9));
}</langsyntaxhighlight>
Same output.
 
=={{header|Delphi}}==
Example taken from C++
<langsyntaxhighlight lang="delphi">type
TIntArray = array of Integer;
 
Line 3,146:
ShowMessage('Solved!');
end;
end;</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="delphi">var
SudokuSolver: TSudokuSolver;
begin
Line 3,165:
FreeAndNil(SudokuSolver);
end;
end;</langsyntaxhighlight>
 
=={{header|EasyLang}}==
<syntaxhighlight lang="text">len row[] 810
len col[] 810
len box[] 810
Line 3,245:
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</langsyntaxhighlight>
 
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Sudoku do
def display( grid ), do: ( for y <- 1..9, do: display_row(y, grid) )
Line 3,405:
{{3, 8}, 2}, {{5, 8}, 1},
{{5, 9}, 4}, {{9, 9}, 9}]
Sudoku.task( difficult )</langsyntaxhighlight>
 
{{out}}
Line 3,465:
=={{header|Erlang}}==
I first try to solve the Sudoku grid without guessing. For the guessing part I eschew spawning a process for each guess, instead opting for backtracking. It is fun trying new things.
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( sudoku ).
 
Line 3,628:
display( Solved ),
io:nl().
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 3,712:
0 is the empty cell.
 
<syntaxhighlight lang="erre">
<lang ERRE>
!--------------------------------------------------------------------
! risolve Sudoku: in input il file SUDOKU.TXT
Line 4,119:
 
 
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
===Backtracking===
<!-- By Martin Freedman, 26/11/2021 -->
<langsyntaxhighlight lang="fsharp">module SudokuBacktrack
 
//Helpers
Line 4,197:
/// solve sudoku using simple backtracking
let solve grid = grid |> parseGrid >>= flip backtracker (Some "A1")</langsyntaxhighlight>
'''Usage:'''
<langsyntaxhighlight lang="fsharp">open System
open SudokuBacktrack
 
Line 4,211:
printfn "Press any key to exit"
Console.ReadKey() |> ignore
0</langsyntaxhighlight>
{{Output}}<pre>
Puzzle:
Line 4,240:
===Constraint Satisfaction (Norvig)===
<!-- By Martin Freedman, 27/11/2021 -->
<langsyntaxhighlight lang="fsharp">// https://norvig.com/sudoku.html
// using array O(1) lookup & mutable instead of map O(logn) immutable - now 6 times faster
module SudokuCPSArray
Line 4,364:
let solveNoSearch: string -> string = solver applyCPS
let solveWithSearch: string -> string = solver (applyCPS >> (Option.bind search))
let solveWithSearchToMapOnly:string -> int[][] option = run None id (applyCPS >> (Option.bind search)) </langsyntaxhighlight>
'''Usage'''<langsyntaxhighlight lang="fsharp">open System
open SudokuCPSArray
open System.Diagnostics
Line 4,412:
printfn "Some sudoku17 puzzles failed"
Console.ReadKey() |> ignore
0</langsyntaxhighlight>
{{Output}}Timings run on i7500U @2.75Ghz CPU, 16GB RAM<pre>Easy board solution automatic with constraint propagation
4 8 3 |9 2 1 |6 5 7
Line 4,472:
 
===SLPsolve===
<langsyntaxhighlight lang="fsharp">
// Solve Sudoku Like Puzzles. Nigel Galloway: September 6th., 2018
let fN y n g=let _q n' g'=[for n in n*n'..n*n'+n-1 do for g in g*g'..g*g'+g-1 do yield (n,g)]
Line 4,501:
List.map2(fun n g->List.map(fun(n',g')->((n',g'),n))g) (List.rev n) g|>List.concat|>List.sortBy (fun ((_,n),_)->n)|>List.groupBy(fun ((n,_),_)->n)|>List.sortBy(fun(n,_)->n)
|>List.iter(fun (_,n)->n|>Seq.fold(fun z ((_,g),v)->[z..g-1]|>Seq.iter(fun _->printf " |");printf "%s|" v; g+1 ) 0 |>ignore;printfn "")
</syntaxhighlight>
</lang>
'''Usage:'''
Given sud1.csv:
Line 4,516:
</pre>
then
<langsyntaxhighlight lang="fsharp">
let n=SLPsolve (fE ([1..9]|>List.map(string)) 9 3 3 "sud1.csv")
printSLP ([1..9]|>List.map(string)) (Seq.item 0 n)
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 4,535:
=={{header|Forth}}==
{{works with|4tH|3.60.0}}
<langsyntaxhighlight lang="forth">include lib/interprt.4th
include lib/istype.4th
include lib/argopen.4th
Line 4,898:
;
 
sudoku</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
This implementation uses a brute force method. The subroutine <code>solve</code> recursively checks valid entries using the rules defined in the function <code>is_safe</code>. When <code>solve</code> is called beyond the end of the sudoku, we know that all the currently entered values are valid. Then the result is displayed.
<langsyntaxhighlight lang="fortran">program sudoku
 
implicit none
Line 5,000:
end subroutine pretty_print
 
end program sudoku</langsyntaxhighlight>
{{out}}<pre>
+-----+-----+-----+
Line 5,033:
=={{header|FreeBASIC}}==
{{trans|VBA}}
<langsyntaxhighlight lang="freebasic">Dim Shared As Integer cuadricula(9, 9), cuadriculaResuelta(9, 9)
 
Function isSafe(i As Integer, j As Integer, n As Integer) As Boolean
Line 5,119:
If (i Mod 3 = 0) Then Print !"\n---------+---------+---------" Else Print
Next i
Sleep</langsyntaxhighlight>
{{out}}
<pre>
Line 5,141:
=={{header|FutureBasic}}==
First is a short version:
<langsyntaxhighlight lang="futurebasic">
include "ConsoleWindow"
include "NSLog.incl"
Line 5,250:
print "No solution found"
end if
</syntaxhighlight>
</lang>
 
Output:
Line 5,712:
Input to function solve is an 81 character string.
This seems to be a conventional computer representation for Sudoku puzzles.
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 5,913:
}
c.r.l, c.l.r = &c.x, &c.x
}</langsyntaxhighlight>
{{out}}
<pre>
Line 5,946:
 
Imprime todas las soluciones posibles, sale con un error, pero funciona.
<langsyntaxhighlight lang="golfscript">
'Solution:'
;'2 8 4 3 7 5 1 6 9
Line 5,960:
 
~]{:@0?:^~!{@p}*10,@9/^9/=-@^9%>9%-@3/^9%3/>3%3/^27/={+}*-{@^<\+@1^+>+}/1}do
</syntaxhighlight>
</lang>
 
=={{header|Groovy}}==
Line 5,968:
 
I consider this a "brute force" solution of sorts, in that it is the same method I use when solving Sudokus manually.
<langsyntaxhighlight lang="groovy">final CELL_VALUES = ('1'..'9')
class GridException extends Exception {
Line 6,035:
}
grid
}</langsyntaxhighlight>
'''Test/Benchmark Cases'''
 
Mentions of ''"exceptionally difficult" example in Wikipedia'' refer to this (former) page: [[https://en.wikipedia.org/w/index.php?title=Sudoku_solving_algorithms&oldid=410240496#Exceptionally_difficult_Sudokus_.28hardest_Sudokus.29 Exceptionally difficult Sudokus]]
<langsyntaxhighlight lang="groovy">def sudokus = [
//Used in Curry solution: ~ 0.1 seconds
'819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438',
Line 6,102:
solution.each { println it }
println "\nELAPSED: ${elapsed} seconds"
}</langsyntaxhighlight>
 
{{out}} (last only):
Line 6,136:
 
=={{header|Java}}==
<langsyntaxhighlight lang="java">public class Sudoku
{
private int mBoard[][];
Line 6,254:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 6,293:
====ES6====
 
<langsyntaxhighlight JavaScriptlang="javascript">//-------------------------------------------[ Dancing Links and Algorithm X ]--
/**
* The doubly-doubly circularly linked data object.
Line 6,566:
search(H, []);
};
</syntaxhighlight>
</lang>
 
<syntaxhighlight lang="javascript">[
<lang JavaScript>[
'819..5.....2...75..371.4.6.4..59.1..7..3.8..2..3.62..7.5.7.921..64...9.....2..438',
'53..247....2...8..1..7.39.2..8.72.49.2.98..7.79.....8.....3.5.696..1.3...5.69..1.',
Line 6,593:
let s = new Array(Math.pow(n, 4)).fill('.').join('');
reduceGrid(s);
</syntaxhighlight>
</lang>
 
<pre>+-------+-------+-------+
Line 6,625:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">function check(i, j)
id, im = div(i, 9), mod(i, 9)
jd, jm = div(j, 9), mod(j, 9)
Line 6,691:
0, 5, 0, 6, 9, 0, 0, 1, 0]
 
solve_sudoku(display, grid)</langsyntaxhighlight>
{{out}}
<pre>
Line 6,709:
=={{header|Kotlin}}==
{{trans|C++}}
<langsyntaxhighlight lang="scala">// version 1.2.10
 
class Sudoku(rows: List<String>) {
Line 6,792:
)
Sudoku(rows).solve()
}</langsyntaxhighlight>
 
{{out}}
Line 6,827:
=={{header|Lua}}==
===without FFI, slow===
<langsyntaxhighlight lang="lua">--9x9 sudoku solver in lua
--based on a branch and bound solution
--fields are not tried in plain order
Line 7,009:
if x then
return printer(x)
end</langsyntaxhighlight>
Input:
<pre>
Line 7,041:
Time with luajit: 9.245s
===with FFI, fast===
<langsyntaxhighlight lang="lua">#!/usr/bin/env luajit
ffi=require"ffi"
local printf=function(fmt, ...) io.write(string.format(fmt, ...)) end
Line 7,109:
... .8. .79
]])
end</langsyntaxhighlight>
{{out}}
<pre>> time ./sudoku_fast.lua
Line 7,128:
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight lang="mathematica">solve[sudoku_] :=
NestWhile[
Join @@ Table[
Line 7,137:
Extract[Partition[s, {3, 3}], Quotient[#, 3, -2]]]} & /@
Position[s, 0, {2}],
Length@Last@# &], {s, #}] &, {sudoku}, ! FreeQ[#, 0] &]</langsyntaxhighlight>
Example:
<syntaxhighlight lang="text">solve[{{9, 7, 0, 3, 0, 0, 0, 6, 0},
{0, 6, 0, 7, 5, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 8, 0, 5, 0},
Line 7,147:
{7, 0, 0, 0, 2, 5, 0, 0, 0},
{0, 0, 2, 0, 1, 0, 0, 0, 8},
{0, 4, 0, 0, 0, 7, 3, 0, 0}}]</langsyntaxhighlight>
{{out}}
<pre>{{{9, 7, 5, 3, 4, 2, 8, 6, 1}, {8, 6, 1, 7, 5, 9, 4, 3, 2}, {3, 2, 4,
Line 7,158:
 
For this to work, this code must be placed in a file named "sudokuSolver.m"
<langsyntaxhighlight MATLABlang="matlab">function solution = sudokuSolver(sudokuGrid)
 
%Define what each of the sub-boxes of the sudoku grid are by defining
Line 7,510:
%% End of program
end %end sudokuSolver</langsyntaxhighlight>
[http://www.menneske.no/sudoku/eng/showpuzzle.html?number=6903541 Test Input]:
All empty cells must have a value of NaN.
<langsyntaxhighlight MATLABlang="matlab">sudoku = [NaN NaN NaN NaN 8 3 9 NaN NaN
1 NaN NaN NaN NaN NaN NaN 3 NaN
NaN NaN 4 NaN NaN NaN NaN 7 NaN
Line 7,521:
NaN 2 NaN NaN NaN NaN NaN NaN NaN
NaN 8 NaN NaN NaN 9 2 NaN NaN
NaN NaN NaN 2 5 NaN NaN NaN 6]</langsyntaxhighlight>
[http://www.menneske.no/sudoku/eng/solution.html?number=6903541 Output]:
<langsyntaxhighlight MATLABlang="matlab">solution =
 
7 6 5 4 8 3 9 2 1
Line 7,533:
9 2 6 1 4 7 5 8 3
5 8 1 3 6 9 2 4 7
4 7 3 2 5 8 1 9 6</langsyntaxhighlight>
 
=={{header|Nim}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="nim">{.this: self.}
 
type
Line 7,611:
var puzzle = Sudoku()
puzzle.init(rows)
puzzle.solve()</langsyntaxhighlight>
 
{{out}}
Line 7,644:
=={{header|OCaml}}==
uses the library [http://ocamlgraph.lri.fr/index.en.html ocamlgraph]
<langsyntaxhighlight lang="ocaml">(* Ocamlgraph demo program: solving the Sudoku puzzle using graph coloring
Copyright 2004-2007 Sylvain Conchon, Jean-Christophe Filliatre, Julien Signoles
 
Line 7,713:
module C = Coloring.Mark(G)
 
let () = C.coloring g 9; display ()</langsyntaxhighlight>
 
=={{header|Oz}}==
Using built-in constraint propagation and search.
<langsyntaxhighlight lang="oz">declare
%% a puzzle is a function that returns an initial board configuration
fun {Puzzle1}
Line 7,800:
end
in
{Inspect {Solve Puzzle1}.1}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
 
Build plugin for PARI's function interface from C code: sudoku.c
<langsyntaxhighlight Clang="c">#include <pari/pari.h>
 
typedef int SUDOKU [9][9];
Line 7,875:
return gen_0; /* no solution */
}
</syntaxhighlight>
</lang>
Compile plugin: gcc -O2 -Wall -fPIC -shared sudoku.c -o libsudoku.so -lpari
 
Install plugin from home directory and play:
<langsyntaxhighlight lang="parigp">install("plug_sudoku", "G", "sudoku", "~/libsudoku.so")</langsyntaxhighlight>
 
Output:<pre> gp > S=[5,3,0,0,7,0,0,0,0;6,0,0,1,9,5,0,0,0;0,9,8,0,0,0,0,6,0;8,0,0,0,6,0,0,0,3;4,0,0,8,0,3,0,0,1;7,0,0,0,2,0,0,0,6;0,6,0,0,0,0,2,8,0;0,0,0,4,1,9,0,0,5;0,0,0,0,8,0,0,7,9]
Line 7,907:
{{works with|Free Pascal}}
Simple backtracking implimentation, therefor it must be fast to be competetive.With doReverse = true same sequence for trycell. nearly 5 times faster than [[Sudoku#C|C]]-Version.
<langsyntaxhighlight lang="pascal">Program soduko;
{$IFDEF FPC}
{$CODEALIGN proc=16,loop=8}
Line 8,163:
Outfield(solF);
writeln(86400*1000*(T1-T0)/k:10:3,' ms Test calls :',callCnt/k:8:0);
end.</langsyntaxhighlight>
{{out}}
<pre>
Line 8,199:
 
=={{header|Perl}}==
<langsyntaxhighlight Perllang="perl">#!/usr/bin/perl
use integer;
use strict;
Line 8,238:
}
}
solve();</langsyntaxhighlight>
{{out}}
<pre>
Line 8,256:
=={{header|Phix}}==
Simple brute force solution. Generally quite good but will struggle on some puzzles (eg see "the beast" below)
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">board</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">split</span><span style="color: #0000FF;">(</span><span style="color: #008000;">"""
Line 8,308:
<span style="color: #000000;">brute_solve</span><span style="color: #0000FF;">()</span>
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%s\n(solved in %3.2fs)\n"</span><span style="color: #0000FF;">,{</span><span style="color: #7060A8;">join</span><span style="color: #0000FF;">(</span><span style="color: #000000;">solution</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"\n"</span><span style="color: #0000FF;">),</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span><span style="color: #0000FF;">})</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 8,326:
contains 339 puzzles, can be run as a command-line or gui program, check for multiple solutions, and produce
a more readable single-puzzle output (example below).
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #000080;font-style:italic;">-- Working directly on 81-character strings ultimately proves easier: Originally I
Line 8,970:
<span style="color: #008080;">end</span> <span style="color: #008080;">procedure</span>
<span style="color: #000000;">test</span><span style="color: #0000FF;">()</span>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 9,039:
=={{header|PHP}}==
{{trans|C++}}
<langsyntaxhighlight lang="php"> class SudokuSolver {
protected $grid = [];
protected $emptySymbol;
Line 9,163:
$solver = new SudokuSolver('009170000020600001800200000200006053000051009005040080040000700006000320700003900');
$solver->solve();
$solver->display();</langsyntaxhighlight>
{{out}}
<pre>
Line 9,183:
Using constraint programming.
 
<langsyntaxhighlight lang="picat">import util.
import cp.
 
Line 9,253:
"....839..1......3...4....7..42.3....6.......4....7..1..2........8...92.....25...6",
"..3......4...8..36..8...1...4..6..73...9..........2..5..4.7..686........7..6..5.."
].</langsyntaxhighlight>
 
{{out}}
Line 9,285:
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(load "lib/simul.l")
 
### Fields/Board ###
Line 9,366:
(0 6 0 0 0 0 2 8 0)
(0 0 0 4 1 9 0 0 5)
(0 0 0 0 8 0 0 7 9) ) )</langsyntaxhighlight>
{{out}}
<pre> +---+---+---+---+---+---+---+---+---+
Line 9,388:
+---+---+---+---+---+---+---+---+---+
a b c d e f g h i</pre>
<syntaxhighlight lang PicoLisp="picolisp">(go)</langsyntaxhighlight>
{{out}}
<pre> +---+---+---+---+---+---+---+---+---+
Line 9,413:
=={{header|PL/I}}==
Working PL/I version, derived from the Rosetta Fortran version.
<langsyntaxhighlight lang="pli">sudoku: procedure options (main); /* 27 July 2014 */
 
declare grid (9,9) fixed (1) static initial (
Line 9,496:
 
end sudoku;
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 9,530:
 
Another PL/I version, reads sudoku from the text data file as 81 character record.
<langsyntaxhighlight lang="pli">
*PROCESS MARGINS(1,120) LIBS(SINGLE,STATIC);
*PROCESS OPTIMIZE(2) DFT(REORDER);
Line 9,669:
 
end sudoku;
</syntaxhighlight>
</lang>
 
=={{header|Prolog}}==
<langsyntaxhighlight Prologlang="prolog">:- use_module(library(clpfd)).
sudoku(Rows) :-
Line 9,697:
[5,_,_,_,_,_,_,7,3],
[_,_,2,_,1,_,_,_,_],
[_,_,_,_,4,_,_,_,9]]).</langsyntaxhighlight>
 
===GNU Prolog version===
{{works with|GNU Prolog|1.4.4}}
<langsyntaxhighlight Prologlang="prolog">:- initialization(main).
 
 
Line 9,754:
 
main :- test(T), solve(T), maplist(show,T), halt.
show(X) :- write(X), nl.</langsyntaxhighlight>
{{Out}}
<pre>[1,2,3,4,5,6,7,8,9]
Line 9,769:
=={{header|PureBasic}}==
A brute force method is used, it seemed the fastest as well as the simplest.
<langsyntaxhighlight PureBasiclang="purebasic">DataSection
puzzle:
Data.s "394002670"
Line 9,879:
Input()
CloseConsole()
EndIf</langsyntaxhighlight>
{{out}}
<pre>+-----+-----+-----+
Line 9,913:
 
A simple backtrack algorithm -- Quick but may take longer if the grid had been more than 9 x 9
<langsyntaxhighlight lang="python">
def initiate():
box.append([0, 1, 2, 9, 10, 11, 18, 19, 20])
Line 9,997:
print grid[i*9:i*9+9]
raw_input()
</syntaxhighlight>
</lang>
 
=={{header|Racket}}==
Line 10,006:
===Brute Force===
{{trans|Perl}}
<syntaxhighlight lang="raku" perl6line>my @A = <
5 3 0 0 2 4 7 0 0
0 0 2 0 0 0 8 0 0
Line 10,046:
}
}
solve;</langsyntaxhighlight>
 
{{out}}
Line 10,064:
This is an alternative solution that uses a more ellaborate set of choices instead of brute-forcing it.
 
<syntaxhighlight lang="raku" perl6line>#
# In this code, a sudoku puzzle is represented as a two-dimentional
# array. The cells that are not yet solved are represented by yet
Line 10,285:
}
}
}</langsyntaxhighlight>
 
{{out}}
Line 10,303:
A sudoku is represented as a matrix, see Rascal solutions to matrix related problems for examples.
 
<langsyntaxhighlight Rascallang="rascal">import Prelude;
import vis::Figure;
import vis::Render;
Line 10,386:
<0,7,0>, <1,7,0>, <2,7,9>, <3,7,0>, <4,7,0>, <5,7,8>, <6,7,0>, <7,7,0>, <8,7,0>,
<0,8,0>, <1,8,2>, <2,8,6>, <3,8,4>, <4,8,0>, <5,8,0>, <6,8,7>, <7,8,3>, <8,8,5>
};</langsyntaxhighlight>
 
Example
Line 10,679:
Example of a back-tracking solver, from [[wp:Algorithmics of sudoku]]
{{works with|Ruby|2.0+}}
<langsyntaxhighlight lang="ruby">def read_matrix(data)
lines = data.lines
9.times.collect { |i| 9.times.collect { |j| lines[i][j].to_i } }
Line 10,769:
print_matrix(matrix)
puts
print_matrix(solve_sudoku(matrix))</langsyntaxhighlight>
 
{{out}}
Line 10,803:
=={{header|Rust}}==
{{trans|Ada}}
<langsyntaxhighlight lang="rust">type Sudoku = [u8; 81];
 
fn is_valid(val: u8, x: usize, y: usize, sudoku_ar: &mut Sudoku) -> bool {
Line 10,866:
println!("Unsolvable");
}
}</langsyntaxhighlight>
 
{{out}}
Line 10,888:
Use CLP solver in SAS/OR:
 
<langsyntaxhighlight lang="sas">/* define SAS data set */
data Indata;
input C1-C9;
Line 10,934:
/* print solution */
print X;
quit;</langsyntaxhighlight>
 
Output:
Line 10,955:
This solver works with normally 9x9 sudokus as well as with sudokus of jigsaw type or sudokus with additional condition like diagonal constraint.
{{works with|Scala|2.9.1}}
<langsyntaxhighlight lang="scala">object SudokuSolver extends App {
 
class Solver {
Line 11,086:
println(solution match {case Nil => "no solution!!!" case _ => f2Str(solution)})
}</langsyntaxhighlight>
{{out}}
<pre>riddle:
Line 11,120:
The implementation above doesn't work so effective for sudokus like Bracmat version, therefore I implemented a second version inspired by Java section:
{{works with|Scala|2.9.1}}
<langsyntaxhighlight lang="scala">object SudokuSolver extends App {
 
object Solver {
Line 11,237:
+("\n"*2))
}
}</langsyntaxhighlight>
{{out}}
<pre>riddle used in Ada section:
Line 11,368:
The grid should be input in <code>Init_board</code> as a 9x9 matrix. The blanks should be represented by 0. A rule that the initial game should have at least 17 givens is enforced, for it guarantees a unique solution. It is also possible to set a maximum number of steps to the solver using <code>break_point</code>. If it is set to 0, there will be no break until it finds the solution.
 
<syntaxhighlight lang="text">Init_board=[...
5 3 0 0 7 0 0 0 0;...
6 0 0 1 9 5 0 0 0;...
Line 11,540:
disp('Invalid solution found.');
disp_board(Solved_board);
end</langsyntaxhighlight>
 
{{out}}
Line 11,600:
=={{header|Sidef}}==
{{trans|Raku}}
<langsyntaxhighlight lang="ruby">func check(i, j) is cached {
var (id, im) = i.divmod(9)
var (jd, jm) = j.divmod(9)
Line 11,648:
)
 
solve(grid)</langsyntaxhighlight>
{{out}}
<pre>5 3 9 8 2 4 7 6 1
Line 11,663:
 
=={{header|Shale}}==
<langsyntaxhighlight lang="shale">
#!/usr/local/bin/shale
 
Line 12,193:
 
// I'd like to see an irregular sudoku with a knight's move constraint. Any takers...
</syntaxhighlight>
</lang>
 
'''Output'''
Line 12,234:
The input and output are presented as strings of 81 characters, where each character is either a digit or a space (indicating an empty cell in the grid). The translation between grids and such strings is trivial (convert grid to string by concatenating rows, reading left to right and then top to bottom), and not covered in the solution. The input is given as a bind variable, ''':game'''.
 
<langsyntaxhighlight lang="sql">with
symbols (d) as (select to_char(level) from dual connect by level <= 9)
, board (i) as (select level from dual connect by level <= 81)
Line 12,262:
from r
where pos = 0
;</langsyntaxhighlight>
 
A better (faster) approach - taking advantage of database-specific features - is to create a '''table''' NEIGHBORS (similar to the inline view in the WITH clause) and an index on column I of that table; then the query execution time drops by more than half in most cases.
Line 12,286:
The example grid given below is taken from [https://en.wikipedia.org/wiki/Sudoku_solving_algorithms Wikipedia]. It does not require any recursive call (it's entirely filled in the first step of ''solve''), as can be seen with additional ''printf'' in the code to follow the algorithm.
 
<langsyntaxhighlight lang="stata">mata
function sudoku(a) {
s = J(81,20,.)
Line 12,386:
sudoku(a)
a
end</langsyntaxhighlight>
 
'''Output'''
Line 12,407:
Two more examples, from [http://www.7sudoku.com/very-difficult here] and [http://www.extremesudoku.info/sudoku.html there].
 
<langsyntaxhighlight lang="stata">a = 7,9,.,.,.,3,.,.,2\
.,6,.,5,1,.,.,.,.\
.,.,.,.,.,2,.,.,6\
Line 12,459:
8 | 3 8 5 4 7 9 2 1 6 |
9 | 7 6 9 3 2 1 4 5 8 |
+-------------------------------------+</langsyntaxhighlight>
 
=={{header|Swift}}==
{{trans|Java}}
<langsyntaxhighlight Swiftlang="swift">import Foundation
 
typealias SodukuPuzzle = [[Int]]
Line 12,586:
let puzzle = Soduku(board: board)
puzzle.solve()
puzzle.printBoard()</langsyntaxhighlight>
{{out}}
<pre>
Line 12,606:
{{works with|Swift 3}}
 
<syntaxhighlight lang="swift">
<lang Swift>
func solving(board: [[Int]]) -> [[Int]] {
var board = board
Line 12,671:
 
print(solving(board: puzzle))
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 12,690:
 
 
<langsyntaxhighlight lang="systemverilog">
 
//////////////////////////////////////////////////////////////////////////////
Line 12,820:
end
endprogram
</syntaxhighlight>
</lang>
 
It can be seen that SystemVerilog randomization is a very powerfull tool, in this implementation I directly described the game constraints and the randomization engine takes care of producing solutions, and when multiple solutions are possible they will be chosen at random.
Line 12,875:
 
=={{header|Tailspin}}==
<langsyntaxhighlight lang="tailspin">
templates deduceRemainingDigits
templates findOpenPosition
Line 13,021:
'> 'solves sudoku and outputs pretty solution'
end 'sudoku solver'
</syntaxhighlight>
</lang>
 
=={{header|Tcl}}==
Line 13,028:
Note that you can implement more rules if you want. Just make another subclass of <code>Rule</code> and the solver will pick it up and use it automatically.
{{works with|Tcl|8.6}} or {{libheader|TclOO}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.6
oo::class create Sudoku {
variable idata
Line 13,276:
return 0
}
}</langsyntaxhighlight>
Demonstration code:
<langsyntaxhighlight lang="tcl">SudokuSolver create sudoku
sudoku load {
{3 9 4 @ @ 2 6 7 @}
Line 13,301:
}
}
sudoku destroy</langsyntaxhighlight>
{{out}}
<pre>+-----+-----+-----+
Line 13,317:
+-----+-----+-----+</pre>
If we'd added a logger method (after creating the <code>sudoku</code> object but before running the solver) like this:
<langsyntaxhighlight lang="tcl">oo::objdefine sudoku method Log msg {puts $msg}</langsyntaxhighlight>
Then this additional logging output would have been produced prior to the result being printed:
<pre>::RuleOnlyChoice solved ::sudoku at 8,0 for 1
Line 13,371:
 
=={{header|Ursala}}==
<langsyntaxhighlight Ursalalang="ursala">#import std
#import nat
 
Line 13,383:
~&rgg&& ~&irtPFXlrjrXPS; ~&lrK2tkZ2g&& ~&llrSL2rDrlPrrPljXSPTSL)+-,
//~&p ^|DlrDSLlrlPXrrPDSL(~&,num*+ rep2 block3)*= num block27 ~&iiK0 iota9,
* `0?=\~&iNC ! ~&t digits+-</langsyntaxhighlight>
test program:
<langsyntaxhighlight Ursalalang="ursala">#show+
 
example =
Line 13,400:
010067008
009008000
026400735]-</langsyntaxhighlight>
{{out}}
<pre>
Line 13,418:
=={{header|VBA}}==
{{trans|Fortran}}
<langsyntaxhighlight VBlang="vb">Dim grid(9, 9)
Dim gridSolved(9, 9)
 
Line 13,519:
Debug.Print
Next i
End Sub</langsyntaxhighlight>
{{out}}
<pre>
Line 13,538:
{{trans|VBA}}
To run in console mode with cscript.
<langsyntaxhighlight lang="vb">Dim grid(9, 9)
Dim gridSolved(9, 9)
Line 13,639:
End Sub 'Sudoku
 
Call sudoku</langsyntaxhighlight>
{{out}}
<pre>Problem:
Line 13,664:
=={{header|Wren}}==
{{trans|Kotlin}}
<langsyntaxhighlight lang="ecmascript">class Sudoku {
construct new(rows) {
if (rows.count != 9 || rows.any { |r| r.count != 9 }) {
Line 13,741:
"000036040"
]
Sudoku.new(rows).solve()</langsyntaxhighlight>
 
{{out}}
Line 13,778:
can be verified by several other examples.
{{trans|C}}
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, CrLf=9, IntOut=11, Text=12;
 
proc Show(X);
Line 13,848:
..9 ..8 ...
.26 4.. 735 ");
]</langsyntaxhighlight>
 
{{out}}
Line 13,867:
=={{header|zkl}}==
{{trans|C}} Note: Unlike in the C solution, 1<<-1 is defined (as 0).
<langsyntaxhighlight lang="zkl">fcn trycell(sdku,pos=0){
row,col:=pos/9, pos%9;
Line 13,888:
sdku[pos]=0;
return(False);
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">problem:=
#<<<
" 5 3 0 0 7 0 0 0 0
Line 13,907:
s[n*27,27].pump(Console.println,T(Void.Read,8),("| " + "%s%s%s | "*3).fmt); // 3 lines
println("+-----+-----+-----+");
}</langsyntaxhighlight>
{{out}}
<pre>
10,343

edits