gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:37:47 26 4
gpt4 key购买 nike

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

起始索引 == 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])
}

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

关于arrays - Swift:在数组中追加项目的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55087874/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com