Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: Random numbers

  1. #1
    Junior Member
    Join Date
    Jul 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Random numbers

    Hi All,

    I have been assigned a problem of generating set of random numbers. I found out that I could use java.util.Random class for the same. But the problem is, the generated numbers should not repeat. How can I assure this?

    Thanks In Advance!


  2. #2
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Random numbers

    Good morning Pooja Deshpande,

    How many random numbers do you need to generate?

    You could add each random number to an array and loop through to check the previous number hasn't already been added.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  3. #3
    Junior Member
    Join Date
    Jul 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random numbers

    thanks for the reply!

    Ya I can do that, but then it would overload on the system. the efficiency won't be good was what I thought. So was trying to know if there exists an algorithm or implementation(in Java) which doesnt generate duplicates?

  4. #4
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Random numbers

    Why would it overload on the system? You would have to be generating lots of numbers for that to be happening I think. How many numbers are you looking to generate?

    There is no built in method in java.util.Random not to print duplicates.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

  5. #5
    Junior Member
    Join Date
    Jul 2008
    Posts
    4
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Random numbers

    Oh ok... I guess I'm asking for too much

    I will implement it myself, and as you pointed out, the overload would be neglible, because I'm going to generate just 30-40 numbers.

    Thanks for the reply!

  6. #6
    Little Star
    Join Date
    May 2009
    Posts
    30
    Thanks
    0
    Thanked 9 Times in 7 Posts

    Default Re: Random numbers

    If you need to pick numbers in random order from x to y then I agree that using random function this way would be unefficient. There are several ways of doing this depending on how big is the range (y-x).

    One of them would be: You can use array from x to y, then go through it and mix number places using random function, then you will have numbers in random order.

    /**
     * I haven't checked if this code works, or if dosn't have any errors
     * so please use it more as a pseudocode than java code
     */
    //create array
    int[] array = new int[100];
    //lets populate our array
    for (int i=0; i<100;i++){
        array[i] = i;
    }
    for (int i=0; i<100;i++){
        //randomly generate new number
        int newPlace = Math.random()*100;
        //temporary place to hold current integer
        int temp = array[i];
        //move new integer to current place
        array[i] = array[newPlace];
        //move back current integer to the empty number place
        array[newPlace] = temp;
    }
    //now you have an array with random numbers from 0 to 99
    //pick first random number
    int first = array[0];
    //pick second random number
    int second = array[1];
    //pick last random number
    int last = array[99];
    }

    Also worth to mention that with very large numbers you will be using a lot of memory..

  7. #7
    Little Star
    Join Date
    May 2009
    Posts
    30
    Thanks
    0
    Thanked 9 Times in 7 Posts

    Default Re: Random numbers

    Quote Originally Posted by Pooja Deshpande View Post
    Oh ok... I guess I'm asking for too much

    I will implement it myself, and as you pointed out, the overload would be neglible, because I'm going to generate just 30-40 numbers.

    Thanks for the reply!
    You say that you will generate 30-40 numbers.. That is a lot if the range is just 40 numbers(f.e. from 1 to 40), and you would overload system. But if the range is one billion (f.e. from 1 to 1 000 000 000 000) Then you must be lucky to strike even one of those numbers twice. So for my second example you will have no system overload.

    So for us to be able to help you, you need to tell exactly what you need it for.

  8. #8
    Senile Half-Wit Freaky Chris's Avatar
    Join Date
    Mar 2009
    Posts
    834
    My Mood
    Cynical
    Thanks
    7
    Thanked 105 Times in 90 Posts

    Default Re: Random numbers

    Quote Originally Posted by Dalisra View Post
    If you need to pick numbers in random order from x to y then I agree that using random function this way would be unefficient. There are several ways of doing this depending on how big is the range (y-x).

    One of them would be: You can use array from x to y, then go through it and mix number places using random function, then you will have numbers in random order.

    /**
     * I haven't checked if this code works, or if dosn't have any errors
     * so please use it more as a pseudocode than java code
     */
    //create array
    int[] array = new int[100];
    //lets populate our array
    for (int i=0; i<100;i++){
        array[i] = i;
    }
    for (int i=0; i<100;i++){
        //randomly generate new number
        int newPlace = Math.random()*100;
        //temporary place to hold current integer
        int temp = array[i];
        //move new integer to current place
        array[i] = array[newPlace];
        //move back current integer to the empty number place
        array[newPlace] = temp;
    }
    //now you have an array with random numbers from 0 to 99
    //pick first random number
    int first = array[0];
    //pick second random number
    int second = array[1];
    //pick last random number
    int last = array[99];
    }

    Also worth to mention that with very large numbers you will be using a lot of memory..
    EDIT: If you choose to use this method then I suggest you use the Knuth Shuffle/Fisher-Yates Shuffle. The code that they present is as follows
    public static void shuffle (int[] array) 
        {
            Random rng = new Random();   // i.e., java.util.Random.
            int n = array.length;        // The number of items left to shuffle (loop invariant).
            while (n > 0) 
            {
                n--;                     // n is now the last pertinent index;
                int k = rng.nextInt(n + 1);  // 0 <= k <= n.
                if ( n != k )
                {
                    int tmp = array[k];
                    array[k] = array[n];
                    array[n] = tmp;
                }
            }
        }
    This is one of the best Shuffling methods out there, it presents the closest to real random as possible within a good exectution time.

    This approach is very good. However if you are looking for one that uses less memory but takes a little longer to execute then perhaps you could do something like this

    import java.util.Random;
     
    public class RandomGen {
    	public static void main(String[] args){
    		Random rng = new Random();
    		int n = 50, x;
    		boolean[] repeat = new boolean[n+1];
    		for(int i = 1;i<=n;){
    			x = rng.nextInt(n+1);
    			if(!repeat[x]){
    				repeat[x] = true;
    				System.out.println((i++) + ": " + x + " : " + repeat[x]);
    			}else x = rng.nextInt(n+1);
    		}
    	}
    }
    Which uses a boolean array which ofcouse saves on alot of space in comparision to an int array or even a long array if you are after bigger numbers. The downside is it may take more than one attempt to find a number that hasn't already been generated.

    Regards,
    Chris
    Last edited by Freaky Chris; June 5th, 2009 at 03:41 AM.

  9. #9
    mmm.. coffee JavaPF's Avatar
    Join Date
    May 2008
    Location
    United Kingdom
    Posts
    3,336
    My Mood
    Mellow
    Thanks
    258
    Thanked 294 Times in 227 Posts
    Blog Entries
    4

    Default Re: Random numbers

    Good post Chris.
    Please use [highlight=Java] code [/highlight] tags when posting your code.
    Forum Tip: Add to peoples reputation by clicking the button on their useful posts.

Similar Threads

  1. Generation of random number using random class
    By JavaPF in forum Java SE API Tutorials
    Replies: 1
    Last Post: December 7th, 2011, 05:46 PM
  2. [SOLVED] Random number method implementation
    By big_c in forum Java Theory & Questions
    Replies: 2
    Last Post: April 15th, 2009, 01:10 PM

Tags for this Thread