Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a random number in a range (10...20) using Swift [duplicate]

I'm able to pick a random number for my items in my game but is it possible to pick a random number between 2 numbers?

so instead of

let number = (arc4random_uniform(100))

I would like something like this:

let number = (arc4random_uniform(10...20))

or something like that? Now if I get a weapon drop it can be everything in my list. This way I could make it so that only the first few would have a drop for a specific monster or at higher level they would drop better weapons and not the low levels anymore.

like image 434
Kristof.V Avatar asked Jan 11 '16 00:01

Kristof.V


People also ask

How do you generate a random number between ranges 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 number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

How do you generate a random number from a list of numbers?

Note: If you want to generate random number based on a list, you can use this formula =INDEX($I$2:$I$7, RANDBETWEEN(1, 6)), and press Enter key.

How do you generate a random number between 1000 and 9999 in Java?

int randomNumber = ( int )( Math. random() * 9999 ); if( randomNumber <= 1000 ) { randomNumber = randomNumber + 1000; Math. random() is a method that generates a random number through a formula.


1 Answers

Xcode 11 • Swift 5.1 or later

extension Range where Bound: FixedWidthInteger {
    var random: Bound { .random(in: self) }
    func random(_ n: Int) -> [Bound] { (0..<n).map { _ in random } }
}

extension ClosedRange where Bound: FixedWidthInteger  {
    var random: Bound { .random(in: self) }
    func random(_ n: Int) -> [Bound] { (0..<n).map { _ in random } }
}

Note: For older Swift versions check the edit history

Usage:

(10...20).random    // 16
(0...1).random(10)  // [0, 1, 0, 0, 1, 1, 1, 1, 1, 0]
like image 189
Leo Dabus Avatar answered Oct 02 '22 11:10

Leo Dabus