Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ <algorithm> permutation

Why is this code note working (the code compiles and run fine, but is not actually showing the permutations):

int main(int argc, char *argv[])
{
    long number;
    vector<long> interval;
    vector<long>::const_iterator it;

    cout << "Enter number: ";
    cin >> number;

    while(number-->0){
        interval.push_back(number);
    }

    do{
        for(it = interval.begin(); it < interval.end(); ++it){
            cout << *it << " ";
        }
        cout << endl;
    } while(next_permutation(interval.begin(), interval.end()));

    return (0);
}

But after changing this line:

while(next_permutation(interval.begin(), interval.end()));

with:

while(prev_permutation(interval.begin(), interval.end()));

Isn't permutation changing the elements in the vector by acting on positions ?

PS: I've edited the code now.

like image 565
Andrei Ciobanu Avatar asked Mar 20 '26 19:03

Andrei Ciobanu


2 Answers

Permutations are lexicographically ordered, that's what std::next_permutation and std::prev_permutation algorithms traverse.

Here you enter the "biggest" permutation, so there's no next one in order.

like image 60
Nikolai Fetissov Avatar answered Mar 23 '26 09:03

Nikolai Fetissov


Isn't permutation changing the elements in the vector by acting on positions ?

No. next_permutation uses the ordering of the elements to determine the next permutation.

For example, if A < B < C, then the next_permutation of [A,B,C] (012) would be [A,C,B] (021). However, if A < C < B, then the next_permutation of [A,B,C] (021) would be [C,A,B] (102).

Since your vector was initially in decreasing order, it would have been the last permutation.

You could use the std::greater ordering to reverse the comparison direction.

} while(next_permutation(interval.begin(), interval.end(), greater<long>()));
//                                                         ^^^^^^^^^^^^^^^
like image 29
kennytm Avatar answered Mar 23 '26 08:03

kennytm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!