从数组列表中随机选择5个元素,而无需重复元素 [英] Randomly select 5 elements from an array list without repeating an element

查看:464
本文介绍了从数组列表中随机选择5个元素,而无需重复元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试为iOS开发一个应用程序,但是我无法获得一些简单的代码.基本上,我需要从数组列表中随机选择5个元素,而无需重复一个元素.我有一个草稿,但只显示一个元素.

I am currently trying to make an app for iOS but I can't get some simple code down. Basically I need to randomly select 5 elements from an array list without repeating an element. I have a rough draft, but it only displays one element.

这是我的代码:

let array1 = ["salmon", "turkey", "salad", "curry", "sushi", "pizza"]

let randomIndex1 = Int(arc4random_uniform(UInt32(array1.count)))

print(array1[randomIndex1])

推荐答案

您可以这样做:

let array1 = ["salmon", "turkey", "salad", "curry", "sushi", "pizza", "curry", "sushi", "pizza"]
var resultSet = Set<String>()

while resultSet.count < 5 {
    let randomIndex = Int(arc4random_uniform(UInt32(array1.count)))
    resultSet.insert(array1[randomIndex])
}

let resultArray = Array(resultSet)

print(resultArray)

set只能包含唯一元素,因此同一元素不能超过一次.

A set can contain unique elements only, so it can't have the same element more than once.

我创建了一个空的set,然后只要该数组包含少于5个元素(您选择的数字),我就会对其进行迭代并向set添加一个随机元素.

I created an empty set, then as long as the array contains less than 5 elements (the number you chose), I iterated and added a random element to the set.

在最后一步,我们需要将集合转换为数组以获得所需的数组.

In the last step, we need to convert the set to an array to get the array that you want.

这篇关于从数组列表中随机选择5个元素,而无需重复元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆