The weekly challenge 291 - Task 1: Middle Index

 1 #!/usr/bin/env perl
 2 # https://theweeklychallenge.org/blog/perl-weekly-challenge-291/#TASK1
 3 #
 4 # Task 1: Middle Index
 5 # ====================
 6 #
 7 # You are given an array of integers, @ints.
 8 #
 9 # Write a script to find the leftmost middle index (MI) i.e. the smallest
10 # amongst all the possible ones.
11 #
12 ## A middle index is an index where ints[0] + ints[1] + … + ints[MI-1] ==
13 ##  ints[MI+1] + ints[MI+2] + … + ints[ints.length-1].
14 #
15 # If MI == 0, the left side sum is considered to be 0. Similarly,
16 # if MI == ints.length - 1, the right side sum is considered to be 0.
17 #
18 # Return the leftmost MI that satisfies the condition, or -1 if there is no
19 # such index.
20 #
21 ## Example 1
22 ##
23 ## Input: @ints = (2, 3, -1, 8, 4)
24 ## Output: 3
25 ##
26 ## The sum of the numbers before index 3 is: 2 + 3 + -1 = 4
27 ## The sum of the numbers after index 3 is: 4 = 4
28 #
29 ## Example 2
30 ##
31 ## Input: @ints = (1, -1, 4)
32 ## Output: 2
33 ##
34 ## The sum of the numbers before index 2 is: 1 + -1 = 0
35 ## The sum of the numbers after index 2 is: 0
36 #
37 ## Example 3
38 ##
39 ## Input: @ints = (2, 5)
40 ## Output: -1
41 ##
42 ## There is no valid MI.
43 #
44 ############################################################
45 ##
46 ## discussion
47 ##
48 ############################################################
49 #
50 # Starting at the beginning, we check the left and right side sum
51 # at each step. If they match, we return the index. If in the
52 # end, we didn't find the index, we return -1.
53 
54 use strict;
55 use warnings;
56 use List::Util qw(sum);
57 
58 middle_index(2, 3, -1, 8, 4);
59 middle_index(1, -1, 4);
60 middle_index(2, 5);
61 
62 sub middle_index {
63    my @ints = @_;
64    print "Input: (" . join(", ", @ints) . ")\n";
65    foreach my $i (0..$#ints) {
66       my $l = sum(@ints[0..$i-1]) // 0;
67       my $r = sum(@ints[$i+1..$#ints]) // 0;
68       if($r == $l) {
69          return print "Output: $i\n";
70       }
71    }
72    print "Output: -1\n";
73 }