Peter’s blog ✴ Week 182 ✴ 12 September 2022

THE WEEKLY CHALLENGE
Find the biggest and the deepest

The Perl Camel

Task 1

Max index

Write a script to find the index of the first biggest number in the list.

Examples

Example
Input: @n = (5, 2, 9, 1, 7, 6)
Output: 2 (as 3rd element in the list is the biggest number)
Input: @n = (4, 2, 3, 1, 5, 0)
Output: 4 (as 5th element in the list is the biggest number)

Analysis

We are to find the index of the first occurrence of the largest number in @list.

We are going to have to look at every number in the list. It therefore seems best to make a single pass through the list, keeping track of the largest value found so far, and its index. And that's the solution I have submitted.

I thought about solutions involving sorting the list, but that's overkill for such a simple requirement.

Perl Weekly’s review

from PW issue 582

Story telling narrative of weekly task is irresistable. Thanks for everything.

This review may cover either or both challenges for this week.

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



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

Script


#!/usr/bin/perl

# Peter Campbell Smith - 2022-09-15
# PWC 182 task 1

use v5.28;
use utf8;
use warnings;

my ($input, @tests, $test, @array, $largest, $position, $j);

@tests = ([5, 2, 9, 1, 7, 6], 
    [4, 2, 3, 1, 5, 0], 
    [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
    [-2, -7, -10, -5, -14]);

TEST: for $test (@tests) {
    
    # initialise and show input
    @array = @$test;
    $input = '';
    $input .= qq[$_, ] for @array;
    say qq[\nInput:  (] . substr($input, 0, -2) . ')';
    
    # look for the largest
    $largest = -1e6;
    for $j (0 .. $#array) {
        next if $array[$j] <= $largest;
        $largest = $array[$j];
        $position = $j;
    }
    say qq[Output: $position (largest value = $array[$position])];
}
    

19 lines of code

Output from script


Input:  (5, 2, 9, 1, 7, 6)
Output: 2 (largest value = 9)

Input:  (4, 2, 3, 1, 5, 0)
Output: 4 (largest value = 5)

Input:  (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20)
Output: 19 (largest value = 20)

Input:  (-2, -7, -10, -5, -14)
Output: 0 (largest value = -2)

 

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