Results 1 to 2 of 2
Thread: swapping elements of vector
- 01-07-2010, 09:16 PM #1
Member
- 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 :
but the above code will swap with redunducy:(Java Code:for( int x=0;x<v1size();x++) { for ( int w=0;w< v1.size();w++){ Collections.swap(v1, x, w);
- 01-07-2010, 09:45 PM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,547
- Rep Power
- 11
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: 01-15-2012, 08:49 PM -
Binary Tree Traversals and Swapping
By Sylar in forum New To JavaReplies: 0Last Post: 03-08-2009, 07:52 AM -
compare newly added Vector Element with previous elements
By nidhirastogi in forum Advanced JavaReplies: 10Last Post: 09-10-2008, 01:32 AM -
swapping the contents of the file and writing to another file
By Ms.Ranjan in forum New To JavaReplies: 9Last Post: 07-10-2008, 04:52 PM -
Finding elements in a vector
By Java Tip in forum java.langReplies: 0Last Post: 04-14-2008, 08:37 PM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks