# p01 / LICENSE.txt Created September 20, 2011 — forked from 140bytes/LICENSE.txt

### SSH clone URL

You can clone with HTTPS or SSH.

Sudoku Solver in 140bytes

 1 2 3 4 5 6 7 8 9 10 11 12 13 ``` DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE 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.   DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION   0. You just DO WHAT THE FUCK YOU WANT TO. ```

# Sudoku Solver in 140 bytes

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

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 ```function R ( a, // the array representing the sudoko 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 for ( i=80; a[i]; // keep going if the cell isn't empty i--||+a // decrease the index and call 'a.toString()' if we went through the whole grid ); // phase 2: check all candidate numbers for the cell 'i' for ( m=10; 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*= // turn 'g' falsy if a[j^i==j] // we are not on the cell 'i' ^m // and the cell 'j' is set to 'm' || // and we are in the same row|col|node as 'i' i/9^j/9&&i%9^j%9&&i/27^j/27|i%9/3^j%9/3 } ```
 1 2 3 4 5 6 7 8 9 10 11 12 ```{ "name": "sudokuSolver",   "description": "Brute force sudoku solver.",   "keywords": [ "sudoku", "solver", "recursive", "brute force" ] } ```
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 ``` Sudoku Solver in 140bytes
Expected value: 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
Actual value:
```

you're my hero

Haha cool :)

I think you can rewrite ~--i to i-- and be fine.

Also, why would you return the original grid in the callback? Isn't it safe to assume that the original calling code would have some reference to that array under closure? Or was this a requirement for your specific need? In fact, why have the callback there at all? There's nothing async to this code, why introduce it that way..? Cut it out and you'll have your 7 bytes. In fact, you could then just get rid of the first for loop completely. So there's probably something to that callback that I'm missing :)

Owner

@evert: :)

@qfox: :p doh! Thanks for the `i--`instead of `~--i`

The callback costs 7 bytes in total, but it saves the expensive hassle of having to return ( 6 byte for the statement alone ) with fall through for the recursions that don't lead to a solution.

Also, `f` isn't called with original grid, but with a grid that has been modified through several recursions testing all possible candidates for each empty cell ;)

@p01 `f` is called with `a` by reference... so it is passing on the same array, albeit changed. Nowhere in the code are you creating a new array. So if the callback has a closure over the original array, it will now have a closure over a modified array since you're changing the array in place.

Owner

I see. Another byte bites the dust! 145 bytes

An option I am not too fond of would be to push some logic into `f` and change:
`for(i=80;a[i];i--||f());`
into
`for(i=80;a[i];f(i--));`
thus saving 2 bytes ( down to 143 bytes )

We could save a whooping 6 bytes ( down to 139 bytes ) by requiring ES5 ( thus loosing IE8 support ) and use
`f(i=a.indexOf(0));`

Ok, so unless you were explicitly trying to make this async, I still don't see the point of the callback.

Aside from that, I would not call the callback <=80 times for every recursion. It would kind of defy the point of the callback anyways.

What exactly is the callback supposed to do?

In your test, if `myFunction` would not have a callback at all, it would become:

``````myFunction( testGrid);
document.getElementById( "ret" ).textContent=testGrid;
``````

Same code. So I don't see a reason for the callback unless you had something else in mind :)

So basically it would be something like this:
`function R(a,i,j,m,g){for(i=80;a[i--];);for(m=10;g=a[i]=--m;g&&R(a))for(j in a)g*=a[j^i==j]^m||i/9^j/9&&i%9^j%9&&i/27^j/27|i%9/3^j%9/3}` (135 bytes). Only stripped the callback part.

Owner

You are missing the very important fact that the loop in phase 2 keeps changing the array and eventually resets the cell to 0 in order to test next subtree of the recursion in case the current one only leads to invalid grids.

Owner

Indeed calling `f` all the time would be stupid.

The callback ( which costs 9 bytes ) is called once a solution is found AND allows us to not care about the following recursions.

Without the callback we would have to shortcut the loop in phase 2 to prevent the next recursions from changing the array. Doubt it's possible in less than 9 bytes :\

Yeah I see now, ok let's see about that :)

this is just incredible.

You people amaze me... +100 for the commented code!

Very nice.

ES5 indexOf could save us 1 byte:
`function R(a,f,i,j,m,g){for(i=a.indexOf(0),~i||f(),m=10;g=a[i]=--m;g&&R(a,f))for(j in a)g*=a[j^i==j]^m||i/9^j/9&&i%9^j%9&&i/27^j/27|i%9/3^j%9/3}`

@p01 Out of curiosity (related to a side project I'm working on) - what would happen if the grid provided had no solution?

ie: If it fell out-with of the 6,670,903,752,021,072,936,960 possible permutations

Would it be easy enough to return false, or something to that effect?

The number of actual calculated permutations is already reduced by the number of zeros in the input array; anyway, can a solution not be found, it would enter an infinite loop as at least one zero in the field cannot be cleared up.

Owner

I must say I find the closure thing wonky. Calling `myFunction(a,f);` which in turn calls `f` with no arguments just feel strange to me.

Owner

So I was thinking why not simply use the `.toString` method of the array to output the grid, and ... Boom! We have a winner!

140 bytes

`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*=a[j^i==j]^m||i/9^j/9&&i%9^j%9&&i/27^j/27|i%9/3^j%9/3}`

Sleepy again? Why +a? Without checking further, either you meant ++a or the ||+a is completely useless...

@qfox +a is just invoking a.toString(), not intended as an increment.

the example doesn't work anymore, unfortunately.

@cjcliffe I understand, but it's in the third part of the for statement, who's return-value is discarded. Hence, useless, because the toString has no notable side effects. At least none in this code.

@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)

Owner

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.

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.

Owner

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.

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

``````testSudoku=[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];
for(var sudoku={toString:function(){ document.getElementById( "ret" ).textContent=... }},s=0,t=testSudoku.length;s<t;s++)sudoku[s]=testSudoku[s];
``````

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: https://gist.github.com/1247640

Owner

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`

Bravo sir, bravo.

I want to be like you when I grow up.

You make me happy.

This is awesome.

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.)

Owner

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 140byt.es

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

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... :)

Owner

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

However things seem a more lax at 140byt.es. 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`

However things seem a more lax at 140byt.es. See the base64 entries for instance

Fair enough :)

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