Hi,

I was wondering how do i go about generating unique random numbers?
ie
i want to generate numbers between 0-9 randomly. I dont want to repeat the numbers.Then that no: should display on the buttons.ie there are 9 buttons. first randomly generated number should display on the first button & 2nd no: should display on 2nd button. & so on for example I have the numbers 9371482065 then 9 should display on the first button ,3 should display on 2nd button ....
But the following code i'm having is repeating some numbers...can any one help me in solving...please.....

code::::


        Random rgen = new Random();  // Random number generator
        int[] cards = new int[10];  

//      --- Initialize the array to the ints 0-51
        for (int i=0; i<10; i++) {
            cards[i] = i;
        }

//      --- Shuffle by exchanging each element randomly
        for (int i=0; i<10; i++) {
            int randomPosition = rgen.nextInt(10);
            System.out.println(" randomPosition   " + randomPosition);
            int temp = cards[i];
            System.out.println(" temp" + temp);
            cards[i] = cards[randomPosition];
            cards[randomPosition] = temp;

            System.out.println(" Random Number" + cards[randomPosition]);

        }

Dani AI

Generated

Good news: your array shuffle is the right idea, but the “duplicates” you saw are almost certainly from printing while the shuffle is in progress. You were logging values at changing positions, not the final order. Shuffle first, then write the results to the buttons. Also note 0..9 is 10 digits; if you only have 9 buttons, use 0..8 or ignore one digit. is right to use a single Random; recreating it repeatedly can look non-random. ’s boolean-array approach works but is more work than needed when you want a permutation. And , careful: while(count < 11) with a 10-element array will throw an ArrayIndexOutOfBounds.

Java (uniform Fisher-Yates) and mapping to buttons:

// digits 0..9 without repeats, then assign to buttons
int[] digits = {0,1,2,3,4,5,6,7,8,9};
Random r = new Random(); // reuse this, e.g., as a field

for (int i = digits.length - 1; i > 0; i--) {
    int j = r.nextInt(i + 1);          // pick from [0, i]
    int t = digits[i]; digits[i] = digits[j]; digits[j] = t;
}

// now set labels; if you have 9 buttons, only take the first 9
for (int i = 0; i < Math.min(buttons.length, digits.length); i++) {
    buttons[i].setText(Integer.toString(digits[i]));
}

Since the thread is tagged javascript too, here is the same idea in JS. Avoid array.sort(() => Math.random() - 0.5); it is biased.

const digits = Array.from({length: 10}, (_, i) => i);

// Fisher-Yates
for (let i = digits.length - 1; i > 0; i--) {
  const j = Math.floor(Math.random() * (i + 1));
  [digits[i], digits[j]] = [digits[j], digits[i]];
}

// assign to an array/NodeList of buttons
buttons.forEach((btn, i) => { if (i < digits.length) btn.textContent = digits[i]; });

Side note for : in Swing, 100 buttons in a grid are easy with new GridLayout(10, 10).

Recommended Answers

All 8 Replies

Are you creating the Random object each time that method is called? The Random object should bounce around and hit every number before repeating itself.

Suppose you want to generate 50 unique random numbers from 0 to 100.

//Create an array of size 100 that remembers which integers are taken
boolean[] taken = new boolean[100];

//start count at 0
int count =0;

//create random gen
Random r = new Random();

//create array to hold 50 unique random numbers
int[] uniqueRNums = new int[50];

//begin the loop, stop when got 50 unique random numbers
while(count < 50)
{
     //get random integer 0-100
     int rNum = r.nextInt(100);

     //check if it is taken
     if(!taken[rNum] )
     {
        //mark as taken
        taken[rNum] = true;

        //add to unique random numbers list
        uniqueRNums[count]=rNum;

        //update count
        count++;
     }
}

Hope this helps.

:?: For more help,

Hi

thanks. it worked. Thanks once again

And what did you learn by slavishly copying it?
Nothing at all.

Hi this is Program .. without Creating the Random object each time and without Boolean Array...

// Random 1-10 Numbers..
import java.lang.*;
import java.util.*;

class rand{
    public static void main(String args[]) {
        int arr[] = new int[10];
        int count = 0;
        boolean found;
        Random r=new Random();  

        while(count < 11) {
             int num=r.nextInt(10); 
            found = false;

            for(int i = 0; i < count; i++)
                if(arr[i] == num){
                    found = true;
                    break;
                }

            if(found==false){
                System.out.println(num);
                arr[count++] = num;
            }
        }
    }   
}

I'm sorry, but, why did you ressurrect this two year old thread?

because it's a lazy kid that wants its homework done for free. It's also spamming me with PMs and resurrecting other threads.

Hello Sir,

I am doing a small mini project for my college and i need code on how to create a minimun of hundred buttons placed in a grid.

you will be a lifesaver if you can provide me with this little task

Thanking You.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.