7

In python you can do something like this:

arr = list(set(randint(-50, 50) for _ in range(10)))

I do know how to program a extension method that fills a array, list or whatever you need with random values. I find this cumbersome though, and I really admire how you can do it in python. Although, I only know of Enumerable.Range, which only can be used for generating fixed sequences, to my knowledge.

Is it possible in C# as well?

nawfal
  • 70,104
  • 56
  • 326
  • 368
CasperT
  • 3,425
  • 11
  • 41
  • 56

4 Answers4

16

You could do like this:

Random rnd = new Random();
List<int> = Enumerable.Range(0,10).Select(n => rnd.Next(-50, 51)).ToList();
Guffa
  • 687,336
  • 108
  • 737
  • 1,005
2
var r = new Random();

var l = Enumerable.Range(0, 10).Select(x => r.Next(100) - 50).ToList();
Rob Bell
  • 3,542
  • 5
  • 28
  • 49
leppie
  • 115,091
  • 17
  • 196
  • 297
  • 1
    This doesn't compile. `Enumerable.Range` takes two arguments - start and count. You need to pass a 0 as the first argument. – adrianbanks Aug 17 '09 at 11:42
2

Sure, Something like...

Random r = new Random();
var ints = Enumerable.Range(0, 50).OrderBy(i => r.Next());
Tim Jarvis
  • 18,465
  • 9
  • 55
  • 92
  • Note, this one is more like a shuffle (if thats what you are after) other wise the select is the better answer. – Tim Jarvis Aug 17 '09 at 11:46
  • Note that there is a slight skew with that method when you get duplicate random numbers. The best shuffle method is a classic by Knuth, described here: http://stackoverflow.com/questions/1262480/how-to-shuffle-a-listt/1262521 – Guffa Aug 17 '09 at 12:36
1

Just to add a variation, you could create a very simple static method like this:

    public static IEnumerable<int> RandomSequence(int minValue, int maxValue)
    {
        Random r = new Random();
        while (true)
            yield return r.Next(minValue, maxValue);
    }

And then use it like this:

    var numbers = RandomSequence(-50, 50).Take(10));

    foreach(var number in numbers)
        Console.WriteLine(number);

I love yield return... hehe c",)

Svish
  • 152,914
  • 173
  • 462
  • 620