I'm doing a C# coding. In my coding, I need to generate a random list of numbers. Normally, if we create a random, we need to select the range of the number. However for my case, I need to create a random number from an array. Any idea? I am using XAML and C#.
private void Submit_Click(object sender, RoutedEventArgs e)
{
int[] numbers = new int[5] {32, 67, 88, 13, 50};
Random rd = new Random();
//int myNo = rd.Next(numbers[])?
}
EXTRA: Each time i click the submit button, a random number of numbers[] will selected. How can i make sure the number is not repeated. For example: 1st click, myNo = 67; 2nd click, myNo = 50; 3rd click, myNo = 88; 4th click, myNo = 32; 5th click, myNo = 13. Thanks!
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.
Computational random number generators can typically generate pseudorandom numbers much faster than physical generators, while physical generators can generate "true randomness."
For example if you want to generate five random integers (or a single one) in the range [0, 10], just do: Random r = new Random(); int[] fiveRandomNumbers = r. ints(5, 0, 11).
You can create a random number whihch would represent the index from the array. Access the array element from that random index and you will get your number, since all your numbers in the array seems to be distinct.
int[] numbers = new int[5] { 32, 67, 88, 13, 50 };
Random rd = new Random();
int randomIndex = rd.Next(0, 5);
int randomNumber = numbers[randomIndex];
EDIT: (Thanks to @Corak) You can generate random Index based on array length, that would make it dynamic and work for any array's length.
int randomIndex = rd.Next(0, numbers.Length);
Edit 2: (For extra part of question).
You need to maintain a list of unique index numbers at class level. So your code would be something like:
Random rd = new Random(); //At class level
List<int> uniqueIndices = new List<int>(); //At class level
private void Submit_Click(object sender, RoutedEventArgs e)
{
int[] numbers = new int[5] {32, 67, 88, 13, 50};
int randomIndex = rd.Next(0, numbers.Length);
while(list.Contains(randomIndex)) //check if the item exists in the list or not.
{
randomIndex = rd.Next(0, numbers.Length);
}
list.Add(randomInex);
//...rest of your code.
}
Random r = new Random();
int index = r.Next(0, 5);
int randomNum = numbers[index];
This will give you random numbers between 0 and 4 which can be used to index your array and in turn pull random values from the array
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With