By Shahed Nooshmand

Perl Weekly Challenge: week 59

Task #1

You are given a linked list and a value k. Write a script to partition the linked list such that all nodes less than k come before nodes greater than or equal to k. Make sure you preserve the original relative order of the nodes in each of the two partitions.

raku -e 'put join " → ", |.grep(* < 3), |.grep(* ≥ 3) given « 1 4 3 2 5 2 »'

Because grep preserves the relative order of the nodes, this script works.

Task #2

Let me just quote the whole thing, first:

Helper Function

For this task, you will most likely need a function f(a,b) which returns the count of different bits of binary representation of a and b.

For example, f(1,3) = 1, since:

Binary representation of 1 = 01

Binary representation of 3 = 11

There is only 1 different bit. Therefore the subroutine should return 1. Note that if one number is longer than the other in binary, the most significant bits of the smaller number are padded (i.e., they are assumed to be zeroes).

Script Output

You script should accept n positive numbers. Your script should sum the result of f(a,b) for every pair of numbers given:

For example, given 2, 3, 4, the output would be 6, since f(2,3) + f(2,4) + f(3,4) = 1 + 2 + 3 = 6

Again, there is a one-liner for this:

raku -e '(2..4).combinations(2).map({ (.comb Z≠ sprintf("\%0{.chars}b", @_.min).comb).grep(1) given @_.max.base(2) }).sum.say'

The helper function is the block that’s run via map. Since the number of necessary bits to represent a number is potentially more for the greater number, for each pair of numbers we first convert the bigger one to binary and pad the other one’s binary with enough zeros to make them equal in length. Then we zip each of one’s bits to the corresponding bit in the other number with ; for each pair of equal bits we get a False, and for each pair of different bits we get a True. By grepping 1, we only get the Trues, and when used in a numeric context such as sum, the list acts as its own cardinal, i.e. the number of Trues, i.e. the number of different bits. Hence, the script returns 6.