I'm trying to change the elements of an array randomly, by changing the indexes.
My code so far is the following:
public static string[] Shuffle(string[] wordArray)
{
int swapIndex = 0;
string temp;
Random random = new Random();
for (int i = 0; i < wordArray.Length; i++)
{
System.Console.WriteLine("random " + random.Next(0, wordArray.Length));
swapIndex = (int)(random.Next(0, wordArray.Length));
temp = wordArray[i];
wordArray[i] = wordArray[swapIndex];
wordArray[swapIndex] = temp;
}
return wordArray;
}
And the function that calls that method is the following:
static string[] words1 = new string[] { "1", "2", "3" };
static string[] days = new string[] { "M", "T", "W", "Th", "F", "S", "Su" };
public static void playListCreation()
{
for (int j = 0; j < days.Length; j++)
{
var result = Shuffle(words1);
foreach (var i in result)
{
System.Console.WriteLine(i + " ");
}
System.Console.WriteLine("/n");
}
}
The problem with the code is that every time Im getting the same number in the swapIndex value. I always get:
random 2
random 2
random 0
In all the iterations. And I don't know what I'm doing wrong.
Any ideas? thanks in advance.
Aucun commentaire:
Enregistrer un commentaire