Look at your "more complex" problem. An exhaustive search works great!
Here is a comparison with Sergeyโs decision, which can be significantly improved by factoring common goals:
m([1|A], X) :- A = [_|_], append(X, [2], A). m([E | X], Z) :- m(X, Y), ( E = 3, append(Y, Y, Z) ; E = 4, reverse(Y, Z) ; E = 5, Y = [_ | Z] ; E = 6, Z = [1 | Y] ; E = 7, Z = [2 | Y] ).
For the query time(findall(_, (question3(X), write(X), nl), _)). I get with B 8.1, SICStus 4.3b8:
ฬ B tabled 104.542s ฬ B 678.394s false B 16.013s false B tabled 53.007s ฬ SICStus 439.210s false SICStus 7.990s ฬ SWI 1383.678s, 5,363,110,835 inferences false SWI 44.743s, 185,136,302 inferences
Additional questions are not so difficult to answer. Only SICStus with above m/2 and call_nth/2 :
| ?- time(call_nth( ( length(Xs0,N),append(Xs0,Xs0,Ys),m(Xs0,Ys), writeq(Ys),nl ), 10)). [4,3,7,4,3,1,4,3,7,4,3,1,2,4,3,7,4,3,1,4,3,7,4,3,1,2] [3,4,7,4,3,1,3,4,7,4,3,1,2,3,4,7,4,3,1,3,4,7,4,3,1,2] [4,3,7,3,4,1,4,3,7,3,4,1,2,4,3,7,3,4,1,4,3,7,3,4,1,2] [3,4,7,3,4,1,3,4,7,3,4,1,2,3,4,7,3,4,1,3,4,7,3,4,1,2] [3,5,4,5,3,1,2,2,1,3,5,4,5,3,1,2,3,5,4,5,3,1,2,2,1,3,5,4,5,3,1,2] [3,5,5,3,4,1,2,1,4,3,5,5,3,4,1,2,3,5,5,3,4,1,2,1,4,3,5,5,3,4,1,2] [5,4,7,4,3,3,1,2,5,4,7,4,3,3,1,2,5,4,7,4,3,3,1,2,5,4,7,4,3,3,1,2] [4,7,4,5,3,3,1,2,4,7,4,5,3,3,1,2,4,7,4,5,3,3,1,2,4,7,4,5,3,3,1,2] [5,4,7,3,4,3,1,2,5,4,7,3,4,3,1,2,5,4,7,3,4,3,1,2,5,4,7,3,4,3,1,2] [3,5,4,7,4,3,1,_2735,3,5,4,7,4,3,1,2,3,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