Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Random Enumerable?

I have a class Rectangle which has a method RandomPoint returning a random point within it. It looks like:

class Rectangle {
    int W,H;
    Random rnd = new Random();

    public Point RandomPoint() {
        return new Point(rnd.NextDouble() * W, rnd.NextDouble() * H);
    }
}

But I hope it to be a IEnumerable<Point> so that I can use LINQ on it, e.g. rect.RandomPoint().Take(10).

How to implement it succinctly?

like image 336
Lai Yu-Hsuan Avatar asked Nov 30 '22 04:11

Lai Yu-Hsuan


2 Answers

You can use an iterator block:

class Rectangle
{
    public int Width { get; private set; }
    public int Height { get; private set; }

    public Rectangle(int width, int height)
    {
        this.Width = width;
        this.Height = height;
    }

    public IEnumerable<Point> RandomPoints(Random rnd)
    {
        while (true)
        {
            yield return new Point(rnd.NextDouble() * Width,
                                   rnd.NextDouble() * Height);
        }
    }
}
like image 195
Mark Byers Avatar answered Dec 05 '22 04:12

Mark Byers


IEnumerable<Point> RandomPoint(int W, int H)
{
    Random rnd = new Random();
    while (true)
        yield return new Point(rnd.Next(0,W+1),rnd.Next(0,H+1));
}
like image 45
L.B Avatar answered Dec 05 '22 04:12

L.B