The weekly challenge 269 - Task 1: Bitwise OR

 1 #!/usr/bin/perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-269/#TASK1
 3 #
 4 # Task 1: Bitwise OR
 5 # ==================
 6 #
 7 # You are given an array of positive integers, @ints.
 8 #
 9 # Write a script to find out if it is possible to select two or more elements
10 # of the given array such that the bitwise OR of the selected elements has
11 # atlest one trailing zero in its binary representation.
12 #
13 ## Example 1
14 ##
15 ## Input: @ints = (1, 2, 3, 4, 5)
16 ## Output: true
17 ##
18 ## Say, we pick 2 and 4, thier bitwise OR is 6. The binary representation of 6 is 110.
19 ## Return true since we have one trailing zero.
20 #
21 ## Example 2
22 ##
23 ## Input: @ints = (2, 3, 8, 16)
24 ## Output: true
25 ##
26 ## Say, we pick 2 and 8, thier bitwise OR is 10. The binary representation of 10 is 1010.
27 ## Return true since we have one trailing zero.
28 #
29 ## Example 3
30 ##
31 ## Input: @ints = (1, 2, 5, 7, 9)
32 ## Output: false
33 #
34 ############################################################
35 ##
36 ## discussion
37 ##
38 ############################################################
39 #
40 # The bitwise OR of two or more numbers has a trailing 0 if all numbers
41 # have a trailing 0. This is the case if these numbers are even. So the
42 # problem boils down to the question whether or not the array has at least
43 # two even numbers.
44 
45 use strict;
46 use warnings;
47 
48 bitwise_or(1, 2, 3, 4, 5);
49 bitwise_or(2, 3, 8, 16);
50 bitwise_or(1, 2, 5, 7, 9);
51 
52 sub bitwise_or {
53    my @ints = @_;
54    my $found_even = 0;
55    print "Input: (", join(", ", @ints), ")\n";
56    foreach my $int (@ints) {
57       $found_even++ unless $int % 2;
58    }
59    if($found_even >= 2) {
60       print "Output: true\n";
61    } else {
62       print "Output: false\n";
63    }
64 }