The weekly challenge 292 - Task 1: Twice Largest

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-292/#TASK1
 3 #
 4 # Task 1: Twice Largest
 5 # =====================
 6 #
 7 # You are given an array of integers, @ints, where the largest integer is unique.
 8 #
 9 # Write a script to find whether the largest element in the array is at least
10 # twice as big as every element in the given array. If it is return the index
11 # of the largest element or return -1 otherwise.
12 #
13 ## Example 1
14 ##
15 ## Input: @ints = (2, 4, 1, 0)
16 ## Output: 1
17 ##
18 ## The largest integer is 4.
19 ## For every other elements in the given array is at least twice as big.
20 ## The index value of 4 is 1.
21 #
22 ## Example 2
23 ##
24 ## Input: @ints = (1, 2, 3, 4)
25 ## Output: -1
26 ##
27 ## The largest integer is 4.
28 ## 4 is less than twice the value of 3, so we return -1.
29 #
30 ############################################################
31 ##
32 ## discussion
33 ##
34 ############################################################
35 #
36 # We find the maximum value. Then we walk the array. If a value
37 # is indentical to the maximum, we found the index. Otherwise,
38 # if double of the value is bigger than the max, we return -1.
39 # In the end, we return the index.
40 
41 use strict;
42 use warnings;
43 use List::Util qw(max);
44 
45 twice_largest(2, 4, 1, 0);
46 twice_largest(1, 2, 3, 4);
47 
48 sub twice_largest {
49    my @ints = @_;
50    my $m = max(@ints);
51    print "Input: (" . join(", ", @ints) . ")\n";
52    my $index = -1;
53    foreach my $i (0..$#ints) {
54       if($ints[$i] == $m) {
55          $index = $i;
56          next;
57       } else {
58          if( 2 * $ints[$i] > $m) {
59             return print "Output: -1\n";
60          }
61       }
62    }
63    return print "Output: $index\n";
64 }