aboutsummaryrefslogtreecommitdiff
path: root/challenge-154/luca-ferrari/postgresql/ch-1b.sql
blob: 6f0d61420ee5d3f0a0cdeb083c781e82d327183b (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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
CREATE SCHEMA IF NOT EXISTS pwc154;

CREATE TABLE IF NOT EXISTS
pwc154.permutations
(
  pk int generated always as identity
  , perm text not null
  , primary key( pk )
);

TRUNCATE pwc154.permutations;

INSERT INTO pwc154.permutations( perm )
VALUES
( 'PELR' ),
( 'PREL' ),
( 'PERL' ),
( 'PRLE' ),
( 'PLER' ),
( 'PLRE' ),
( 'EPRL' ),
( 'EPLR' ),
( 'ERPL' ),
( 'ERLP' ),
( 'ELPR' ),
( 'ELRP' ),
( 'RPEL' ),
( 'RPLE' ),
( 'REPL' ),
( 'RELP' ),
( 'RLPE' ),
( 'RLEP' ),
( 'LPER' ),
( 'LPRE' ),
( 'LEPR' ),
( 'LRPE' ),
( 'LREP' )
;


CREATE OR REPLACE FUNCTION pwc154.all_permutations( text )
RETURNS SETOF text
AS $CODE$
 use List::Permutor;
 my @letters = split( //, $_[ 0 ] );
 my $engine  = List::Permutor->new( @letters );
 while ( my @permutation = $engine->next() ) {
    my $current = join( '', @permutation );
    return_next( join( '', @permutation ) );
 }

 return undef;
$CODE$
LANGUAGE plperlu;


CREATE OR REPLACE FUNCTION pwc154.find_missing_permutations( text )
RETURNS SETOF text
AS $CODE$
  elog( INFO, "SELECT perm FROM pwc154.all_permutations( $_[ 0 ] ) WHERE perm NOT IN ( SELECT perm FROM pwc154.permutations )" );
  my $result_set = spi_exec_query( "SELECT perm FROM pwc154.all_permutations( " . quote_literal( $_[ 0 ] ) . " ) t(perm) WHERE perm NOT IN ( SELECT perm FROM pwc154.permutations )" );
  for my $i ( 0 .. $result_set->{ processed } ) {
      return_next( $result_set->{ rows }[ $i ]->{ perm } );
  }
  return undef;
$CODE$
language plperl;