Hey guys, this is my first post.
I'm in this C++ competitions and I'm doing some tasks for practice.
In some tasks I need to shuffle elements in an array and find the permutation that is correct.
For example, user inputs an array of numbers and I have to output a permutation of that array to that no sum of adjacent 2 numbers is a prime number.
I had an idea about making a recursion that tries every combination and finds the one that works but as I began coding it, it became so confusing that I couldn't keep up with my own code.
So I ask you, what is the best way of approaching problem such as this?
And before you say do your own homework know that this isn't homework but a hobby and I just want to know what the best method to solve that kind of problems is.
Thanks in advance.
Here's the unfinished code that you can look at, tho I doubt you'll understand anything since I don't even understand it =P
Code:#include <iostream>
#include <iomanip>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <cstring>
#include <queue>
using namespace std;
int from, to;
vector<int>niz;
bool isPrim( int n ) {
for (int i=2; i<sqrt(n); ++i){
if (!n%i) return false;
}
return true;
}
bool rek (vector<int> o, int step){
if (step==to-from) {
vector<int> noviNiz(step);
for (int i=0; i<step; ++i){
noviNiz[i]=niz[o[i]];
}
niz=noviNiz;
return true;
}
vector<pair <int, int> > noviNiz(to-from-step);
int skip=0;
for (int i=0; i<to-from; i++){
for (int j=0; j<step; ++j){
if (o[j]==i){
skip=1;
break;
}
}
pair <int,int> tempPair;
tempPair.first=niz[i];
tempPair.second=i;
if (!skip) noviNiz.push_back(tempPair);
}
for (int i=0; i<noviNiz.size(); ++i){
if (isPrim(niz[o[step]]+noviNiz[i].first)) continue;
vector <int> o2=o;
o2.resize(o2.size()+1);
o2.push_back(noviNiz[i].second);
rek(o2,step+1);
}
}
int main (){
cin >> from >> to;
niz.resize(to-from);
for (int i=0; i<to-from;++i){
niz[i]=i+to;
}
for (int i=0; i<to-from;++i){
vector<int> niz2(1);
niz2[0]=i;
if (rek(niz2,1)) break;
}
for (int i=0; i<to-from;++i){
cout << niz[i];
if (i!=to-from-1) cout << endl;
}
system("PAUSE");
return 0;
}