Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random Number In A Range

Tags:

java

random

ios

I have an app I am writing for iOS and Android. On startup I am trying to get a random number between 1 and 6.

iOS (Objective-C):

int random = rand() % (6 - 1) + 1;

Android (Java):

Random random = new Random();
int num = random.nextInt(6)+1;

In both cases they return 3 every time.

From other questions I have read, people are having the same issue because they are looping through randoms and keep reinstantiating the Random object. But I just want one random number, so I am only instantiating it once.

So, how can I get either of these pieces of code to get a number 1-6 instead of just 3?

like image 315
Ryan Avatar asked Apr 10 '26 19:04

Ryan


2 Answers

For the Objective-C part, I can tell you that you have to seed the random, like this:

srand(time(0)); // seed it using the current time

And for the Java part, the new Random() constructor automatically seeds it in the default JVM for desktop applications, but not on Android. On Android, it uses a default seed value.

Random rand = new Random(System.nanoTime());
like image 99
Martijn Courteaux Avatar answered Apr 12 '26 09:04

Martijn Courteaux


In Objective-C, you could alternately use the recommended arc4random() function that does not need to be seeded. You would use it like this:

int random = (arc4random() % 5) + 1;

A huge benefit of this function over rand() is that is has twice the range of rand(), thus allowing for "more random" numbers.

like image 34
pasawaya Avatar answered Apr 12 '26 10:04

pasawaya