Next predicate confusion

Viewed 712

I'm in the process of learning prolog, I'm currently writing a next predicate for a game which is really simple.

you have a list [1,0,1,0,0,1] A legal move is move a 1 to a zero position, the 1 can only move right to the first position containing 0, but it is allowed to jump over other values if necessary.

firstly I wrote a predicate to change the value 0 to 1:

flip_first_zero([0|Tail], [1|Tail]). 

simple enough, now I'm trying to find the legal moves, I will try to explain my thought process:

next([],[],[]).
next([Head|Tail], Rest, Out):-
    flip_first_zero([Head|Tail],List1),
    append(Rest,List1,Out).

next([Head|Tail], [Head|Rest], List):-
    next(Tail,Rest, List).

an example [1,0,0,1,1,1,0] the output should be [0,1,0,1,1,1,0] ; [1,0,0,0,1,1,1]; [1,0,0,1,0,1,1] ; [1,0,0,1,1,0,1].

[1,0,0,1,1,1,0] -> [0,1,0,1,1,1,0]

[1,0,0,1,1,1,0] -> [1,0,0,0,1,1,1]

[1,0,0,1,1,1,0] -> [1,0,0,1,0,1,1]

[1,0,0,1,1,1,0] -> [1,0,0,1,1,0,1]

So how I've understood this is, I loop through removing the head each time by conserving this in Rest so I can append it back on after.

Am I approaching this wrong?

3 Answers
Related