Nov 5, 2015 at 2:32am UTC
I need to generate a vector such that [6, 5, 4, 3, 2, 1, 7, 8, 9, . . . , n − 4, n − 3, n, n − 1, n − 2] for n = 100, 200, 400, 800, 1600, 3200, 6400.
For example: for n = 16,
[6,5,4,3,2,1,7,8,9,10,11,12,13,16,15,14]
I can't understand the pattern here. I know I can code this if someone can explain to me the pattern.
Nov 5, 2015 at 2:39am UTC
The first 6 elements are 6, 5, 4, 3, 2, 1. The next elements are 7, 8, 9, ... n. So to populate the vector, use 2 loops. The first loop does the first 6 elements. The next loop does elements 7 through n
Nov 5, 2015 at 3:01am UTC
That would never work, also - note: the last 3 elements are weirdly placed such that n, n-1, n-2
Nov 5, 2015 at 3:28am UTC
Here is what I ending up using as my solution dhayden. Were you thinking of something faster? I know you are alot more versed in c++ then me, I've seen you help others before. Thanks in advance. This is what I'm currently using.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
void printvector(vector<int > v)
{
if (v.size() == 0)
{
cout << "Empty" << endl;
return ;
}
for (int i = 0; i < v.size(); i++)
{
cout << v[i] << " " ;
}
}
int main()
{
vector<int >test;
int N = 16;
int t = N;
t = t / 2;
int tempSize;
bool firstCase = true ;
int counter = 3;
for (int i = 0; i < (t - 1); i++)
{
test.push_back(N - counter);
counter++;
}
tempSize = counter - 4;
cout << "counter = " << counter << endl;
reverse(test.begin(), test.end());
//Add extra 3 cases
//n, n-1, n-2
test.push_back(N);
test.push_back(N - 1);
test.push_back(N - 2);
counter = 1;
for (int i = 0; i < tempSize; i++)
{
test.insert(test.begin(), counter);
counter++;
}
cout << endl;
printvector(test);
system("pause" );
}
Last edited on Nov 5, 2015 at 3:41am UTC
Nov 5, 2015 at 3:54am UTC
Yeah but isn't your way slower since your algorithm is O(n^2) (quadratic) and mine is only O(n)?