The Weekly Challenge - 291

TASK #1: Middle Index
You are given an array of integers, @ints.

Write a script to find the leftmost middle index (MI) i.e. the smallest amongst all the possible ones.

A middle index is an index where ints[0] + ints[1] + … + ints[MI-1] == ints[MI+1] + ints[MI+2] + … + ints[ints.length-1].

If MI == 0, the left side sum is considered to be 0. Similarly,
if MI == ints.length - 1, the right side sum is considered to be 0.
Return the leftmost MI that satisfies the condition, or -1 if there is no such index.

#!/usr/bin/perl
use strict;
use warnings;

sub middle_index {
    my $total = 0;
    $total += $_ for @_;

    my $left_sum = 0;
    for my $index (0 .. @_ - 1) {
        return ($index) if ($left_sum == $total - $left_sum - $_[$index]);
        $left_sum += $_[$index];
    }

    return (-1);
}

# Tests

my @ints;

# Example 1
@ints = (2, 3, -1, 8, 4);
print(middle_index(@ints), "\n"); # Output: 3

# Example 2
@ints = (1, -1, 4);
print(middle_index(@ints), "\n"); # Output: 2

# Example 3
@ints = (2, 5);
print(middle_index(@ints), "\n"); # Output: -1"