gpt4 book ai didi

iOS swift : Track and store indices of all duplicate values in an array?

转载 作者:行者123 更新时间:2023-11-28 15:23:58 25 4
gpt4 key购买 nike

我最近问了这个问题:iOS Swift: How to store the index of all duplicate values in array?

我得到了我的问题的确切答案,但我发现我无法使用它来实现我在代码中需要的东西。

我正在尝试存储 Date 数组的任何重复值的所有索引,并存储在另一个数组 [ [Int] ] 中。

例如,这是我的 Date 数组:

let dates = [2016-01-02 08:00:00 +0000, 2016-01-02 08:00:00 +0000,
2016-02-02 08:00:00 +0000, 2016-03-02 08:00:00 +0000,
2016-05-01 08:00:00 +0000, 2016-05-01 08:00:00 +0000]

我正在尝试做的,与我之前的问题类似,是将所有重复的 Date 值的所有索引存储到一个单独的数组中。

例如,下面的数组将包含:

repeatedIndices = [ [0, 1], [2], [3], [4, 5] ]

其中索引 01 包含重复日期 2016-01-02 08:00:00 +0000 和索引 45 包含重复的日期 2016-05-01 08:00:00 +0000

我之前的问题在 [ String: [Int] ] 中提供了答案,作为初学者,我不知道如何操纵它来使用我的代码,因为字典是无序,我需要一个有序数组。

如有必要,请标记为重复,但我不想编辑问题并取消标记答案,因为这不公平。

谢谢。

最佳答案

使用带有示例值的[Date:[Int]] 字典,

var duplicatedDict : [Date:[Int]] = [:]

for (index,date) in datesArray.enumerated() {
if(duplicatedDict[date] == nil)
{
duplicatedDict[date] = [index]
}else
{
duplicatedDict[date]?.append(index)
}
}

debugPrint(duplicatedDict)

到目前为止,控制台中的结果非常好

[2016-02-02 08:00:00 +0000: [2], 2016-05-01 08:00:00 +0000: [5, 6], 2016-03-02 08:00:00 +0000: [3, 4], 2016-01-02 08:00:00 +0000: [0, 1]]

然后我们需要循环排序的字典键并将每个键数组中的值添加到数组

func returnValuesOrdered() ->[[Int]]{

var result : [[Int]] = []

for key in duplicatedDict.keys.sorted(by: {$0 < $1})
{
result.append(duplicatedDict[key]!)
}

debugPrint(result)
return result
}

控制台结果

[[0, 1], [2], [3, 4], [5, 6]]

希望对你有帮助

关于iOS swift : Track and store indices of all duplicate values in an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45537650/

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