Question

Say i have a text box with the following content:

Word
Entry
List
Sentry

Each on their own line. How can i randomize them, to appear something like this(on button click):

Entry
List
Sentry
Word

Or any random combination. Now note, i have something like 100,000 separate lines for some of the files i import. I need the to be randomized on button click. Thanks!

What im going to do is have 2 multi-line text boxes next to each other, the user can randomize each list, then a separate button will combine both lists into one file, delimited by a colon(:). Thanks a ton!

Was it helpful?

Solution

Instead of "Randomize", think "Shuffle":

void Shuffle<T>(IList<T> items)
{
    // creating a new object here for demo purposes
    // Really, the same object should be re-used across method calls
    var random = new Random(); 

    for (int i = items.Count; i > 1; i--)
    {
        // Pick random element to swap.
        int j = random.Next(i); // 0 <= j <= i-1
        // Swap.
        T tmp = items[j];
        items[j] = items[i - 1];
        items[i - 1] = tmp;
    }
}

The Windows Forms textbox has a helpful Lines property to make this easy to use:

 string[] lines = MyTextBox.Lines;
 Shuffle(lines);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top