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

时间:2019-03-10 12:53:28

标签: arrays swift algorithm genetic-algorithm

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

起始索引== 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我正在处理对象,为简单起见,仅使用字符串作为示例

4 个答案:

答案 0 :(得分:0)

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

尝试添加此内容

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

enter image description here

更新:  将条件更改为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
}

enter image description here

答案 1 :(得分:0)

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

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 {
    ($0.offset - 2) % 6 == 0 ? "X" : $0.element
}

Array.insert(_:at:)

我们可以使用内置功能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
}

答案 2 :(得分:0)

这有效并且比公认的答案更简单:

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"))

答案 3 :(得分:0)

这里是另一个,更简单一些。

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

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

  print(result)