views:

170

answers:

3

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.

+5  A: 

Permutations are lexicographically ordered, that's what next_permutation and prev_permutation algorithms traverse. See here.

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

Nikolai N Fetissov
I understand now. So if I want to generate all the permutations I will need to have all the numbers sorted. Thanks!
Andrei Ciobanu
Exactly: sorted, and then use next_permutation. Or, reverse sorted, and then use prev_permutation.
rturrado
@Andrie: Or just run both prev and next without the need to sort.
Moron
+1  A: 

I don't think next_permutation can work on positions (where will it store that info?). You need to be able to compare elements for next_permutation to work, and that is what it uses to generate the lexicographically next permutation.

Try inserting the numbers in the reverse order and see if that works.

Moron
Yes, inserting is working by inserting the numbers in reverse order..
Andrei Ciobanu
+2  A: 

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>()));
//                                                         ^^^^^^^^^^^^^^^
KennyTM