aboutsummaryrefslogtreecommitdiff
path: root/challenge-160/luca-ferrari/postgresql/ch-2.plperl
blob: 6af0daa5d59578dccd1782c5cffdcc8b2cc01ee8 (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
-- Perl Weekly Challenge 160

CREATE SCHEMA IF NOT EXISTS pwc160;

/*
testdb=> select pwc160.equilibrium( array[1,2,3,6]::int[] );
 equilibrium 
-------------
           3

*/
CREATE OR REPLACE FUNCTION
pwc160.equilibrium( int[] )
RETURNS int
AS $CODE$
my ( @A ) = @{ $_[0] };

# compute the sum of an array
my $do_sum = sub {
   my ( @a ) = @_;
   my $sum = 0;
   $sum += $_  for ( @a );
   return $sum;
};

for my $index ( 1 .. $#A ) {
    return $index if ( $do_sum->( @A[ 0 .. $index - 1 ] ) == $do_sum->( @A[ $index .. $#A ] ) );
}

return -1;
$CODE$
LANGUAGE plperl;