Robbie Hatley's Solutions To The Weekly Challenge #258
For those not familiar with "The Weekly Challenge", it is a weekly programming puzzle with two parts, cycling every Sunday. You can find it here:
This week (2024-02-25 through 2024-03-02) is weekly challenge #258. Its tasks are as follows:
Task 258-1: Count Even Digits Number Submitted by: Mohammad Sajid Anwar You are given a array of positive integers, @ints. Write a script to find out how many integers have even number of digits. Example 1: Input: @ints = (10, 1, 111, 24, 1000) Output: 3 There are 3 integers having even digits i.e. 10, 24 and 1000. Example 2: Input: @ints = (111, 1, 11111) Output: 0 Example 3: Input: @ints = (2, 8, 1024, 256) Output: 1
I'm "traveling light" this week, so my solutions for 258-1 and 258-2 are about 50 times shorter than the programs I normally write for The Weekly Challenge. My solution for 258-1 is especially short; it uses "grep" to filter @ARGV for numbers with an even number of digits, then uses "scalar" to count them:
#!/usr/bin/perl print scalar grep {0==length($_)%2} @ARGV, "\n";
Task 258-2: Sum of Values Submitted by: Mohammad Sajid Anwar You are given an array of integers, @int and an integer $k. Write a script to find the sum of values whose index binary representation has exactly $k number of 1-bit set. Example 1: Input: @ints = (2, 5, 9, 11, 3), $k = 1 Output: 17 Binary representation of index 0 = 0 Binary representation of index 1 = 1 Binary representation of index 2 = 10 Binary representation of index 3 = 11 Binary representation of index 4 = 100 So the indices 1, 2 and 4 have total one 1-bit sets. Therefore the sum, $ints[1] + $ints[2] + $ints[4] = 17 Example 2: Input: @ints = (2, 5, 9, 11, 3), $k = 2 Output: 11 Example 3: Input: @ints = (2, 5, 9, 11, 3), $k = 0 Output: 2
This one was a little more involved than task 1. First, I popped $k off the right end of @ARGV, then I used "grep" to grab just those values of index for which the sum of binary digits (which is also the number of "1" digits set) is equal to $k, then I used those indexes to "slice" @ARGV, then summed the slice:
#!/usr/bin/perl use List::Util 'sum0'; my $k = pop @ARGV; print sum0(@ARGV[grep {$k == sum0(split //, sprintf("%b", $_))} 0..$#ARGV]), "\n";
That's it for challenge 258; see you on challenge 259!
Comments
Post a Comment