Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get random values from array in C# [duplicate]

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;
like image 646
Shebystian Avatar asked Jan 12 '13 20:01

Shebystian


People also ask

What does RAND () do in C?

Description. The C library function int rand(void) returns a pseudo-random number in the range of 0 to RAND_MAX. RAND_MAX is a constant whose default value may vary between implementations but it is granted to be at least 32767.


3 Answers

I use the random.next(0, array.length), but this give random number of the length and i need the random array numbers.

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]);
like image 185
Tilak Avatar answered Oct 23 '22 06:10

Tilak


To shuffle

int[] numbers = new [] {0, 1, 4, 6, 8, 2};
int[] shuffled = numbers.OrderBy(n => Guid.NewGuid()).ToArray();
like image 30
Seth Flowers Avatar answered Oct 23 '22 05:10

Seth Flowers


You just need to use the random number as a reference to the array:

var arr1 = new[]{1,2,3,4,5,6}
var rndMember = arr1[random.Next(arr1.Length)];
like image 5
faester Avatar answered Oct 23 '22 05:10

faester