Find the biggest

and the deepest

Weekly challenge 182 — 12 September 2022

Week 182 - 12 Sep 2022

Task 1

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

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)

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.

#!/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])]; }

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)

The content of this website which has been created by

Peter Campbell Smith is hereby placed in the public domain

Peter Campbell Smith is hereby placed in the public domain