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

Thread: how to ensure that my method wont return the same random number twice in a row

  1. #1
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default how to ensure that my method wont return the same random number twice in a row

    I want to use this idea in a different context but for the sake of the argument lets suppose I have this method:

     
    public int random number(int range)
    {
        Random rand = new Random();
        int randomNumber = rand.nextInt(range);
                                .
                                .
                                .
        return randomNumber;
    }

    Any suggestions how to avoid getting the same random number twice in a row?


  2. #2
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    The simple way would be to remember what value you returned the last time.
    When your method is called again and the random value you got is the same as last time you simply produce another random number.

    In theory this could (in the worst case) end with an infinite loop and your problem will crash.
    In practice this is pretty much impossible.

  3. #3
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    Well, not in theory... trying to solve this problem with a similar idea, I declared a field inside the class to hold the result of the previous returned number and use that in a condition statement so that to generate a new random number if they match, but I came to a dead end because of the possibility to get again the same random number and so on and so on.... When I tried to use a loop it crushed ... Actually I am trying this all day and no result...
    But this is part of an exercise in the book I am studding so It should be a way...

  4. #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: how to ensure that my method wont return the same random number twice in a row

    There's more than one way, but one is to use a Set to hold the random numbers generated. Attempting to add. add()ing each new random number as it is created will return either false, indicating that the number already exists in the Set, or true, a new random number has been created. Checking the size of the set should also indicate when all possible random numbers in a range have been created.

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

    bihlas (July 7th, 2014)

  6. #5
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    My concern was not to return the same random number twice in the row and not to ensure that the same random number wont be returned at all...
    Do you have any suggestion to that?
    To put you in the context of my exercise I will explain exactly what I want:
    The project is a technical support system that generates a response according to users question for a software they have purchased.
    When the user's input doesn't contain any word that is being used as key to a hashMap in order to generate the related response that is being held as a value to that key, it generates a random response from several ones that are stored in an Arrayylist. The exercise is to ensure that the same random response is never repeated twice in a row.
    Below are the related methods method:
     
        public String generateResponse(HashSet<String> words)
        {
            for(String word : words) {
                String response = responseMap.get(word);
                if(response != null) {
                    return response;
                }
            }
            return pickDefaultResponse();
        }
     
     public String pickDefaultResponse()
        {
            int r = randomGenerator.nextInt(defaultResponses.size());
            return defaultResponses.get(r);
     
        }

    the pickDefaultResponse is that I have to modify so that it wont generate the same result twice in a row. Any suggestions how to do that?

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    See post#2.
    If you don't understand my answer, don't ignore it, ask a question.

  8. #7
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    You mean is impossible? I cant understand why a book has an exercise that it has no possible solution.... It mentions though that it is a quite challenging programming exercise...

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    No, it is definitely possible. Save the last value and compare against the current value.
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Junior Member
    Join Date
    Jun 2014
    Posts
    22
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    And if it is the same generate a new random number? And if it is the same again? generate a new and so on...

    Anyway I am giving up, I cant short this out in a definite manner, I can ensure that it wont most likely generate the same response twice in a row but not definitely.

    Gregg if you read this I am trying to do your suggestion as an exercise. I am using a HashSet but I realized that it doesn't except int as a type....?
    p.s. I turned every int into a string and it worked as hashSet of Strings....
     public void printOneRandom(int range)
        {
           HashSet<String> randomSet = new HashSet<String>();
            for(int index = 0; index < range; index++) {
                int r = rand.nextInt(range);
                String s = r + "";
                if(!randomSet.contains(s)) { 
                    randomSet.add(s);
                    System.out.println(s);
                }
                else {
                    index--;
                }
            }
        }
    I checked it and it is right I will try to apply this idea to my pickDefaultResponse method....
    Last edited by bihlas; July 7th, 2014 at 02:16 PM.

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    it wont most likely generate the same response twice in a row
    To see: Write a small test program that gets a large number of random numbers and test how often there were two in a row that were the same.
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Senior Member
    Join Date
    Jul 2013
    Location
    Europe
    Posts
    666
    Thanks
    0
    Thanked 121 Times in 105 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    Here is some pseudo code for my solution from post #2:

    1) generate random number i
    2) check against previous random number
    3) if equal, go to 1)
    4) save i as "new" previous number
    5) return i




    A different approach would be:

    1) generate random number i
    2) check against previous random number
    3) if equal increment i by 1
    4) save i as "new" previous number
    5) return i

    This way you would definitely always return, even in the worst case. I would still argue, that the result is random.

  13. #12
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: how to ensure that my method wont return the same random number twice in a row

    Quote Originally Posted by Cornix View Post
    A different approach would be:

    1) generate random number i
    2) check against previous random number
    3) if equal increment i by 1
    4) save i as "new" previous number
    5) return i

    This way you would definitely always return, even in the worst case. I would still argue, that the result is random.
    This was my initial idea, also, but it fails because the returned value might now be out of range. A fix would only get messy, because there could be a very narrow range and whatnot.

  14. #13
    Forum VIP
    Join Date
    Jul 2010
    Posts
    1,676
    Thanks
    25
    Thanked 329 Times in 305 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    the returned value might now be out of range.
    Then make i the lowest possible number if it goes out of range. That way you would cover the entire range. If the entire range has been used, you would have to throw an exception or something.
    NOTE TO NEW PEOPLE LOOKING FOR HELP ON FORUM:

    When asking for help, please follow these guidelines to receive better and more prompt help:
    1. Put your code in Java Tags. To do this, put [highlight=java] before your code and [/highlight] after your code.
    2. Give full details of errors and provide us with as much information about the situation as possible.
    3. Give us an example of what the output should look like when done correctly.

    Join the Airline Management Simulation Game to manage your own airline against other users in a virtual recreation of the United States Airline Industry. For more details, visit: http://airlinegame.orgfree.com/

  15. #14
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,140
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: how to ensure that my method wont return the same random number twice in a row

    Step 3) needs to be extended to "wrap" the value to lower end of range when past end.
    Or use modulus
    If you don't understand my answer, don't ignore it, ask a question.

  16. #15
    Member
    Join Date
    Jun 2014
    Posts
    33
    My Mood
    Inspired
    Thanks
    9
    Thanked 1 Time in 1 Post

    Default Re: how to ensure that my method wont return the same random number twice in a row

    I'm throwing my two pence in. Would this work?
    int previousRand = 0;
    int newRand = 0;
    Random rand = new Random();
     
    int getAnotherRand(int range){
    	if(range == 0) {
    		return 0;
    	}
    	while(previusRand == newRand) {
    		newRand = rand.nextInt(range);
    	}
    	previousRand = newRand;
    	return newRand;
    Another variant:
    int getAnotherRand(int range) {
    	newRand = rand.nextInt(range);
    	if(range == 0) {
    		newRand = getAnotherRand(1);
    	}
    	else if(newRand == previousRand) {
    		newRand = getAnotherRand(range);
    	}
    	previousRand = newRand;
    	return newRand;
    }
    Safeguard included in both examples for illegal ranges (of zero) and thus the risk of perpetual looping.
    Last edited by Baldyr; July 8th, 2014 at 11:43 AM.

Similar Threads

  1. Replies: 2
    Last Post: December 13th, 2013, 12:01 AM
  2. How do you add a value to a 2-d array by row number and column number?
    By JohnEliot in forum Java Theory & Questions
    Replies: 1
    Last Post: April 14th, 2013, 06:39 AM
  3. How do I return the current number of trades(number) from an array?
    By lovely92 in forum What's Wrong With My Code?
    Replies: 4
    Last Post: December 12th, 2012, 06:15 PM
  4. Need help my values wont return
    By sajeed in forum What's Wrong With My Code?
    Replies: 6
    Last Post: January 7th, 2012, 08:46 AM
  5. Generation of random number using random class
    By JavaPF in forum Java Code Snippets and Tutorials
    Replies: 0
    Last Post: April 16th, 2009, 06:10 AM