how to generate random numbers from 1 to 4 and 8 in swift

607 Views Asked by At

I'm making an iOS SpriteKit game right now for first time I'm developing any app and it's tough challenge for me because it's really a big project for first time. My game is a Dice game and I defined move as 4 number. So when ever I touch the screen Player moves 4 blocks, But now I want to add Dice to the Game and I need Numbers from 1 to 4 and 8. So it will be 1,2,3,4 and 8 Numbers in the Dice. I know in Swift we can get Random Numbers with "arc4random" but how do I get numbers 1 to 4 and also 8 can I do it with arc4random and if possible I need 4 and 8 numbers to come 20% more often. Any Help will be really Helpful. Thanks.

2

There are 2 best solutions below

0
vacawama On BEST ANSWER

Put your sides into an array and use randomElement() to perform the roll:

let sides = [1, 2, 3, 4, 8]
let roll = sides.randomElement()!

if possible I need 4 and 8 numbers to come 20% more often

That means, 4 and 8 should come up 6 times for every time the others come up 5. So put 5 of each of 1-3 in your array, and 6 each of 4 and 8:

let sides = [1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 8, 8, 8, 8, 8, 8]
let roll = sides.randomElement()!

Note: It is perfectly safe and appropriate to force unwrap the result of randomElement() with ! here because randomElement() only returns nil when the collection is empty, and we know it’s not.


Also, check out MartinR's randomNumber(probabilities:) function.

You'd use his function like this:

let sides = [1, 2, 3, 4, 8]
let probabilities = [1.0, 1.0, 1.0, 1.2, 1.2]

let rand = randomNumber(probabilities: probabilities)
let roll = sides[rand]
1
Saifur Rahman Sany On

You can generate a random number from 1-8, and if 5,6,7 comes, you can run the random number function again until an acceptable value. Its kinda a workaround, but it works because the dataset is small.