Swift:在数组中追加项目的算法

Swift: algorithm to append items in array

我需要使用特定算法将项目附加到数组:

起始索引 == 2 和分隔符 == 5

例如输入数组:

["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

例如输出数组:

["1", "1", "X", "1", "1", "1", "1", "1", "X", "1", "1", "1", "1", "1", "X", "1", "1", "1", "1"]

这是我的代码,但我找不到让它正常工作的方法,期待一些帮助

var mixStartIndex = 2
var mixSeparator = 5

let array = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]
var result = [AnyObject]()
for (index, item) in array.enumerated() {
    if (index > mixStartIndex+mixSeparator && index % mixSeparator == 0) || index == mixStartIndex {
        result.append("X" as AnyObject)
    }
    result.append(item as AnyObject)
}
print(result)

PS 我正在处理对象,为了简单起见,我只是用字符串做了例子

您缺少将输入数组附加为输出数组的一部分

尝试添加这个

else
        {
            result.append(array[index])
        }

更新: 将条件更改为 if (((index-mixStartIndex)%mixSeparator)==0 || index == mixStartIndex) 适用于第五个索引

var mixStartIndex = 2
var mixSeparator = 6

func mix(array: [String]) -> [String] {
    guard !array.isEmpty else { return array }
    var result = [String]()
    for (index, _) in array.enumerated() {
        if (((index-mixStartIndex)%mixSeparator)==0 || index == mixStartIndex) {
            result.append("X")
     }
        else
        {
            result.append(array[index])
        }
}
    return result
}

创建数组的功能性解决方案,其中元素插入到结果数组中:

let result: [String] = array.enumerated().reduce(into:[]) { acc, elm in
    let tempo = ((elm.offset - 2) % 5 == 0 ? ["X"] : []) + [elm.element]
    acc.append(contentsOf: tempo)
}

如果您想替换元素而不是插入:

let result = array.enumerated().map {
    ([=11=].offset - 2) % 6 == 0 ? "X" : [=11=].element
}

Array.insert(_:在:)

我们可以使用内置函数 Array.insert(_:at:)

let newCount = array.count > 2 ? array.count + 1 + (array.count - 3) / 6 : array.count

var index = 2
let mixSeparator = 6

var result = array

while index < newCount {
    result.insert("X", at: index)
    index += mixSeparator
}

但那会很低效,不仅因为你整个数组然后开始插入,还因为 insert(_:at:) 是一个 O(n) 操作。这意味着应该移动插入索引之后的所有元素。一个更有效的解决方案是迭代地进行插入:


迭代插入

这是一个非常容易理解的迭代解决方案:

let array = ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

var result = array
let x = "X"

let startIndex = 2
let step = 6

var count = 0
var index = 2

while index < array.count {
    result[index] = x
    count += 1
    index += step
}

result.append(contentsOf: Array(repeating: "1", count: count))

或者,如果您想一次性创建 result 数组:

let newCount = array.count > 2 ? array.count + 1 + (array.count - 3) / 6 : array.count

var result = [String]()
result.reserveCapacity(newCount)

let startIndex = 2
let step = 6

var nextIndexToPutX = startIndex
var index = 0

while index < newCount {
    if index == nextIndexToPutX {
        result.append("X")
        nextIndexToPutX += step
    } else {
        result.append("1")
    }
    index += 1
}

迭代替换

var result = [String]()
result.reserveCapacity(array.count)

var nextIndexToPutX = 2
let step = 6

var index = 0

while index < array.count {
    if index == nextIndexToPutX {
        result.append("X")
        nextIndexToPutX += step
    } else {
        result.append(array[index])
    }
    index += 1
}

这个有效并且比接受的答案更简单:

extension Array {
    func example(start: Index, seperator: Index, insert: Element) -> [Element] {
        var result = self
        var index = start
        while index < result.count {
            result.insert(insert, at: index)
            index += seperator + 1
        }
        return result
    }

    // a functional solution
    func example2(start: Index, seperator: Index, insert: Element) -> [Element] {
        return self.enumerated().flatMap { offset, element in
            offset == start || offset > start && (offset - start) % seperator == 0 ? [insert, element] : [element]
        }
    }
}

print(array.example(start: mixStartIndex, seperator: mixSeparator, insert: "X"))
print(array.example2(start: mixStartIndex, seperator: mixSeparator, insert: "X"))

这是另一个,更直接一点。

  let array = ["1","1","1","1","1","1","1","1","1","1","1","1","1","1","1"]

  let result = array.enumerated().flatMap{ ([=10=].offset - 1)  % 5 == 0 ? [[=10=].element, "X"] : [[=10=].element]}

  print(result)