aboutsummaryrefslogtreecommitdiff
path: root/challenge-145/luca-ferrari/postgresql/ch-2.sql
blob: 0319ca15d80ae16c7467d39ab44dc8b63f15ad52 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
testdb=> select * from f_eertree( 'redivider' );
current_root |  string
--------------+-----------
r            | redivider
e            | edivide
d            | divid
i            | ivi
(4 rows)

testdb=> select * from f_eertree( 'hello' );
current_root | string
--------------+--------
l            | ll
(1 row)

*/
CREATE OR REPLACE FUNCTION
f_eertree( s text )
RETURNS TABLE( current_root char, string text )
AS $CODE$
DECLARE
        current int;
        other   int;
        other_root   char;
BEGIN

        FOR current IN 1 .. length( s ) LOOP
           current_root := substring( s FROM current FOR  1 );

           FOR other IN current + 1 .. length( s ) LOOP
               other_root := substring( s FROM other FOR 1 );
               IF other_root <> current_root THEN
                  CONTINUE;
               END IF;

               string := substring( s, current, other - current + 1 );

               IF string = reverse( string ) THEN
                  RETURN NEXT;
               END IF;

           END LOOP;
        END LOOP;

        RETURN;

END
$CODE$
LANGUAGE plpgsql;