Raku Challenge, Week 85

Welcome back to another week of the Weekly Challenge, and today I’ll briefly describe my solutions to the Week 85. Task 1. Triplet Sum. Task 2. Power of Two Integers.

Welcome back to another week of the Weekly Challenge, and today I’ll briefly describe my solutions to the Week 85.

The solutions of this week actually make me think that Raku changes my definition of what is a straightforward solution. All those tiny Raku bits such as any or X or ^$N are awesome even in a not fully-optimised program.

Task 1. Triplet Sum

You are given an array of real numbers greater than zero. Write a script to find if there exists a triplet (a, b, c) such that 1 < a + b + c < 2. Print 1 if you succeed otherwise 0.

So, the task is to find such three numbers from the given list so that they add up to a number between 1 and 2. Sounds as a good task for using the combinations routine.

my @r = 1.2, 0.4, 0.1, 2.5;
say +so 1 < any(@r.combinations(3)>>.sum) < 2;

As you see, the solution is extremely short. It creates the possible 3-element combinations from the input data and computes the sums of each. Then, we make a test 1 < any(...) < 2 using the any-junction, which allows us to avoid any explicit loops in the program. Finally, the +so construct converts the result to first to a Boolean value (so), and then to either 1 or 0 as the task requires.

Task 2. Power of Two Integers

You are given a positive integer $N. Write a script to find if it can be expressed as a ^ b where a > 0 and b > 1. Print 1 if you succeed otherwise 0.

Well, some mathematics can be applied before going to the code, but let’s skip this useful step 🙂

my $N = @*ARGS[0] // 8;

for 1..^$N X ^$N -> ($a, $b) {
    say "$N = $a^$b" if $N == $a ** $b;
}

The program is quite wordy and self-explanatory, but I must mention that parentheses around loop variables are important here. Without them, you will get two pairs such as (7 2) (7 3) on each iteration instead of just two integers.

The program prints all the possible solutions, and prints nothing if it could not find it.

* * *

→ GitHub repository
→ Navigation to the Raku challenges post series

Leave a Reply

Your email address will not be published. Required fields are marked *

Retype the CAPTCHA code from the image
Change the CAPTCHA codeSpeak the CAPTCHA code