如何从C#中的数组中获取随机值
可能的重复:
访问列表中的随机项目
我有一个带数字的数组,我想从这个数组中获取随机元素.例如:{0,1,4,6,8,2}.我想选择 6 并将这个数字放在另一个数组中,新数组的值将是 {6,....}.
I have an array with numbers and I want to get random elements from this array. For example: {0,1,4,6,8,2}. I want to select 6 and put this number in another array, and the new array will have the value {6,....}.
我使用 random.next(0, array.length),但这给出了长度的随机数,我需要随机数组数.
I use random.next(0, array.length), but this gives a random number of the length and I need the random array numbers.
for (int i = 0; i < caminohormiga.Length; i++ )
{
if (caminohormiga[i] == 0)
{
continue;
}
for (int j = 0; j < caminohormiga.Length; j++)
{
if (caminohormiga[j] == caminohormiga[i] && i != j)
{
caminohormiga[j] = 0;
}
}
}
for (int i = 0; i < caminohormiga.Length; i++)
{
int start2 = random.Next(0, caminohormiga.Length);
Console.Write(start2);
}
return caminohormiga;
我使用 random.next(0, array.length),但这给出了长度的随机数,我需要随机数组数.
I use the random.next(0, array.length), but this give random number of the length and i need the random array numbers.
使用 random.next(0, array.length)
的返回值作为索引从 array
Use the return value from random.next(0, array.length)
as index to get value from the array
Random random = new Random();
int start2 = random.Next(0, caminohormiga.Length);
Console.Write(caminohormiga[start2]);