In this challenge, we define a range similarly to Python's range
function: A list of positive integers with equal differences between them. For example, [1, 2, 3]
is a range from 1 to 3 with a skip count of 1, because there is a difference of 1 between each item, and [4, 7, 10, 13]
is a range from 4 to 13 with a skip count of 3.
Here, I'll represent ranges as a list of integers, but you can use any reasonable format that unambiguously represents a single range, e.g representing it as [start, skip, end]
or something.
Your challenge is to, given a strictly increasing list of positive integers, represent it as a union of multiple ranges of integers with as few ranges as possible. For example, [1, 2, 4, 7, 12]
can be represented as a union of [1, 4, 7]
and [2, 7, 12]
, and this is (an) optimal solution as it uses two ranges and there is no way to represent it as one range.
This is code-golf, shortest wins!
Testcases
Note that these only show one possible solution. In almost all cases there will be multiple optimal solutions, and you can output any one or all of them.
[1, 5] -> [1, 5]
[1, 2, 3] -> [1, 2, 3]
[1, 2, 4, 7, 12] -> [1, 4, 7], [2, 7, 12]
[1, 2, 3, 11, 12, 13, 21, 22, 23] -> [1, 2, 3], [11, 12, 13], [21, 22, 23]
[8, 9, 13] -> [8, 9], [13]
[23, 24, 25, 27, 30, 33, 35, 37, 40, 44, 45] -> [24, 27, 30, 33], [23, 30, 37, 44], [25, 30, 35, 40, 45]
[1,2,3,4,5,6,7,9,10,11,12,13,14,15] -> [1,2,3,4,5,6,7], [9,10,11,12,13,14,15]
[1, 2, 4, 7, 12, 17] -> [1, 4, 7], [2, 7, 12, 17]
[1,2,3,4,5,6,7,9,10,11,12,13,14,15] -> [1,2,3,4,5,6,7], [9,10,11,12,13,14,15]
. The greedy algorithm fails in this one, and gives[1,3,5,7,9,11,13,15], [2,6,10,14], [4, 12]
. Can be generalized as[1,2,...,2^n-1,2^n+1,...,2^(n+1)-1]
\$\endgroup\$