Skip to Main Content

SQL & PL/SQL

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Explanation of a complex query to solve sudoku using recursive hierarchical query

Nirav_A_ShahSep 13 2018 — edited Sep 17 2018

Hi Experts,

I came across the following sql that is said to solve sudoku:

https://technology.amis.nl/2009/10/13/oracle-rdbms-11gr2-solving-a-sudoku-using-recursive-subquery-factoring/

The query is as follows. I want to understand how it works and have no clue on it. Can someone help by explaining how this query is formed, the logic in it. I do have some basic idea of what is recursive hierarchical query and have watched Tim's video but how the below query works in not clear at all.

with x( s, ind ) as

( select sud, instr( sud, ' ' )

  from ( select '53 7 6 195 98 6 8 6 34 8 3 17 2 6 6 28 419 5 8 79' sud from dual )

  union all

  select substr( s, 1, ind - 1 ) || z || substr( s, ind + 1 )

  , instr( s, ' ', ind + 1 )

  from x

  , ( select to_char( rownum ) z

  from dual

  connect by rownum <= 9

  ) z

  where ind > 0

  and not exists ( select null

  from ( select rownum lp

  from dual

  connect by rownum <= 9

  )

  where z = substr( s, trunc( ( ind - 1 ) / 9 ) * 9 + lp, 1 )

  or z = substr( s, mod( ind - 1, 9 ) - 8 + lp * 9, 1 )

  or z = substr( s, mod( trunc( ( ind - 1 ) / 3 ), 3 ) * 3

  + trunc( ( ind - 1 ) / 27 ) * 27 + lp

  + trunc( ( lp - 1 ) / 3 ) * 6

  , 1 )

  )

)

select s

from x

where ind = 0

/

This post has been answered by Sven W. on Sep 13 2018
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Oct 15 2018
Added on Sep 13 2018
16 comments
1,537 views