patternMinor
Sample n items without replacement in Prolog
Viewed 0 times
withoutsampleprologitemsreplacement
Problem
I have the following Prolog code which samples n items from a list without replacement:
Is there a 'nicer' way to do this?
samp(0,_,Sample,Sample).
samp(N,Domain0, Sample0, Sample):-
N >= 0,
length(Domain0,L),
RandomNumber is random(L),
nth0(RandomNumber, Domain0, X),
delete(Domain0,X,Domain1),
append(Sample0,[X],Sample1),
N1 is N-1,
samp(N1,Domain1,Sample1,Sample).
sample(Domain,N,Sample):-
samp(N,Domain,[],Sample).Is there a 'nicer' way to do this?
Solution
In SWI-Prolog you could do this that way:
Be careful, this predicate is not a true relation (just as in your code).
sample_swi(Domain, N, Sample) :-
random_permutation(Domain, Permutation),
length(Sample, N),
append(Sample, _, Permutation).Be careful, this predicate is not a true relation (just as in your code).
Code Snippets
sample_swi(Domain, N, Sample) :-
random_permutation(Domain, Permutation),
length(Sample, N),
append(Sample, _, Permutation).Context
StackExchange Code Review Q#49471, answer score: 4
Revisions (0)
No revisions yet.