diff options
| author | Luca Ferrari <fluca1978@gmail.com> | 2022-11-22 09:13:10 +0100 |
|---|---|---|
| committer | Luca Ferrari <fluca1978@gmail.com> | 2022-11-22 09:13:10 +0100 |
| commit | ea525b69ae60150592aabbeef4fb6c6c4b656ee1 (patch) | |
| tree | 4262d5207e502ae822168bb922c46f8ebafb8f46 | |
| parent | 6fefc120fec1fd8de9ab11fcadbf73b4b88ac4e4 (diff) | |
| download | perlweeklychallenge-club-ea525b69ae60150592aabbeef4fb6c6c4b656ee1.tar.gz perlweeklychallenge-club-ea525b69ae60150592aabbeef4fb6c6c4b656ee1.tar.bz2 perlweeklychallenge-club-ea525b69ae60150592aabbeef4fb6c6c4b656ee1.zip | |
Task 2 plperl
| -rw-r--r-- | challenge-192/luca-ferrari/postgresql/ch-2.plperl | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/challenge-192/luca-ferrari/postgresql/ch-2.plperl b/challenge-192/luca-ferrari/postgresql/ch-2.plperl new file mode 100644 index 0000000000..32c13b6000 --- /dev/null +++ b/challenge-192/luca-ferrari/postgresql/ch-2.plperl @@ -0,0 +1,58 @@ +-- Perl Weekly Challenge 192 +-- Task 2 + +CREATE SCHEMA IF NOT EXISTS pwc192; + +CREATE OR REPLACE FUNCTION +pwc192.task2_plperl( int[] ) +RETURNS int +AS $CODE$ + my @moves; + my ($array) = @_; + + # utility function to get the + # max value from the array + my $find_max = sub { + my $max = 0; + for ( @_ ) { + elog(INFO, "value $_" ); + $max = $_ if $_ > $max; + } + + return $max; + }; + + # utility function to get the sum of the array + my $sum_array = sub { + my $sum = 0; + $sum += $_ for ( @_ ); + return $sum; + }; + + my $item = $sum_array->( $array->@* ) / scalar( $array->@* ); + return -1 if ( $item != int($item) ); + + push @moves, $array; + + while ( scalar( grep( { $_ == $item } $array->@* ) ) != scalar( $array->@* ) ) { + my $max = $find_max->( $array->@* ); + for my $index ( 0 .. scalar $array->@* ) { + next if $array->[ $index ] != $max; + + for my $borrow ( 0 .. scalar $array->@* ) { + next if $borrow == $index; + next if $array->[ $borrow ] >= $array->[ $index ]; + next if $array->[ $borrow ] >= $item; + $array->[ $borrow ]++; + last; + } + + $array->[ $index ]--; + } + + push @moves, $array; + } + + return scalar @moves; +$CODE$ +LANGUAGE plperl; |
