Random Assortment

How do you randomly assort a string of values? This is to virtually "shuffle" cards.
[85 byte] By [Modderman] at [2007-12-16]
# 1
Modderman -

There are many ways to virtually "shuffle". Here is one simple example in C#:


static
void Shuffle(string[] items, int numTimesToShuffle)

{

// Create a random number generator

Random random = new Random();

// Loop over the array swapping random elements

for (int i = 0; i < numTimesToShuffle; i++)

{

// Pick two indexes in the array to swap

int r1 = random.Next(items.Length);

int r2 = random.Next(items.Length);

// Swap the two elements

string temp = items[r1];

items[r1] = items[r2];

items[r2] = temp;

}

}

Thanks,
Luke Hoban
Visual C# IDE Program Manager

LukeHoban at 2007-9-9 > top of Msdn Tech,Visual Studio Express Editions,Installing and Registering Visual Studio 2005 Express Editions...
# 2
I was trying with almost same kind of code but compiler gives me this error:

Error 3 Property or indexer 'string.this[int]' cannot be assigned to -- it is read only path\to\Program.cs 70 17 ProjectName

Here is my code:




static string scrambleText(string scText)
{
Random rand = new Random();

for (int i = 0; i < scText.Length; i++)
{

int swap = rand.Next(i, scText.Length);
char temp;

temp = scText[ i];
scText[ i] = scText[swap];
scText[swap] = scText[ i];
}
return scText;
}


RajNair at 2007-9-9 > top of Msdn Tech,Visual Studio Express Editions,Installing and Registering Visual Studio 2005 Express Editions...
# 3
String access using [int index] is read-only, you probably want to copy your string to a char array, then return a new string, passing the scrambled char[] in the constructor.
JeffJohnson at 2007-9-9 > top of Msdn Tech,Visual Studio Express Editions,Installing and Registering Visual Studio 2005 Express Editions...