Peter’s blog ✴ Week 250 ✴ 1 January 2024

THE WEEKLY CHALLENGE
Smallest index, largest element

The Perl Camel

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.

Examples


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

Analysis

There seems little alternative to iterating along the array and finding the first (if any) element $i which meets the condition $i % 10 == $ints[$i]. Since we are looking for the lowest $i that satisfies that condition we can stop iterating as soon as we find an element that meets it.

Perl Weekly’s review

from PW issue 650

DIY solutions like always. Well structured and presented too. Highly recommended.

Try it 

Try running the script with any input:



example: 1, 2, 3, 4, 5, 6, 7, 7

Script


#!/usr/bin/perl

use v5.16;    # The Weekly Challenge - 2024-01-01
use utf8;     # Week 250 task 1 - Smallest index
use strict;   # Peter Campbell Smith
use warnings; # Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

binmode STDOUT, ':utf8';

smallest_index(4, 3, 2, 1);
smallest_index(2, 4, 6, 7, 3, 9, 1, 0, 2, 4, 7, 8, 2, 3);
smallest_index(1, 2, 3, 4, 5, 6, 7, 8, 9, 0);

sub smallest_index {
    
    my (@ints, $i, $i_mod10);
    
    #initialise
    @ints = @_;
    say qq[\nInput:  \@ints = (] . join(', ', @ints) . ')';
    
    # loop over supplied values
    for $i (0 .. @ints - 1) {
        $i_mod10 = $i % 10;
        
        # apply stated rule
        if ($i_mod10 == $ints[$i]) {
            say qq[Output: $i ∵ \$i = $i, \$i mod 10 = $i_mod10, \$ints[$i] = $ints[$i]];
            return;
        }
    }
    say qq[Output:  -1];
}
        

10 lines of code

Output from script


Input:  @ints = (4, 3, 2, 1)
Output: 2 ∵ $i = 2, $i mod 10 = 2, $ints[2] = 2

Input:  @ints = (2, 4, 6, 7, 3, 9, 1, 0, 2, 4, 7, 8, 2, 3)
Output: 12 ∵ $i = 12, $i mod 10 = 2, $ints[12] = 2

Input:  @ints = (1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
Output:  -1

 

Any content of this website which has been created by Peter Campbell Smith is in the public domain