Last active
October 20, 2018 12:09
-
-
Save manisero/403913ad856454e64d7e5954fd52f24c to your computer and use it in GitHub Desktop.
Method generating set of unique random numbers.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary>Generates set of unique random numbers from 1 to specified max value.</summary> | |
public static ISet<int> NextUniqueSet( | |
this Random random, | |
int count, | |
int maxValueInclusive) | |
{ | |
// Taken from https://stackoverflow.com/a/2394292/10401390 | |
if (maxValueInclusive < count) | |
{ | |
throw new ArgumentException($"{nameof(maxValueInclusive)} cannot be lower than {nameof(count)}.", nameof(maxValueInclusive)); | |
} | |
var m = count; | |
var n = maxValueInclusive; | |
var s = new HashSet<int>(); | |
for (var j = n - m + 1; j <= n; j++) | |
{ | |
var t = random.Next(1, j); | |
if (!s.Add(t)) | |
{ | |
s.Add(j); | |
} | |
} | |
return s; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment