c# - 使用 Random 类随机化二维数组

标签 c# arrays random

我正在尝试随机化二维数组中的一组预定元素。

using System;

namespace array
{
    public class tiles
    {
        static void Main(string[] args)
        {
            Random random = new Random();
            int[,] tilearr = { { 0, 1, 2 }, { 3, 4, 5 }, { 6, 7, 8 } };

            for (int i = 0; i < 3; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    Console.Write(tilearr[i, j] + " ");
                }
                Console.WriteLine();
            }

            Console.ReadLine();
        }
    }
}

我的问题是,如果我执行类似 tilearr[i, j] = random.Next(0, 8); 的操作,它会随机化数组但不关心是否有任何重复项相同的元素。

2 6 7
1 1 3
2 7 0

我追求的更像这样:

2 4 8  1 3 0
0 3 1  5 6 8 
6 7 5, 2 4 7

最佳答案

一个简单而切题的解决方案是拥有一个可用号码列表,然后逐个位置并从列表中随机选择号码。

像这样:

var numbers = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8 };
for(int x = 0; x < 3; ++x) {
    for(int y = 0; y < 3; ++y) {
        // select a random number from the list ...
        int rand = random.Next(0, numbers.Count - 1);
        tilearr[x, y] = numbers[rand];
        // ... and remove it from the list
        numbers.RemoveAt(rand);
    }
}

关于c# - 使用 Random 类随机化二维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60491678/

相关文章:

c# - 在现有 XML 中插入新的子节点

c# - Visual Studio 2010 认为它处于 Debug模式(但它设置为 Release模式)

c++ - 循环中的 RNG 并从字符串数组中打印单词

c# - 为什么我的 ListView 看起来是空的?

c# - 如何在用户选择电子邮件时在收件箱 Pane 上获取鼠标单击事件

java - 什么是 float 组?

c# - 结构和类对象数组的内存分配

java - Eclipse 中数组索引越界

java - 生成初始化 vector 真的需要 SecureRandom 还是足够随机?

reverse - 可逆伪随机序列发生器