I've looked everywhere on how to shuffle/randomize a string list in C# for the windows phone 7. I'm still a beginner you could say so this is probably way out of my league, but I'm writing a simple app, and this is the base of it. I have a list of strings that I need to shuffle and output to a text block. I have bits and pieces of codes I've looked up, but I know I have it wrong. Any suggestions?
Asked
Active
Viewed 1,701 times
0
-
1http://stackoverflow.com/search?q=%5Bc%23%5D+shuffle – dtb Apr 07 '11 at 23:21
-
If you don't need the shuffling to be random, one simple option is to return "strings.OrderBy( s => s.GetHashCode() );" ;) – Morten Mertner Apr 07 '11 at 23:43
-
possible duplicate of [C#: Is using Random and OrderBy a good shuffle algorithm?](http://stackoverflow.com/questions/1287567/c-is-using-random-and-orderby-a-good-shuffle-algorithm) – Jon Apr 08 '11 at 00:49
1 Answers
3
The Fisher-Yates-Durstenfeld shuffle is a proven technique that's easy to implement. Here's an extension method that will perform an in-place shuffle on any IList<T>
.
(It should be easy enough to adapt if you decide that you want to leave the original list intact and return a new, shuffled list instead, or to act on IEnumerable<T>
sequences, à la LINQ.)
var list = new List<string> { "the", "quick", "brown", "fox" };
list.ShuffleInPlace();
// ...
public static class ListExtensions
{
public static void ShuffleInPlace<T>(this IList<T> source)
{
source.ShuffleInPlace(new Random());
}
public static void ShuffleInPlace<T>(this IList<T> source, Random rng)
{
if (source == null) throw new ArgumentNullException("source");
if (rng == null) throw new ArgumentNullException("rng");
for (int i = 0; i < source.Count - 1; i++)
{
int j = rng.Next(i, source.Count);
T temp = source[j];
source[j] = source[i];
source[i] = temp;
}
}
}
-
Now how would you go about setting a random string from the list to a textblock? – Christian Apr 08 '11 at 02:07
-
1If you only need a single random string then perhaps you don't really need to shuffle the list at all; simply pick a random string from the existing list: `var rng = new Random(); yourTextBlock.Text = yourStringList[rng.Next(yourStringList.Length)];` – LukeH Apr 08 '11 at 09:01