How can I generate all the possible combinations of the elements of a list?
For example, given the list [1,2,3], I want to design a predicate with the form comb([1,2,3], L).
which should return the following answer for L:
[1]
[2]
[3]
[1,2]
[2,1]
[1,3]
[3,1]
[2,3]
[3,2]
[1,2,3]
[1,3,2]
[2,1,3]
[2,3,1]
[3,1,2]
[3,2,1]
相关问题
- Creating a SPARQL parameterized query using append
- How to join rules and print out outputs in prolog
- Splitting list and iterating in prolog
- Accumulating while in recursion/backtracking
- prolog trace how to use
相关文章
- What are the problems associated to Best First Sea
- How can I fix this circular predicate in Prolog?
- How to negate in Prolog
- Remove incorrect subsequent solutions without once
- prolog two lists are exactly the same
- Simplify Expressions in Prolog
- Check if any element's frequency is above a li
- Prolog — symetrical predicates
there is a predefined predicate called permutation ...
hope this helps ..
What you are asking for involves both combinations (selecting a subset) and permutations (rearranging the order) of a list.
Your example output implies that the empty list is not considered a valid solution, so we will exclude it in the implementation that follows. Reconsider if this was an oversight. Also this implementation produces the solutions in a different order than your example output.
Tested with Amzi! Prolog:
Hint: This is easy to do if you have written a predicate
inselt(X,Y,Z)
, which holds if any insertion ofY
intoX
givesZ
:Then
comb/3
can be coded recursively usinginselt/3
.Stay pure by defining
comb/2
based onsame_length/2
,prefix/2
,foldl/4
andselect/3
:Here's the sample query given by the OP:
Ok! But what if the list given as the first argument contains duplicates?
Not quite! Can we get rid of above redundant answers? Yes, simply use
selectd/3
!So let's re-run above query again with the improved implementation of
comb/2
!