假設,我有一個清單:
List<Point2d> listOfCoordinates = new List<Point2d>();
假設這個串列有 15 個元素。即listOfCoordinates.Count == 15。
假設,我想以特定概率列印串列中的專案。即,如果我運行 1000 次迭代,則應在 30% 的時間內列印前五個元素(概率 = 0.30);中間的五個元素應在 50% 的時間內列印(概率 = 0.50),最后五個元素應在 20% 的時間內列印(概率 = 0.20)。
請記住,概率在Point2d類中存盤為雙精度值。IE
class Point2d
{
public double X, Y, Probability;
}
因此,我無法操縱回圈陳述句來實作這一點。
我怎樣才能運行一個foreach回圈來實作這一點?
uj5u.com熱心網友回復:
假設列印每個Point2d都是一個獨立的事件,概率為Probability,并且您有一個串列,例如:
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)
};
你可以像這樣列印出來:
void Print(List<Point2d> list, Random random) {
foreach (var point in list) {
if (random.NextDouble() < point.Probability) {
Console.WriteLine(point);
}
}
}
請注意,NextDouble回傳 0(包括)和 1(不包括)之前的值。
做 1000 次迭代會給你大約 5000 行:
var random = new Random();
for (int i = 0 ; i < 1000 ; i ) {
Print(list, random);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/468874.html
