Skip to content

Instantly share code, notes, and snippets.

@manisero
Last active October 20, 2018 12:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manisero/403913ad856454e64d7e5954fd52f24c to your computer and use it in GitHub Desktop.
Save manisero/403913ad856454e64d7e5954fd52f24c to your computer and use it in GitHub Desktop.
Method generating set of unique random numbers.
/// <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