I want to delete only second appearance of each element in given array and return the result in a new array. The given array can have have atomic elements but also can have list like element within it.
the predicate should be called like this: delete_second(L1,L2).
L1=[1,2,4,1,[1,2,3,[4]],2,1]
L2=[1,2,4,[1,3,[]],2,1].
2
votes
If you want to return a favor to gusbro, you can accept his answer.
– Cephalopod
1 Answers
1
votes
You might use two accumulator lists. In one accumulator you would have the items that appeared just once, and on the other accumulator you would have the items that appeared more than once. So you would have to go through all the items of the input list updating those accumulators and selecting and discarding the item from the output list if required.
Something like:
delete_second(In, Out):-
delete_second(In, [], [], _, _, Out).
delete_second([], Once, Twice, Once, Twice, []):- !.
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [Y|Out]):-
delete_second(X, Once, Twice, MOnce, MTwice, Y),
!,
delete_second(Tail, MOnce, MTwice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
member(X, Twice),
!,
delete_second(Tail, Once, Twice, NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, Out):-
append(OnceP, [X|OnceT], Once),
append(OnceP, OnceT, MOnce),
!,
delete_second(Tail, MOnce, [X|Twice], NOnce, NTwice, Out).
delete_second([X|Tail], Once, Twice, NOnce, NTwice, [X|Out]):-
!,
delete_second(Tail, [X|Once], Twice, NOnce, NTwice, Out).