aboutsummaryrefslogtreecommitdiff
path: root/challenge-245/dave-jacoby/perl/ch-2.pl
blob: faa02d0afe705dd715d82a043e8e57df46b37f16 (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
#!/usr/bin/env perl

use strict;
use warnings;
use experimental qw{ say postderef signatures state };

use Algorithm::Combinatorics qw{ variations };

my @examples = (

    [ 8, 1, 9 ],
    [ 8, 6, 7, 1, 0 ],
    [1],
    [ 9, 0, 1, 2, 5 ]
);
for my $e (@examples) {
    my $input  = join ', ', $e->@*;
    my $output = largest_of_three( $e->@* );

    say <<~"END";
    Input:  \$input = ($input)
    Output:          $output
    END
}

sub largest_of_three (@input) {
    my @output;
    my $o = -1;
    for my $c ( reverse 1 .. scalar @input ) {
        my $iter = variations( \@input, $c );
        while ( my $p = $iter->next ) {
            my $combo = 0 + join '', $p->@*;
            next        if $combo % 3 != 0;
            $o = $combo if $combo > $o;
        }
    }
    return $o;
}