Search code examples
c#arraysrandomfisher-yates-shuffle

How to randomize/shuffle two arrays in the same way in c#


I have two arrays one is a PictureBox array and the other is an Integer array both have the same number of elements. I want both arrays to be shuffled randomly each time but both shuffled the same way.

Here is a code that works if I use two PictureBox arrays or two Integer arrays, however I want it to shuffle one PictureBox array and one Integer array.

This is the code I want to work: (two different arrays)

PictureBox[] cards = new PictureBox[13];
// PictureBox[] numValue = new PictureBox[13];
int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };

Random rnd = new Random();

for (int i = 0; i < cards.Length - 1; i++)
{
    int j = rnd.Next(i, cards.Length);

    PictureBox temp = cards[j];
    cards[j] = cards[i];
    cards[i] = temp;

    temp = numbers[j]; //An error occurs here because numbers is not a PictureBox variable
    numbers[j] = numbers[i];
    numbers[i] = temp; 
}

This is the code that works: (for same arrays)

PictureBox[] numValue = new PictureBox[13];
PictureBox[] cards = new PictureBox[13];
// int[] numbers = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10 };

Random rnd = new Random();

for (int i = 0; i < cards.Length - 1; i++)
{
    int j = rnd.Next(i, cards.Length);

    PictureBox temp = cards[j];
    cards[j] = cards[i];
    cards[i] = temp;

    temp = numValue [j]; 
    numValue [j] = numValue [i];
    numValue [i] = temp; 
}

If you know another different code that can help me feel free to share it!


Solution

  • Just create two temporary variables

    for (int i = 0; i < cards.Length - 1; i++)
    {
        int j = rnd.Next(i, cards.Length);
    
        PictureBox tempPictureBox = cards[j]; // One for PictureBox
        cards[j] = cards[i];
        cards[i] = tempPictureBox;
    
        int tempInt = numValue[j]; // Another one for int
        numValue[j] = numValue[i];
        numValue[i] = tempInt; 
    }