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

4

2 回答 2

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.)

于 2012-08-26T17:25:38.387 回答
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

于 2012-08-26T17:47:28.497 回答