I don’t really know how to describe what I’m doing, but this example should help:
val vals = Array( (0, true),
(1, true),
(2,true),
(3,true),
(4,false),
(5, true),
(6, true),
(7, false),
(8, true),
(9,true))
I’m looking to identify the first and last elements in each of the ‘true’ regions, though partitioning the array when the value changes could work as well. I could do this imperatively, but what’s the best way to do this in scala?
If you don’t mind adding some infrastructure to handle a
groupedWhilefeature, you can steal from Rex Kerr’s answer on extending scala collection. Use the section that handles array, in the second part of the answer.Then it’s a breeze:
Edit:
I came up with a solution that does not require
groupedWhile. It’s based on usingIterator.iteratewhich starts from a seed and repeatedly applies thespanfunction to extract the next group of elements that have the same boolean property. In this instance the seed is a tuple of the next group and the remainder to process:Which prints the same result as above. Note that
spanfor empty arrays does not call the predicate, so we don’t get an exception onrest.headif rest is empty.