PWC182 - Max Index


Here we are with TASK #1 from The Weekly Challenge #182. Enjoy!

The challenge

You are given a list of integers.

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


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)

The questions

Many people might remember that around here it was all countryside and Perl was the main benevolent owner, together with sister Raku.

Then came other languages, the host deemed it good and the whole thing became more inclusive: from The Perl Weekly Challenge it became The Weekly Challenge.

Which, at this point, officially includes Pascal, right? So what’s the index supposed to start from? It’s a bit vague! 🙄

Anyway, I’ll code in Perl and Raku, so the indexes will definitely start at 0.

The solution

The idea is to prefer simplicity over efficiency. We generate a list of all indexes, order this list based on the magnitude of the corresponding item (ascendingly), then take the last element.

#!/usr/bin/env raku
use v6;
sub MAIN (*@args) {
   @args = 5, 2, 9, 1, 7, 6 unless @args;
   put max-index(@args);

sub max-index (@args) {
   (0 ..^ @args).sort(
         @args[$^a] <=> @args[$^b] # sort by value, but if equal...
         || $^b <=> $a             # just be anti-stable
   )[*-1] # then just take the last element

The attentive reader will have noticed by now that the condition is slightly pickier than previously described. In case two values are the same, the bigger index comes before the smaller. This makes sure that the smaller one gets pushed to the end of the array, where we will eventually collect it. To make a long story short, this works also in case the maximum value is repeated in multiple positions in the input array.

The Perl translation is straightforward:

#!/usr/bin/env perl
use v5.24;
use warnings;
use experimental 'signatures';
no warnings 'experimental::signatures';

my @args = @ARGV ? @ARGV : (5, 2, 9, 1, 7, 6, 9);
say max_index(@args);

sub max_index (@args) {
   return (
      sort {
         $args[$a] <=> $args[$b] # sort ascending, BUT...
         || $b <=> $a            # be anti-stable if equal
      } (0 .. $#args)

Stay safe!

Comments? Octodon, Twitter, GitHub, Reddit, or drop me a line!