How can I randomize numbers in an array [duplicate

2020-02-12 11:26发布

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.

6条回答
别忘想泡老子
2楼-- · 2020-02-12 12:15

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.

查看更多
Lonely孤独者°
3楼-- · 2020-02-12 12:18

It works:

numbers = numbers.OrderBy(s => Guid.NewGuid()).ToArray();
查看更多
▲ chillily
4楼-- · 2020-02-12 12:24

Try something like this:

System.Random rnd = new System.Random();
var numbers = Enumerable.Range(1, 4).OrderBy(r => rnd.Next()).ToArray();
查看更多
地球回转人心会变
5楼-- · 2020-02-12 12:24
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;
    }  
}
查看更多
神经病院院长
6楼-- · 2020-02-12 12:26

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;
}
查看更多
Bombasti
7楼-- · 2020-02-12 12:31

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();
        }
查看更多
登录 后发表回答