递归函数不中断



我想遍历 2D 数组,并在特定列中找到不同的值时创建子数组。例:

TEST <----- This value should be ignored. Start counting at index 1.
A
A
A
-------- split here --------
B
B
B
-------- split here --------
C
-------- split here --------

这将产生 3 个数组。

  1. 数组 1: [A,A,A]
  2. array2: [B,B,B]
  3. 阵列 3: [C]

我对这个问题的解决方案是一种采用 2D 数组的递归方法:

static func splitArray(fromArray array: [[String]], startIndex: Int = 1) {
for x in startIndex..<array.count {
if array.indices.contains(x+1)  {
if (array[x][7]) != array[x+1][7] {
splitArray(fromArray: array, startIndex: x+1)
}
} else {
break
}
}
}

在这种方法中,我执行以下操作:

  1. 从索引 1 开始遍历数组。
  2. 将当前索引与下一个索引进行比较。如果下一个索引具有不同的值,则拆分数组(如果不恢复迭代(。
  3. 为了防止数组越界,我检查是否有下一个索引 - 如果没有下一个索引中断该方法(应该在整个数组迭代后调用(

额外信息:

  1. 神奇的数字 7 是我要迭代的 2D 数组中的列。
  2. 该方法确实到达了break命令..但是不知何故,尽管它没有被递归splitArray调用调用,但它会跳回该方法。
  3. 此方法尚未创建子数组,因为此时的逻辑已损坏。

为什么我的函数没有中断?它确实完成了它的工作 - 它正确地拆分,但它会在不应该的时候重新开始。

PS:如果有任何编码建议,我将不胜感激,我觉得这段代码总体上很糟糕。

解决了:

static func split(_ array: [[String]], startIndex: Int = 1) {
for x in startIndex..<array.count {
if array.indices.contains(x+1)  {
if (array[x][7]) != array[x+1][7] {
split(array, startIndex: x+1)
break
}
}
}
}

"修复"是在调用递归函数后包括中断。我猜 for 循环在调用拆分后恢复。

最新更新