Skip to end of metadata
Go to start of metadata

This page describes a Groovy solution for ShortestSudokuSolver. Check the link for all the details, but basically the puzzle state is fed in as a String. Each line of the script must be no more than 80 characters in length.

The solution (184 characters plus 2 newlines):

Notes:

  • The script could be 25 characters shorter if Groovy supported integer division.
  • The script executes more efficiently if you use logical operators '&&' and '||' instead of '&' and '|' because short-circuiting kicks in at the expense of 3 characters.
  • The script would be 1 character longer if for clarity you wanted to use '0' instead of the first 48.
  • The script would be 2 characters longer if you want to use println rather than print if you are fussy about the formatting
  • To make the function stop as soon as it finds the first solution (proper puzzles will only have one solution), the part before the else becomes {print a;System.exit(1)}

Add the following line to the script to solve a partially complete puzzle (should take just a few seconds):

Alternatively, add the following line to the script to solve a puzzle from scratch (may take 30-60 minutes or more):

The expected output is:

Here is the more usual representation of the puzzle:

You can run it from the command-line by adding ;r args[0] to the end of the script (saved in a file called sudoku.groovy) and then invoking:

If you use '.groovy' as your script file extension, you can even leave off the extension as follows:

A slightly longer version using a matcher and no inner closure (209 characters plus 2 newlines):

Or without the matcher (193 characters plus two newlines):

Also see another version for a more understandable (though much longer) algorithm - but it also does a lot more.

  • No labels

1 Comment

  1. This example throws GroovyCastException.

    Here should be parentheses:g={(int)it(info)==(int)it(j)}