-1

我从一维数组中获取值的方式是:

Random random = new Random();
getit = w[r.Next(0, w.Length)];

你能告诉我如何对二维数组做同样的事情吗?

4

3 回答 3

8

为确保您的分布均匀,您不应生成多个随机数。通过乘以维度的长度来计算可能的值的总数,选择一个索引,然后找到与该索引对应的一项:

public static T GetRandomValue<T>(T[,] array, Random random)
{
    int values = array.GetLength(0) * array.GetLength(1);
    int index = random.Next(values);
    return array[index / array.GetLength(0), index % array.GetLength(0)];
}
于 2013-04-08T16:33:46.193 回答
4

假设您有一个简单的二维数组[,]1而不是锯齿数组[][],那么您可以使用该Array.GetLength方法获取每个数组维度的长度。例如:

Random random = new Random();
string[,] arr = new string[10, 10];

int i1 = r.Next(0, arr.GetLength(0));
int i2 = r.Next(0, arr.GetLength(1));
string value = arr[i1, i2];

1 ) 多维数组的下界有可能与默认的0不同。这种情况下,请适当使用该Array.GetLowerBound方法


如果你有一个锯齿状数组[][],而不是一个真正的二维数组[,],那么你可以按顺序进行:

Random random = new Random();
string[][] arr = new string[][10];
for (int i = 0; i < arr.Length; i++)
    arr[i] = new string[10];

int i1 = r.Next(0, arr.Length);
string[] subarr = arr[i1];
int i2 = r.Next(0, subarr.Length);
string value = subarr[i2];
于 2013-04-08T16:32:11.977 回答
0

Not really the fastest method, but you could also do this with a bit of Linq:

var totalSize = Enumerable.Range(0, array.Rank).Aggregate(0, (l, r) => l * array.GetLength(r));
var getit = w.ElementAt(r.Next(0, totalSize));

This works for arrays of any dimension.

于 2013-04-08T16:39:32.787 回答