Jason Thomas
Jason Thomas

Reputation: 11

Prolog: Generating Every Possibility of a List Given a Pattern

Let's say you have a list in Prolog such as: [3,4,2,2,1,4]. How would one go about generating a list of lists of all possible patterns that start at the first element of the list, then either go to the i + 2th element, or the i + 3rd element, and so on from there.

Example: Say I have [3,4,2,2,1,4,8]. I want to be able to generate a list of lists such as: [[3,2,1,8], [3,2,4], [3,2,8]]

I.e. all possibilities of either every other element or every i+3 element, or any other combination, such as i+2,i+3,i+2,i+2, etc.

I've implemented my own version of a powerset, but I can't seem to figure out where to start.

Upvotes: 1

Views: 576

Answers (1)

malbarbo
malbarbo

Reputation: 11177

gen([], []).
gen([A], [A]).
gen([A, _ | T], [A | Xs]) :- gen(T, Xs).
gen([A, _, _ | T], [A | Xs]) :- gen(T, Xs).

results in

?- gen([3,4,2,2,1,4,8], X).
X = [3, 2, 1, 8] ;
X = [3, 2, 1] ;
X = [3, 2, 4] ;
X = [3, 2, 4] ;
X = [3, 2, 8] ;
false.

You can use findall/3 to get all results

?- findall(X, gen([3,4,2,2,1,4,8], X), Z).
Z = [[3, 2, 1, 8], [3, 2, 1], [3, 2, 4], [3, 2, 4], [3, 2, 8]].

Upvotes: 1

Related Questions