【问题标题】:Get new array of values from within sorted array从排序数组中获取新的值数组
【发布时间】:2021-02-05 14:09:19
【问题描述】:

我有一个按 y 位置排序的 SCNNode 数组(浮点数):

nodesSortedByY = scene.rootNode.childNodes.sorted { $0.position.y > $1.position.y }

我想做的是从 nodesSortedByY 获取一个新数组,其中 y 值在一定范围内,与 subscript 的工作方式类似,但传递的是实际值而不是索引。

例如:

let nodesSortedByY = [5.0, 4.0, 4.0, 3.0, 2.0, 2.0, 1.0]
let subRange = nodesSortedByY(4.0...2.0)
print(subRange) // [4.0, 4.0, 3.0, 2.0, 2.0]

我尝试使用最初与 this binary search 结合的索引,但如果数组中不存在这些值,则它不起作用:

let yPositions = nodesSortedByY.map({ $0.position.y })
let firstIndex = yPositions.binarySearch(forFirstIndexOf: firstValue) ?? 0
let lastIndex = yPositions.binarySearch(forLastIndexOf: lastValue) ?? 0
nodesSortedByY[lastIndex...firstIndex]

【问题讨论】:

  • 您在寻找filter()吗? let filtered = nodesSortedByY.filter({ (2.0...4.0).contains($0) })
  • 不完全是,它必须以某种方式被一系列节点 y 位置过滤?
  • 如果“y”的值在 2.0 和 4.0 之间,您不想获取它们吗?这就是过滤器的作用。否则,保留您的最后一个想法:let lowerBound = nodesSortedByY.firstIndex(where: { $0 <= 4.0 }) let upperBound = nodesSortedByY.lastIndex(where: { $0 >= 2.0 }) let sub = nodesSortedByY[lowerBound!...upperBound!]
  • 我仍然想要一个 SCNNode 数组,但按 y 对其进行排序并通过节点 y 值获取新的范围数组
  • 我猜是这样,但作者使用了map,并将他的示例简化为[Double],但我的解决方案应该可以工作。

标签: swift


【解决方案1】:

你想要的是filter()

let sub = nodesSortedByY.filter { (2.0...4.0).contains($0.position.y) }

我们只保留nodesSortedByY 中的元素,其中y 的位置在[2.0; 4.0]。

由于您对数组进行了排序(降序),您也可以应用该逻辑(修改您的尝试)

let lowerBound = nodesSortedByY.firstIndex(where: { $0 <= 4.0 }) ?? nodesSortedByY.startIndex
let upperBound = nodesSortedByY.lastIndex(where: { $0 >= 2.0 }) ?? nodesSortedByY.endIndex
let sub = nodesSortedByY[lowerBound...upperBound]

【讨论】:

  • let sub = nodesSortedByY.filter { (2.0...4.0).contains($0.position.y) } 非常适合我谢谢你,我没有意识到你可以这样过滤
  • @Wazza 2.0...4.0 ~= $0.position.y
猜你喜欢
  • 2018-06-16
  • 2013-06-26
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 2019-03-25
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多