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?
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);
}
}
}
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));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With