user3006475
user3006475

Reputation: 47

Prolog exercise: filter sequence of consecutive elements

I am getting mad of prolog. I have to do an exercise which is filter_Sequences(N,L1,L2) and then SWI Prolog will answer in L2 the result of the elements which are consecutive in L1, I give you an example to explain it:

?- filter_sequence(2,[a,b,b,c,a,a,b,b,b,b,c,c,d],L2).
L2= [b,b,a,a,b,b,b,b,c,c]

It means 3 because of is the element N, is an integer which is the lowest rate of consecutive elements and then the list with 3 b's 3 a's and 4 b's and more digits but L2 keeps just the consecutive elements.

Thanks in advance.

Upvotes: 1

Views: 176

Answers (2)

salva
salva

Reputation: 10242

Update: As Will Ness has pointed out, this solution misses the N parameter.

  1. Get the first element from the list
  2. Compare with the second element from the list
  3. If the two elements are equal:
    1. place the two elements in the output
    2. and any following element that is also equal
  4. Otherwise discard the first element
  5. Repeat until the list is exhausted.

In Prolog:

% untested
delete_singles([], []).
delete_singles([A|T], O) :-
     (    T = [A|T1]
     ->   O = [A, A|O1],
          delete_singles(T1, A, O1)
     ;    delete_singles(T, O)).

delete_singles([], _, []).
delete_singles([H|T], A, O) :-
     (    H = A
     ->   O = [A|O1],
          delete_singles(T, A, O1)
     ;    delete_singles([H|T], O)).

Upvotes: 1

Will Ness
Will Ness

Reputation: 71119

Let's take a high-level approach.

mad(N,S,L2):- nrle(N,S,L),expand(L,L2).

right? nrle does an RLE encoding, but only keeps entries with at least N duplicates.

nrle(_,[],[]).
nrle(N,[A|B],L):- nrle(N,B,A-1,L).
nrle(N,[A|B],E-I,L):- 
    A = E -> I1 is I+1, nrle(N,B,E-I1,L) ;
    I >= N -> L=[E-I|L2], nrle(N,B,A-1,L2) ;
    nrle(N,B,A-1,L).
nrle(N,[],E-I,[E-I]):- I >= N.
nrle(N,[],E-I,[]):- I < N.

testing:

9 ?- nrle(3,[a,b,b,b,c,a,a,a,b,b,b,b,c,c,d],L2).
L2 = [b-3, a-3, b-4] ;
false.

10 ?- nrle(4,[a,b,b,b,c,a,a,a,b,b,b,b,c,c,d],L2).
L2 = [b-4] ;
false.

11 ?- nrle(2,[a,b,b,b,c,a,a,a,b,b,b,b,c,c,d],L2).
L2 = [b-3, a-3, b-4, c-2] ;
false.

Now, expand:

expand([A-1|C],[A|D]):- expand(C,D).
expand([A-B|C],[A|D]):- B>1, B1 is B-1, expand([A-B1|C],D).
expand([],[]).

And then,

25 ?- mad(3,[a,b,b,b,c,a,a,a,b,b,b,b,c,c,d],L2).
L2 = [b, b, b, a, a, a, b, b, b, b] ;
false.

See, Prolog is fun.

Upvotes: 2

Related Questions