V
V
valerahex2018-12-18 13:05:10
Prolog
valerahex, 2018-12-18 13:05:10

Is it possible to compare the positions of elements in two lists?

Hello, I'm asking for help in implementing an algorithm for comparing the positions of elements in two lists.
The first list is a sequence of arbitrary elements. The second list is a sequence of elements from the first list. It is necessary to write a predicate that will return true if the elements of the second list have the same order as in the first. For example
[1, 1, 1, 2, 2, 2, 3, 3, 3]
[1, 2, 3]
true
[1, 1, 1, 2, 2, 2, 3, 3, 3]
[1, 3, 2]
false

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Paramonov, 2018-12-18
@varagian

Help is on the way :) but the task is not fully explained - as I understand it, in the first case, the numbers go in blocks, and in the second? Well, maybe in the first case [1,2,3,3,3,222,1]? Or the order is fixed -- i.e. objects occur many times -- but if 3 comes after 2 and before 5, i.e. [2,2,2,2,3,3,5] then the triple can't appear later?
In this case, the solution is: r_duplicates -- removes duplicate elements from both lists -- i.e. [1, 1, 1, 2, 2, 2, 3, 3, 3] => turns into [1,2,3] -- and then compares the lists head-on.

r_duplicates([],[]).

r_duplicates([H | T], List) :-
     member(H, T),
     r_duplicates( T, List).

r_duplicates([H | T], [H|T1]) :-
      \+member(H, T),
      r_duplicates( T, T1).

compare_order(X,Y) :- r_duplicates(X,Z), r_duplicates(Y,H), H == Z.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question