I have a 12 digit number in which first 8 digits are fixed but last 4 digits(number) i want to be different,It gives me range(0000-9999). Problem is this script may run 2-3 times daily or different days as well. If i use random function it might happen one number which is generated today is same as tomorrow's. Any solution to get different 4 digit number every-time/everyday.
Asked
Active
Viewed 901 times
1
-
3Why should you use random here? Just count from 0 to 9999 and store somewhere, what the last used number was. – Tom May 06 '16 at 12:50
-
Possible duplicate of [Generating Unique Random Numbers in Java](http://stackoverflow.com/questions/8115722/generating-unique-random-numbers-in-java) – vefthym May 06 '16 at 12:56
2 Answers
1
You can't compress a time uniquely down to a 4 digit number so that approach can be immediately eliminated.
What you need to do is to store a count somewhere. Start from 0. Your script needs to increment that stored number, perform its task, then store the incremented value. If that value reaches 10000 then you've reached your capacity limit for your scheme.
If you need the scheme to appear random to your users, then map that consecutive scheme to a shuffled set of numbers solely for the purpose of constructing the 12 digit number.

Bathsheba
- 231,907
- 34
- 361
- 483
0
I know this may not be what you want but this is a method I made which generates a random number from the time and a couple arrays, manipulate and use it if you can :)
import java.text.*;
import java.util.*;
public class Randomizer {
public void randomizer() throws InterruptedException {
Randomizer r = new Randomizer();
int[] numbers = { 3, 7, 2, 62, 1, 53, 16, 563, 12, 13, 75 };
Calendar rightNow = Calendar.getInstance();
int hour = rightNow.get(Calendar.HOUR_OF_DAY);
int minute = rightNow.get(Calendar.MINUTE);
int seconds = rightNow.get(Calendar.SECOND);
int[] numbers2 = { 10, 32, 61, 2, 5 };
int[] date = { hour, minute, seconds };
int RandomNumber = (r.getRandom(date) * r.getRandom(numbers)) + r.getRandom(numbers2);
System.out.println("Random number generated: " + RandomNumber);
}
public static int getRandom(int[] array) {
int rnd = new Random().nextInt(array.length);
return array[rnd];
}
public static void main(String[] args) throws InterruptedException {
Randomizer r = new Randomizer();
r.randomizer();
}
}

Nathan Marotta
- 136
- 12
-
if this you have questions ask, if this code has no relevance in your situation please tell me. – Nathan Marotta May 06 '16 at 13:31
-
@Nathan-Thank you so much for this program. The only point is it is generating 3 digits number but i want 4 digits only. – sunny May 09 '16 at 11:43
-
@sunny manipulate it as you want for use, if this was the answer you were looking for than please click the checkmark and upvote so the question will be closed, any other questions don't hesitate in asking me or the community :) – Nathan Marotta May 09 '16 at 18:06