-6

I want the random numbers like:

{1,2,6} {8,9,5} {4,3,5}

  • 1
    Can you please be more specific about your requirement, and include what you have tried already? – sujith karivelil May 17 '17 at 10:07
  • 1
    http://stackoverflow.com/questions/8870193/making-an-array-of-random-ints might be usefull. – Vladimir May 17 '17 at 10:08
  • I have tried this: `Random rnd = new Random(); int i = rnd.Next(1, 7);` @BugFinder Sorry sir I forgot to mention that. I have tried with array also but didn't get the expected solution. – Nishank Jain May 17 '17 at 11:24

3 Answers3

1

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}
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

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;
}
Syl20
  • 117
  • 2
  • 18
0

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();
Sean
  • 60,939
  • 11
  • 97
  • 136