I want the random numbers like:
{1,2,6} {8,9,5} {4,3,5}
You can try Linq:
// Easiest, but not thread safe
private static Random s_Generator = new Random()
...
int outerCount = 3; // 3 groups
int innerCount = 3; // each group has 3 items
int[][] randoms = Enumerable
.Range(0, outerCount)
.Select(x => Enumerable
.Range(0, innerCount)
.Select(y => s_Generator.Next(1, 10)) // let randoms be in [1..9] range
.ToArray())
.ToArray();
Test:
string report = string.Join(" ", randoms
.Select(item => "{" + string.Join(",", item) + "}"));
Console.Write(report);
Outcome (may differ from run to run since we output random numbers):
{7,4,5} {1,7,4} {6,5,6}
One way to generate random numbers in C# is to use the Random object and to specify the min and max numbers such as:
Random r = new Random();
var n = r.Next(1, 6);//this will generate number between 1 and 5
Console.WriteLine(n);
Edit 1 : to get 3 random numbers at a time, the simplest way I can think of is to just generate the random numbers, and add them to an array:
public int[] generateRandomArray(int arraySize, int min, int max)
{
Random r = new Random();
int[] results = new int[arraySize];
for(int i = 0 ; i < arraySize; i++)
{
var n = r.Next(min, max);
results[i] = n;
}
return results;
}
You can use the Random
class along with yield
:
static IEnumerable<Tuple<int, int, int>> GenerateRandomNumbers(int maxValue)
{
var random = new Random();
while(true)
{
var x = random.Next(maxValue);
var y = random.Next(maxValue);
var z = random.Next(maxValue);
yield return Tuple.Create(x, y, z);
}
}
So, if you want 20 triplets between 0 and 10 as an array you can write
var items = GenerateRandomNumbers(10).Take(20).ToArray();