Generating Random Values in Swift Between Two Integer Values

Generating random values in Swift between two integer values

try this

let randomNumber = arc4random_uniform(40) + 10
println(randomNumber)

in general form

let lower : UInt32 = 10
let upper : UInt32 = 50
let randomNumber = arc4random_uniform(upper - lower) + lower
println(randomNumber)

Swift 3 - Make a Random number generate in between 2 integer variables

Swift 4.2 Edit:

func randomBetween(min: Int, max: Int) -> Int {
return Int.random(in: min ..< max)
}

import GameKit

func randomBetween(min: Int, max: Int) -> Int {
return GKRandomSource.sharedRandom().nextInt(upperBound: max - min) + min
}

How to generate different random number in a range in Swift?

A Set is simpler, it guarantees unique values

var randomIndex = Set<Int>()

while randomIndex.count < 3 {
randomIndex.insert(Int.random(in: 1 ... 10))
}

Another approach is to create an array of the values, pick a random element and remove this element from the array

var randomValues = Set<Int>()
var valueArray = Array(1...10)
for _ in 0..<3 {
guard let randomElement = valueArray.randomElement() else { break }
randomValues.insert(randomElement)
valueArray.remove(at: valueArray.firstIndex(of: randomElement)!)
}

Regarding is there any way to optimize my approach the for loop in your code is extremely expensive.

First of all the recommended syntax for an index based loop is

for i in 0 ..< generatedValue.count {

But actually you don't need the index so Fast Enumeration is better

for value in generatedValue {
if randomValue != value {

The most expensive part of the loop is that the entire array is always iterated even if the value was already found. At least add a break statement to exit the loop

for value in generatedValue {
if randomValue != value {
randomIndex.append(randomValue)
c += 1
break
}
}

But there is still a more efficient syntax

if !generatedValue.contains(randomValue) {
randomIndex.append(randomValue)
c += 1
}

Two different random generated numbers in Swift

Try approaching this another way: keep generating new numbers until you have two different values.

var a = 0
var b = 0
while a == b {
a = Int(arc4random_uniform(10))
b = Int(arc4random_uniform(10))
}

Alternatively, you can regenerate just one of the numbers:

var a = Int(arc4random_uniform(10))
var b = 0
repeat {
b = Int(arc4random_uniform(10))
} while a == b

How to generate a random number in Swift?

Swift 4.2+

Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types.
You can call the random() method on numeric types.

let randomInt = Int.random(in: 0..<6)
let randomDouble = Double.random(in: 2.71828...3.14159)
let randomBool = Bool.random()

Swift: Generate random number between multiple ranges

There is a general solution for generating a random integer within several nonoverlapping ranges.

  1. Find the number of integers in each range; this is that range's weight (e.g., if each range is a closed interval [x, y], this weight is (y - x) + 1).
  2. Choose a range randomly according to the ranges' weights (see this question for how this can be done in Swift).
  3. Generate a random integer in the chosen range: CGFloat.random(in: range).

Generate list of unique random numbers in Swift from range

There are 2 problems here:

  1. You don't generate enough numbers. You need to keep generating random numbers until your set is large enough:

    func getRandomNumbers(maxNumber: Int, listSize: Int)-> [Int] {
    var randomNumbers = Set<Int>()
    while randomNumbers.count < listSize {
    let randomNumber = Int(arc4random_uniform(UInt32(maxNumber+1)))
    randomNumbers.insert(randomNumber)
    }
    return randomNumbers
    }
  2. You're biasing your random numbers by putting them in the ordering Set chooses, which is highly predictable. You should append your numbers to an array (to keep them in order that they are generated), while still leveraging a set in parallel, for its fast deduplication:

    func getRandomNumbers(maxNumber: Int, listSize: Int)-> [Int] {
    precondition(listSize < maxNumber, "Cannot generate a list of \(listSize) unique numbers, if they all have to be less than \(maxNumber)")

    var randomNumbers = (array: [Int](), set: Set<Int>())

    while randomNumbers.set.count < listSize {
    let randomNumber = Int(arc4random_uniform(UInt32(maxNumber+1)))
    if randomNumbers.set.insert(randomNumber).inserted { // If the number is unique
    randomNumbers.array.append(randomNumber) // then also add it to the arary
    }
    }

    return randomNumbers.array
    }

Generating a random number in Swift

It really depends on how much casting you want to avoid. You could simply wrap it in a function:

func random(max maxNumber: Int) -> Int {
return Int(arc4random_uniform(UInt32(maxNumber)))
}

So then you only have to do the ugly casting once. Everywhere you want a random number with a maximum number:

let r = random(max: _names.count)
let name: String = _names[r]

As a side note, since this is Swift, your properties don't need _ in front of them.

Generating random numbers with Swift

let randomIntFrom0To10 = Int.random(in: 1..<10)
let randomFloat = Float.random(in: 0..<1)

// if you want to get a random element in an array
let greetings = ["hey", "hi", "hello", "hola"]
greetings.randomElement()


Related Topics



Leave a reply



Submit