Shuffle in prolog

前端 未结 2 422
清酒与你
清酒与你 2020-11-29 12:03

I\'m trying to write a procedure in prolog where if L1 = [1,2,3] and L2 = [4,5,6] then L3 = [1,4,2,5,3,6]

so shuffle([1,2,3],[4,5,6],[1,4,2,5,3,6])

相关标签:
2条回答
  • 2020-11-29 12:42
    shuffle([], B, B).
    shuffle([H|A], B, [H|S]) :- shuffle(B, A, S).
    

    In this kind of problems, usually the difficult part is not Prolog but identifying the simplest recursive relation that solves it.

    0 讨论(0)
  • 2020-11-29 12:53

    Here's the simple solution:

    shuffle([], [], []).
    shuffle([X|Xs], [Y|Ys], [X,Y|Zs]) :-
        shuffle(Xs,Ys,Zs).
    

    Generalizing this to handle list of unequal length is a matter of changing the base case into:

    shuffle(Xs, [], Xs).
    shuffle([], Ys, Ys).
    

    although that may generate duplicate solutions. Those can be fixed with a cut if you don't mind the predicate being "one-way".

    (Though I still think you should call this flatzip or interlace instead of shuffle.)

    0 讨论(0)
提交回复
热议问题