Peter’s blog ✴ Week 131 ✴ 20 September 2021

THE WEEKLY CHALLENGE
Consecutive pairs

The Perl Camel

Task 1

Consecutive arrays

You are given a sorted list of unique positive integers. Write a script to return list of arrays where the arrays are consecutive integers.

Examples


Example 1:
Input:  (1, 2, 3, 6, 7, 8, 9)
Output: ([1, 2, 3], [6, 7, 8, 9])

Example 2:
Input:  (11, 12, 14, 17, 18, 19)
Output: ([11, 12], [14], [17, 18, 19])

Example 3:
Input:  (2, 4, 6, 8)
Output: ([2], [4], [6], [8])

Example 4:
Input:  (1, 2, 3, 4, 5)
Output: ([1, 2, 3, 4, 5])

Analysis

The easiest way to do this is to pass through the input list, and:

  • if the current element $n equals the previous one + 1, append , $n to the output string, or
  • if not, append ], [$n to the output string

Finally, bracket the output string thus: ([$output])

I am sorry that the 'Try it' feature is currently working very slowly or not at all owing to some issue with my web hosting provider.

Try it 

Try running the script with any input:



example: 1, 2, 3, 5, 6, 7

Script


#!/usr/bin/perl
use strict;
use warnings;
use v5.26;   # week 131 task 1

consecutive_arrays(1, 2, 3, 6, 7, 8, 9);
consecutive_arrays(11, 12, 14, 17, 18, 19);
consecutive_arrays(2, 4, 6, 8);
consecutive_arrays(1, 2, 3, 4, 5);

sub consecutive_arrays {

    my ($prev, $output, $j);

    # loop over list
    $prev = -1;
    for $j (@_) {
        $output .= ($j == ($prev + 1)) ?   ", $j" : "], [$j";
        $prev = $j;
    }
    $output =~ s|...||;   # tidy the start of $output
    say qq{\nInput:  (} . join(', ', @_) . qq{)\nOutput: ($output])};
}

8 lines of code

Output from script


Input:  (1, 2, 3, 6, 7, 8, 9)
Output: ([1, 2, 3], [6, 7, 8, 9])

Input:  (11, 12, 14, 17, 18, 19)
Output: ([11, 12], [14], [17, 18, 19])

Input:  (2, 4, 6, 8)
Output: ([2], [4], [6], [8])

Input:  (1, 2, 3, 4, 5)
Output: ([1, 2, 3, 4, 5])

 

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