Hi everyone, I got a task to sum up vectors. But each time the amount of the summation reaches 15, I need to insert the value of 0 and sum up the next number until it end of vector.
For example:
Original vector:
5 3 2 4 6 7 1 6 5 3 8 6 1 9 3
Here, total sum of (5 + 3 + 2 + 4) <= 15. Then, I need to insert 0 after 4
The new vector should be:
5 3 2 4 0 6 7 1 6 5 3 8 6 1 9 3
Total sum (6 + 7 + 1) <= 15. Then, I need to insert 0 after 1
The new vector should be:
5 3 2 4 0 6 7 1 0 6 5 3 8 6 1 9 3
Total sum (6 + 5 + 3) <= 15. Then, I need to insert 0 after 3
The new vector should be:
5 3 2 4 0 6 7 1 0 6 5 3 0 8 6 1 9 3
Total sum (8 + 6 + 1) <= 15. Then, I need to insert 0 after 1.
The new vector should be:
5 3 2 4 0 6 7 1 0 6 5 3 0 8 6 1 0 9 3
Total sum (9 + 3) <= 15. Then, I need to insert 0 after 3.
The final vector should be:
5 3 2 4 0 6 7 1 0 6 5 3 0 8 6 1 0 9 3 0
In the code below. I had sum up all the vector using partial sum function. Then each time it reach 15, I will insert 0. I would like to ask is there any other option I could do to get the answer as above. In which each time total sum less than or equal to 15. Zero will be insert automatically.
Any advice is appreciated.
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 55 56 57 58 59 60 61 62 63 64 65
|
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
using namespace std;
const int col = 15;
int main ()
{
int myints [] = { 5, 3, 2, 4, 6, 7, 1, 6, 5, 3, 8, 6, 1, 9, 3 };
vector<int> vec (myints, myints + sizeof(myints) / sizeof(int) );
// Print Original Vector
cout << "Original vector :";
for (int i = 0; i < col; i++)
{
cout << " " << vec[i];
}
cout << endl;
// Compute the partial sum
// Reserve space for the partial sums
vector<int> partialSum (col);
for(int i = 0; i < col; i++)
{
partial_sum(vec.begin(), vec.end(), partialSum.begin());
}
// Display the solution of partial sum
cout << "Partial sum vector :";
for(int i = 0; i < col; i++)
{
cout << " " << partialSum[i];
}
cout << endl;
int Q = 15;
// Iterator used to store the position of searched element
vector<int>::iterator upper;
// upper_bound function
upper = upper_bound (partialSum.begin(), partialSum.end(), Q);
int i1 = (upper - partialSum.begin());
cout << "Position " << i1 << " were chosen.\n";
vec.insert(vec.begin() + i1, 0);
// Display the solution
cout << "Vector after insert new element :";
for(int i = 0; i < vec.size(); i++)
{
cout << " " << vec[i];
}
cout << endl;
system("pause");
return 0;
}
|