SWI-Prolog.
It came to mind such a decision. Get a random alternative from generating permutations in non-lexicographical order.

position(L,X,[X|L]). position([H|T1],X,[H|T2]):-position(T1,X,T2). transposition([],[]). transposition([H|T],L):- transposition(T,T1), position(T1,H,L). % fixed permutation permutation(In, Out) :- len(In, Length), fact(Length, Count), permutation(In, Out, Count), !. permutation(_, _, 0):-!. permutation(In, Out, Count) :- Count > 0, transposition(In, Out), rand(Stop, 0, 10), write(Count), nl, Stop < 5, Count1 is Count - 1, permutation(In, Out, Count1); Stop >=5,!. 

How to make this program stop when Stop> = 5 for example.

  • or maybe there is some kind of built-in predicate for obtaining a random alternative, I know what it is to obtain all alternatives. - shkiper

1 answer 1

Use the random_permutation predicate from the random library.

 3 ?- use_module(library(random)). % library(pairs) compiled into pairs 0.00 sec, 4,568 bytes % library(random) compiled into random 0.03 sec, 46,624 bytes true. 4 ?- L=[1,2,3,4,5], random_permutation(L,K). L = [1, 2, 3, 4, 5], K = [1, 3, 2, 4, 5]. 
  • I will use a ready-made solution, but you can still tell what exactly the joint was with Stop> = 5, why he continued to prove further during backtracking. I tried to rewrite, but still it does not work out permutation ( , _, 0, _): - !. permutation ( , _, _, Rand): - Rand> 5,!. permutation (In, Out, Count, Rand): - transposition (In, Out), write (Count), nl, Count1 is Count - 1, rand (Rand, 0, 10), permutation (In, Out, Count1, Rand )! - shkiper
  • One of the problems was with the placement of brackets, each alternative should be in brackets. Moreover, it was better to use if then else: A -> B; C - Alexander Serebrenik