Hello my task is to swap elements of list, with the index that needs to be swapped in another list, so fx:
If I have:
[3,1,2] as the list
And:
[[1,2],[2,3]] as the index that needs to be swapped
Then it should go like:
[1,2] = 3 and 1 getting swapped
[2,3] = 3 and 2 getting swapped
So i would end up with Output = [1,2,3]
The predicate is specified to be like this:
swap(C,Input,Output)
Where C is the list of which elemenst that should be swapped.
Input is the list that should be swapped.
Output is the swapped list.
I would like some advice on how to swapping those elements based on this, I have already looked at this: swap two elements from list with specified indices
Hope that someone can help me with this.
Edit:
So far I have tried something like this:
swap( Input,[I|J], Input ) :-
I = J.
swap( Input, [I|J], Output ) :-
swap( Input, [I|J], Output, _, _ ).
swap( Input, [I|J], Output ) :-
swap( Input, J, I, Output, _, _ ).
swap( [E2|Ls], I, 0, [E1|Ls], E1, E2 ):-!.
swap( [E1|Es], 0, J, [E2|Rs], E1, E2 ) :-
N2 is J - 1,
swap( Es, -1, N2, Rs, E1, E2 ),!.
swap( [E|Es], [I|J], [E|Rs], E1, E2 ) :-
N1 is I - 1,
N2 is J - 1,
swap( Es, N1, N2, Rs, E1, E2 ).
But I am only able to use "one" list as the indexes of what that has to be swapped, like [1,2], what I am looking for is being able to use multiple like [[1,2],[2,3]] and so on.
Using list_i_j_swapped/4
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).
swap(List,[],List).
swap(List1,Swaps,ListSwapped):-
Swaps =[[Index1,Index2]|T],
list_i_j_swapped(List1,Index1,Index2,List2),
swap(List2,T,ListSwapped).
Q:
?- swap([3,1,2],[[0,1],[1,2]],X).
X = [1, 2, 3] ;
false.
The positions are zero indexed.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments