aboutsummaryrefslogtreecommitdiff
path: root/challenge-164/luca-ferrari/postgresql/ch-2.plperl
blob: 27adb615e480e729a5b8404e988edbe812b9bd14 (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 164
-- Task 2

CREATE SCHEMA IF NOT EXISTS pwc164;

CREATE OR REPLACE FUNCTION
pwc164.task2_plperl( int )
RETURNS SETOF int
AS $CODE$
  my ( $limit ) = @_;

  my $is_happy = sub {
     my ( $num ) = @_;
     my $sum = $num;
     while ( $num > 10 ) {
             $sum = 0;
             $sum += $_ for map { $_ ** 2 }  split( //, $num );
             $num = $sum;
             $sum = 0;
    }

    return $num == 1;
  };

  for ( 10 .. 99999 ) {
      $limit-- and return_next( $_ )  if $is_happy->( $_ );
      last if $limit == 0;
  }

  return undef; 
$CODE$
LANGUAGE plperl;