0

I know how to do this in VB but im coding in C# so i need to figure out how to get two different radomized integers (1 - 8) and i cant seem to get it to work, i get the same over and over even more the harder i try. I have read up alot but i cant find a more specific help as most people just want one rnd number and that i can do...easy ;)

what i have coded is this thou it does not give me two different numbers.

    public string GetFruitCombination()
    {
        Random fruitcombo = new Random();
        int indexone = fruitcombo.Next(0, 8);
        Random fruitcombotwo = new Random();
        int indextwo = fruitcombotwo.Next(0, 8);

        string firstfruit = m_fruit[indexone];
        string secondfruit = m_fruit[indextwo];

        return string.Format("{0}&{1}", firstfruit, secondfruit);
    }

There must be an easier way to get 2 different rnd numbers right? So i need someone to push me in the right direction!

Thanks in advance for any idea and help!!!

//Regards

user1501127
  • 865
  • 1
  • 18
  • 32
  • 2
    Use the *same* random number generator. Search for "random number duplicate C#". –  Aug 26 '12 at 17:38
  • http://stackoverflow.com/questions/3887481/problem-in-generating-random-number , http://stackoverflow.com/questions/767999/random-number-generator-not-working-the-way-i-had-planned-c , http://stackoverflow.com/questions/8834589/not-so-random-number-why (for instance) –  Aug 26 '12 at 17:40
  • (FWIW: Java's random "default seed" implementation is better than this, but it is still possible to run into degenerate situations ..) –  Aug 26 '12 at 17:42

2 Answers2

5

Don't create a second instance of Random, just use the same one twice.

(The default seed is time based, so in creating two so quickly there is a significant chance they will both have the same seed.)

Richard
  • 106,783
  • 21
  • 203
  • 265
2
   public string GetFruitCombination() 
    { 
        Random fruitcombo = new Random(Environment.TickCount); 
        int indexone = fruitcombo.Next(0, 8); 
        int indextwo = fruitcombo.Next(0, 8); 

        string firstfruit = m_fruit[indexone]; 
        string secondfruit = m_fruit[indextwo]; 

        return string.Format("{0}&{1}", firstfruit, secondfruit); 
    } 

Although personally I use a static version of Random so the seed is set at start up and then just Nexted each use. There is also a better random in the RNGCryptoServiceProvider example HERE

Wolf5370
  • 1,374
  • 11
  • 12