说
possiblepositionsArray = [p1,p2,p3,p4,p5,p6,p7,p8,p9,p10,p11,p12,p13,p14,p15]filledpositions = [p1,p15]
两者都是CGPoints的数组,并且都具有相同的y位置并且按升序排列.
如果我选择p11.x,则以下将是右侧和左侧的3个连续点.
[p7,p9] and [p8,p10] To the left of p11[p12,p14] and [p13,p15] to the right of p11
但是左边和右边最远的是:
farthest to left of p11 is [p7,p9]farthest to right of p11 is [p13,p15]
我怎样才能做到这一点?
解决方法 首先从filledpositions开始.在possiblepositionsArray中找到fillpositions中的第一项.检查两个阵列中的下两个项是否相互匹配.第一个连续组是所选元素左侧最远的组.即使possiblepositionsArray元素中的x值不是等间距也是如此.之后,你按相反的顺序执行此 *** 作,以找到最右边的.
代码就是这样的:
let selectedElement = yourSelectedElement//left consecutive group var consleft = [CGPoint]()//right consecutive groupvar consRight = [CGPoint]()if filledpositions.count >= 3 { for i in 0..<filledpositions.count-2 { // find the index of the element from filledpositions in possiblepositionsArray let indexInPossiblePostionArray = possiblepositionsArray.indexOf(filledpositions[i])! if indexInPossiblePostionArray < possiblepositionsArray.count-2 && // safety check filledpositions[i+2].x < selectedElement.x && // Only check left of selected element //check equality of second items filledpositions[i+1].x == possiblepositionsArray[indexInPossiblePostionArray+1].x && //check equality of third items filledpositions[i+2].x == possiblepositionsArray[indexInPossiblePostionArray+2].x { //3 consecutive elements to left selected element was found for j in i...i+2 { //add to left consecutive group consleft.append(filledpositions[j]) } //break out of the for loop break } } //The same thing in reversed order for i in (2..<filledpositions.count).reverse() { let indexInPossiblePostionArray = possiblepositionsArray.indexOf(filledpositions[i])! if indexInPossiblePostionArray-2 >= 0 && filledpositions[i-2].x > selectedElement.x && filledpositions[i-1].x == possiblepositionsArray[indexInPossiblePostionArray-1].x && filledpositions[i-2].x == possiblepositionsArray[indexInPossiblePostionArray-2].x { for j in i-2...i { consRight.append(filledpositions[j]) } break } }}总结
以上是内存溢出为你收集整理的数组 – 如何从数组中找到最远的3个连续元素全部内容,希望文章能够帮你解决数组 – 如何从数组中找到最远的3个连续元素所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)