如何将2d数组随机唯一数字重制为3d?

时间:2015-11-01 22:32:44

标签: c#

{"id":"mainListings","view":{"image":false}}
{"id":"mainListings","view":{"image":"true"}}
{"id":"mainListings","view":{"image":"false"}}

//我想要像3D和4 D阵列这样的方法那样做,我可以更改或添加什么?

2 个答案:

答案 0 :(得分:1)

您可以直接做更高维度的工作。

这是我的3D代码:

var r = new Random();

int [,,] x = new int[10, 8, 8];

var count =
    Enumerable
        .Range(0, x.Rank)
        .Select(y => x.GetLength(y))
        .Aggregate((y, z) => y * z);

var values =
    Enumerable
        .Range(10, count)
        .OrderBy(y => r.Next())
        .ToArray();

var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
    for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
        for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
            x[i, j, k] = values[v++];

要将其更改为4D,这些行会更改:

int [,,,] x = new int[10, 8, 8, 12];

// ...

var v = 0;
for (var i = x.GetLowerBound(0); i <= x.GetUpperBound(0); i++)
    for (var j = x.GetLowerBound(1); j <= x.GetUpperBound(1); j++)
        for (var k = x.GetLowerBound(2); k <= x.GetUpperBound(2); k++)
            for (var l = x.GetLowerBound(3); l <= x.GetUpperBound(3); l++)
                    x[i, j, k, l] = values[v++];

现在,在这段代码中,我明确地调用了GetLowerBound以及GetUpperBound,因为在.NET代码中可以使用非零的数组。

此外,在您拥有唯一数字之前,我不是重复尝试获取随机数,而是简单地生成一系列唯一数字,然后对它们进行随机排序。这与原始代码略有不同。您需要80(10 x 8)个随机值,并且您选择的值范围从1099。所以你的数字有一些漏洞。

答案 1 :(得分:0)

随机r = new Random();

        int[,,] x = new int[10, 8, 8];

        int[] temp = new int[x.Length];



        #region one dimensional array unique numbers.

        for (int i = 0; i < temp.Length; i++)
        {

            temp[i] = r.Next(10, 650);

            for (int j = 0; j < i; j++)
            {

                if (temp[i] == temp[j])
                {

                    i--;

                    break;

                }

            }

        }

        #endregion



        for (int i = 0, index = 0; i < x.GetLength(0); i++)
        {

            for (int j = 0; j < x.GetLength(1); j++)
            {
                for (int k = 0; k < x.GetLength(2); k++)
                {



                    x[i, j, k] = temp[index++];

                    Console.Write(x[i, j, k] + " ");

                }

                Console.WriteLine();

            }
        }// i think it's correct code i've changed it