微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何从数组中获取随机元素并将其从数组中删除?

如何解决如何从数组中获取随机元素并将其从数组中删除?

我知道有一个函数% set a {This is the new begin.\With old memories} This is the new begin.\With old memories % string map {.\\ .} $a This is the new begin.With old memories 获取随机元素并将其返回。

randomElement()

所以它工作得很好,但是所有数组都保持原样。如何从数组中删除随机元素?有没有一种快速方法,而无需迭代,查找和删除它?

解决方法

选择随机索引,而不是随机元素。

if let index = array.indices.randomElement() {
    let value = array.remove(at: index)
    // ...
}
,
extension Array {
    mutating func removeRandom() -> Element? {
        if let index = indices.randomElement() {
            return remove(at: index)
        }
        return nil
    }
}
,

您可以尝试一下。

var array = ["a","b","c","d","e"]
var result = array.randomElement()
if let index = array.firstIndex(of: result ?? "")  {
  array.remove(at: index)
}
print(array) //["a","e"]
print(result) //Optional("c")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。