Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to loop through array and group consecutive numbers in another array SWIFT 4?

Tags:

arrays

swift

I'm trying to figure out the most efficient way using SWIFT 4 to loop through an array of numbers, get the range of any consecutive numbers and add those to a new array. I could do the standard loop checks but I believe I can use a map filter? -- can someone point me in the right direction?

Beginning:

myNumbersArray:[Int] = [1,2,3,4,10,11,15,20,21,22,23]

Wanted result:

newNumbersArray = [
   [1,2,3,4],
   [10,11],
   [15],
   [20,21,22,23]
]

I will post my solution if I figure it out...

like image 239
Mavro Avatar asked Aug 25 '18 17:08

Mavro


1 Answers

My suggestion is IndexSet where consecutive items are stored as ranges.

  • Create the index set from the array.
  • Get the rangeView.
  • Map the ranges to arrays.

let myNumbersArray = [1,2,3,4,10,11,15,20,21,22,23]
let indexSet = IndexSet(myNumbersArray)
let rangeView = indexSet.rangeView
let newNumbersArray = rangeView.map { Array($0.indices) }
like image 104
vadian Avatar answered Nov 15 '22 10:11

vadian