aboutsummaryrefslogtreecommitdiff
path: root/challenge-164/e-choroba/perl/ch-2.pl
blob: 4fa13de04a53d207c8dbc307ac9e7f4313c45687 (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
#!/usr/bin/perl
use warnings;
use strict;

sub happy_numbers {
    my ($tally) = @_;
    my @happy_numbers;
    my $number = 1;

  CANDIDATE:
    while (@happy_numbers < $tally) {
        my $replace = $number;
        my %loop;
        my $sum;
        do {
            $sum = 0;
            $sum += $_ * $_ for split //, $replace;
            $replace = $sum;
            next CANDIDATE if $loop{$sum}++;

        } until 1 == $sum;

        push @happy_numbers, $number;

    } continue {
        ++$number;
    }

    return \@happy_numbers
}

use Test::More tests => 1;
is_deeply happy_numbers(8),
    [1, 7, 10, 13, 19, 23, 28, 31];