Peter
Peter Campbell Smith

Bits distribution

Weekly challenge 269 — 13 May 2024

Week 269: 13 May 2024

Task 1

Task — Bitwise or

You are given an array of positive integers, @ints. Write a script to find out if it is possible to select two or more elements of the given array such that the bitwise OR of the selected elements has at least one trailing zero in its binary representation.

Examples


Example 1
Input: @ints = (1, 2, 3, 4, 5)
Output: true
Say, we pick 2 and 4, their bitwise OR is 6. The binary 
representation of 6 is 110.
Return true since we have one trailing zero.

Example 2
Input: @ints = (2, 3, 8, 16)
Output: true
Say, we pick 2 and 8, their bitwise OR is 10. The binary 
representation of 10 is 1010.
Return true since we have one trailing zero.

Example 3
Input: @ints = (1, 2, 5, 7, 9)
Output: false

Analysis

The bitwise or of two non-negative integers will only end in zero if the bitwise representation of each of them ends in zero (that is, they are multiples of 2).

My solution uses grep to filter @ints for such numbers, and returns true if it finds at least two of them, or false if not.

Try it 

Try running the script with any input:



example: 1, 3, 5, 7, 8, 10

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-05-13
use utf8;     # Week 269 - task 1 - Bitwise or
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

bitwise_or(1, 2, 3, 4, 5);
bitwise_or(2, 3, 9, 16);
bitwise_or(1, 2, 5, 7, 9);
bitwise_or(1, 3, 3, 7, 5, 9, 19, 20, 99, 100);
bitwise_or(1, 3, 3, 7, 5, 9, 19, 20, 99, 101);

sub bitwise_or {
    
    # filter out even numbers
    my @result = grep { ! ($_ & 1) } @_;
    
    # there are at least 2 of them if $result[1] is defined
    say sprintf(qq[\nInput:  \@ints = (%s)], join(', ', @_));
    say qq[Output: ] . ($result[1] ? qq[true ($result[0], $result[1])] : 'false');
}

Output


Input:  @ints = (1, 2, 3, 4, 5)
Output: true (2, 4)

Input:  @ints = (2, 3, 9, 16)
Output: true (2, 16)

Input:  @ints = (1, 2, 5, 7, 9)
Output: false

Input:  @ints = (1, 3, 3, 7, 5, 9, 19, 20, 99, 100)
Output: true (20, 100)

Input:  @ints = (1, 3, 3, 7, 5, 9, 19, 20, 99, 101)
Output: false

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain