Info

This question is closed. Reopen it to edit or answer.

How I can get a vector from another through swaps?

1 view (last 30 days)
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)

Azzi Abdelmalek
Azzi Abdelmalek on 28 Jun 2015
Do you mean randomly?
A=[1 5 8 7 4 3 2 6]
B=A(randperm(numel(A)))
  1 Comment
lucia del gaudio
lucia del gaudio on 28 Jun 2015
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.

Image Analyst
Image Analyst on 28 Jun 2015
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
Image Analyst
Image Analyst on 28 Jun 2015
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.
lucia del gaudio
lucia del gaudio on 28 Jun 2015
@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.

Community Treasure Hunt

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

Start Hunting!