aboutsummaryrefslogtreecommitdiff
path: root/challenge-258/dave-jacoby/perl/ch-2.pl
blob: 501e50a66917d179ba4e5afe4a013ec13ddcfb5b (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
39
40
41
42
43
44
45
46
47
#!/usr/bin/env perl

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

use List::Util qw{ sum0 };

my @examples = (

    {
        ints => [ 2, 5, 9, 11, 3 ],
        k    => 1
    },
    {
        ints => [ 2, 5, 9, 11, 3 ],
        k    => 2
    },
    {
        ints => [ 2, 5, 9, 11, 3 ],
        k    => 0
    }
);

for my $example (@examples) {
    my @output = sum_of_values($example);
    my $ints   = join ', ', $example->{ints}->@*;
    my $k      = join ', ', $example->{k};
    my $output = join ', ', @output;

    say <<~"END";
    Input:  \@ints = ($ints), \$k = $k
    Output: $output
    END
}

sub sum_of_values ($obj) {
    my @ints   = $obj->{ints}->@*;
    my $k      = $obj->{k};
    my $output = 0;

    for my $i ( 0 .. $#ints ) {
        my $s = sum0 split //, sprintf '%b', $i;
        $output += $ints[$i] if $s == $k;
    }
    return $output;
}