dimanche 27 août 2017

How to choose random float in a square weighted against arbitrary zones?

I have a square, which goes from -1 to 1 in x and y.

Choosing a random point in this square is pretty easy:

Random r = new Random();
float x = (float)Math.Round(r.NextDouble() * 2 - 1, 4);
float y = (float)Math.Round(r.NextDouble() * 2 - 1, 4);

This gives me any point, with equal probability, in my square.

enter image description here

It would be pretty easy too to just remove a section of the square from the possibilities

Random r = new Random();
float x = (float)Math.Round(r.NextDouble() * 1.5 - 1, 4);
float y = (float)Math.Round(r.NextDouble() * 2 - 1, 4);

enter image description here

But what I'm really struglling to do, is to weight the random towards a certain zone. Specifically, I would like the section highlighted here to be more likely, and everything else (except the red section, which is still off-limits) should have a probability lower depending on the distance from the highligthed line. The furthest point should have 0 chance, and the rest an existing chance which is higher when closer to the line, with points exactly on my line (since I round them to a specific decimal, there are points with are on the line) having the best odds.

enter image description here

Sorry for the ugly pictures. This is the best i could do in paint to show my thoughts.

The "most likely" area is an empty diamond (just the that with the vertices (-1, 0), (0, -0.5), (1, 0), (0, 0.5), with of course the red area override the weighting because it's off limits. The red area is anything with x > 0.5

Does anyone knows how to do this? I'm working in C# but honestly an algorithm in any non-esoteric language would do the trick. I'm completely lost as to how to proceed.




Aucun commentaire:

Enregistrer un commentaire