【发布时间】:2017-04-26 09:44:50
【问题描述】:
我在 Swift 中组合了一个算法,其中一部分需要检查给定的数组并确定是否有 2 个(或 3、4 个 - 已注释掉)数字的任何序列重复。我的源代码是来自 Java 的代码块,据我所知,我尝试将其转换为 Swift - Playgrounds。它有点工作,但运行代码后会引发错误
“不能用upperBound 在它崩溃之前,输出是正确的并提供模式的序列。请问如何预防? 我在这里错过了什么?谢谢。let array1 = [12, 4, 5, 7, 1, 2]
let array2 = [1, 2, 3, 1, 2, 3, 1, 2, 3]
let array3 = [1, 1, 1, 1, 1, 1 ]
let array4 = [1, 2, 4, 12, 13, 1, 8, 4, 12, 4 ]
let array5 = [17,39,78,324,43,33,234,99,34,555,39,78,324,43,45,92 ]
func hasPattern(c:Array<Int>) {
for i in 0..<c.count {
var jj = i + 1
let step2 = (c.count - i)
for j in jj..<step2 {
if(c[j] == c[i]){
// pattern of 4 numbers repeating
/*if(c[j+1] == c[i+1] && c[j+2] == c[i+2] && c[j+3] == c[i+3]){
print("\(c[i]), \(c[i+1]), \(c[i+2]), \(c[i+3])")
}*/
// pattern of 3 numbers repeating
/*
if(c[j+1] == c[i+1] && c[j+2] == c[i+2]){
print("\(c[i]), \(c[i+1]), \(c[i+2])")
}
*/
// pattern of 2 numbers repeating
if(c[j+1] == c[i+1]){
print("\(c[i]), \(c[i+1])")
}
}
}
}
}
/*
print(hasPattern(c: array1))
print(hasPattern(c: array2))
print(hasPattern(c: array3))*/
//print(hasPattern(c: array4))
print(hasPattern(c: array5))
【问题讨论】:
-
你的问题很不清楚。您期望输出什么?您的
hasPattern函数没有返回任何内容。您的 5 个样本阵列的预期结果是什么? -
你说得对,我应该解释得更好。我在 Swift-Playgrounds 中编写了这个块,所以我能够看到 print() 行的输出。在这一行上,我将添加一个数组并附加结果编号。然后将返回该数组。因此,目标是扫描数组以查找重复数字的模式,将模式添加到数组中并返回它。所以对于 array4 它将返回数组 [4, 12] 中的数字
-
也就是说,您正在检查每个数组是否包含一个多次出现的子数组(最长为 4)?您想要满足条件的最长子数组还是满足条件的所有子数组?
-
是的,正确,所有子数组都需要。因此,对于数组 5,它将返回 2 个数字 39、78 和 78、324 的 2x 模式。如果我选择 3 个数字的模式,它将只返回一个模式 39、78、324
标签: arrays swift algorithm numbers pattern-matching