-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[API Proposal]: Avoiding Duplication for Random.GetItems #102229
Comments
The current implementation(s) don't rely on the objects having any sense of equality. Such an implementation would require either an appropriate constraint and/or some sort of key extractor. (In addition to needing to be a unique method, since you can't break the existing uses of the method by substituting this implementation). There are potentially better workarounds using |
Even if In my oppinion; unique random selection is necessary in the method. |
Tagging subscribers to this area: @dotnet/area-system-runtime |
This can be done in a fairly straightforward way with the current API. var numbers = new[] { 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9 };
var distinct = numbers.Distinct().ToArray();
Random.Shared.Shuffle(distinct);
Console.WriteLine(string.Join(", ", distinct)); |
But that's not correct, as an object by definition should be equal to itself. I am more inclined towards the reasoning that we can ask for a greater number of items than the length of the source, in which case anyway there will be duplicates. |
Requires that the type be equatable, which isn't guaranteed to be the case. |
Yes, that too. |
Background and motivation
The Random.Shared.GetItems method will not get items in a mutually exclusive way.
When retrieves items randomly, resulting random collection can include duplicate entries.
Therefore, I use dictionary to store values as key and boolean flag value as value in GetItems method.
In my idea, I guaranteed the distinct and randomly selection using the dictionary,
If randomly selected value has already taken, it will not get items again.
API Proposal
API Usage
Alternative Designs
Risks
Not identified but defined potencial exceptions using below code blocks
ArgumentException(SR.Arg_EmptySpan, nameof(choices));
ArgumentOutOfRangeException.ThrowIfNegative(length);
The text was updated successfully, but these errors were encountered: