Random items in Prolog
Asked Answered
W

2

7

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?

Worshipful answered 14/2, 2010 at 13:43 Comment(0)
S
5

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/

Selfappointed answered 15/2, 2010 at 12:54 Comment(1)
Whoa there, the first clause of choose/2 isn't what you want. If the list it empty you should produce no solutions instead of unifying Elt with the empty list. "choose([],_) :- !, fail." would fix it. Also, this generates an infinite number of solutions which is usually undesirable.Protract
B
7

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.

Bandeau answered 8/2, 2012 at 12:48 Comment(0)
S
5

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/

Selfappointed answered 15/2, 2010 at 12:54 Comment(1)
Whoa there, the first clause of choose/2 isn't what you want. If the list it empty you should produce no solutions instead of unifying Elt with the empty list. "choose([],_) :- !, fail." would fix it. Also, this generates an infinite number of solutions which is usually undesirable.Protract

© 2022 - 2024 — McMap. All rights reserved.