Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient coding help

Tags:

c++

pointers

I am currently writing code in C++ to find all possible permutations of 6 integers and store the best permutation (i.e. the one whose total is closest to a given value).

I am trying to write this code as efficiently as possible and would apreciate any advice or examples.

I was considering storing the integers in an array and performing the permutations using pointers within a loop. Is this a good approach?

like image 847
user103572 Avatar asked Jun 18 '26 17:06

user103572


1 Answers

They already thought of this one for you:

#include <algorithm>

int ra[6] = { 1, 2, 3, 4, 5, 6 };

do {
    // whatever
} while (std::next_permutation(ra, ra+6));

Note that the elements have to start in increasing order (by comparison via operator<), or else the loop will terminate before you've seen every permutation. See http://en.cppreference.com/w/cpp/algorithm/next_permutation for details.

It probably doesn't give the fastest runtime possible, because at each step it has to examine the array to work out what to change. But it's certainly the most efficient in programmer effort, and without knowing the compiler and platform it's not really possible to micro-optimise the nested loop approaches anyway.

like image 104
Steve Jessop Avatar answered Jun 21 '26 06:06

Steve Jessop



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!