Home > Software engineering >  How can I traverse a list with specific probability?
How can I traverse a list with specific probability?

Time:05-01

Suppose, I have a list:

List<Point2d> listOfCoordinates = new List<Point2d>();

Suppose, this list has 15 elements. I.e. listOfCoordinates.Count == 15.

Suppose, I want to print the items in the list with specific probabilities. I.e. if I run, say, 1000 iterations, 1st five elements should be printed 30% of the time(probability = 0.30); the middle five elements should be printed 50% of the time (probability = 0.50), and the last five elements should be printed 20% of the time (probability = 0.20).

Remember that, the probability is stored in Point2d class as a double value. I.e.

class Point2d
{
    public double X, Y, Probability;
}

Therefore, I can't manipulate the looping statements to achieve this.

How can I run a foreach loop to achieve this?

CodePudding user response:

Assuming printing each Point2d is an independent event, with probability Probability, and you have a list such as:

var list = new List<Point2d> {
    // first 5 all have probability 0.3
    new(1, 2, 0.3),
    new(3, 4, 0.3),
    new(5, 6, 0.3),
    new(7, 8, 0.3),
    new(9, 10, 0.3),
    // middle 5 all have probability 0.5
    new(11, 12, 0.5),
    new(13, 14, 0.5),
    new(15, 16, 0.5),
    new(17, 18, 0.5),
    new(19, 20, 0.5),
    // last 5 all have probability 0.2
    new(21, 22, 0.2),
    new(23, 24, 0.2),
    new(25, 26, 0.2),
    new(27, 28, 0.2),
    new(29, 30, 0.2)
};

You can print them out like this:

void Print(List<Point2d> list, Random random) {
    foreach (var point in list) {
        if (random.NextDouble() < point.Probability) {
            Console.WriteLine(point);
        }
    }
}

Note that NextDouble returns a value before 0 (inclusive) and 1 (exclusive).

Doing 1000 iterations will give you about 5000 lines:

var random = new Random();
for (int i = 0 ; i < 1000 ; i  ) {
    Print(list, random);
}
  • Related