Possible Duplicate:
Access random item in list
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,....}.
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;
Try like this
instead of
You just need to use the random number as a reference to the array:
Use the return value from
random.next(0, array.length)
as index to get value from thearray
To shuffle
I noticed in the comments you wanted no repeats, so you want the numbers to be 'shuffled' similar to a deck of cards.
I would use a
List<>
for the source items, grab them at random and push them to aStack<>
to create the deck of numbers.Here is an example:
So then: