Prolog: search for length subscriptions> = 3

I would like to create a predicate that can check if the list will be divided into sublists, each of which contains at least three atoms.

For instance:

findgroups([1,2,3,4,5,6,7,8,9],L1).

Has such solutions as:

L1=[[1,2,3],[4,5,6],[7,8,9]]
L1=[[1,2,3,4],[5,6,7,8,9]]
L1=[[1,2,3,4,5],[6,7,8,9]]
L1=[[1,2,3,4,5,6],[7,8,9]]

However, the following errors will not be executed:

findgroups([1,2,3,4,5]).

I wrote several predicates based on splitting lists into two subheadings using append, but I got confused about handling multiple subscriptions.

Many thanks for your help.

Best regards j

+4
source share
2 answers

Perhaps this very simple solution could make

findgroups([], []).
findgroups(L, [[A,B,C|D]|Gs]) :-
    append([A,B,C|D], R, L),
    findgroups(R, Gs).

The last one solution is not requested, but it is correct, since you do not exclude a group of 1 element

?- findgroups([1,2,3,4,5,6,7,8,9], Gs).
Gs = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ;
Gs = [[1, 2, 3], [4, 5, 6, 7, 8, 9]] ;
Gs = [[1, 2, 3, 4], [5, 6, 7, 8, 9]] ;
Gs = [[1, 2, 3, 4, 5], [6, 7, 8, 9]] ;
Gs = [[1, 2, 3, 4, 5, 6], [7, 8, 9]] ;
Gs = [[1, 2, 3, 4, 5, 6, 7, 8|...]] ;
false.

To exactly follow the examples, I would write

findgroups(L, Gs) :- findgroups_(L, Gs), Gs = [_,_|_].
findgroups_([], []).
findgroups_(L, [[A,B,C|D]|Gs]) :-
    append([A,B,C|D], R, L),
    findgroups_(R, Gs).
0

! findgroups/2 , Prolog: Prolog ! ! ? :

?- findgroups(L, [[1,2,3],[4,5,6],[7,8,9]]).

- ? ! . , . - , - . :

?- list_lists(L, [[1,2,3],[4,5,6],[7,8,9]]).

, . :

?- elements_trigroups(L, [[1,2,3],[4,5,6],[7,8,9]]).

, : , ? - , els .

( ) :

es_trigroups(Es, Ess) :-
   phrase(seqq(Ess), Es).

: Es: E s. Ess - Es, , , E s.

seqq//1, .

Darn, :

?- es_trigroups([1,2,3,4,5], [Es,Fs]).
   Es = [], Fs = [1,2,3,4,5]
;  Es = [1], Fs = [2,3,4,5]
;  ...

, , . : . .

, :

es_trigroups(Es, Ess) :-
   trigroups(Ess),
   phrase(seqq(Ess), Es).

trigroups([]).
trigroups([Es|Ess]) :-
   Es = [_,_,_|_],
   trigroups(Ess).

, . , : . .

es_trigroups_bis(Es, Ess) :-
   phrase(seqq(Ess), Es),
   trigroups(Ess).

:

es_trigroups(A,B)terminates_if b(B).
    % optimal. loops found: [es_trigroups(_,[[_,_,_|_]|_]),es_trigroups(y,[[_,_,_|_]|_])]. NTI took    0ms,74i,74i
es_trigroups_bis(A,B)terminates_if b(B).
    % optimal. loops found: [es_trigroups_bis(_,[[]|_]),es_trigroups_bis(y,[[]|_])]. NTI took    0ms,79i,79i

, B ( ), A. , A B . :

es_trigroups_ter(Es, Ess) :-
   phrase(seq3s(Ess), Es).

seq3s([]) --> [].
seq3s([Es|Ess]) --> {Es = [_,_,_|_]}, seq(Es), seq3s(Ess).

!

es_trigroups_ter(A,B)terminates_if b(A);b(B).
    % optimal. loops found: [es_trigroups_ter([A|_],[[A,_,_|_]|_])]. NTI took    0ms,77i,77i
+5

All Articles