The weekly challenge 258 - Task 2: Sum of Values
1 #!/usr/bin/env perl 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-258/#TASK2 3 # 4 # Task 2: Sum of Values 5 # ===================== 6 # 7 # You are given an array of integers, @int and an integer $k. 8 # 9 # Write a script to find the sum of values whose index binary representation has 10 # exactly $k number of 1-bit set. 11 # 12 ## Example 1 13 ## 14 ## Input: @ints = (2, 5, 9, 11, 3), $k = 1 15 ## Output: 17 16 ## 17 ## Binary representation of index 0 = 0 18 ## Binary representation of index 1 = 1 19 ## Binary representation of index 2 = 10 20 ## Binary representation of index 3 = 11 21 ## Binary representation of index 4 = 100 22 ## 23 ## So the indices 1, 2 and 4 have total one 1-bit sets. 24 ## Therefore the sum, $ints[1] + $ints[2] + $ints[3] = 17 25 # 26 ## Example 2 27 ## 28 ## Input: @ints = (2, 5, 9, 11, 3), $k = 2 29 ## Output: 11 30 # 31 ## Example 3 32 ## 33 ## Input: @ints = (2, 5, 9, 11, 3), $k = 0 34 ## Output: 2 35 # 36 ############################################################ 37 ## 38 ## discussion 39 ## 40 ############################################################ 41 # 42 # For each element of the list: 43 # - calculate the number of 1-bit sets 44 # - compare to $k 45 # - return result of all ints[$i] where $i has $k 1-bits set 46 47 use strict; 48 use warnings; 49 50 sum_of_values([2, 5, 9, 11, 3], 1); 51 sum_of_values([2, 5, 9, 11, 3], 2); 52 sum_of_values([2, 5, 9, 11, 3], 0); 53 54 sub dec2bin { 55 my $num = shift; 56 return unpack("B32", pack("N", $num)); 57 } 58 59 sub sum_of_values { 60 my ($ints, $k) = @_; 61 my @tmp = @$ints; 62 print "Input: (", join(", ", @tmp), "), $k\n"; 63 my $result = 0; 64 foreach my $index (0..$#tmp) { 65 my $bin = dec2bin($index); 66 my $bits_set = 0; 67 foreach my $bit (split//, $bin) { 68 if($bit eq "1") { 69 $bits_set++; 70 } 71 } 72 if($bits_set == $k) { 73 $result += $tmp[$index]; 74 } 75 } 76 print "Output: $result\n"; 77 } 78