My goal is to implement the pivot(Before,After) predicate that returns true when Before's first half is equal to After's second half and Before's second half is equal to After's first half.
- With an even number of elements in input list, the lengths of the two halves are same.
- With an odd number of elements, the lengths of the two halves are same with the center element doesn't change.
I tried to implement the predicate and it is working but not perfectly. Below is my predicate.
pivot(Before,After) :-
append(A,B,Before),
length(A,N),
length(B,N),
append(B,A,After).
pivot(Before,After) :-
append(A,B,Before),
length(A,N),
N1 is N + 1,
length(B,N1),
append(C,Tail,B),
length(C,1),
append(Tail,C,F),
append(F,A,After).
The pivot(A,[1,2,3,4,5]) is running, but I do not get output.
I am expecting A = [4,5,3,1,2].
A possible solution is:
How does the predicate work?
Another examples:
A comparison of the various suggested solutions for this problem, using SWI-Prolog 8.4.3.
Results:
Gusbro's solution caused stack overflow for list with length 9000000.