I am trying to merge the elements in a list, the rules are as follows:
1. Merge a list in a way that if 2 consecutive numbers in a list are a same number they should merge into one by summing them (i.e. [4,4,0,0] -> [8,0,0,0]).
2. A newly merged tile cannot be combined with another tile in the same turn (Example: [4,4,8,0] ->[8,8,0,0] True, but [16,0,0,0] False)
3. List length should be 4. Which adds a zero to the tail if list decreases after merging. (Example: [4,4,0,2] -> [8,0,2,0]).
4. Note in case of zeros: [0,0,2,2] -> [0,4,0,0].
I have been able to create the code, however I want to find a simpler approach explained in detail.
My approach:
merge([H|T],L):-
merge2([H|T],J),
(
length(J,2)->
append(J,[0,0],L);
length(J,3)->
append(J,[0],L);length(J,4)-> J=L).
merge2(_,[]).
merge2([X],[X|_]).
merge2([H1,H2|T],[W|L]):-
H1=H2,
W is H1+H2,
merge2(T,L).
merge2([H1,H2|T],[H1|L]):-
H1\=H2,
merge2([H2|T],L).