Peter
Peter Campbell Smith

Consecutive pairs

Weekly challenge 131 — 20 September 2021

Week 131: 20 Sep 2021

Task 1

Task — 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])

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;

my $input;

# loop over input examples
until (eof(DATA)) {
    $input = <DATA>;
    chop $input;
    do_task();
}

sub do_task {

    my ($prev, $output);

    # loop over list
    $prev = -1;
    while ($input =~ m|(\d+)|g) {          # consecutive  # non-consecutive
        $output .= ($1 == ($prev + 1)) ?   ", $1" :       "], [$1";
        $prev = $1;
    }
    $output =~ s|...|(|;   # tidy the start of $output
    say "\nInput:  ($input)\nOutput: $output])";
}

__DATA__
1, 2, 3, 6, 7, 8, 9
11, 12, 14, 17, 18, 19
2, 4, 6, 8
1, 2, 3, 4, 5

Output


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