The weekly challenge 244 - Task 2: Group Hero

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-244/#TASK2
 3 #
 4 # Task 2: Group Hero
 5 # ==================
 6 #
 7 # You are given an array of integers representing the strength.
 8 #
 9 # Write a script to return the sum of the powers of all possible combinations;
10 # power is defined as the square of the largest number in a sequence,
11 # multiplied by the smallest.
12 #
13 ## Example 1
14 ##
15 ## Input: @nums = (2, 1, 4)
16 ## Output: 141
17 ##
18 ## Group 1: (2) => square(max(2)) * min(2) => 4 * 2 => 8
19 ## Group 2: (1) => square(max(1)) * min(1) => 1 * 1 => 1
20 ## Group 3: (4) => square(max(4)) * min(4) => 16 * 4 => 64
21 ## Group 4: (2,1) => square(max(2,1)) * min(2,1) => 4 * 1 => 4
22 ## Group 5: (2,4) => square(max(2,4)) * min(2,4) => 16 * 2 => 32
23 ## Group 6: (1,4) => square(max(1,4)) * min(1,4) => 16 * 1 => 16
24 ## Group 7: (2,1,4) => square(max(2,1,4)) * min(2,1,4) => 16 * 1 => 16
25 ##
26 ## Sum: 8 + 1 + 64 + 4 + 32 + 16 + 16 => 141
27 #
28 ############################################################
29 ##
30 ## discussion
31 ##
32 ############################################################
33 #
34 # Iterating over all subsets of the @nums array, we calculate both the
35 # minimum and maximum value of the elements therin. Then we just need
36 # to calculate the sum of the minimum and the square of the maximum and
37 # in the end sum up all of these.
38 # By using Algorithm::Combinatorics we can easily get an iterator for
39 # the subsets, so we don't have to implement that ourselves
40 
41 use strict;
42 use warnings;
43 use Algorithm::Combinatorics qw(subsets);
44 
45 group_hero(2, 1, 4);
46 group_hero();
47 group_hero(1, 2);
48 
49 
50 sub group_hero {
51    my @nums = @_;
52    print "Input: (" . join(", ", @nums) . ")\n";
53    my $result = 0;
54    my $iter = subsets(\@nums);
55    while(my $s = $iter->next) {
56       $result += min_max_squared($s);
57    }
58    print "Output: $result\n";
59 }
60 
61 sub min_max_squared {
62    my $set = shift;
63    unless(@$set) {
64       return 0;
65    }
66    my ($min, $max) = ( $set->[0], $set->[0] );
67    foreach my $elem(@$set) {
68       $max = $elem if $elem > $max;
69       $min = $elem if $elem < $min;
70    }
71    return $min * $max * $max;
72 }