Suppose you have an array with some known set of values (e.g. a string of \$0\$ and \$1\$) and you want to get all the locations of \$1\$s. Instead of storing a list of all the indices, if the \$1\$s come in "clumps" you can sometimes save space by storing starting and ending indices of "runs" of values -- i.e. substrings which contain just a bunch of \$1\$s in a row. For example, take the following list:
i = 0 1 2 3 4 5 6 7 8 9
a = [1 0 0 1 1 1 0 0 1 1]
^ ^ ^ ^ ^ ^
i = 0 3 4 5 8 9
So we output \$[(0,0), (3,5), (8,9)]\$.
More formally: Given an array \$[a_1, \ldots, a_n]\$ consisting of two distinct values \$x\$ and \$y\$, output all tuples of indices \$(i,j)\$ where the values in the contiguous subsequence \$[a_i, \ldots, a_j]\$ are all \$y\$. You must return as few tuples as necessary to cover all \$y\$ in the array -- e.g. in the above example you should not return \$[(0,0), (3,4), (5,5), (8,9)]\$ .
You may use any two distinct values for the input list, and your indices may start from 0 or 1.
Some test cases:
Input | Output |
---|---|
[] | [] |
[0] | [] |
[1, 1, 1] | [(0, 2)] |
[1, 0, 0, 1] | [(0, 0), (3, 3)] |
[0, 1, 0, 1] | [(1, 1), (3, 3)] |
[1, 0, 0, 1, 1, 1, 0, 0, 1, 1] | [(0,0), (3,5), (8,9)] |
Here's a program to generate test cases.
Standard loopholes are forbidden. Since this is code-golf, the shortest program wins.
[0,0,3,5,8,9]
for example) an acceptable output format? \$\endgroup\$