swift Array randomElement() Function



The randomElement() function is a predefined function and it is used to find a random element from the given array. It selects an element randomly so whenever we run the program we will get different output. It returns only one element at a time. It can work for both mutating and non-mutating arrays.

For example, we have an array = [34, 10, 38, 9, 19]. Now using the randomElement() function we get a random element that is 38 from the array.

We can use the randomElement() function in two different ways −

  • randomElement() function
  • randomElement()(using:) function

Swift Array randomElement() Function

The randomElement() function is used to find a random element from the given array. If the given collection is empty, then this function will return nil. That means this function returns an optional type value, so to get the actual value we have to unwarp using (!) forcefully.

Syntax

Following is the syntax of the randomElement() function −

func randomElement()->Self.Element?

Parameters

This function does not take any parameter.

Return Value

This function returns a random element from the given array.

Now we will discuss how to use the randomElement() function with the help of the following examples:

Example 1

Swift program to generate random element from the given array using randomElement() function. Here we are using different types of arrays.

import Foundation

// Array 1
var number = [12, 33, 45, 7]

// Finding random Element 
// Using randomElement() function
let res1 = number.randomElement()!
print("Random element from number array:", res1)

// Array 2
var names = ["Jack", "Mona", "Soniya"]

// Finding random Element 
// Using randomElement() function
let res2 = names.randomElement()!

print("Random element from names array:", res2)

// Array 3
var mix : [Any] = ["Jack", 12, true, 23.2, 32.23244353534545, "C"]

// Finding random Element 
// Using randomElement() function
let res3 = mix.randomElement()!

print("Random element from mix array:", res3)

Output

Random element from number array: 33
Random element from names array: Mona
Random element from mix array: 23.2

Example 2

Swift program to replace a random element from the given array.

import Foundation

// Defining array of string type
var names = ["Jack", "Mona", "Soniya"]

print("Original Array:", names)

// Using randomElement() to random index value
if let randomIndexValue = names.indices.randomElement() {

    // Replace the element 
    names[randomIndexValue] = "Mango"
    print("Array after replacing a random element:", names)
} else {
    print("Empty Array")
}

Output

Original Array: ["Jack", "Mona", "Soniya"]
Array after replacing a random element: ["Jack", "Mona", "Mango"]

Swift Array randomElement(using: ) Function

The randomElement(using:) function is used to get the random element of the given array according to the given random number generator. You can use a predefined random number generator or a custom random number generator.

Syntax

Following is the syntax of the randomElement(using:) function −

func randomElement() <T>(using generator: inout T)->Self.Element? where T : RandomNumberGenerator

Parameters

This function takes only one parameter which is a generator. The generator represents the random number generator that is used to generate random numbers in the array.

Return Value

This function returns a random element.

Now we will discuss how to use the randomElement(using:) function with the help of the following examples:

Example 1

Swift program to generate a random element using randomElement(using:) function.

import Foundation

// Defining an array of string type
var inputArr: [String] = ["Cow", "Dog", "Pig", "Hen"]

print("Original Array:", inputArr)

// Create a custom random number generator
var randomGenerator = SystemRandomNumberGenerator()

// Generating random element 
// Using randomElement() function
let element = inputArr.randomElement(using: &randomGenerator)!

print("Random Element:", element)

Output

Original Array: ["Cow", "Dog", "Pig", "Hen"]
Random Element: Cow

Example 2

Swift program to generate a random row from the given matrix using randomElement() and then find their sum.

import Foundation

// Defining matrix
var inputMatrix = [
[1, 2, 4],
[3, 4, 6], 
[1, 4, 6]
]

print("Original Matrix:")
for x in inputMatrix{
    print(x)
}

// Create a custom random number generator 
var randomGen = SystemRandomNumberGenerator()

// Generating a random row from the given matrix
// Using randomElement() function
let numRow = inputMatrix.randomElement(using: &randomGen)!

print("Random row from the given matrix:", numRow)

// Find the sum of row elements
let sum = numRow.reduce(0, +)
print("Sum:", sum)

Output

Original Matrix:
[1, 2, 4]
[3, 4, 6]
[1, 4, 6]
Random row from the given matrix: [1, 2, 4]
Sum: 7
Advertisements