如何使用闭包计算最大连续正数?
var numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
//in this case it should be 3
print(numbers.reduce(0, { $1 > 0 ? $0 + 1 : $0 } ))//this counts total positive numbers
答案 0 :(得分:6)
更新:更简单的解决方案:将数组拆分为 正元素,并确定最大切片长度:
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let maxConsecutive = numbers.split(whereSeparator: { $0 <= 0 }).map { $0.count }.max()!
print(maxConsecutive) // 3
旧答案:)使用Swift running sum中的想法:
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let maxConsecutive = numbers.map({
() -> (Int) -> Int in var c = 0; return { c = $0 > 0 ? c + 1 : 0; return c }
}()).max()!
这里map()
将每个数组元素映射到连续正数的计数
数字到元素位置,在这种情况下
[1, 2, 3, 0, 0, 1, 2, 0, 0, 0, 1]
转换创建为“立即评估
闭包“捕获保存当前数量的变量c
连续的正数。转换增加或重置c
,
并返回更新后的值。
如果数组可能很大,则将其更改为
let maxConsecutive = numbers.lazy.map( ... ).max()!
以确定最大游程长度而不创建 中间阵列。
答案 1 :(得分:2)
var currentResult = 0
var maxResult = 0
for i in numbers {
currentResult = i > 0 ? currentResult + 1 : 0
if maxResult < currentResult {
maxResult = currentResult
}
}
print(maxResult)
没有闭包的解决方案
答案 2 :(得分:2)
var numbers = [1, 3, 4, -1, -2, 5, 2, -2, -3, -4, 5]
let result = numbers.reduce((current: 0, max: 0)) { result, number in
var value = result
if number > 0 {
value.current += 1
value.max = max(value.current, value.max)
} else {
value.current = 0
}
return value
}
result.max
答案 3 :(得分:1)
生成子序列:
let numbers = [1,3,4,-1,-2,5,2,-2,-3,-4,5]
let subsequences: [[Int]] = numbers.reduce(into: []) { (result, number) in
guard
var currentSequence = result.last,
let lastNumber = currentSequence.last
else {
result = [[number]]
return
}
if number == lastNumber + 1 {
currentSequence.append(number)
result.removeLast()
result.append(currentSequence)
} else {
result.append([number])
}
}
let longest = subsequences.max { $0.count < $1.count }
print(subsequences)
print("Longest subsequence: \(longest)")
print("Longest length: \(longest?.count)")
答案 4 :(得分:0)
检测数组中连续的三个数
var data = [1,2,5,4,56,6,7,9,6,5,4,5,1,2,5,4,56,6,7,9,8,1,1,2,5,4,56,6,7,9,8,1,1,2,5,4,56,6,7,9,8,1,1,2,5,4,56,6,7,9,8,1,1,2,5,4,56,6,7,9,8,11,2,5,4,56,6,7,9,8,1,2,3]
for i in 0...data.count{
if i+2 < data.count{
if Int(data[i] + data[i+2]) / 2 == data[i+1] && Int(data[i] + data[i+2]) % data[i+1] == 0 && data[i+1] != 1 && data[i] < data[i+1]{
print(data[i] ,data[i+1], data[i+2])
}
}
}