Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random element from a set in Swift?

Tags:

swift

set

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:

  • Convert the set into array (var array = [Int](set)) and use its subscript (which perfectly accepts Int); or
  • Get index of a first element in a set, traverse the chain of successor() methods to get to the N-th index, and then read corresponding element via set's subscript.

Do I miss some other way?

like image 382
0x416e746f6e Avatar asked Feb 12 '15 23:02

0x416e746f6e


People also ask

How do I select a random item from a list in Swift?

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).") }

How do you generate a random number in Swift?

To generate a random number in Swift, use Int. random() function. Int. random() returns a number, that is randomly selected, in the given range.

How do you generate a random value from an array in Python?

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.


1 Answers

Starting with Swift 4.2, you can use randomElement:

let random = set.randomElement()
like image 141
Cœur Avatar answered Sep 27 '22 20:09

Cœur