-2

The method takes 1 array and using random to shuffle the array the value of rndm1-4 didn't change. and after the loop, it acts normal. I think the problem is in the while loop.

public static string[] Shuffle(string[] array)
{
    string str1, str2, str3, str4;
    Random rnd1 = new Random();
    Random rnd2 = new Random();
    Random rnd3 = new Random();
    Random rnd4 = new Random();
    int rndm1 = rnd1.Next(3);
    int rndm2 = rnd2.Next(3);
    int rndm3 = rnd3.Next(3);
    int rndm4 = rnd4.Next(3);
    
    while ((rndm1 != rndm2) && (rndm1 != rndm3) && (rndm1 != rndm4) 
        && (rndm2 != rndm3) && (rndm2 != rndm4) && (rndm3 != rndm4))
    {
        rndm1 = rnd1.Next(3);
        rndm2 = rnd2.Next(3);
        rndm3 = rnd3.Next(3);
        rndm4 = rnd4.Next(3);
    }
    
    str1 = array[0];
    str2 = array[1];
    str3 = array[2];
    str4 = array[3];
    array[rndm1] = str1;
    array[rndm2] = str2;
    array[rndm3] = str3;
    array[rndm4] = str4;
    return array;
}
Peter Csala
  • 17,736
  • 16
  • 35
  • 75
  • 2
    You should use only a single instance of Random. Check: https://stackoverflow.com/a/1654902/3888657 – TheTanic May 31 '21 at 13:15

1 Answers1

-1

Not using strings but this illustrates a pretty solid shuffle method...

  var inputArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
  // Get a rapidly changing seed for the generator (for fun)
  var randgen = new Random((int)(DateTime.Now.Ticks % (long)(int.MaxValue) + 1));
  var n = inputArray.Length;
  var returnArray = new int[n];
  for (int i = 0; i < inputArray.Length; i++)
  {
    var pick = randgen.Next(n); // a number from 0..(n-1)
    returnArray[i] = inputArray[pick];
    n--;
    // after picking an item out of the input array, replace it with the last entry of the input array...
    // so that number can't be picked again and the last entry remains in contention
    inputArray[pick] = inputArray[n];
  }
  foreach (var t in returnArray)
    Console.Write($"{t}, ");
}

Output of a test run

9, 4, 1, 3, 7, 10, 5, 8, 6, 2,
AlanK
  • 1,827
  • 13
  • 16