Forum Stats

  • 3,741,235 Users
  • 2,248,398 Discussions
  • 7,861,695 Comments

Discussions

Pascal's triangle or binomial coefficients

146850
146850 Member Posts: 116
edited May 3, 2008 5:06PM in SQL & PL/SQL
<font color="red">you know Pascal's triangle like below.</font>

1
11
121
1331
14641
...
...

my question is to find out a query giving nth sequence,
that is to say,

when n=1, that query yields
1

when n=2
1
1

when n=3
1
2
1

when n=4
1
3
3
1

...
...

(oh, but you have NOT to use any subqueries)


for more SQL problems & questions, please visit
http://cafe.daum.net/oraclesqltuning
«1

Comments

  • Ghulam Mustafa Butt
    Ghulam Mustafa Butt Member Posts: 694 Blue Ribbon
    If you dont want subqueries, you can try in PL/SQL.

    Assuming your biggest length of the charector is 6, If the length is more you can copy and paste more ElsIf's:
    DECLARE
    lv_text VARCHAR2(50);
    lv_len NUMBER;
    CURSOR c1 IS
    SELECT text, length(text)
    FROM table;
    BEGIN
    OPEN c1;
    LOOP
    FETCH c1 INTO lv_text;
    EXIT WHEN c1%NOTFOUND;
    IF nvl(lv_length) = 1 THEN
    dbms_output.put_line (lv_text);
    ELSIF
    nvl(lv_length) = 2 THEN
    FOR i IN 1..2 LOOP
    dbms_output.put_line (substr(lv_text, i, i));
    ELSIF
    nvl(lv_length) = 3 THEN
    FOR i IN 1..3 LOOP
    dbms_output.put_line (substr(lv_text, i, i));
    ELSIF
    nvl(lv_length) = 4 THEN
    FOR i IN 1..4 LOOP
    dbms_output.put_line (substr(lv_text, i, i));
    ELSIF
    nvl(lv_length) = 5 THEN
    FOR i IN 1..5 LOOP
    dbms_output.put_line (substr(lv_text, i, i));
    ELSIF
    nvl(lv_length) = 6 THEN
    FOR i IN 1..6 LOOP
    dbms_output.put_line (substr(lv_text, i, i));
    END IF;
    END LOOP;
    CLOSE c1;
    END;
    /
    Not tested !

    HTH
    Ghulam
  • 452095
    452095 Member Posts: 332
    Are there restrictions on creating functions?
  • Ghulam Mustafa Butt
    Ghulam Mustafa Butt Member Posts: 694 Blue Ribbon
    FOR i IN 1..2 LOOP
    dbms_output.put_line (substr(lv_text, i, i));
    END LOOP;

    Sorry you have to add END LOOP; at the end of all For Loops.

    HTH
    Ghulam
  • 146850
    146850 Member Posts: 116
    sorry, but i want it in one SQL , not PL/SQL

    a variable n is given.
    no subqueries allowed.

    * this is not a sort of exam.
  • 146850
    146850 Member Posts: 116
    and the result is n rows....

    when n=1
    1 (one row)

    when n=2
    1
    1 (two rows)

    where n=3
    1
    2
    1 (three rows)
    ...
    ...
  • APC
    APC Member Posts: 11,316 Bronze Crown
    * this is not a sort of exam.
    Do you have a solution and you're just testing us, or is this a kite flying exercise to see whether its possible?

    I imagine it might be possible to do this with the Model clause but not having 10g to try it on I can't explore this theory at the moment.

    Cheers, APC
  • 94799
    94799 Member Posts: 2,208
    I recall the triangle starting at row 0 (perhaps that is a matter of choice)...
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    
    SQL> VARIABLE n NUMBER;
    SQL> EXEC :n := 0;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
    
    SQL> EXEC :n := 1;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
             1
    
    SQL> EXEC :n := 2;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
             2
             1
    
    SQL> EXEC :n := 3;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
             3
             3
             1
    
    SQL> EXEC :n := 4;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
             4
             6
             4
             1
    
    SQL> EXEC :n := 5;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
             5
            10
            10
             5
             1
    
    6 rows selected.
    
    SQL> EXEC :n := 6;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
      2            EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) 
      3               OVER (ORDER BY LEVEL)) *
      4            EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1))) 
      5               OVER (ORDER BY LEVEL DESC))) n
      6  FROM   dual
      7  CONNECT BY LEVEL <= CEIL (:n + 1);
    
             N
    ----------
             1
             6
            15
            20
            15
             6
             1
    
    7 rows selected.
    
    SQL> 
  • Laurent Schneider
    Laurent Schneider Member Posts: 5,219
    edited Nov 14, 2005 10:52AM
    by the way, how are you going to generate multiple rows in plain SQL?
    def n=5
    
    with fac as (select rownum n,exp(sum(ln(rownum))over(order by rownum)) fac from all_objects where rownum<12)
    select nvl(n.fac/r.fac/nr.fac,1)
    from (select rownum-1 r from all_objects where rownum<=&n+1),
        fac n, fac r, fac nr
    where n.n (+)=&n and r.n (+)=r and nr.n(+)=(&n-r)
    order by r
    /
    
                            1
                            5
                           10
                           10
                            5
                            1
    Message was edited by:
    Laurent Schneider
    padders, your one is better ;-)
  • Laurent Schneider
    Laurent Schneider Member Posts: 5,219
    edited Nov 14, 2005 11:01AM
    note that I consider CONNECT BY without PRIOR to be disallowed... as specified in the doc, CONNECT BY must contain a PRIOR operator defining the parent-child relationship... but this is just a small note of mines and feel free to use CONNECT BY if you like / trust it ;-)

    Message was edited by:
    Laurent Schneider
    still padders method with analytics rules, because it does not use subquery
  • 452095
    452095 Member Posts: 332
    Should this work for all values of :n?

    When :n = 10...

    N
    0
    10
    45
    120
    210
    252
    210
    120
    45
    10
    0
  • APC
    APC Member Posts: 11,316 Bronze Crown
    edited Nov 14, 2005 11:20AM
    Should this work for all values of :n?
    interesting. Padders version works for me (allowing for the fatc that the CONNECT BY trick doesn't work propperly in 9.2)...
    SQL> EXEC :n := 10

    PL/SQL procedure successfully completed.

    SQL> SELECT * FROM
    2 (
    3 SELECT EXP (SUM (LN (LEVEL)) OVER ()) / (:n + 1) / (
    4 EXP (SUM (LN (GREATEST (LEVEL - 1, 1)))
    5 OVER (ORDER BY LEVEL)) *
    6 EXP (SUM (LN (GREATEST (:n - (LEVEL - 1), 1)))
    7 OVER (ORDER BY LEVEL DESC))) n
    8 FROM dual
    9 CONNECT BY LEVEL <= CEIL (:n + 1))
    10 /
    N
    ----------
    1
    10
    45
    120
    210
    252
    210
    120
    45
    10
    1

    11 rows selected.

    SQL>
    Cheers, APC
  • 49084
    49084 Member Posts: 340
    interesting. Padders version works for me (allowing for the fatc that the CONNECT BY trick doesn't work propperly in 9.2)...
    There's an easy workaround for that (I'm sure you're well aware, but just for those who don't know yet):
    SELECT EXP (SUM (LN (L)) OVER ()) / (:n + 1) / (
          EXP (SUM (LN (GREATEST (L - 1, 1))) 
                     OVER (ORDER BY L)) *
                 EXP (SUM (LN (GREATEST (:n - (L - 1), 1))) 
                   OVER (ORDER BY L DESC))) n
      FROM   ( SELECT LEVEL L 
                 FROM DUAL 
              CONNECT BY LEVEL <= CEIL (:n + 1)
             )
    /
    It works perfect on my 9.2 box.

    MHE
  • 452095
    452095 Member Posts: 332
    I'm using 9.2.0.6.0... so there's a flaw with connect by in this version thats affecting the output of the query sometimes? When I use values 0 through 9 and 11 it appears to return the correct values, but for whatever reason it doesn't work when :n equals 10.

    Can anyone explain how the query works, not what each function does individually, but why when you put them together they return pascal's triangle?
  • APC
    APC Member Posts: 11,316 Bronze Crown
    I'm using 9.2.0.6.0
    Me likewise
    Can anyone explain how the query works
    basically the query is calculating the value of each element in the row; it implements the nCr method using analytic functions to generate factorials.

    Cheers, APC
  • 452095
    452095 Member Posts: 332
    Thanks for your reply APC. I understand the formula (I accept that it works although I have no idea why it works). But how do the functions that padders uses perform the same functionality that a factorial (!) does?
  • 245482
    245482 Member Posts: 1,254
    The following are all the same. This is a (sort of) common trick for implementing factorial.
    select exp(sum(ln(level)))
      from dual
    connect by level <= N
    
    exp(ln(1) + ln(2) + ... ln(N))
    
    exp(ln(1)) * exp(ln(2)) * ... exp(ln(N))
    
    1*2*...N
    
    N!
  • select x,y,count(1) from (
    select x,y,sys_connect_by_path('['||x||','||y||'>',' ') path
    from (
    select level x from dual
    connect by level < 5
    ), (
    select level y from dual
    connect by level < 5
    ) connect by prior x+1 = x and prior y = y
    or prior x = x and prior y+1 = y
    start with x = 1 and y = 1
    ) group by x,y;

    Nice exercise to include into a book.
  • 452095
    452095 Member Posts: 332
    Thanks Scott, I must have missed that day in my SQL class.
  • 146850
    146850 Member Posts: 116
    edited May 28, 2007 7:44AM
    good job, padders.

    and my solution is
    SELECT       EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) OVER ())
               / EXP (SUM (LN (GREATEST (LEVEL - 1, 1))) OVER (ORDER BY LEVEL))
               / EXP (SUM (LN (GREATEST (:n - LEVEL, 1))) OVER (ORDER BY LEVEL DESC)
                     ) bin_coef
          FROM DUAL
    CONNECT BY LEVEL <= :n
    Query Your Dream & Future at
    http://www.soqool.com
  • 94799
    94799 Member Posts: 2,208
    Just a couple of variations on the theme using a table function as a row source and a user-defined product aggregate (source available on request).
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    
    SQL> VARIABLE r NUMBER;
    SQL> EXEC :r := 5;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT product (GREATEST (n, 1)) OVER () / 
      2         product (GREATEST (n, 1)) OVER (ORDER BY n) /
      3         product (GREATEST (:r - n, 1)) OVER (ORDER BY n DESC) n
      4  FROM   TABLE (many (0, :r));
    
             N
    ----------
             1
             5
            10
            10
             5
             1
    
    6 rows selected.
    
    SQL> SELECT SUBSTR (SYS_CONNECT_BY_PATH (
      2            r, ','), 2) pascals_triangle
      3  FROM  (SELECT a.n an, b.n bn, 
      4                product (GREATEST (b.n, 1)) OVER (
      5                   PARTITION BY a.n) /
      6                product (GREATEST (b.n, 1)) OVER (
      7                   PARTITION BY a.n ORDER BY b.n) /
      8                product (GREATEST (a.n - b.n, 1)) OVER (
      9                   PARTITION BY a.n ORDER BY b.n DESC) r
     10         FROM   TABLE (many (0, :r)) a, 
     11                TABLE (many (0, a.n)) b) 
     12  WHERE  CONNECT_BY_ISLEAF = 1
     13  START WITH bn = 0
     14  CONNECT BY an = PRIOR an AND bn = PRIOR bn + 1;
    
    PASCALS_TRIANGLE
    --------------------------------------------------------------------------------
    1
    1,1
    1,2,1
    1,3,3,1
    1,4,6,4,1
    1,5,10,10,5,1
    
    6 rows selected.
    
    SQL> 
  • 94799
    94799 Member Posts: 2,208
    LOL. Is this better?
    Oracle Database 10g Enterprise Edition Release 10.2.0.1.0 - Production
    With the Partitioning, OLAP and Data Mining options
    
    SQL> VARIABLE r NUMBER;
    SQL> EXEC :r := 10;
    
    PL/SQL procedure successfully completed.
    
    SQL> SELECT LPAD (' ', 5 * (:r - an) / 2) ||
      2           REPLACE (SYS_CONNECT_BY_PATH (
      3              LPAD (r, 5), '/'), '/') pascals_triangle
      4  FROM  (SELECT a.n an, b.n bn,
      5                product (GREATEST (b.n, 1)) OVER (
      6                   PARTITION BY a.n) /
      7                product (GREATEST (b.n, 1)) OVER (
      8                   PARTITION BY a.n ORDER BY b.n) /
      9                product (GREATEST (a.n - b.n, 1)) OVER (
     10                   PARTITION BY a.n ORDER BY b.n DESC) r
     11         FROM   TABLE (many (0, :r)) a,
     12                TABLE (many (0, a.n)) b)
     13  WHERE  CONNECT_BY_ISLEAF = 1
     14  START WITH bn = 0
     15  CONNECT BY an = PRIOR an AND bn = PRIOR bn + 1;
    
    PASCALS_TRIANGLE
    --------------------------------------------------------------------------------
                                 1
                              1    1
                            1    2    1
                         1    3    3    1
                       1    4    6    4    1
                    1    5   10   10    5    1
                  1    6   15   20   15    6    1
               1    7   21   35   35   21    7    1
             1    8   28   56   70   56   28    8    1
          1    9   36   84  126  126   84   36    9    1
        1   10   45  120  210  252  210  120   45   10    1
    
    11 rows selected.
    
    SQL> 
  • Nicolas Gasparotto
    Nicolas Gasparotto Member Posts: 25,514 Silver Crown
    Splendid !!

    Nicolas.
  • Aketi Jyuuzou
    Aketi Jyuuzou Member Posts: 1,072 Bronze Badge
    SQL> col PASCALS_TRIANGLE for a80
    SQL>
    SQL> with Renban as (
    2 select RowNum-1 as Val
    3 from dual connect by Level <= 15),
    4 WorkView as (
    5 select Ra.Val as n,Rb.Val as r
    6 from Renban Ra,Renban Rb
    7 where Ra.Val >= Rb.Val),
    8 RowList as (
    9 select n,r,
    10 case when r=0 then 1
    11 else (select round(exp(sum(Ln(a.N-b.R+1)))) from WorkView b
    12 where b.N=a.N
    13 and b.R > 0
    14 and b.R<=a.R) end as NPR,
    15 case when r=0 then 1
    16 else (select round(exp(sum(Ln(b.R)))) from WorkView b
    17 where b.N=a.N
    18 and b.R > 0
    19 and b.R<=a.R) end as "R!"
    20 from WorkView a),
    21 PascalTriangle as (
    22 select N,SubStr(sys_connect_by_path(Val,' '),2) as Pascal
    23 from (select N,R,NPR / "R!" as Val from RowList)
    24 where Connect_by_IsLeaf = 1
    25 start with R=0
    26 connect by prior N=N
    27 and prior R=R-1)
    28 select Lpad(' ',(MaxLength-Length(Pascal))/2-1) || Pascal as PASCALS_TRIANGLE
    29 from PascalTriangle,(select max(Length(Pascal)) as MaxLength from PascalTriangle);

    PASCALS_TRIANGLE
    --------------------------------------------------------------------------------
    1
    1 1
    1 2 1
    1 3 3 1
    1 4 6 4 1
    1 5 10 10 5 1
    1 6 15 20 15 6 1
    1 7 21 35 35 21 7 1
    1 8 28 56 70 56 28 8 1
    1 9 36 84 126 126 84 36 9 1
    1 10 45 120 210 252 210 120 45 10 1
    1 11 55 165 330 462 462 330 165 55 11 1
    1 12 66 220 495 792 924 792 495 220 66 12 1
    1 13 78 286 715 1287 1716 1716 1287 715 286 78 13 1
    1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
  • 146850
    146850 Member Posts: 116
    Thanks, Vadim Tropashko.
    I'm reading your book, SQL Design Patterns.

    Query Your Dream & Future at
    http://www.soqool.com
This discussion has been closed.