How can I randomize numbers in an array [duplicate

2020-02-12 11:59发布

问题:

I have an array like this one:

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

I'd like to randomize this (different each time) so that it makes another array with the same size and numbers but in a different order each time.

回答1:

Try something like this:

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


回答2:

Here's 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 using 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 a List<int> you can invoke .ToArray() instead.

Of course, that will work for any array of int, not only for 1, 2, 3, ..., n. You can even make the method generic in T.



回答3:

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;
    }  
}


回答4:

This even takes care that the values dont repeat ;

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;
}


回答5:

In my eyes the easiest way would be this:

 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();
        }


回答6:

It works:

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