The weekly challenge 303 - Task 1: 3-digits Even
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-303/#TASK1 3 # 4 # Task 1: 3-digits Even 5 # ===================== 6 # 7 # You are given a list (3 or more) of positive integers, @ints. 8 # 9 # Write a script to return all even 3-digits integers that can be formed using 10 # the integers in the given list. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (2, 1, 3, 0) 15 ## Output: (102, 120, 130, 132, 210, 230, 302, 310, 312, 320) 16 # 17 ## Example 2 18 ## 19 ## Input: @ints = (2, 2, 8, 8, 2) 20 ## Output: (222, 228, 282, 288, 822, 828, 882) 21 # 22 ############################################################ 23 ## 24 ## discussion 25 ## 26 ############################################################ 27 # 28 # First, we create all subsets of @ints containing 3 elements 29 # Then, we create all possible permutations of those 3 element lists 30 # and turn those into 3-digit numbers. If that number doesn't start 31 # in 0 and is even, we keep it for the result (eliminating duplicates 32 # along the way by storing them as keys in a hash). In the end, 33 # we can use those as the output. 34 35 use strict; 36 use warnings; 37 use Data::PowerSet qw(powerset); 38 use Algorithm::Combinatorics qw(permutations); 39 use Data::Dumper; 40 41 three_digist_even(2, 1, 3, 0); 42 three_digist_even(2, 2, 8, 8, 2); 43 44 sub three_digist_even { 45 my @ints = @_; 46 print "Input: (" . join(", ", @ints) . ")\n"; 47 my $result = {}; 48 my $powerset = powerset( { min => 3, max => 3 }, @ints ); 49 foreach my $p (@$powerset) { 50 my @all_permutations = permutations($p); 51 foreach my $perm (@all_permutations) { 52 my $num = join("", @$perm); 53 next if $num =~ m/^0/; 54 $result->{$num} = 1 unless $num % 2; 55 } 56 } 57 print "Output: (" . join(", ", sort {$a<=>$b} keys %$result) . ")\n"; 58 }