遍历数组并在另一个数组SWIFT 4中对连续数字进行分组的最佳方法? [英] Best way to loop through array and group consecutive numbers in another array SWIFT 4?

查看:196
本文介绍了遍历数组并在另一个数组SWIFT 4中对连续数字进行分组的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试找出使用SWIFT 4遍历数字数组,获取任何连续数字范围并将它们添加到新数组中的最有效方法.我可以进行标准循环检查,但是我可以使用地图过滤器吗? -有人可以指出我正确的方向吗?

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?

开始:

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

想要的结果:

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

如果解决了,我将发布解决方案...

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

推荐答案

我的建议是IndexSet,其中将连续项存储为范围.

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

  • 从数组创建索引集.
  • 获取rangeView.
  • 将范围映射到数组.
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) }

这篇关于遍历数组并在另一个数组SWIFT 4中对连续数字进行分组的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆