How to Generate Random Number in Specific Range in Android

How can I generate a random number in a certain range?

To extend what Rahul Gupta said:

You can use Java function int random = Random.nextInt(n).

This returns a random int in the range [0, n-1].

I.e., to get the range [20, 80] use:

final int random = new Random().nextInt(61) + 20; // [0, 60] + 20 => [20, 80]

To generalize more:

final int min = 20;
final int max = 80;
final int random = new Random().nextInt((max - min) + 1) + min;

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

Android: Random Number list to an actual number

Quick and nasty solution. You could also create a method that will take your final ArrayList and join the contents together into a String using a similar process like I've shown. A method like this may already exist, but I don't know what it will be called.

Random rand = new Random();

ArrayList<Integer> randNumber = new ArrayList<Integer>();
StringBuilder newNumber = new StringBuilder();
for (int i = 0; i < 11; i++) //randNumber.add(i);
{
int number = rand.nextInt(10);
randNumber.add(number);
newNumber.append(number);
Log.d("random", "number:" + number);
Log.d("Random", "list" + randNumber);
}

//this.setResultData("12345678910");
this.setResultData(newNumber.toString());

final String newNumber = this.getResultData();

How to generate random numbers so that every number only occurs once?

run { nextnumberbutton } doesn't do anything. It's a lambda that will simply return Unit.

Supposing you did call the click listener again when a repeated number is found, you would still be adding the number to the list again, since you don't return from the function early. So you would end up with duplicates in your list.

Your strategy could be done with a while loop instead of calling the whole function again when a duplicate is picked. e.g. you could use while (rand !in arrayList) rand = Random.nextInt(75). However, this has the potential to take longer and longer to pick the number as you approach the limit of values because it is simply guessing numbers and has to try again if the number is already picked.

A better strategy would be to start with a set of all the numbers and remove from this set as you go. You also need to handle the case of when all numbers are picked, perhaps by showing a message to the user.

val unpickedNumbers = (0..75).toMutableSet()

nextnumberbutton.setOnClickListener {
if (unpickedNumbers.isEmpty()) {
Toast.makeText(context, "All numbers already picked", Toast.LENGTH_LONG).show()
return
}
val rand = unpickedNumbers.random()
numbertextview.text = rand.toString()
unpickedNumbers.remove(rand)
}


Related Topics



Leave a reply



Submit