I\'ve searched for a while and been struggling to find this, I\'m trying to generate several random, unique numbers is C#. I\'m using System.Random
, and I\'m us
This console app will let you shuffle the alphabet five times with different orders.
using System;
using System.Linq;
namespace Shuffle
{
class Program
{
static Random rnd = new Random();
static void Main(string[] args)
{
var alphabet = new string[] { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" };
Console.WriteLine("Alphabet : {0}", string.Join(",", alphabet));
for (int i = 0; i < 5; i++)
{
var shuffledAlphabet = GetShuffledAlphabet(alphabet);
Console.WriteLine("SHUFFLE {0}: {1}", i, string.Join(",", shuffledAlphabet));
}
}
static string[] GetShuffledAlphabet(string[] arr)
{
int?[] uniqueNumbers = new int?[arr.Length];
string[] shuffledAlphabet = new string[arr.Length];
for (int i = 0; i < arr.Length; i++)
{
int uniqueNumber = GenerateUniqueNumber(uniqueNumberArrays);
uniqueNumberArrays[i] = uniqueNumber;
newArray[i] = arr[uniqueNumber];
}
return shuffledAlphabet;
}
static int GenerateUniqueNumber(int?[] uniqueNumbers)
{
int number = rnd.Next(uniqueNumbers.Length);
if (!uniqueNumbers.Any(r => r == number))
{
return number;
}
return GenerateUniqueNumber(uniqueNumbers);
}
}
}