How I can get a vector from another through swaps?
Info
Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.
Ältere Kommentare anzeigen
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.
Antworten (2)
Azzi Abdelmalek
am 28 Jun. 2015
Do you mean randomly?
A=[1 5 8 7 4 3 2 6]
B=A(randperm(numel(A)))
1 Kommentar
lucia del gaudio
am 28 Jun. 2015
Image Analyst
am 28 Jun. 2015
0 Stimmen
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 Kommentare
lucia del gaudio
am 28 Jun. 2015
Jan
am 28 Jun. 2015
@lucia: What kind of help do you expect? It is your homework and we cannot solve it for you without forcing you to cheat.
Image Analyst
am 28 Jun. 2015
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
Image Analyst
am 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
am 28 Jun. 2015
Diese Frage ist geschlossen.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!