As of Swift 1.2, Apple introduces Set
collection type.
Say, I have a set like:
var set = Set<Int>(arrayLiteral: 1, 2, 3, 4, 5)
Now I want to get a random element out of it. Question is how? Set
does not provide subscript(Int)
like Array
does. Instead it has subscript(SetIndex<T>)
. But firstly, SetIndex<T>
does not have accessible initializers (hence, I can not just create an index with the offset I need), and secondly even if I can get the index for a first element in a set (var startIndex = set.startIndex
) then the only way I can get to the N-th index is through consecutive calls to successor()
.
Therefore, I can see only 2 options at the moment, both ugly and expensive:
var array = [Int](set)
) and use its subscript (which perfectly accepts Int
); orsuccessor()
methods to get to the N-th index, and then read corresponding element via set's subscript.Do I miss some other way?
To get a random element from an array you can use the randomElement() function for arrays. Here is a code example: let numbers = [5, 2, 9, 11, 20, 3030] if let random = numbers. randomElement() { print("The random number is \(random).") }
To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.
Use the numpy. random. choice() function to generate the random choices and samples from a NumPy multidimensional array. Using this function we can get single or multiple random numbers from the n-dimensional array with or without replacement.
Starting with Swift 4.2, you can use randomElement
:
let random = set.randomElement()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With