NCNecros NCNecros - 4 months ago 14
Java Question

How can I split sequence of integer into ranges (java\kotlin)

Now I have a sequence like this

("1,3,5,7,11,13,15,17,21,23,25,27,29,33,35")


How can I split into non-breaking ranges. For example I need get list with odd ranges like this:

([1,3,5,7] [11,13,15,17] [21,23,25,27,29] [33,35])


UPD. My code:

fun test1 (arr : List<Int>): List<List<Int>>{
var lastElem: Int? = null
val arr = ArrayList(arr)
Collections.sort(arr)
val iter = arr.iterator()
val resultList = ArrayList<List<Int>>()
val tmlList = ArrayList<Int>()
while(iter.hasNext()){
val currElem = iter.next()
if (lastElem == null) {
lastElem = currElem
tmlList.add(currElem)
}else if(lastElem+2==currElem){
tmlList.add(currElem)
lastElem = currElem
}else if(lastElem+2 != currElem){
resultList.add(ArrayList(tmlList))
tmlList.clear()
tmlList.add(currElem)
lastElem = currElem
}
}
resultList.add(ArrayList(tmlList))
return resultList;
}


UPD. I'm sorry about code. I added my version of solution. I'm looking for a more beautiful version.

Answer

Here's one way using map, let:

val a = ("1,3,5,7,11,13,15,17,21,23,25,27,29,33,35")
val nonBreakingRanges = a.split(',')
    .map { it.toLong() }
    .let { list ->
        var lastRange = mutableListOf<Long>()
        list.map {
            val previousElement = lastRange.lastOrNull() ?: it
            if (it == previousElement + 2) {
                lastRange.add(it)
            } else {
                lastRange = mutableListOf(it)
            }
            lastRange
        }.distinct()
    }