Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making an array of random ints

What i try to to, is generate an array of random int values, where the random values are taken between a min and a max.

So far i came up with this code:

int Min = 0; int Max = 20;  int[] test2 = new int[5]; Random randNum = new Random(); foreach (int value in test2) {     randNum.Next(Min, Max); } 

But its not fully working yet. I think i might be missing just 1 line or something. Can anyone help me out pushing me in the right direction ?

like image 863
Dante1986 Avatar asked Jan 15 '12 14:01

Dante1986


People also ask

How do you create an array of random integers in python?

To create a matrix of random integers in Python, randint() function of the numpy module is used. This function is used for random sampling i.e. all the numbers generated will be at random and cannot be predicted at hand. Parameters : low : [int] Lowest (signed) integer to be drawn from the distribution.

How do you create an array of random integers in Matlab?

You can use the randperm function to create a double array of random integer values that have no repeated values. For example, r4 = randperm(15,5);

How do I generate a random integer array in NumPy?

randint. Return random integers from low (inclusive) to high (exclusive). Return random integers from the “discrete uniform” distribution of the specified dtype in the “half-open” interval [low, high).


1 Answers

You are never assigning the values inside the test2 array. You have declared it but all the values will be 0. Here's how you could assign a random integer in the specified interval for each element of the array:

int Min = 0; int Max = 20;  // this declares an integer array with 5 elements // and initializes all of them to their default value // which is zero int[] test2 = new int[5];   Random randNum = new Random(); for (int i = 0; i < test2.Length; i++) {     test2[i] = randNum.Next(Min, Max); } 

alternatively you could use LINQ:

int Min = 0; int Max = 20; Random randNum = new Random(); int[] test2 = Enumerable     .Repeat(0, 5)     .Select(i => randNum.Next(Min, Max))     .ToArray(); 
like image 91
Darin Dimitrov Avatar answered Oct 13 '22 19:10

Darin Dimitrov