开发者

randomly select some numbers c#

Let's say we have this numbers 51,53,58,60,78. How can we select a number randomly in such a way if its already selected/picked, it will not be sel开发者_开发知识库ected in the next run.

Also, after all numbers are selected, everything is restarted and the process repeats itself.


Put the numbers into an array and then do the Knuth Shuffle on the array. The contents of the array are then in a random order, and if you iterate through it, you won't get repeats.

Be careful; it is easy to get the shuffle wrong.


Load your integers into an array. Create an instance of the Random class. Call the Random.Next(int minValue, int maxValue) method with 0 being the minValue, and your array count minus 1 being your maxValue. Then use that random integer to reference your integer array.

Random rnd = new Random();
int nextArrayIndex;
int[] randomNumbers = new int[] {51, 53, 58, 60, 78};

nextArrayIndex = rnd.Next(0, randomNumbers.Count() - 1);

Console.Writeline("Random Value: {0}", randomNumbers[nextArrayIndex].ToString());

Edit: for non repeating data, just store the index that was already use of the integer array in a separate list and prior to utilizing the random number, do a check on the list to see if it was already used. If so, then re-run the random number code. If it is full, then don't allow that to continue in an endless loop.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜