How can I randomize numbers in an array

I have an array like this:

int[] numbers = new [] { 1, 2, 3, 4 }; 

I would like to randomize this (every time every time) so that every other array has the same size and numbers, but in a different order.

+4
source share
6 answers

Try something like this:

 System.Random rnd = new System.Random(); var numbers = Enumerable.Range(1, 4).OrderBy(r => rnd.Next()).ToArray(); 
+12
source

This will use a method that will work:

 public List<int> Randomize(int[] numbers) { List<int> randomized = new List<int>(); List<int> original = new List<int>(numbers); Random r = new Random(); while (original.Count > 0) { int index = r.Next(original.Count); randomized.Add(original[index]); original.RemoveAt(index); } return randomized; } 

Edit:

Another way could be to use LINQ extension methods for IEnumerable<T> collections:

 var random = new Random(); List<int> randomized = numbers.OrderBy(x => random.Next()).ToList(); 

If you want to have an array instead of List<int> , you can use .ToArray() instead.

Of course, this will work for any int array, and not just for 1, 2, 3, ..., n . You can even make a general method in T

+4
source
 public static void Shuffle<T>(T[] array) { Random random = new Random(); for (int i = 0; i < 10; i++) { int idx = random.Next(i, 10); //swap elements T tmp = array[i]; array[i] = array[idx]; array[idx] = tmp; } } 
+2
source

This will even make sure that the values ​​are not repeated;

 for(int i=0;i<4;i++) { int no_repeat = -1; int x,j; while(no_repeat!=1) { x=rand()%4; for(j=0;j<4;j++) { if(numbers[j]==x) break; } if(j==4) no_repeat=1; } if(no_repeat) numbers[i]=x; } 
0
source

In my eyes, the simplest way would be the following:

  int[] grid = new int[9];//size of array Random randomNumber = new Random();//new random number var rowLength = grid.GetLength(0); var colLength = grid.GetLength(1); for (int row = 0; row < rowLength; row++) { grid[col] = randomNumber.Next(4)+1;//Fills grid with numbers from //1-4 Console.Write(String.Format("{0}\t", grid[col])); //Displays array in console Console.WriteLine(); } 
0
source

Works:

 numbers = numbers.OrderBy(s => Guid.NewGuid()).ToArray(); 
-2
source

All Articles