-1

How do I generate random numbers x times and write them as a string? I know how to generate random numbers:

Random rnd= new Random();
int num= rnd.Next(1, 51);

but how do I generate them x times and write them like "5, 15, 45"?

I hope my question is understandable.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Nicole
  • 127
  • 7
  • 8
    You use a loop. – tkausl Jan 20 '19 at 11:25
  • 1
    Be sure to not create the `Random` in a loop - see, e.g. [this](https://stackoverflow.com/q/767999/1364007) for why. – Wai Ha Lee Jan 20 '19 at 11:28
  • Using `System.Linq`:`IEnumerable r = Enumerable.Repeat(1, x).Select(_ => rnd.Next(1, 51))`...where x is count... – Johnny Jan 20 '19 at 11:29
  • Keep in mind that the Random class does **not** generate true random numbers, if you require something closer to true random use:`System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes()`. for more details see: [](https://stackoverflow.com/a/4892631/488699) – Menahem Jan 20 '19 at 11:49
  • Possible duplicate of [fill array with random but unique numbers in C#](https://stackoverflow.com/questions/35973361/fill-array-with-random-but-unique-numbers-in-c-sharp) – mjwills Jan 20 '19 at 12:22

2 Answers2

2
var x = 10;
List<int> numbers = new List<int>();
Random random = new Random();
for (int i = 0; i < x; i++)
{
    numbers.Add(random.Next(1, 100));
}

Console.WriteLine(string.Join(", ", numbers));

enter image description here

Jan Feyen
  • 535
  • 3
  • 13
0

Below is the example from https://www.dotnetperls.com/random.

Best thing to note is to make sure that you use same instance of Random class. If you used a new Random at the method level as a local, it would not be as good. The time-dependent seed would repeat itself.

using System;

class Program
{
    static void Main()
    {
         for(int i =0; i < 100; i++)
         {
             int number = GetRandom();
         }        
    }

    static Random _r = new Random();
    static int GetRandom()
    {
        // Use class-level Random.
        // ... When this method is called many times, it still has good Randoms.
        int n = _r.Next();

        // If this method declared a local Random, it would repeat itself.
        return n;
    }
}

Hope this helps.

Manoj Choudhari
  • 5,277
  • 2
  • 26
  • 37