. , 0,1, 0,3, 0,2, 0,1, 0,3. A A = [0,1, 0,4, 0,6, 0,7, 1,0], A [n] = A [n-1] + p_n, n > 0 A [0] = p_0, p_n - n. r x A, , A [x] > r, x - .
:
cumulative_chances = [chances[0]]
for i=1 to chances.size()
cumulative_chances.append(chances[i]+cumulative_chances[i-1])
r=random(0, cumulative_chances.last())
i=0
while cumulative_chances[i]<r
i++
return i
, , p_n > 0 n. , , .
If nothing in your applications is performance sensitive, you can do this calculation inside a function. In other cases, I tentatively calculated it. Note that pseudo-code is not sensitive to normalization of values. They don't need to add upp to 1 (or 100 if you want a percentage), it works anyway.
klutt source
share