help /to complete this program: (insert a <0> where, a sequence of n integers, can be split into two balanced ones (ideally equal sums) //e.i.: this sequence 4 7 3 6 9 8 becomes 4 7 3 0 9 8
#include <ctime> #include <iostream> using namespace std; int m[40], n, Lsum=0, Rsum=0, diff[20]; void genArr() {for(int r=0;r<n;r++) m[r]=1+rand()%9;} void prnArr() {for(int r=0;r<n;r++) cout<<m[r]<<" "; cout<<endl;} void splitArr() { } void main() { srand(time(0)); while (1) { cout<<"\nEnter n<20\t"; cin>>n; cout<<endl; genArr(); prnArr(); splitArr(); prnArr(); } }
can u help with this @wio
Where are you stuck?
on the splitArr, i need to split the numbers by 0 for example if the the original number is 586793725, split them by number 0 like this 586703725.. every time i try to split them, the 0 is misplaced or out of order
By the way I love your coding style. It is rebellious.
What happens if it can't be split into equal sums?
as long as they are close to each other, it would be okay
So you want them to be as close as possible?
I would recommend having two indices, a right and a left one.
the left one starts at 0 and the right one starts at n-1
You want to loop through so long as the difference between the right and left pointer is one.
keeps sums along with these pointers.
If the left sum is smaller, increment the left index and add the next item to it. If the right sume is smaller, decrement the right index and add the next item to it.
The loops should end when the when the loop ends, then the indices will be right next to the middle one which should be set to 0
I'm thinking something like this ``` int sumL = 0, sumR = 0, posL = 0, posR = n-1; while (posR > posL) { if (sumL > sumR) sumR += m[posR--]; else sumL += m[posL++]; } if (posL < n) m[posL] = 0; ``` Hard to right code as badass as yours.
lol thanks alot.. that make sense.. u made it look easy
Join our real-time social learning platform and learn together with your friends!