Perl Weekly Challenge 106

Tags:

This week I quickly did the Perl Weekly Challenge as a live coding session on Twitch (now also on Youtube: https://www.youtube.com/watch?v=E4Bwh-FVTns ).

If you watch the video hopefully you'll see the approach I take to these challenges, I don't write defensively, I do write in a test first and test as you go basis. Below is the test file that i ended up with, it could be made better I nkow, but it got me to a working, tested solution nice and quickly.

# t/01-maxgap.t
use Test2::V0 -target => Maxgap;

my @example1 = (2, 9, 3, 5);
my $expected1 = 4;

is $CLASS->maxgap(@example1), $expected1, 'Example 1';

my @example2 = (1, 3, 8, 2, 0);
my $expected2 = 5;

is $CLASS->maxgap(@example2), $expected2, 'Example 2';


my @example3 = (5);
my $expected3 = 0;

is $CLASS->maxgap(@example3), $expected3, 'Example 3';

done_testing;

Using test2::V0 hides the horrible "stutter", by which I mean the module name and the method repeat: Maxgap::maxgap. So ideally I would change the names.

The code looks like this:

# lib/Maxgap.pm
package Maxgap;

sub maxgap {
    my ($self, @integers) = @_;

    @integers = sort @integers;

    my $maxgap = 0;
    for my $i (1 .. @integers-1){
        my $gap = $integers[$i] - $integers[$i-1];
        if ( $gap > $maxgap) {
            $maxgap = $gap;
        }
    }

    return $maxgap;
}

1;

It's not too complex, and I am sure with some refactoring it could be made more idiomatic. This version however works and was up and running in less than 30 minutes (of coding time).

The final step is to use it in a simple command line script:

# ch-1.pl
use strict;
use warnings;

use lib './lib';
use Maxgap;

my $maxgap = Maxgap::maxgap(@ARGV);

print "Output: $maxgap\n";

You can see the "stutter" is pretty pronounced here. There is zero error checking so that's not great.

Anyway... I am working on the Elm version and will share another day if I come up with a version I like.