Random items in Prolog

南笙酒味 提交于 2019-12-10 14:33:18

问题


I know I can do X is random(10). to get a random number from 0 to 10, but is there a similar command to get a random matching item?


回答1:


You can implement it. Here is a version:

%% choose(List, Elt) - chooses a random element
%% in List and unifies it with Elt.
choose([], []).
choose(List, Elt) :-
        length(List, Length),
        random(0, Length, Index),
        nth0(Index, List, Elt).

From http://ozone.wordpress.com/2006/02/22/little-prolog-challenge/




回答2:


SWI-Prolog v6 has random_member/2 defined like this:

?- listing(random_member).
random:random_member(D, A) :-
    length(A, B),
    C is random(B),
    nth0(C, A, D).

Usage example:

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 1.

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 1.

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 2.

?- random_member(a(N), [a(1), a(2), b(3)]).
false.

?- random_member(a(N), [a(1), a(2), b(3)]).
false.

?- random_member(a(N), [a(1), a(2), b(3)]).
N = 2.

You probably want to use it in the (-,+) mode though.



来源:https://stackoverflow.com/questions/2261238/random-items-in-prolog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!