iHacks4iPhone
iHacks4iPhone

Reputation: 51

How to print a random array in swift 2?

If i have a array like

var array = ["heads", "tails"]

How can i print or display a random? Like sometimes heads or tails?

I'm a beginner currently.

Language - Swift 2

Upvotes: 0

Views: 381

Answers (5)

user3441734
user3441734

Reputation: 17544

There are two options that may be used with the IBM Sandbox...

import SwiftShims
var array = ["heads", "tails"]
for _ in 0..<10 {
    print(array[Int(_swift_stdlib_arc4random_uniform(UInt32(array.count))])
}

or

import Glibc
var array = ["heads", "tails"]
for _ in 0..<10 {
   print(array[Int(random() % array.count)])
}

Upvotes: 2

Luca Angeletti
Luca Angeletti

Reputation: 59506

You just need to generate a random Int between 0 and array length - 1.

Then use that number to access the array.

let list = ["heads", "tails"]
assert(!list.isEmpty)
let random = Int(arc4random_uniform(UInt32(list.count)))
print(list[random])

Upvotes: 1

dfrib
dfrib

Reputation: 73186

For a more generic solution, make an extension to array that returns a random element (or nil if the array is empty)

extension Array {
    func getRandomElement() -> Element? {
        if self.count > 0 {
            return self[Int(arc4random_uniform(UInt32(self.count) ?? 0))]
        }
        else {
            return nil
        }
    }
}

var arr = ["heads", "tails"]
print(arr.getRandomElement() ?? "Array empty...") // "tails", ...

Or, using a non-generic condensed solution

print(arr[Int(arc4random_uniform(2))])

The method arc4random_uniform(n) returns a random integer in the span 0..<n, and is, in this case, preferable over using random() followed by a modulo operation; random() returns any integer representable by Int.


(I now noted that you mentioned in the comments to Qbyte:s answer that your are using an online compiler which seemingly doesn't support e.g. arc4random_uniform. See @user3441734:s answer for how to access e.g. the arc4random_uniform method for a such a case)

Upvotes: 0

Omar Faruqe
Omar Faruqe

Reputation: 135

You can try like this

var array = ["heads", "tails"]

Suppose

var range = 100
random() % range  // It Returns int

It will return a random number between 0 and 100

rand() % 2 // It Returns Int32

array[rand()%2]  //Error
array[random()%2]  //Random

Upvotes: 0

Qbyte
Qbyte

Reputation: 13243

Use the random function which returns a random Int:

import Foundation

// returns randomly 0 or 1
random() % 2

// returns randomly had or tails
array[random() % 2]

Unfortunately online Swift compilers don't support random() therefore we have to implement a random generator ourselves (from the Swift Book):

// random generator
final class LinearCongruentialGenerator {
    var lastRandom = 42.0
    let m = 139968.0
    let a = 3877.0
    let c = 29573.0

    func random() -> Double {
        lastRandom = ((lastRandom * a + c) % m)
        return lastRandom / m
    }
}

let r = LinearCongruentialGenerator()

var array = ["heads", "tails"]
for _ in 0..<100 {
    print(array[Int(r.random() * 2)])
}

Here the IBM Swift Sandbox

Upvotes: 0

Related Questions