我在Swift中整理了一個算法,其中一部分需要檢查給定的數組並確定是否有2(或3,4個註釋掉)數字的序列是重複。我的源代碼是來自Java的代碼塊,爲了我最好的理解,我試圖將它轉換爲Swift - Playgrounds。它有點工作,但其上運行的代碼Swift - 搜索數組中的數字模式
後引發錯誤「無法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] – Alessign
因此,換句話說,你檢查每個數組包含一個不止一次出現的子數組(長度爲4)?你是否想要滿足條件的最長的子陣列或符合該條件的所有子陣列? –