4

その中にランダムポイントを返すRectangleメソッドを持つクラスがあります。RandomPoint次のようになります。

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

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

しかし、それIEnumerable<Point>を使用できるようになることを願っています。LINQrect.RandomPoint().Take(10)

それを簡潔に実装する方法は?

4

3 に答える 3

12

イテレータ ブロックを使用できます。

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);
        }
    }
}
于 2012-12-17T14:08:39.740 に答える
7
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));
}
于 2012-12-17T14:08:41.263 に答える
1

yieldオプションになる可能性があります。

public IEnumerable<Point> RandomPoint() {
    while (true)
    {
        yield return new Point(rnd.NextDouble() * W, rnd.NextDouble() * H);
    }
于 2012-12-17T14:09:17.037 に答える