How I can get a vector from another through swaps?

Hi! I have two vectors obtained as permutations of 8 numbers: A=[1 5 8 7 4 3 2 6] B=[2 1 4 8 5 3 6 7] How I can get the second from the first with the fewest number of swaps? thanks.

Answers (2)

Do you mean randomly?
A=[1 5 8 7 4 3 2 6]
B=A(randperm(numel(A)))

1 Comment

thanks for the answer, but the problem is that i have the vectors and i would know how many swaps (exchanges) are needed starting from A to obtain B.
Wouldn't that simply be 7, at most? You simply do a swap of each element of A in turn to put it in the correct location as defined by B. It could take up to 7 swaps to get the first 7 numbers in the right location, and the 8th one will have to be in the correct location because how could it not be if all the others are correct. It could be less than 7 but 7 would be the most.

5 Comments

sorry but i'm not very pratical with matlab .. How i can do it?
@lucia: What kind of help do you expect? It is your homework and we cannot solve it for you without forcing you to cheat.
Is this homework? It's tagged as homework. If so, use a for loop. I think it's only like 3 or 4 lines of code. See http://www.mathworks.com/matlabcentral/answers/8626-how-do-i-get-help-on-homework-questions-on-matlab-answers
This works.
A=[1 5 8 7 4 3 2 6]
B=[2 1 4 8 5 3 6 7] % What we should get.
indexes = 1 : length(A);
for k = 1 : length(B)
% Find out where in A B(k) occurs
indexInA = find(B(k) == A)
% Rather than just do an assignment to an output vector,
% we're required by the question to do a swap instead.
otherIndex = setdiff(.........)
if isempty(otherIndex)
break; % ' Quit when we're done.
end
% Do the swap
[A(indexInA), A(k)] = deal(..........)
end
It's a for loop like I said. The hint I'm giving is to use setdiff() to find the indexes that you want to swap, and to use deal() to do the actual swapping itself. See if you can figure out what goes inside. To get the other index, realize that it can't be the same index you're working on or any prior to that, and it can't be the source location that you just found.
@Jan Simon: I was just trying an help to understand what commands could be used to solve the problem; that I have written is just one example.
@Image Analyst: thanks a lot for the suggestion! I will try to do in this way.

This question is closed.

Asked:

on 28 Jun 2015

Closed:

on 20 Aug 2021

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!