Shuffle the elements of array in c#
Csharp program for Shuffle the elements of array. Here more information.
// Include namespace system
using System;
/*
Csharp program for
Shuffle the array elements
*/
public class Shuffling
{
// Function which is swapping two array elements
// of given location
public static void swapElement(int[] arr, int i, int j)
{
// Get i location element
var temp = arr[i];
// Set new values
arr[i] = arr[j];
arr[j] = temp;
}
// Returns the random location of array elements
public static int randomLocation(int min, int max)
{
Random rand = new Random();
// Calculate random number
return rand.Next(min, max+1);
}
// Function which is shuffle given array elements
public static void shuffleElement(int[] arr, int size)
{
// (i,j) indicate locations
var j = 0;
var i = 0;
// Variable which is controlling the
// execution process of loop
var counter = 0;
// Loop which is shuffling random elements in array
while (counter < size)
{
// Get random location of array index
i = Shuffling.randomLocation(0, size - 1);
j = Shuffling.randomLocation(0, size - 1);
if (i != j)
{
// Swap array elements
Shuffling.swapElement(arr, i, j);
counter++;
}
}
}
// Function which is display array elements
public static void display(int[] arr, int size)
{
for (var i = 0; i < size; ++i)
{
// Disply element value
Console.Write(" " + arr[i].ToString());
}
Console.Write("\n");
}
public static void Main(String[] args)
{
// Define array of integer elements
int[] arr = {
1 , 0 , -3 , 8 , 7 , 3 , 9 , 4 , 2 , 5 , 10 , 6
};
var size = arr.Length;
// Before shuffling array elements
Console.WriteLine(" Initial array elements");
Shuffling.display(arr, size);
Console.WriteLine(" After Shuffle array elements");
Shuffling.shuffleElement(arr, size);
Shuffling.display(arr, size);
Shuffling.shuffleElement(arr, size);
Shuffling.display(arr, size);
Shuffling.shuffleElement(arr, size);
Shuffling.display(arr, size);
}
}
Output
Initial array elements
1 0 -3 8 7 3 9 4 2 5 10 6
After Shuffle array elements
1 6 8 -3 7 0 2 10 9 4 5 3
3 8 7 9 6 0 2 4 5 1 10 -3
5 8 1 4 9 6 -3 3 2 0 7 10
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment