Peter’s blog ✴ Week 302 ✴ 30 December 2024

THE WEEKLY CHALLENGE
All about ones

The Perl Camel

Task 2

Step by step

You are given an array of integers, @ints. Write a script to find the minimum positive start value such that the step-by-step sum is never less than one.

Examples


Example 1
Input: @ints = (-3, 2, -3, 4, 2)
Output: 5
For start value 5.
5 + (-3) = 2
2 + (+2) = 4
4 + (-3) = 1
1 + (+4) = 5
5 + (+2) = 7

Example 2
Input: @ints = (1, 2)
Output: 1

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

Analysis

Unless I have misunderstood, this seems quite easy.

Do a trial run with a starting value of 0, and call the final value $least. The answer is then 1 - $least.

The only slight twist is that we are asked for the minimum positive value, so if 1 - $least < 1 then we return 1.

Perl Weekly’s review

from PW issue 702

Using the CPAN power, the job becomes cake walk for anyone. See it yourself to believe.

Try it 

Try running the script with any input:



example: -3, 5, 4, 2, 7, -10

Script


#!/usr/bin/perl

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

use v5.26;    # The Weekly Challenge - 2024-12-30
use utf8;     # Week 302 - task 2 - Step by step
use warnings; # Peter Campbell Smith
binmode STDOUT, ':utf8';

step_by_step(-3, 2, -3, 4, 2);
step_by_step(1, -2, -3);
step_by_step(6, 7, 8, 9, 10);

# larger example
my @ints;
push @ints, int(rand(50)) - 25 for 0 .. 99;
step_by_step(@ints);

sub step_by_step {
    
    my (@ints, $i, $sum, $least);
    @ints = @_;
    
    # find the smallest sum ($least) if we start with 0
    $least = 1e6;
    for $i (@ints) {
        $sum += $i;
        $least = $sum if $sum < $least;
    }
    
    # the answer is (1 - $least)
    say qq[\nInput:  \@ints = (] . join(', ', @ints) . qq[)];
    say qq[Output: ] . ((1 - $least) > 0 ? (1 - $least) : 1);
}

9 lines of code

Output from script


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

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

Input:  @ints = (6, 7, 8, 9, 10)
Output: 1

Input:  @ints = (-7, 8, 10, -12, -22, -15, 18, 1, -8, 6,
5, 20, 19, -12, -18, 14, -22, -14, 3, -19, -23, 20, 6,
-18, 10, -24, 17, -22, -15, 16, 2, 2, -1, 17, -24, 14,
-21, 15, 13, 13, 24, 5, -16, 15, -11, 13, 10, 20, 8, -15,
11, -21, 8, 3, -2, 17, -6, 0, 7, 14, 16, -9, -2, -10, -2,
-18, 19, -18, 0, -8, 23, 7, -8, 15, -18, 7, 22, -2, 21,
-18, 3, 20, -14, 19, 2, 17, -6, -9, 1, 2, -24, 1, 24, -1,
6, -9, -11, 23, 16, -2)
Output: 95

 

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