SQL> ed
Wrote file afiedt.buf
1 With n as
2 (select level l from dual connect by level<=6),
3 t as(
4 select 1 n, 1.0 v from dual union all
5 select 2 n, 2.0 v from dual union all
6 select 3 n, 4.0 v from dual union all
7 select 4 n, 168.0 v from dual),
8 ta(n, v, res, lv, ll) as(
9 select t1.n, t1.v, cast(t1.v as varchar2(100)) res, 1 lv, t1.v ll from t t1
10 union all
11 select t2.n, t2.v,
12 cast( case when n.l=1 then t1.res || '+' || t2.v
13 when n.l=2 then t1.res || '-' || t2.v
14 when n.l=3 then t1.res || '*' || t2.v
15 when n.l=4 then t1.res || '/' || t2.v
16 when n.l=5 then t1.res || '|' || t2.v
17 when n.l=6 then t1.res || '\' || t2.v
18 end as varchar(100)),
19 lv+1,
20 case when n.l=1 then t1.ll+t2.v
21 when n.l=2 then t1.ll-t2.v
22 when n.l=3 then t1.ll*t2.v
23 when n.l=4 then decode(t2.v,0,cast(null as number), t1.ll/t2.v)
24 when n.l=5 then t2.v-t1.ll
25 when n.l=6 then decode(t1.ll,0,cast(null as number), t2.v/t1.ll)
26 end
27 from ta t1, t t2, n where t1.n<>t2.n
28 )
29 CYCLE n SET cycle_flag TO 'Y' DEFAULT 'N',
30 tt1 as(
31 select *
32 from ta WHERE lv=4 AND cycle_flag='N' and ll=24
33 ),
34 tta as(
35 select t1.n n1, t1.v v1, t2.n n2, t2.v v2, n.l,
36 cast( case when n.l=1 then t1.v || '+' || t2.v
37 when n.l=2 then t1.v || '-' || t2.v
38 when n.l=3 then t1.v || '*' || t2.v
39 when n.l=4 then t1.v || '/' || t2.v
40 end as varchar(100)) res,
41 case when n.l=1 then t1.v+t2.v
42 when n.l=2 then t1.v-t2.v
43 when n.l=3 then t1.v*t2.v
44 when n.l=4 then decode(t2.v,0,cast(null as number), t1.v/t2.v)
45 end ll
46 from t t1, t t2, n where t1.nt2.n and mod(n.l,2)=0)
47 ), tt2 as (
48 select cast( case when n.l=1 then t1.res || '+' || t2.res
49 when n.l=2 then t1.res || '-' || t2.res
50 when n.l=3 then t1.res || '*' || t2.res
51 when n.l=4 then t1.res || '/' || t2.res
52 end as varchar(100)) res,
53 case when n.l=1 then t1.ll+t2.ll
54 when n.l=2 then t1.ll-t2.ll
55 when n.l=3 then t1.ll*t2.ll
56 when n.l=4 then decode(t2.ll,0,cast(null as number), t1.ll/t2.ll)
57 end ll
58 from tta t1, tta t2, n
59 where t1.n1<>t2.n1 and t1.n1<>t2.n2
60 and t1.n2<>t2.n1 and t1.n2<>t2.n2
61 and ((t1.l=1 and t2.l=1 and (n.l=3 or n.l=4))
62 or (t1.l=1 and t2.l=2 and (n.l=3 or n.l=4))
63 or (t1.l=2 and t2.l=1 and (n.l=3 or n.l=4))
64 or (t1.l=2 and t2.l=2 and (n.l=3 or n.l=4))
65 or (t1.l=3 and t2.l=3 and (n.l=1 or n.l=2))
66 or (t1.l=3 and t2.l=4 and (n.l=1 or n.l=2))
67 or (t1.l=4 and t2.l=3 and (n.l=1 or n.l=2))
68 or (t1.l=4 and t2.l=4 and (n.l=1 or n.l=2)))
69 and case when n.l=1 then t1.ll+t2.ll
70 when n.l=2 then t1.ll-t2.ll
71 when n.l=3 then t1.ll*t2.ll
72 when n.l=4 then decode(t2.ll,0,cast(null as number), t1.ll/t2.ll)
73 end = 24
74 )
75 select t1.res, t1.ll, '1' n from tt1 t1
76 union all
77* select t2.res, t2.ll, '2' n from tt2 t2
78 /
RES LL N
-------------------- ---------- -
1+2+4\168 24 1
1+4+2\168 24 1
2+1+4\168 24 1
2+4+1\168 24 1
4+1+2\168 24 1
4+2+1\168 24 1
2*4-1\168 24 1
4*2-1\168 24 1
8 rows selected.
SQL>