I generate a random number with this code :
int randomNumber = (int) (Math.random() * 7);
I want to stop generating duplicate numbers and I want to generate a new number after my app opens again.
how can I do ?
Store the numbers you generate in a Set
. Then every time you generate a new random number, test that it's not already present in this Set
.
Set<Integer> nums = new HashSet<Integer>();
// Initialize set on app boot
int rnum;
do {
rnum = (int) (Math.random() * 7);
} while (!nums.contains(rnum));
// Update the set
nums.add(rnum);
// Use rnum now..
You'll also need to persist the Set
values before your app shuts down; in onPause()
or onStop()
method. You could use SharedPreferences
or simply serialize/deserialize the Set
. Using a database would be an overkill.
Here's one way you could ensure there are no duplicates;
public int generateRandomNumber(){
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
final int lastNumber = sp.getInt("lastNumber", 0);
int randomNumber = (int) (Math.random() * 7);
while(randomNumber == lastNumber){
randomNumber = (int) (Math.random() *7);
}
sp.edit().putInt("lastNumber", randomNumber).apply();
return randomNumber;
}
Edit: Here is a dumb way to do what you want:
String _p = sp.getString("previousNumbers", "");
String[] previousNumbers = _p.split(";");
int randomNumber = (int) (Math.random() * 7);
while(Arrays.asList(previousNumbers).contains(Integer.toString(randomNumber))
{
randomNumber = (int) (Math.random() * 7);
}
_p.concat(Integer.toString(randomNumber) + ";");
sp.edit().putString("previousNumbers",_p).apply();
return randomNumber;
To generate distinct value at every app open you can use
System.currentTimeMillis()
This will return a long
instead of int
Step 1: create array
Step 2: Fill array with proper numbers
Step 3: Shuffle array.
private Integer[] randomNumbersRange(int numberRange) {
//Create and shuffle array
Integer[] randomNumbers = new Integer[numberRange];
for (int i = 0; i < randomNumbers.length; i++) {
randomNumbers[i] = 1 + i;
}
Collections.shuffle(Arrays.asList(randomNumbers));
return randomNumbers;
}
Perhaps check out seeding your number with the system timestamp, or some other value you persist outside the application (in storage / a db / etc).
https://developer.android.com/reference/java/util/Random.html#setSeed(long)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.