OraQA

Oracle Question and Answer

  • Do you have a solution to a problem? Do you have an unanswered question? Login and share it with the Oracle community. More...

Oracle News


Entries RSS feed

Comments RSS feed

How to solve the 3 Digits Plus 3 Digits Puzzle in SQL

November 2nd, 2008 By Frank Zhou

The following is an interesting problem posted by mathforum.org:

Use the digits 1 to 9 only once in a sum that must be a three-digit number plus another three-digit number to equal another three-digit number. Each digit can only be used once, but all must be used.

———————————-SQL Solution——————————-

SELECT num1||' + '||num2||' = '|| num3 as Equation_str,
       CASE WHEN lag(cnt) over (order by num1) <> cnt
              OR lag(cnt) over (order by num1) IS NULL
     THEN  cnt END AS Counter
FROM
(SELECT num1, num2, num3, count(*) over ( ) as cnt
 FROM
 (SELECT substr(num,1,3) num1, substr(num,4,3) num2, substr(num,7,3) num3
  FROM
  (SELECT replace(sys_connect_by_path(n,','), ',') num
   FROM (SELECT LEVEL n FROM dual CONNECT BY LEVEL <=9)
   WHERE LEVEL = 9
   CONNECT BY NOCYCLE PRIOR n != n
   AND LEVEL <=9
   AND CASE LEVEL
            WHEN 1
            THEN CASE WHEN n < 9 THEN 1 END
            WHEN 4
            THEN CASE WHEN n  + CONNECT_BY_ROOT(n) < 10 THEN 1 END
            WHEN 7
            THEN CASE WHEN CONNECT_BY_ROOT(n) =1
                      THEN CASE WHEN n >= 3 THEN 1 END
                      ELSE CASE WHEN n >= CONNECT_BY_ROOT(n) + 1 THEN 1 END
                 END
           ELSE 1 END = 1
   )
  )
 WHERE to_number(num1)  + to_number(num2)  =  to_number(num3)
 );

EQUATION_STR                                               COUNTER
------------------------------------------                  ----------
124 + 659 = 783                                              336
125 + 739 = 864
127 + 359 = 486
127 + 368 = 495
128 + 367 = 495
128 + 439 = 567
129 + 357 = 486
129 + 735 = 864
129 + 654 = 783
129 + 438 = 567
134 + 658 = 792
.....................................................
.....................................................
.....................................................
.....................................................
.....................................................

762 + 183 = 945
763 + 182 = 945
782 + 154 = 936
782 + 163 = 945
783 + 162 = 945
784 + 152 = 936

336 rows selected.

Leave a Reply

You must be logged in to post a comment.

RSS feed for comments on this question