2014-10-06 88 views
-2

在Xcode中使用swift我有一个浮点值'IMProdArray'的数组。
我想确定一个函数,检查数组中的值,以确定是否有任何值在0.200之内。如果他们返回'假',如果他们不是,返回'真'。Swift比较单个数组中的值

作为类似的函数I还要计算两个值之间的最大距离,并返回的中间点的值:即

在阵列我有值:1, 3, 4, 10, 11, 12

两个值之间的最大间隙(如果他们是为了)是4-10。这个中间值是7.所以返回7.

在正确的方向微调将不胜感激。

回答

0

既然你问了一个解决方案,这里是解决方案(尽管我真的不应该只是为你写代码)。

这适用于按升序排序的数组(排序使用此代码,如果它是不是已经排序之前,你的阵列):

var maxGap = -1 
var maxGapIndex = -1 
for i in [1..<IMProdArray.count] { 
    let gap = IMProdArray[i] - IMProdArray[i-1] 
    if gap <= 0.2 { 
     // handle the values being within 0.2 of each other 
    } 
    if gap > maxGap { 
     maxGap = gap 
     maxGapIndex = i-1 // store the index of the first number 
    } 
} 

然后,您可以从maxGapIndex检索的差距指数。对于你的例子,maxGapIndex将是2,这是你的数组中的的索引。