如何从数组中找到最远的3个连续元素

时间:2016-09-27 15:37:33

标签: arrays swift swift3

我有一组可能的位置和另一个填充位置数组,这是possiblePositionsArray的子数组。 possiblePositionsArray已修复,已经确定。我想在filledPositions中找到所选数组元素x位置右侧和左侧最远的3个连续点。让我用这个例子进一步解释。 说

possiblePositionsArray = [p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15]
filledPositions = [p1, p2, p4, p7, p8, p9, p10, p12, p13, p14, p15]

两者都是CGPoint s的数组,并且都具有相同的y位置并按升序排列。 如果我选择p11.x,则以下将是右侧和左侧的3个连续点。

[p7, p8, p9] and [p8, p9, p10] To the Left of p11
[p12, p13, p14] and [p13, p14, p15] to the right of p11

但是左边和右边最远的地方是:

farthest to left of p11 is [p7, p8, p9]
farthest to right of p11 is [p13, p14, p15]

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

首先从filledPositions开始。在filledPositions中找到possiblePositionsArray中的第一项。检查两个阵列中的下两个项是否相互匹配。第一个连续组是所选元素左侧最远的组。即使x元素中的possiblePositionsArray值不是等间距也是如此。

之后,你按相反的顺序执行此操作,以找到最右边的。

代码就是这样的:

let selectedElement = yourSelectedElement

//left consecutive group   
var consLeft = [CGPoint]()
//right consecutive group
var 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
        }
    }
}