gpt4 book ai didi

swift - swift 中的随机播放功能似乎是删除卡片而不是交换卡片

转载 作者:行者123 更新时间:2023-11-30 12:11:12 28 4
gpt4 key购买 nike

我正在研究下面一位同事在面试问题中给出的洗牌函数,用于洗牌。在我看来,原始索引“from”处的卡将被删除并丢失。它不是被交换,而是被删除。我错过了什么吗?

func shuffle() {
var from = 0
var to = 0
for _ in cards {
from = Int(arc4random_uniform(UInt32(cards.count)))
to = Int(arc4random_uniform(UInt32(cards.count)))
cards.insert(cards.remove(at: from), at: to)
}
print("\nShuffled deck\n")
}

最佳答案

Arrayremove(at:) 函数不仅仅从数组中删除项目;它还返回被删除的元素。上面的代码立即将删除的元素传递给 insert(at:),这会导致删除的元素插入到其他位置。

关于swift - swift 中的随机播放功能似乎是删除卡片而不是交换卡片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46029771/

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