Results 1 to 2 of 2
Thread: swapping elements of vector
 01072010, 09:16 PM #1Member
 Join Date
 Dec 2009
 Posts
 59
 Rep Power
 0
swapping elements of vector
hello
I need to swap elements of vector but without redunducy. for example swapping elements 1 with 2 is the same as swapping element 2 with 1 so I don't want to save the second result I want to save it only one time
my code is the following :
Java Code:for( int x=0;x<v1size();x++) { for ( int w=0;w< v1.size();w++){ Collections.swap(v1, x, w);
 01072010, 09:45 PM #2Moderator
 Join Date
 Feb 2009
 Location
 New Zealand
 Posts
 4,716
 Rep Power
 18
One way of calling each of the (size*(size+1))/2 distinct pairs of list indices would be
Java Code:for(int x = 0; x<v1.size(); x++) { for(int w = x; w< v1.size();w++) {
ie swap an index position with those to its right.
Do you realise that once you call Collections.swap() the index positions now refer to different objects? That's why I said that the code above was one way of doing it. If you do all the (size*(size+1))/2 swaps in a different order you will end up with a different result. And you haven't described the result you want!
As an example of this, consider a list of three objects:
A B C
There are exactly three swaps possible (0,1)=(1,0) (0,2)=(2,0) (1,2)=(2,1). If we follow the "swap to the right" rule we get
A B C (0,1) > B A C
B A C (0,2) > C A B
C A B (1,2) > C B A
But if we do the same three "non redundant" swaps in a different order we get
A B C (1,2) > A C B
A C B (0,1) > C A B
C A B (0,2) > B A C
Similar Threads

Swapping elements of an array help please
By ikillu in forum New To JavaReplies: 11Last Post: 01152012, 08:49 PM 
Binary Tree Traversals and Swapping
By Sylar in forum New To JavaReplies: 0Last Post: 03082009, 07:52 AM 
compare newly added Vector Element with previous elements
By nidhirastogi in forum Advanced JavaReplies: 10Last Post: 09102008, 01:32 AM 
swapping the contents of the file and writing to another file
By Ms.Ranjan in forum New To JavaReplies: 9Last Post: 07102008, 04:52 PM 
Finding elements in a vector
By Java Tip in forum java.langReplies: 0Last Post: 04142008, 08:37 PM
Bookmarks