Consecutive pairs
Weekly challenge 131 — 20 September 2021
Week 131: 20 Sep 2021
You are given a sorted list of unique positive integers. Write a script to return list of arrays where the arrays are consecutive integers.
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])
The easiest way to do this is to pass through the input list, and:
$n
equals the previous one + 1, append , $n
to the output string, or
], [$n
to the output stringFinally, bracket the output string thus: ([$output])
#!/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
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