Perl Weekly Challenge 231: Min Max

These are some answers to the Week 231, Task 1, of the Perl Weekly Challenge organized by Mohammad S. Anwar.

Spoiler Alert: This weekly challenge deadline is due in a few days from now (on August 27, 2023 at 23:59). This blog post offers some solutions to this challenge. Please don’t read on if you intend to complete the challenge on your own.

Task 1: Min Max

You are given an array of distinct integers.

Write a script to find all elements that is neither minimum nor maximum. Return -1 if you can’t.

Example 1

Input: @ints = (3, 2, 1, 4)
Output: (3, 2)

The minimum is 1 and maximum is 4 in the given array. So (3, 2) is neither min nor max.

Example 2

Input: @ints = (3, 1)
Output: -1

Example 3

Input: @ints = (2, 1, 3)
Output: (2)

The minimum is 1 and maximum is 3 in the given array. So 2 is neither min nor max.

Min Max in Raku

We're simply looking for input integers that are different from the minimal and maximal values. We return these integers if there is at least one, or return -1 otherwise.

sub min-max (@in) {
    my @vals = grep {$_ != @in.min && $_ != @in.max}, @in;
    return @vals ?? @vals !! [-1];
}

for <3 2 1 4>, <3 1>, <2 1 3> -> @test {
    printf "%-10s => ", "@test[]";
    say min-max @test;
}

This program displays the following output:

$ raku ./min-max.raku
3 2 1 4    => [3 2]
3 1        => [-1]
2 1 3      => [2]

Min Max in Perl

This program does the same thing as the above Raku program, except that we need to implement our own find_min_max subroutine.

use strict;
use warnings;
use feature 'say';

sub find_min_max {
    my $min = my $max = $_[0];
    for my $val (@_) {
        $min = $val if $val < $min;
        $max = $val if $val > $max;
    }
    return ($min, $max);
}

sub min_max {
    my ($min, $max) = find_min_max(@_);
    my @vals = grep {$_ != $min && $_ != $max} @_;
    return @vals ? @vals : (-1);
}

for my $test ([<3 2 1 4>], [<3 1>], [<2 1 3>]) {
    printf "%-10s => ", "@$test";
    say join " ", min_max @$test;
}

This program displays the following output:

$ perl ./min-max.pl
3 2 1 4    => 3 2
3 1        => -1
2 1 3      => 2

Wrapping up

The next week Perl Weekly Challenge will start soon. If you want to participate in this challenge, please check https://perlweeklychallenge.org/ and make sure you answer the challenge before 23:59 BST (British summer time) on September 3, 2023. And, please, also spread the word about the Perl Weekly Challenge if you can.

Leave a comment

About laurent_r

user-pic I am the author of the "Think Perl 6" book (O'Reilly, 2017) and I blog about the Perl 5 and Raku programming languages.