Swap two elements from list with specified indices

2019-06-01 20:06发布

问题:

I need to swap two elements in list with specified indices using predicate:

swap(List, index1, index2).

I tried this way:

change_value([X|List], 0, Y, [Y|List2]) :- 
        copy_rest([X|List], List2). 
change_value([], P, Y, []).   
change_value([X|List], Pos, Y, [X|List2]) :- 
        X \== Y, 
        Pos > 0, 
        NewPos is Pos - 1, 
        change_value(List, NewPos, Y, List2). 

copy_rest([], []). 
copy_rest([X|List], [X|List2]) :- 
        copy_rest(List, List2).

Is there any better solution?

Thank you very much!

回答1:

No need to write recursive code!

Simply use the builtin predicates length/2, same_length/2, and append/3 like so:

list_i_j_swapped(As,I,J,Cs) :-
   same_length(As,Cs),
   append(BeforeI,[AtI|PastI],As),
   append(BeforeI,[AtJ|PastI],Bs),
   append(BeforeJ,[AtJ|PastJ],Bs),
   append(BeforeJ,[AtI|PastJ],Cs),
   length(BeforeI,I),
   length(BeforeJ,J).

Done! Let's put it to use!

?- list_i_j_swapped([e0,e1,e2,e3,e4,e5],5,1,Ys).
  Ys = [e0,e5,e2,e3,e4,e1]
; false.

OK! Does it work in the "other direction", too?

?- list_i_j_swapped(Xs,5,1,[e0,e5,e2,e3,e4,e1]).
  Xs = [e0,e1,e2,e3,e4,e5]
; false.

Alright! What about the following quite general query?

?- list_i_j_swapped([A,B,C],I,J,Ys).
  I = 0, J = 0, Ys = [A,B,C]
; I = 0, J = 1, Ys = [B,A,C]
; I = 0, J = 2, Ys = [C,B,A] 
; I = 1, J = 0, Ys = [B,A,C]
; I = 1, J = 1, Ys = [A,B,C]
; I = 1, J = 2, Ys = [A,C,B]
; I = 2, J = 0, Ys = [C,B,A]
; I = 2, J = 1, Ys = [A,C,B]
; I = J, J = 2, Ys = [A,B,C]
; false.

It worked! At last, we run the most general query:

?- list_i_j_swapped(Xs,I,J,Ys).
  I = 0, J = 0, Xs = [_A]      , Ys = [_A]
; I = 0, J = 0, Xs = [_A,_B]   , Ys = [_A,_B]
; I = 0, J = 1, Xs = [_A,_B]   , Ys = [_B,_A]
; I = 1, J = 0, Xs = [_A,_B]   , Ys = [_B,_A]
; I = 1, J = 1, Xs = [_A,_B]   , Ys = [_A,_B]
; I = 0, J = 0, Xs = [_A,_B,_C], Ys = [_A,_B,_C]
...

Fair enumeration out-of-the-box? What's not to like?



标签: list prolog swap