0

I want to ask how to generate non repeating numbers in my buttons. I want to generate a non repeating number because whenever i run my project it shows all the same numbers.

Below is the code I have:

int arr1[]={1,2,3,4,5,6,7,8,9,10};
int num=(int)(Math.random()*10);
    one.setText(""+arr1[num]);
    two.setText(""+arr1[num]);
    three.setText(""+arr1[num]);

I want to know how to set the one,two and three buttons not having the same value if possible.

sealz
  • 5,348
  • 5
  • 40
  • 70
user2699948
  • 23
  • 1
  • 6

3 Answers3

3

Your code is nearly equivalent to :

int arr1[]={1,2,3,4,5,6,7,8,9,10};
int num = arr1[(int)(Math.random()*10)];
one.setText(""+num);
two.setText(""+num);
three.setText(""+num);

That's why you see 3 times the same number.

You should use Random#nextInt(int n) instead of your array and generate 3 random numbers :

Random r = new Random();
one.setText(Integer.toString(1 + r.nextInt(10)));
two.setText(Integer.toString(1 + r.nextInt(10)));
three.setText(Integer.toString(1 + r.nextInt(10)));

And if you want your numbers to be non-repetitive, you can for example use a Set :

Random r = new Random();
Set<Integer> randomNumbers = new HashSet<Integer>();
while(randomNumbers.size() <= 3){
  //If the new integer is contained in the set, it will not be duplicated.
  randomNumbers.add(1 + r.nextInt(10));
}
//Now, randomNumbers contains 3 differents numbers.
Arnaud Denoyelle
  • 29,980
  • 16
  • 92
  • 148
1

In android you can generate a random number like this. If needed you can use a min and max instead of an array.

int min = 1;
int max = 10;
Random r = new Random();
int someRandomNo = r.nextInt(max - min + 1) + min;
one.setText(""+someRandomNo);

To double check that you dont get the same random number you will just need some logic that checks if it has already been generated. You can stick to your array and remove that number before the next call. Or just check a stored integer before you call again if you use min and max.

sealz
  • 5,348
  • 5
  • 40
  • 70
0
private int previous = -1000; // Put a value outside your min and max

/**
 * min and max is the range inclusive
 */
public static int getRandomNumber(int min, int max) {

    int num;

    do {

        num = min + (int)(Math.random() * ((max - min) + 1));

    } while(previous == num); // Generate a number that is not the same as previous

    previous = num;

    return num;    
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74