Skip to content

Instantly share code, notes, and snippets.

Forked from 140bytes/LICENSE.txt
Last active March 9, 2024 13:40
Show Gist options
  • Save p01/1230481 to your computer and use it in GitHub Desktop.
Save p01/1230481 to your computer and use it in GitHub Desktop.
Sudoku Solver in 140bytes

Sudoku Solver in 140 bytes

Solve a Sudoku grid only using magic, recursion, and 140bytes of brute force.

This entry was inspired and built on top of the itsy bitsy shoulders of the smallest sudoku solvers in Perl (120b), Ruby (122b), Python (178b), ...

Credits go this way:

166b @p01 .......... initial implementation
147b @p01 .......... initial golf
146b @qfox ......... loop optimization
145b @qfox ......... output with closured callback
140b @p01 .......... output with hijacked Array.prototype.toString()
141b @maksverver ... fixed the glitchy j^i==j test
140b @fgnass ....... ReferenceError exit trick + cross browser fix

Thanks to everyone who helped golf and fix this puppy.

// /!\ WARNING this function assumes that there is no variable 'A' in the global scope
function R
a, // the array representing the sudoku grid
// placeholder arguments
i, // index of the last empty cell
j, // index to check the candidates for the cell 'i'
m, // candidate number for the the cell 'i'
g // flag whether 'm' is a already used in the same row|col|node as 'i'
// phase 1: look for an empty cell
a[i]; // keep going if the cell isn't empty
i--||A // decrease the index and throw a ReferenceError exception if we went through the whole grid
// phase 2: check all candidate numbers for the cell 'i'
g=a[i]=--m; // put the candidate in the cell 'i' already and set 'g' to something truthy
// at the end of phase 2, the cell 'i' is reset to 0 for "higher" branches of the recursion
g&&R(a) // recurse if 'm' isn't already used in the same row|col|node as 'i'
// phase 3: check if the candidate number is used already
for(j in a) // loop through the whole grid again
g*= //
j==i // keep 'g' as is if we are on the cell 'i'
|| // otherwise, turn 'g' falsy if
a[j]^m // the cell 'j' is set to 'm'
|| // and 'i' and 'j' are in the same row|col|node
function R(a,i,j,m,g){for(i=80;a[i];i--||A);for(m=10;g=a[i]=--m;g&&R(a))for(j in a)g*=j==i||a[j]^m||i%9^j%9&&i/9^j/9&&i/27^j/27|i%9/3^j%9/3}
Version 2, December 2004
Copyright (C) 2011 Mathieu 'p01' Henri -
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
"name": "sudokuSolver",
"description": "Brute force sudoku solver.",
"keywords": [
"brute force"
<!doctype html>
body {
font: normal 1.1em/1.5 sans-serif;
<title>Sudoku Solver in 140bytes</title></head><body>
<h1>Sudoku Solver in 140bytes</h1>
<p>Input value: <code id="inp"></code></p>
<p>Expected value: <code>4,2,8,1,5,9,6,7,3,1,9,6,3,7,4,8,2,5,3,7,5,8,6,2,9,4,1,9,8,1,4,2,3,5,6,7,5,6,4,7,1,8,3,9,2,7,3,2,5,9,6,1,8,4,2,4,3,6,8,1,7,5,9,6,1,7,9,4,5,2,3,8,8,5,9,2,3,7,4,1,6</code></p>
<p>Actual value: <code id="ret"></code></p>
var testGrid = [0,0,0,1,5,0,0,7,0,1,0,6,0,0,0,8,2,0,3,0,0,8,6,0,0,4,0,9,0,0,4,0,0,5,6,7,0,0,4,7,0,8,3,0,0,7,3,2,0,0,6,0,0,4,0,4,0,0,8,1,0,0,9,0,1,7,0,0,0,2,0,8,0,5,0,0,3,7,0,0,0];
var myFunction = function R(a,i,j,m,g){for(i=80;a[i];i--||A);for(m=10;g=a[i]=--m;g&&R(a))for(j in a)g*=j==i||a[j]^m||i%9^j%9&&i/9^j/9&&i/27^j/27|i%9/3^j%9/3};
var solutionFound = false;
document.getElementById('inp').textContent = testGrid;
myFunction( testGrid );
solutionFound = true;
document.getElementById('ret').textContent = testGrid;
Copy link

atk commented Sep 27, 2011

Please provide a working example.

Copy link

@qfox ah, how I was reading I assumed it would just set a to a.toString() when i reached 0 (when the || condition would trigger it)

Copy link

p01 commented Sep 28, 2011

Sorry for the broken example guys. Fixed now.

Yes +a does invoke .toString() here when i is equal to 0 and the cell #0 was not empty.

Copy link

jed commented Sep 28, 2011

hey @p01, can you figure out why it works in firefox and not in chrome? if indeed you golfed it down to a reliably working 140, that would be HUGE.

Copy link

p01 commented Sep 28, 2011

It does work in Opera and Firefox.

I'll try to figure what is going with the other browsers... if my baby girl "let" me, Priorities.
Meanwhile any help is appreciated.

Copy link

atk commented Sep 28, 2011

Chrome/V8 is somewhat critical on having his prototypes overwritten. Perhaps we can do with an object looking like an array and having a toString property? like in

for(var sudoku={toString:function(){ document.getElementById( "ret" ).textContent=... }},s=0,t=testSudoku.length;s<t;s++)sudoku[s]=testSudoku[s];

Copy link

fgnass commented Sep 28, 2011

Here's another (maybe a little less dirty) approach that raises an error in order to stop the recursion. Hence the invocation has to be wrapped inside a try/catch block:

Copy link

p01 commented Sep 28, 2011

Nice moves!

@fgnass: Clever (ab)use of a ReferenceError. Before even using a callback method I tried a similar but more expensive approach with throw a

Copy link

Bravo sir, bravo.

Copy link

I want to be like you when I grow up.

Copy link

lrvick commented Sep 28, 2011

You make me happy.

Copy link

This is awesome.

Copy link

Just a notification: as I wrote on on Reddit the current version of the code is buggy. (See the linked post for details and a solution.)

Copy link

p01 commented Sep 29, 2011

Finally someone managed to reproduce this glitch. I tried the exact fix you suggested a few days ago: It works, unfortunately it is one byte bigger ( not smaller ), which bring us back to 141 bytes. One byte too many for

But I'm sure we can golf a valid version down to 140 bytes.

Copy link

pvdz commented Sep 29, 2011

Oh, I only see now that you're adding sugar for the toString "callback" in the test. I hadn't seen that before, just read the comments. That's why I was confused by the ||+a part. If you modify toString, the rules obviously change.

So I can see what you mean, but do you think this would be possible or acceptable in a js1k? I'd think the (temporary) toString modification is boiler plate, but still required for the solution. Guess what I'm asking is, do you really think this is a proper 140b entry, or should the toString modification actually kind of be part of it. Especially when golfing, I think it matters. And I think it does. Just my two cents... :)

Copy link

p01 commented Sep 29, 2011

The toString sugar would definitely count in a JS1K: Every thing counts in JS1K.

However things seem a more lax at See the base64 entries for instance where the whole list of characters is passed as argument ( a whooping 64+ bytes for free ).

That being said, if people are OK with encapsulating the call in a try/catch, then we can settle this at 140 bytes with a mix of fgnass ReferenceError trick and maksverver decomposition of the test i!=j && a[j]!=m

Copy link

pvdz commented Sep 29, 2011

However things seem a more lax at See the base64 entries for instance

Fair enough :)

Copy link

atk commented Sep 30, 2011

I agree, though I'd rather find a way to shorten up the calculation for 1 bit...

Copy link

My head just explo***BOOOOOOM***

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment