Perl Weekly Challenge: Week 85

Challenge 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.

Example 1:
Input: @R = (1.2, 0.4, 0.1, 2.5)
Output: 1 as 1 < 1.2 + 0.4 + 0.1 < 2
Example 2:
Input: @R = (0.2, 1.5, 0.9, 1.1)
Output: 0
Example 3:
Input: @R = (0.5, 1.1, 0.3, 0.7)
Output: 1 as 1 < 0.5 + 1.1 + 0.3 < 2

In Raku, we can do this as a one-liner.

say @*ARGS.combinations(3).grep({ ([+] @_) ~~ 1.0 .. 2.0 }).elems ?? 1 !! 0;

(Full code on Github.)

Perl is more verbose, lacking as it does some of Rakus' features. combinations() is my tried and trusted Perl workalike I used most recently in PWC 83.

my $results = 0;

for my $combo (combinations(\@ARGV, 3)) {
    my $total = 0;
    for my $elem (@{$combo}) {
        $total += $elem;
    }
    if ($total > 1.0 && $total < 2.0) {
        $results++;
    }
}

say $results ? 1 : 0;

(Full code on Github.)

Challenge 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.

Example 1:
Input: 8
Output: 1 as 8 = 2 ** 3
Example 2:
Input: 15
Output: 0
Example 3:
Input: 125
Output: 1 as 125 = 5 ** 3

As I sat down to solve this, I had a nagging suspicion that I had done something like it before. Sure enough, this is extremely similar to the "Power Integers" challenge in PWC 66. I reused the isPower() function I had developed for that challenge. The only change I needed to make to it was to disallow (1,1) as our spec clearly states that b > 1. Once I had that function working properly, the solution to this challenge became a one liner.

say scalar isPower(shift) ? 1 : 0;

Note that isPower() returns all powers of two integers but for this problem we only need to know if there was atleast 1 and we don't even have to print out what it was.

(Full code on Github.)

This is the Raku version wrapped up in sub MAIN() though that isn't strictly necessary.

sub MAIN(Int $N) {
    say isPower($N).elems ?? 1 !! 0;
}

(Full code on Github.)