Peter
Peter Campbell Smith

Find the biggest
and clear the balls

Weekly challenge 292 — 21 October 2024

Week 292: 21 Oct 2024

Task 1

Task — Twice largest

You are given an array of integers, @ints, where the largest integer is unique. Write a script to find whether the largest element in the array is at least twice as big as every other element in the given array. If it is return the index of the largest element or return -1 otherwise.

Examples


Example 1
Input: @ints = (2, 4, 1, 0)
Output: 1
The largest integer is 4.
For every other elements in the given array is at least 
twice as big.
The index value of 4 is 1.

Example 2
Input: @ints = (1, 2, 3, 4)
Output: -1
The largest integer is 4.
4 is less than twice the value of 3, so we return -1.

Analysis

Clearly there are lots of ways to do this. This is what I chose:

  • Make a @sorted copy of @ints
  • Check whether the last (ie largest) element of @sorted is at least twice the second last (ie second largest)
  • If it isn't, return -1
  • If it is, loop through @ints to find the original index of the last element of @sorted

Try it 

Try running the script with any input:



example: 7, 4, 3, 2, 1

Script


#!/usr/bin/perl

# Blog: http://ccgi.campbellsmiths.force9.co.uk/challenge

use v5.26;    # The Weekly Challenge - 2024-10-21
use utf8;     # Week 292 - task 1 - Twice largest
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

twice_largest(1, 2, 3, 4);
twice_largest(2, 4, 1, 0);
twice_largest(1, 2, 8, 3, 4);
twice_largest(3, 8, 7, 5, 1, 0, 9, 3, 17, 7, 5, 6, 2, 4, 9, 6, 2);
twice_largest(3, 8, 7, 5, 1, 0, 9, 3, 18, 7, 5, 6, 2, 4, 9, 6, 2);
twice_largest(3, 8, 7, 5, 1, 0, 9, 3, 19, 7, 5, 6, 2, 4, 9, 6, 2);

sub twice_largest {
    
    my (@ints, @sorted, $result, $i);
    
    # initialise
    @ints = @_;
    @sorted = sort { $a<=>$b } @ints;
    $result = -1;

    # check if largest >= 2nd largest
    if ($sorted[$#ints] >= 2 * $sorted[$#ints - 1]) {
        
        # it is, so find its index
        $result = 0;
        $result ++ while $ints[$result] != $sorted[$#ints];
    }
    
    # say results
    say qq[\nInput:  \@ints = (] . join(', ', @ints) . ')';
    say qq[Output: $result];
}

Output


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

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

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

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

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

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

 

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