Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating random Bool in Swift

I'm needing to create a random bool value in my game, in Swift.

It's basically, if Yes (or 1), spawn one object, if No (or 0), spawn the other.

So far, looking at this question and a similar one on here, I found this:

let randomSequenceNumber = Int(arc4random_uniform(2)) 

Now it works, but it seems bias to 0 to me... like ridiculously bias...

This is how I'm then using the value:

if(randomSequenceNumber == 0)     //spawn object A else     //spawn object B 

Is there a better way to implement this using a random bool value? That isn't bias to a certain value?

Update

Bit of an experiment to see how many 1's vs 0's were were generated in 10,000 calls:

func experiment() {     var numbers: [Int] = []     var tester: Int = 0     var sum = 0      for i in 0...10000 {         tester = Int(arc4random_uniform(2))         numbers.append(tester)         print(i)     }      for number in numbers {         sum += number     }      print("Total 1's: ", sum) }  Test 1: Console Output: Total 1's: 4936 Test 2: Console Output: Total 1's: 4994 Test 3: Console Output: Total 1's: 4995 
like image 670
Reanimation Avatar asked Dec 12 '15 14:12

Reanimation


People also ask

How do you generate random 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.

What is arc4random_uniform Swift?

Swift has three typical functions for random numbers: arc4random() returns a random number between zero and 232–1. arc4random_uniform(_:) returns a random number between zero and the first parameter, minus one. drand48() returns a random Double between 0.0 and 1.0.


2 Answers

Xcode 10 with Swift 4.2

Looks like Apple  engineers are listening

let randomBool = Bool.random() 
like image 102
Warif Akhand Rishi Avatar answered Sep 28 '22 04:09

Warif Akhand Rishi


import Foundation  func randomBool() -> Bool {     return arc4random_uniform(2) == 0 }  for i in 0...10 {     print(randomBool()) } 

for more advanced generator the theory is available here

for basic understanding of Bernoulli (or binomial) distribution check here

like image 22
user3441734 Avatar answered Sep 28 '22 04:09

user3441734