【问题标题】:How to find all single free positions when comparing one array to another?将一个数组与另一个数组进行比较时,如何找到所有单个空闲位置?
【发布时间】:2016-10-01 18:13:48
【问题描述】:

我创建了两个 CGPoint 类型的数组(allPosselectedPos)。一个包含另一个。请参阅下面的示例:

allPos = [point1,..., point10]
selectedPos = [point1, point4, point6, point7, point9, point10]

所有点都具有相同的y 坐标,我将它们从小到大排列。

selectedPos 相比,如何从allPos 中找到只有一个空闲连续位置或只有一个中间空闲位置的位置数组? 从我上面的例子中,这将是

[point5, point8]

【问题讨论】:

    标签: arrays swift


    【解决方案1】:

    您只需要 selectedPos 数组,只需查看每个点之后的以下位置,看看是否(仅)一个空点或(仅)3个并将其保存到新数组中。

    【讨论】:

      【解决方案2】:

      我为您创建了一个简单的示例,展示了如何找到丢失元素的位置。

      let first = [1,2,6,8,9,10]
      let second = [1,2,3,4,5,6,7,8,9,10]
      
      func fetchIndexesWithoutConsecutive(firstArray: [Int], secondArray: [Int]) -> [Int] {
          //Output array
          var array = [Int]()
      
          //Enumerate second array and compare if first array conteins this elments if not we add postion of the missing item
          for (index, value) in secondArray.enumerate() {
              if (!firstArray.contains(value)) {
                  array.append(index)
              }
          }
      
          guard array.count > 1 else {
              return array
          }
      
          var result = [Int]()
      
          for i in 0...array.count-2 {
              let first = array[i]
              let second = array[i+1]
              if second - first > 1 {
                  result.append(second)
              }
          }
      
          return result // [6] position of the elements in second array that are not in first array without consecutive
      }
      
      fetchIndexesWithoutConsecutive(first, secondArray: second)
      

      【讨论】:

      • 谢谢,但这并不能完全解决我的问题。您的代码将提供所有空闲位置,但我只对具有单个空闲空间的位置感兴趣。使用我的allPosselectedPos 示例,您提供的代码将生成[point2, point3, point5, point8]。我只需要[point5, point8] 的单个空闲空间(没有连续的空闲空间)。我希望这能更好地解释事情
      • 你能不能用真实数据描述点,很难理解
      • 假设我有两个 Int 数组 allPos = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]selectedPos = [1, 4, 6, 7, 9, 10] 按给定顺序(升序)排列。在比较allPosselectedPos 时,未选中的元素是[2, 3, 5, 8]23 是连续元素,我不希望结果中有连续元素。但是58 不是连续的。所以我对[5, 8] 感兴趣,因为它们是唯一不连续的未选中项。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 2018-08-04
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多