Peter’s blog ✴ Week 163 ✴ 2 May 2022
THE WEEKLY CHALLENGE
Lot of ands and a strange grid
You are given list positive numbers, @n. Write a script to calculate the sum of bitwise & operator for all unique pairs.
Example 1: Input: @n = (1, 2, 3) Output: 3 Since (1 & 2) + (2 & 3) + (1 & 3) => 0 + 2 + 1 => 3. Example 2 Input: @n = (2, 3, 4) Output: 2 Since (2 & 3) + (2 & 4) + (3 & 4) => 2 + 0 + 0 => 2.
The obvious (to me) way of doing this is two nested loops to generate the number pairs, 'and' them together and add the result to a successive sum.
The slightly trickier part is to output the result in the format Mohammad asks, but if we just add
to the eventual output within the inner loop we can get a single say for the output.
The short and sweet narration is really impressive. Thanks for your contributions.
This review may cover either or both challenges for this week.
I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.
#!/usr/bin/perl # Peter Campbell Smith - 2022-05-03 # PWC 163 task 1 use v5.28; use strict; use warnings; use utf8; my (@tests, $test, @n, $last, $i, $j, $term, $sum, $since1, $since2); @tests = ([1, 2, 3], [2, 3, 4], [12, 32, 43, 72, 34, 99, 6, 50]); # loop over tests for $test (@tests) { @n = @$test; say qq[\nInput: \@n = (] . join(', ', @n) . ')'; # loop over unique pairs $sum = 0; $since1 = $since2 = ''; $last = scalar @n; for $i (0 .. $last - 2) { for $j ($i + 1 .. $last - 1) { # create sum and 2 output strings $term = $n[$i] & $n[$j]; $sum += $term; $since1 .= qq[($n[$i] & $n[$j]) + ]; $since2 .= qq[$term + ]; } } # show result say qq[Output: $sum\nSince ] . substr($since1, 0, -3) . ' => ' . substr($since2, 0, -3) . qq[ => $sum]; }
20 lines of code
Input: @n = (1, 2, 3) Output: 3 Since (1 & 2) + (1 & 3) + (2 & 3) => 0 + 1 + 2 => 3 Input: @n = (2, 3, 4) Output: 2 Since (2 & 3) + (2 & 4) + (3 & 4) => 2 + 0 + 0 => 2 Input: @n = (12, 32, 43, 72, 34, 99, 6, 50) Output: 433 Since (12 & 32) + (12 & 43) + (12 & 72) + (12 & 34) + (12 & 99) + (12 & 6) + (12 & 50) + (32 & 43) + (32 & 72) + (32 & 34) + (32 & 99) + (32 & 6) + (32 & 50) + (43 & 72) + (43 & 34) + (43 & 99) + (43 & 6) + (43 & 50) + (72 & 34) + (72 & 99) + (72 & 6) + (72 & 50) + (34 & 99) + (34 & 6) + (34 & 50) + (99 & 6) + (99 & 50) + (6 & 50) => 0 + 8 + 8 + 0 + 0 + 4 + 0 + 32 + 0 + 32 + 32 + 0 + 32 + 8 + 34 + 35 + 2 + 34 + 0 + 64 + 0 + 0 + 34 + 2 + 34 + 2 + 34 + 2 => 433
Any content of this website which has been created by Peter Campbell Smith is in the public domain