公平的非二进制随机物品

huangapple go评论61阅读模式
英文:

Fair non-binary random item

问题

可以根据各自的随机值随机获取元组列表中的一个项目,并且确保公平的机会吗?

例如:

X = [(0.60, test1),  (0.20, test2),  (0.20, test3)]

在这种情况下,test1 有60% 的概率被选择,而其他的则有相应的概率。我尝试使用 maybe/1,但它给我每个元素一个"二进制机会",而我希望每个列表成员都有公平的机会,如果这有意义的话。

英文:

Is it possible to get an item of a list of tuples randomly regarding its own random value with a fair share?

For example:

X = [(0.60, test1),  (0.20, test2),  (0.20, test3)]

In this case test1 has a 60% probability of getting chosen over the other ones.
I tried using maybe/1 but that gives me a "binary chance" over each one whereas I want a fair chance for each member of the list if that makes sense.

答案1

得分: 3

您可以轻松地根据此答案中的解决方案(其中我复制了choice/3choice/4的谓词)进行如下调整:

solve:-
    X = [(0.60, test1),  (0.20, test2),  (0.20, test3)],
    findall(P,member((P,_),X),LP),
    findall(T,member((_,T),X),LT),
    choice(LT,LP,V),
    writeln(V).

choice([X|_], [P|_], Cumul, Rand, X) :-
    Rand < Cumul + P.
choice([_|Xs], [P|Ps], Cumul, Rand, Y) :-
    Cumul1 is Cumul + P,
    Rand >= Cumul1,
    choice(Xs, Ps, Cumul1, Rand, Y).
choice([X], [P], Cumul, Rand, X) :-
    Rand < Cumul + P.

choice(Xs, Ps, Y) :- random(R), choice(Xs, Ps, 0, R, Y), !.

然后调用 ?- solve。这是一个基本的解决方案,可以改进,例如,不需要两次调用findall/2。一个有趣的替代方法是使用概率逻辑编程,请查看它。

英文:

You can easily adapt the solution from this answer (from which i copied the predicates choice/3 and choice/4), in this way:

solve:-
    X = [(0.60, test1),  (0.20, test2),  (0.20, test3)],
    findall(P,member((P,_),X),LP),
    findall(T,member((_,T),X),LT),
    choice(LT,LP,V),
    writeln(V).

choice([X|_], [P|_], Cumul, Rand, X) :-
    Rand &lt; Cumul + P.
choice([_|Xs], [P|Ps], Cumul, Rand, Y) :-
    Cumul1 is Cumul + P,
    Rand &gt;= Cumul1,
    choice(Xs, Ps, Cumul1, Rand, Y).
choice([X], [P], Cumul, Rand, X) :-
    Rand &lt; Cumul + P.

choice(Xs, Ps, Y) :- random(R), choice(Xs, Ps, 0, R, Y), !.

And then call ?- solve. This is a basic solution, it can be improved, for instance without calling findall/2 two times... An interesting alternative is to use probabilistic logic programming, check it out.

huangapple
  • 本文由 发表于 2020年1月4日 01:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582614.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定