【问题标题】:Detecting when numbers are in close range of each other检测数字何时彼此接近
【发布时间】: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


【解决方案1】:

以下是解决方案的概要:

  • 保留三个变量:
    • count,代表当前“连续”通过数字,
    • max,表示当前连续记录中的最大值,
    • min,表示当前连续记录中的最小值
  • 每次有新号码进来
    • 如果小于max,请确保它在0.3max 之内
    • 如果大于min,请确保它在最小的0.3 范围内
    • 如果它通过了前两个条件,则递增计数器并适当更新max/min。如果不是,请将计数器重置为 0,并将 maxmin 分别重置为 Int 的最小值和最大值。
  • 当你的计数器达到 4 时,庆祝

【讨论】:

  • 在这里感谢您的帮助!我在编写以下语法时遇到了困难:“确保它在最大值的 0.3 范围内......确保它在最小值的 0.3 范围内。”
  • 假设当前值为amax - a必须是&lt;= 0.3
  • 这是一个视觉解释。 (忽略计数超过 4)imgur.com/FeqgoqN
  • 我想我正在根据您的大纲朝着解决方案迈出一小步!我迅速尝试编辑了我的原始帖子。我很难记录 minValue。对于最大,这很容易。我只是将它设置为 0.0 的类级别属性。如果 currentValue > maxValue { maxValue = currentValue}。此外,我在 else 语句中遗漏了一些步骤。即重置最大值和最小值
  • minValue + currentValue &gt;= 0.3 应该是minValue + currentValue &lt;= 0.3
猜你喜欢
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 1970-01-01
  • 2021-06-20
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 1970-01-01
相关资源
最近更新 更多