dimanche 3 mai 2015

Function returns the same value instead of unique values [duplicate]

This question already has an answer here:

I found this example on sof. When I use it the code works as designed when it is a singular call. If I make multiple calls to GiveMeaNumber, it returns the same exact number despite the number of calls. However, if I debug the code and step through each call I can see where a unique number is assigned for each call to the function. My problem is when I try to write this information to the console instead of getting all of the unique values I get the same value x amount of times. The only way I can get the unique values to write to the console is to debug and step through each call to the function. Could someone explain why this is occurring and suggest a possible solution? I would like for the function to return unique values, per call. I'm guessing there may be some kind of memory or reference issue?

int main() 
{
    int num1 = GiveMeANumber();
    int num2 = GiveMeANumber();
    int num3 = GiveMeANumber();
Console.WriteLine(num1 + ", " +
}

private int GiveMeANumber()
{
    var exclude = new HashSet<int>() { 5, 7, 17, 23 };
    var range = Enumerable.Range(1, 100).Where(i => !exclude.Contains(i));

    var rand = new System.Random();
    int index = rand.Next(0, 100 - exclude.Count);
    return range.ElementAt(index);
}




Aucun commentaire:

Enregistrer un commentaire