'Generating random int with specific condition C#
Consider some special condition, where we want to generate location data with some random speed.
public class Location
{
public double Lat { get; set; }
public double Lng { get; set; }
public int Speed { get; set; }
public DateTime Date { get; set; }
}
The speed can be randomly generated using Random.Next() method.
Now consider that we are going to have limit of 1 to 200 for speed,
and we want that most of the Random.Next(1,200) result be more likely at the rang of 1 to 120
(for example if we have 160 locations, most of the location speeds be at around 1 to 120(about 60% to 80% of the location) and the rest be at about range of 120 to 200)
I know some bad and ugly ways where you can divide your locations randomly into two list of locations and then generate speed separately for those lists, but I'm looking for a better and more efficient way.
Thanks!
Edit :
I have to mention that there is a property called
Date which is Type of DateTime and defines the time of a locations occurrence.
A list of location that is going to be generated will be a path so the speeds being generated should be relative to locations and time to just seem right(for example 2 continues locations can't have 2 unrelative speed like first location : 80KM/h , second location: 140 KM/h in a short time span of 30 seconds) so just the speed, date time and location should seem logically a normal path.
Solution 1:[1]
Can't you just use two random numbers? The first to determine which range, and the second to choose a number in the appropriate range?
Random rng = new Random(); // This should only be created once, somewhere.
double proportionInLowerRange = 0.7;
int speed;
if (rng.NextDouble() <= proportionInLowerRange)
speed = rng.Next(1, 121);
else
speed = rng.Next(120, 201);
Note: The probabilities are linear across both ranges, so if you wanted a normal distribution this wouldn't work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
