Home > Blockchain >  Given that I have a list of vector <1, 2, 3, 4>, can next_permutation in algorithm library hel
Given that I have a list of vector <1, 2, 3, 4>, can next_permutation in algorithm library hel

Time:03-24

can next_permutation avoid the duplication as what I want is to skip 2th and 4th as only change in first 2 character is important to me.

do {  
   //Do something
} while(next_permutation(s.begin(), s.end()));  

this will get 4! = 24 solution, while I only wanted 4P2 = 12 solution.

The above coding will give me.

1 2 3 4 
1 2 4 3 
1 3 2 4 
1 3 4 2 
1 4 2 3 
1 4 3 2 
2 1 3 4 
2 1 4 3 
2 3 1 4 
2 3 4 1 
2 4 1 3 
2 4 3 1 
3 1 2 4 
3 1 4 2 
3 2 1 4 
3 2 4 1 
3 4 1 2 
3 4 2 1 
4 1 2 3 
4 1 3 2 
4 2 1 3 
4 2 3 1 
4 3 1 2 
4 3 2 1

While actually I only want

1 2
1 3
1 4
2 1
2 3
2 4
3 1
3 2
3 4
4 1
4 2
4 3

CodePudding user response:

do {
   // Do something with the first two entries of `s`.
   std::prev_permutation(s.begin() 2, s.end());
} while(std::next_permutation(s.begin(), s.end()));

This will essentially skip all permutations of the last two items, so it won't iterate all permutations unnecessarily and be relatively efficient even if you change the length of the vector or the number of items you are interested in (the magic number 2 in the code above).

  •  Tags:  
  • c
  • Related