Solving Sudoku with a single sql query?

Unbelievable…

sudoku-problem

WITH solve_sudoku(sud_str,ind) AS
 (SELECT sud, INSTR(sud, ' ')
    FROM (SELECT '4 29 58 339     64  1   9     5 1    4 6 2 3    4 8     7   5  51     279 47 36 8' sud
            FROM dual)
  UNION ALL
  SELECT SUBSTR(sud_str, 1, ind - 1) || z || SUBSTR(sud_str, ind + 1),
         INSTR(sud_str, ' ', ind + 1)
    FROM solve_sudoku, (SELECT TO_CHAR(ROWNUM) z FROM dual CONNECT BY ROWNUM  0
     AND NOT EXISTS
   (SELECT NULL
            FROM (SELECT ROWNUM lp FROM dual CONNECT BY ROWNUM <= 9)
           WHERE z = SUBSTR(sud_str, TRUNC((ind - 1) / 9) * 9 + lp, 1)
              OR z = SUBSTR(sud_str, MOD(ind - 1, 9) - 8 + lp * 9, 1)
              OR z = SUBSTR(sud_str,
                            MOD(TRUNC((ind - 1) / 3), 3) * 3 +
                            TRUNC((ind - 1) / 27) * 27 + lp +
                            TRUNC((lp - 1) / 3) * 6,
                            1)))
SELECT sud_str FROM solve_sudoku WHERE ind = 0;

We will get the answer:

462915873395287164781364952279531486148692735653478291837126549516849327924753618

Ref:
http://oraclemine.com/sql-query-solved-sudoku-seconds/
https://technology.amis.nl/2009/10/13/oracle-rdbms-11gr2-solving-a-sudoku-using-recursive-subquery-factoring/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s