-2

I need to generate random numbers in 6 different edittext. Unfortunately the random numbers duplicates. I need unique numbers from the range I set.

        rndNumber = rndNumbers.nextInt(max);
        num1.setText(Integer.toString(rndNumber));


        rndNumber = rndNumbers.nextInt(max);
        num2.setText(Integer.toString(rndNumber));

        rndNumber = rndNumbers.nextInt(max);
        num3.setText(Integer.toString(rndNumber));

        rndNumber = rndNumbers.nextInt(max);
        num4.setText(Integer.toString(rndNumber));

        rndNumber = rndNumbers.nextInt(max);
        num5.setText(Integer.toString(rndNumber));

        rndNumber = rndNumbers.nextInt(max);
        num6.setText(Integer.toString(rndNumber));
belladonna
  • 175
  • 2
  • 11
  • 2
    I'm confused about this: `int nbr = 1; nbr < 2;`. Doesn't that just execute it once, as if the `for` loop was not even there? –  Jun 20 '13 at 03:03
  • My answer below addresses all of the things you mentioned and does exactly what you asked. –  Jun 20 '13 at 03:55

5 Answers5

2

Wrap the random number generator to store the results in a set. When you generate a number if it exists in the set, do it again:

Comments made by others about the for loops are also valid...

pseudo code:

class MyRandomNums {
    Set<Integer> usedNums;

    public int getRandom()
    {
        int num = random.nextInt();
        while(usedNums.contains(num)) {
            num = random.nextInt();
        }
        usedNums.add(num);
        return num;
    }

    public int reset()
    {
        usedNums.clear();
    }
}
John3136
  • 28,809
  • 4
  • 51
  • 69
  • OP should be aware that this is a non-deterministic approach (there's a small chance that `getRandom()` will never finish). As the set size increases and becomes full, the execution time will increase quite rapidly. – Anti Earth Jun 20 '13 at 03:07
  • @AntiEarth is 99% correct - especially if you are trying to use a range (i.e. 1 to 6 : once you pick 6 numbers you are guaranteed an infinite loop since you have exhausted the range). - easy to detect if you have a set range. Much harder if you don't... Why 99% and not 100? IMHO this is still deterministic (else please explain why it isn't - I'm more a computer guy than a maths guy) – John3136 Jun 20 '13 at 03:09
  • "[Determinism states that] for everything that happens there are conditions such that, given those conditions, nothing else could happen." Consider the condition of having only 1 vacancy in `usedNums`, and the event is the number of random numbers generated (or running time). The outcome (in terms of time) is entirely probabilistic (assuming a purely random number generator, of course. I suppose it **has** to be deterministic in our computers); the number of random numbers generated to fill that last vacancy is not constant across trials (same preconditions, different post). – Anti Earth Jun 20 '13 at 03:33
  • @AntiEarth if you seed the RNG with the same value each time, it would be deterministic wouldn't it? (since the RNG will be a psueso RNG that should generate the same sequence) – John3136 Jun 20 '13 at 03:36
  • Yeah definitely, but if you confine the preconditions to being the state of `usedNums` or the numbers already generated, it's probabilistic (and they're really what matter in terms of the method actually returning; they're what drive the running time) – Anti Earth Jun 20 '13 at 03:43
  • I would also recommend initializing `usedNums` before you get `NullPointerException`s and changing the return-type to void on `reset` –  Jun 20 '13 at 03:53
0

All of your for-loops loop once. Why:

for (int nbr = 1; nbr < 2; nbr++) {
    rndNumber = rndNumbers.nextInt(max);
    num1.setText(Integer.toString(rndNumber));
}

when you can just do:

rndNumber = rndNumbers.nextInt(max);
num1.setText(Integer.toString(rndNumber));

?

Ken
  • 30,811
  • 34
  • 116
  • 155
0
int min = 0;
int max = 100;
List<Integer> randoms = new ArrayList<Integer>();
for(int i = min; i <= max; i++) randoms.add(i);
Collections.shuffle(randoms);

Then you can use it like this:

int randomNumber = randoms.remove(0);
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

Here's one way to do all of the things you mentioned:

private static boolean arrayContainsInt(int array[], int val, int x) {
    for(int i = 0; i < x; i++) {
        if(array[i] == val) {
            return true;
        }
    }
    return false;
}

public static int[] randomNumbers(int count, int minInclusive, int maxNonInclusive) {
    int randoms[] = new int[count];
    Random rand = new Random();
    int impossibleValue = minInclusive - 1;
    for(int i = 0; i < randoms.length; i++) {
        randoms[i] = impossibleValue;
    }
    for(int x = 0; x < count; x++) {
        int thisTry = impossibleValue;
        while(thisTry == impossibleValue || arrayContainsInt(randoms, thisTry, x)) {
            thisTry = (int)(rand.nextFloat() * (float)(maxNonInclusive - minInclusive)) + minInclusive;
        }
        randoms[x] = thisTry;
    }
    return randoms;
}

If you're wondering about speed, here are some stats:

randomNumbers(1000, 0, 10000) ==> 16 milliseconds

(1000 random num. from 0->10,000 with no repeats)

randomNumbers(10000, 0, 10000) ==> 207 milliseconds

(Every number from 0->10,000 generated in random order)

The randomNumbers method is supplied the number of random integers to generate, the minimum value (inclusive), and the maximum value (non-inclusive) and returns an array of randoms given the supplied parameters.

Note: if the count parameter provided is greater than the value of maxNonInclusive - minInclusive then it will loop infinitely, simply because you cannot come up with more integers than the range provides.

Also, arrayContainsInt is sent the x parameter as value following the maximum index in the array to check because only x many elements of the array have been populated, so checking the rest is pointless.

0

for alpha numeric number try this

public String getRandomNum(int randomLength)
{   
    return new BigInteger(130, random).toString(32).toUpperCase().substring(0, randomLength);
}

if you want only numeric random number try this

public String getRandomNum(int randomLength)
{
    int value = (int)(Math.random() * 9999);
    String format = "%1$0"+randomLength+"d";
    String randomNum = String.format(format, value);
    return randomNum;
}
Ram kiran Pachigolla
  • 20,897
  • 15
  • 57
  • 78