aboutsummaryrefslogtreecommitdiff
path: root/challenge-208/luca-ferrari/postgresql/ch-2.plperl
blob: 6e2f8666fc40973ccb4ed6ac8c81cddc40239694 (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
--
-- Perl Weekly Challenge 208
-- Task 2
-- See <https://perlweeklychallenge.org/blog/perl-weekly-challenge-208/>
--

CREATE SCHEMA IF NOT EXISTS pwc208;

/*
testdb=> select pwc208.task2_plperl( array[ 1,2,2,4,5]::int[] );
       task2_plperl       
--------------------------
 (2,"Duplicated value 2")
 (3,"Missing value 3")
(2 rows)

*/
CREATE OR REPLACE FUNCTION
pwc208.task2_plperl( int[] )
RETURNS TABLE( v int, d text )
AS $CODE$
  my ( $list ) = @_;
  my %results;

  my ( $min, $max ) = ( sort $list->@* )[0, -1];
  for my $needle ( $min .. $max ) {
      $results{ $needle } += scalar grep { $_ == $needle } $list->@*;
  }

  for ( sort keys %results ) {
    next if $results{ $_ } == 1;
    return_next( { v => $_, d => "Missing value $_" } ) if ( $results{ $_ } == 0 );
    return_next( { v => $_, d => "Duplicated value $_" } ) if ( $results{ $_ } > 1 );
  }

return undef;
 
$CODE$
LANGUAGE plperl;