【发布时间】:2016-10-07 16:31:02
【问题描述】:
在 Swift 中,我有一个方法可以生成如下所示的数字集:
86.9238759555414
86.4558606813632
86.4277950105986
86.6055803862833
86.1875587264579
86.7055257286376
86.7445244949838
86.5632505027143
86.7381593407261 // This will trigger a function, because 4 consecutive numbers are within .3 range.
每秒都会有一个数字添加到此集合中。我希望能够检测到 4 个 连续 数字之间的距离在 0.3 以内。在上面设置的数字中,这将出现在最后一个数字 86.7381593407261 之后,因为前面的 3 个数字都在 0.3 以内。
我在 swift 中的尝试如下:
属性:
var counter = 0
var maxValue = 0.0
var minValue = 0.0
公式:
// set max - works properly.
if currentValue > maxValue {
maxValue = currentValue
}
// set min - not working. the min always prints 0.0
if currentValue < currentValue {
minValue = currentValue
}
if maxValue - currentValue <= 0.3 && minValue + currentValue <= 0.3{
//if it passes the previous 2 conditions, increment the counter and update max/min appropriately.
counter += 1
}
// If it doesn't, reset the counter to 0, and reset max and min to the Int min and max values, respectively.
else {
counter = 0
// reset max and min to the Int min and max values, respectively.
minValue = DBL_MAX
maxValue = DBL_MIN
}
if counter == 4 {
// celebrate
}
【问题讨论】:
-
它是如何用任何语言实现的?从你想要的伪代码开始,然后从那里填写(如果你有特定问题,然后问一个特定问题)
-
买一只橡皮鸭。放在桌子上。用英语向它解释如何实现你想要的。一旦你这样做了,你会发现电脑版正好落在你的腿上。
-
什么是“4个连续数字”?连续添加?集合通常不保留插入顺序。还是排序时集合中的数字?或者你真的不是指 CS 意义上的系列吗?
标签: swift properties observers