Click here to Skip to main content
15,890,947 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys
I have an array in C# and How can I replace the members of the array randomly with each other?

What I have tried:

for show array I use Listbox

C#
inputCount= lstin.Items.Count;
output = UniqueRandom(0, inputCount).ToArray<int>();//Just Make me random Number Without Duplicate
for (int i = 0; i < output.Length; i++)
   { 
       lstout.Items.Add(lstin.Items[output[i]]);
   }
Posted
Updated 1-Apr-19 1:45am
Comments
johannesnestler 2-Apr-19 9:14am    
if this Code is for a Card game or something similar I recommend not to really "shuflle" the Array - just pick items (cards) randomly and remove them. No shuffling needed - and more secure - no one will know the shuffled order before you draw an item - just init Random with the actual access time - if this is over network it will be even more unpredictable.

Do you mean shuffle[^]?
 
Share this answer
 
Simplest solution:
C#
private Random shuffle = new Random();
public void Randomise<T>(List<T> input)
    {
    int capacity = input.Count;
    if (capacity> 1)
        {
        for (int i = 0; i < capacity * 3; i++)
            {
            int r1 = shuffle.Next(capacity);
            int r2 = shuffle.Next(capacity);
            T temp = input[r1];
            input[r1] = input[r2];
            input[r2] = temp;
            }
        }
    }
 
Share this answer
 
Comments
egball 1-Apr-19 10:35am    
thanks a lot
OriginalGriff 1-Apr-19 10:45am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900