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 10 of 10

Thread: Generating random numbers in java without repeating a specific number

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Generating random numbers in java without repeating a specific number

    Let say i have this code:
    public class MyRandomStuff {
     public static void main (String[]args) {
     
      int [] randomNumbers = new int[5];
     
    for (int i=0; i<randomNumbers.length; i++) {
       randomNumbers[i] = (int)(Math.random()*20)+1;
    System.out.println(randomNumbers[i]);
    }
    }}

    This program generates 5 random numbers within the range of 1-20.
    My question is, is it possible to prevent the program from generating let's say 5,12 12, 3,1 (prevent it from generating a number twice? in this case 12)


  2. #2
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Generating random numbers in java without repeating a specific number

    No, you can't prevent the random number generator from generating specific numbers within the specified range.

    There are other ways to accomplish what you describe.

    Approach 1: Add the resulting random numbers to a set. If accepted (returns true), the random number has not been previously chosen. Otherwise, choose another random number.

    Approach 2: Consider dealing from a deck of cards. If the cards are shuffled, dealing the cards in order results in as many "random" cards as desired. Or, if the cards are not shuffled, dealing cards from random locations in the deck accomplishes the same thing.

    Following the card example, to simulate selecting a random number from a specific range of 20 unique values without repeating, create an array of 20 numbers in the desired range. Randomly select an index 0 - 19, select the value at that index (deal it), swap that value for the value in the last index, and reduce the range by 1. For example (using a range of 10 values):

    randomArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]

    Choose an index randomly from 0 through 9: 6
    Select the number at that index: 7
    Swap index 6 with index 9: randomArray = [ 1, 2, 3, 4, 5, 6, 10, 8, 9, 7 ]
    Reduce the range by 1: 0 through 8.

    Repeat as needed.

  3. The Following User Says Thank You to GregBrannon For This Useful Post:

    ojonugwa (August 25th, 2013)

  4. #3
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: Generating random numbers in java without repeating a specific number

    Thanks.I have moved away from this problem as i now understand i cannot prevent the random number generator from generating a specific number twice.

  5. #4
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,517
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: Generating random numbers in java without repeating a specific number

    Sometimes we move away from one problem and end up next door to another one. Possible solutions to this "problem" are in my response.

  6. #5
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: Generating random numbers in java without repeating a specific number

    Quote Originally Posted by GregBrannon View Post
    Sometimes we move away from one problem and end up next door to another one. Possible solutions to this "problem" are in my response.
    Okay.I'll get right to it.

    --- Update ---

    Ok so am working using Sets now (for the first time) and i discovered it does not allow duplicates which is good.but problem is,when i run the code over and over again, i get varying sizes. for example: (i specified a size of 7)
    at first run [4,8,9]
    second run [5,2,1,3,6,7,8]
    third run [4,7,3,2,]
    why does the size change?

  7. #6
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: Generating random numbers in java without repeating a specific number

    Quote Originally Posted by ojonugwa View Post
    why does the size change?
    There is a tree blocking my view of your screen, so I can not see your code.
    Crystal ball says the size varies because duplicate numbers are omitted and the loop runs a specific number of times only.
    So if you say 7, and two numbers were duplicates the end result is 5.
    If you need more help, post the code in question

  8. The Following User Says Thank You to jps For This Useful Post:

    ojonugwa (August 25th, 2013)

  9. #7
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: Generating random numbers in java without repeating a specific number

    I have found that this is the case.

  10. #8
    Member
    Join Date
    Jul 2013
    Posts
    47
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Generating random numbers in java without repeating a specific number

    EDIT: Ignore this post. I misunderstood what the OP wanted and created a solution to a problem that didn't exist. I'll take a look later and see if I can come up with something - I have a vague idea in my head but if these other people say it's not possible, it's probably not, considering they know WAY, WAY more than I do lol.

    -summit45

  11. #9
    Grand Poobah
    Join Date
    Mar 2011
    Posts
    1,545
    My Mood
    Grumpy
    Thanks
    0
    Thanked 167 Times in 158 Posts

    Default Re: Generating random numbers in java without repeating a specific number

    You get Sets of varying size because you generate N numbers not N unique numbers. Use a Set of 3 for example: if RNG gives a 4 it is added to the Set. Then 9 is generated and added. Then 4 is generated again and not added. That's 3 numbers generated but only 2 are in the Set.
    Improving the world one idiot at a time!

  12. #10
    Junior Member
    Join Date
    Aug 2013
    Posts
    26
    My Mood
    Where
    Thanks
    8
    Thanked 1 Time in 1 Post

    Default Re: Generating random numbers in java without repeating a specific number

    cool.

    --- Update ---

    Found a solution (?) to the problem.
    ...
    ArrayList <Integer> numbers = new ArrayList<Integer>();
    int position=0;
    int maxNum= 0;
     
     for (i=0; i<5;i++) {
          numbers.add((int)(Math.random()*10)+1);  
        }
     
     for (i=0;i<numbers.size();i++){
            if (numbers.get(i) > maxNum) { 
                position=i;
                maxNum = numbers.get(i);
            }
        }
     
        numbers.remove(position); //removes the index that contains the maximum number along with the value in it
     
        System.out.println("Maximum number: " +  maxNum);
     
        System.out.println("Found max at index " + position);
     
       //what this does is iterate through the NEW set of numbers after the maximum has been removed, and it finds the same number,it simply removes it.
     
        for (i=0;i<numbers.size();i++){
            if (numbers.get(i) == maxNum) { 
                position=i;
                numbers.remove(position);
               //maxNum = numbers.get(i);
            }
        }

Similar Threads

  1. Replies: 5
    Last Post: November 29th, 2012, 01:25 PM
  2. [SOLVED] Java- Non repeating random questions.
    By arkaneraven in forum Java Theory & Questions
    Replies: 4
    Last Post: June 15th, 2011, 09:55 AM
  3. Generating a Random Coprime Number
    By phleep in forum What's Wrong With My Code?
    Replies: 0
    Last Post: March 15th, 2011, 12:12 AM
  4. Generating random numbers
    By abelned in forum Object Oriented Programming
    Replies: 1
    Last Post: September 1st, 2010, 07:24 AM
  5. Generating random letters and numbers together
    By newJava in forum Java Theory & Questions
    Replies: 3
    Last Post: March 19th, 2010, 04:08 AM