0

I'm a beginner in Java and I'm stuck on how to make a working random number generator that has no duplicates (ie. create lotto numbers in a certain range). I know how to display a menu through JOptionPane and also accepting a user input through showInputDialog, but the generator has me stumped for days. Would I need to use loops and use other methods within my program also?

Many Thanks. EDIT: I have this example from a Poker Project I found, see generateUniqueHand, how can I take that code out and work in a program where i run that and output the array?

    import javax.swing.JOptionPane;
    public class PokerPart2ToDateWithMethods

{
  public static String userMessage = "";    
  public static void main(String[] args)
  {
    int handSize = 5, winType;
    int[] cards   = new int[handSize];  
    int[] suits   = new int[handSize]; 
    int[] values  = new int[handSize]; 
    generateUniqueHand(cards);
    determineSuitsAndValues(cards, suits, values);
    orderValuesInDescendingSequence(suits, values);
    displayCardsToEndUser(suits, values);       
    winType = evaluateHandOfCards(suits, values);   
    getTypeOfWinIfAnyInText(winType);              
    JOptionPane.showMessageDialog(null,userMessage);
  }

  public static void generateUniqueHand(int [] cards)
  {
    int deckSize = 52;
    int uniqueNumbersRequired = cards.length, aRandomNumber;
    int index = 0, duplicateIndex;
    while (index < uniqueNumbersRequired)
    {
      aRandomNumber = (int) (Math.random() * deckSize);
      cards[index] = aRandomNumber;
      duplicateIndex = 0;
      while (cards[duplicateIndex] != aRandomNumber)
        duplicateIndex++;
      if (index == duplicateIndex)
        index++;
    } 
  }

  public static void determineSuitsAndValues(int [] cards, int [] suits, int [] values)
  {
    for (int i = 0; i < cards.length; i++)
    {
      suits[i]  = cards[i] / 13;
      values[i] = cards[i] % 13;
    }
  } 

  public static void orderValuesInDescendingSequence(int [] suits, int [] values)
  {
    int pass, comparison, temp;
    boolean sorted = false;
    for (pass = 1; pass <= values.length - 1 && !sorted; pass++)
    {
      sorted = true;
      for (comparison = 1; comparison <= values.length - pass; comparison++)
      {
        if (values[comparison - 1] < values[comparison])
        {
          temp = values[comparison - 1];
          values[comparison - 1] = values[comparison];
          values[comparison] = temp;
          temp = suits[comparison - 1];
          suits[comparison - 1] = suits[comparison];
          suits[comparison] = temp;
          sorted = false;
        }  
      }
    }
  }

  public static void displayCardsToEndUser(int[] suits, int[] values)
  {
    for (int i = 0; i < suits.length; i++)
    {
      switch(values[i])
      {
        case 0:  userMessage += "Two of ";   break;
        case 1:  userMessage += "Three of "; break;
        case 2:  userMessage += "Four of ";  break;
        case 3:  userMessage += "Five of ";  break;
        case 4:  userMessage += "Six of ";   break;
        case 5:  userMessage += "Seven of "; break;
        case 6:  userMessage += "Eight of "; break;
        case 7:  userMessage += "Nine of ";  break;
        case 8:  userMessage += "Ten of ";   break;
        case 9:  userMessage += "Jack of ";  break;
        case 10: userMessage += "Queen of "; break;
        case 11: userMessage += "King of ";  break;
        case 12: userMessage += "Ace of ";   break;
      } 
      switch(suits[i])
      {
        case 0:  userMessage += "Clubs\n";    break;
        case 1:  userMessage += "Diamonds\n"; break;
        case 2:  userMessage += "Hearts\n";   break;
        case 3:  userMessage += "Spades\n";   break;
      } 
    }
  }

  public static int evaluateHandOfCards(int[] suits, int[] values)             
  {                                                                         
    int winType = 0;                                                       
    if (cardsOfSameSuit(suits))                                            
    {                                                                      
      if (cardsInConsecutiveDescendingSequence(values))                    
      {                                                                    
        if (values[0] == 12) winType = 9;                                  
        else                 winType = 8;                                  
      }                                                                    
      else                   winType = 7;                                  
    }                                                                      
    else                                                                   
    {                                                                      
      if (cardsInConsecutiveDescendingSequence(values))                    
        winType = 5;                                                          
      else                                                                 
        winType = checkOtherPossibleCombinations(values);                     
    }                                                                        
    return winType;                                                        
  }                                                                        

  public static boolean cardsOfSameSuit(int suits[])                       
  {                                                                        
    boolean sameSuit = true;                                               
    for (int i = 0; (i < suits.length - 1) && sameSuit; i++)               
      if (suits[i] != suits[i + 1])                                        
        sameSuit = false;                                                  
    return sameSuit;                                                       
  }                                                                        

  public static boolean cardsInConsecutiveDescendingSequence(int values[]) 
  {                                                                        
    boolean consecutiveCards = true;                                       
    for (int i = 0; i < values.length - 1 && consecutiveCards; i++)        
       if (values[i] != values[i + 1] + 1)                                  
         consecutiveCards = false;                                          
    return consecutiveCards;                                               
  }                                                                        

  public static int checkOtherPossibleCombinations(int[] values)           
  {                                                                        
    boolean continueCardComparison;                                        
    int sameKind = 0;                                                      
    for (int i = 0; (i < values.length - 1); i++)                          
    {                                                                      
      continueCardComparison = true;                                       
      for (int j = i + 1; j < values.length && continueCardComparison; j++)
      {                                                                    
        if (values[i] == values[j])                                        
          sameKind++;                                                      
        else                                                               
          continueCardComparison = false;                                  
      }                                                                    
    }                                                                      
    return sameKind;                                                       
  }                                                                        

  public static void getTypeOfWinIfAnyInText(int winType)                    
  {                                                                        
    switch(winType)                                                           
    {                                                                         
      case 0: userMessage += "\nNot a winning hand\n"; break;              
      case 1: userMessage += "\nOne pair\n";           break;              
      case 2: userMessage += "\nTwo pair\n";           break;              
      case 3: userMessage += "\nThree of a kind\n";    break;              
      case 4: userMessage += "\nFull house\n";         break;              
      case 5: userMessage += "\nStraight\n";           break;              
      case 6: userMessage += "\nFour of a kind\n";     break;              
      case 7: userMessage += "\nFlush\n";              break;              
      case 8: userMessage += "\nStraight flush\n";     break;              
      case 9: userMessage += "\nRoyal flush\n";        break;              
    }                                                                      
  }                                                                        
}
  • duplicate of http://stackoverflow.com/questions/4040001/creating-random-numbers-with-no-duplicates – jbutler483 Aug 22 '14 at 12:53
  • 3
    "no duplicates" is in direct conflict with "random". Truly random always has the possibility of duplicates. – vcsjones Aug 22 '14 at 12:53
  • Easy way to tackle this: store the generated numbers and when the generator returns a number that has already been used, try again. Not the best solution in terms of performance (depends on how probable collisions are) but easy to implement. And as others said, eventually you might run out of unused numbers. – Thomas Aug 22 '14 at 12:53
  • Welcome to Stack overflow. TO help us help you answer your questions, be sure check I encourage you to check out the Help Center and see how to ask "good" questions. [Help](http://stackoverflow.com/help). WE'll gladly help you out, but you need to offer some form of attempt :) – Adam Aug 22 '14 at 12:53
  • @vcsjones why is it we never see 2 equal lotto numbers from the same week then? Is it not truly random? – Jaqen H'ghar Aug 22 '14 at 12:59

3 Answers3

3

What you want to do is not pick numbers at random, but shuffle a fixed set of numbers. For example, take the set of numbers 1 to 49, shuffle them randomly, then pick the first six entries in the shuffled list.

For this purpose, I recommend you use the Fisher-Yates shuffle. There is already an implementation in Java: the Collections.shuffle method.

Stuart Caie
  • 2,803
  • 14
  • 15
0
public int random(int[] array)
{
    Random generator = new Random(); 
    int lotto = generator.nextInt(20) + 1;
    for(int i = 0; i < array.length; ++i)
       if(array[i] == lotto)
          random(array);
    return lotto;

}

If you were to keep track of your values in an array, you could just check it against the rest of the array. The performance side of things wouldn't be necessarily too fantastic, but this would do you the job essentially.

To answer the edit: In order to "take that out", which I'm doing my best to understand what you mean by that, in order to print the array, just do the code segment

for(int num : cards)
    System.out.println(num)
Adam
  • 2,422
  • 18
  • 29
  • Thanks for responding, please look at my EDIT above, the code I highlighted is exactly what I need, but I dont know how to take that out and make it run on its own to display to the end user. – user3425947 Aug 22 '14 at 13:43
  • So you want to output the array? Like for(int num : cards) System.out.println(num) – Adam Aug 22 '14 at 14:55
0

Here's an implementation:

public class LottoNumbers {
    private ArrayList<Integer> numbersBag;
    private Random rnd = new Random();

    public void init(int size) {
        numbersBag = new ArrayList<Integer>();
        for (int i = 1; i <= size; i++) {
            numbersBag.add(i); //you put all your lotto numbers in the bag
        }
    }

    public Integer pick() {
        return numbersBag.remove(
                rnd.nextInt(numbersBag.size())); //you pick and remove from list a not yet extracted number
    }

}

You can use it this way

LottoNumbers bag =  new LottoNumbers();
bag.init(5);
for (int i = 0; i < 5; i++) {
    System.out.println(bag.pick());
}

In this way you'll keep a correct probabilistic distribution a numbers-in-a-bag-extraction

Luca Putzu
  • 1,438
  • 18
  • 24