Perl Weekly Challenge 250: Smallest Index

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

Task 1: Smallest Index

You are given an array of integers, @ints.

Write a script to find the smallest index i such that i mod 10 == $ints[i] otherwise return -1.

Example 1

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

i=0: 0 mod 10 = 0 == $ints[0].
i=1: 1 mod 10 = 1 == $ints[1].
i=2: 2 mod 10 = 2 == $ints[2].
All indices have i mod 10 == $ints[i], so we return the smallest index 0.

Example 2

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

i=0: 0 mod 10 = 0 != $ints[0].
i=1: 1 mod 10 = 1 != $ints[1].
i=2: 2 mod 10 = 2 == $ints[2].
i=3: 3 mod 10 = 3 != $ints[3].
2 is the only index which has i mod 10 == $ints[i].

Example 3

Input: @ints = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
Output: -1
Explanation: No index satisfies i mod 10 == $ints[i].

Smallest Index in Raku

We'll simply use a for loop to iterate over the input array indexes. We exit the loop and return the current index if suitable. We return -1 if we get to the end of the loop.

sub smallest_index (@in) {
    for 0..@in.end -> $i {
        return $i if $i % 10 == @in[$i];
    }
    return -1
}

for (0, 1, 2), (4, 3, 2, 1), 
    qw/1 2 3 4 5 6 7 8 9 0/ -> @test {
    printf "%-20s => ", "@test[]";
    say smallest_index @test;
}

This program displays the following output:

$ raku ./smallest-index.raku
0 1 2                => 0
4 3 2 1              => 2
1 2 3 4 5 6 7 8 9 0  => -1

Smallest Index in Perl

This is a port to Perl of the above Raku program. Please refer to the previous section if you need any explanations.

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

sub smallest_index {
    my @in = @_;
    for my $i (0..$#in) {
        return $i if $i % 10 == $in[$i];
    }
    return -1
}

for my $test ([0, 1, 2], [4, 3, 2, 1], 
    [qw/1 2 3 4 5 6 7 8 9 0/]) {
    printf "%-20s => ", "@$test";
    say smallest_index @$test;
}

This program displays the following output:

$ perl ./smallest-index.pl
0 1 2                => 0
4 3 2 1              => 2
1 2 3 4 5 6 7 8 9 0  => -1

Wrapping up

Happy new year to everyone. 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 January 14, 2024. 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.