Created
December 23, 2017 07:00
-
-
Save klkucan/9513b2854c3a58a68f8fbebf7c34cedf to your computer and use it in GitHub Desktop.
Random Array
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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
namespace TestConsole | |
{ | |
static class RandomGenerator | |
{ | |
public static int[] KalladystineUniqueRandomNumbers(int min, int max, int howMany) | |
{ | |
// check for impossible combinations | |
if (howMany > max - min) | |
{ | |
// throw new ArgumentException(String.Format("Range {0}-{1} is too small to have {2} unique random numbers.", min, max, howMany)); | |
Console.WriteLine(String.Format("Range {0}-{1} is too small to have {2} unique random numbers.", min, max, howMany)); | |
return null; | |
} | |
int[] myNumbers = new int[howMany]; | |
// special case for range and howMany being equal | |
if (howMany == max - min) | |
{ | |
// Linq version | |
// return Enumerable.Range(min, howMany).ToArray(); | |
// for loop version | |
for (int i = 0; i < howMany; i++) | |
myNumbers[i] = i; | |
return myNumbers; | |
} | |
// actual generation of random numbers | |
System.Random randNum = new System.Random(); | |
for (int currIndex = 0; currIndex < howMany; currIndex++) | |
{ | |
// generate a candidate | |
int randCandidate = randNum.Next(min, max); | |
// generate a new candidate as long as we don't get one that isn't in the array | |
while (myNumbers.Contains(randCandidate)) | |
{ | |
randCandidate = randNum.Next(min, max); | |
} | |
myNumbers[currIndex] = randCandidate; | |
// some optimizations | |
if (randCandidate == min) | |
min++; | |
if (randCandidate == max) | |
max--; | |
} | |
return myNumbers; | |
} | |
public static int[] BrathnannUniqueRandomNumbers(int min, int max, int howMany) | |
{ | |
// check for impossible combinations | |
if (howMany > max - min) | |
{ | |
// throw new ArgumentException(String.Format("Range {0}-{1} is too small to have {2} unique random numbers.", min, max, howMany)); | |
Console.WriteLine(String.Format("Range {0}-{1} is too small to have {2} unique random numbers.", min, max, howMany)); | |
return null; | |
} | |
List<int> myList = new List<int>(howMany); | |
for (int x = min; x < max; x++) | |
{ | |
myList.Add(x); | |
} | |
// special case for range and howMany being equal | |
if (howMany == max - min) | |
{ | |
return myList.ToArray<int>(); | |
} | |
System.Random rnd = new System.Random(); | |
var randomizedList = (from item in myList | |
orderby rnd.Next() | |
select item) | |
.Take<int>(howMany).ToArray<int>(); | |
return randomizedList; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment