Weekly Challenge 269
Each week Mohammad S. Anwar sends out The Weekly Challenge, a chance for all of us to come up with solutions to two weekly tasks. My
solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.
Task 1: Bitwise OR
Task
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.
My solution
So we know that a number that has at least one trialing zero is an even number (i.e. the 1 bit is not set). We also know that OR-ing a value won't remove any set bits. Therefore solving this task is as straight forward as making sure we have at least two even numbers in ints
.
def bitwise_or(ints: list) -> bool:
even_count = sum(1 for i in ints if i % 2 == 0)
return even_count >= 2
Examples
$ ./ch-1.py 1 2 3 4 5
True
$ ./ch-1.py 2 3 8 16
True
$ ./ch-1.py 1 2 5 7 9
False
Task 2: Distribute Elements
Task
You are given an array of distinct integers, @ints
.
Write a script to distribute the elements as described below:
- Put the 1st element of the given array to a new array
@arr1
. - Put the 2nd element of the given array to a new array
@arr2
.
Once you have one element in each arrays, @arr1
and @arr2
, then follow the rule below:
If the last element of the array @arr1
is greater than the last element of the array @arr2
then add the first element of the given array to @arr1
otherwise to the array @arr2
.
When done distribution, return the concatenated arrays. @arr1
and @arr2
.
My solution
For this task, I simply follow the instructions as set out in the task. With each step I remove the item from ints
, and continue until it is exhausted.
def distribute_elements(ints: list) -> list:
arr1 = [ints.pop(0)]
arr2 = [ints.pop(0)]
while ints:
if arr1[-1] > arr2[-1]:
arr1.append(ints.pop(0))
else:
arr2.append(ints.pop(0))
return arr1 + arr2
Examples
$ ./ch-2.py 2 1 3 4 5
(2, 3, 4, 5, 1)
$ ./ch-2.py 3 2 4
(3, 4, 2)
$ ./ch-2.py 5 4 3 8
(5, 3, 4, 8)
Top comments (0)