Peter
Peter Campbell Smith

Lot of ands and
a strange grid

Weekly challenge 163 — 2 May 2022

Week 163: 2 May 2022

Task 1

Task — Sum bitwise operator

You are given list positive numbers, @n. Write a script to calculate the sum of bitwise & operator for all unique pairs.

Examples


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.

Analysis

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.

Try it 

Try running the script with any input:



example: 2, 3, 4, 5, 6

Script


#!/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];

}

Output


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