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; # 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])}; }
last updated 2026-03-09 — 8 lines of code
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