7
$\begingroup$

I have a list dat = {10, 10, 10, 10, 10, 40} .

When the cumulative sum of dat reaches >= 25, the cumulative sum is halted, the difference between 25 and the cumulative sum until that point will be added to the next element of dat and the cumulative sum restarts until hit 25 again and so on.

The desired result should be {{10, 20, 25}, { 15, 25}, {25}, {15}}

I can´t figure out how to accomplish this task, either procedural or functional

Thanks in advance.

$\endgroup$
6
$\begingroup$

Here's a procedural solution:

acc = 0;
rem = 0;
list = {};
sublist = {};
Do[
  acc += el + rem;
  rem = 0;
  If[
   acc >= 25,
   AppendTo[sublist, 25];
   AppendTo[list, sublist];
   sublist = {};
   rem = Mod[acc, 25];
   acc = 0;
   ,
   AppendTo[sublist, acc]
   ]
  , {el, dat}];
If[rem > 0, AppendTo[list, {rem}]];

list

{{10, 20, 25}, {15, 25}, {25}, {15}}

$\endgroup$
  • $\begingroup$ It works!!! With a list of Length=100.000 , Average value 133000 and Partitioning when the Cumulative Sum reaches 1200000 , the Absolute Timing was 0.37. Thank´s for your time $\endgroup$ – Jul Nov 2 at 21:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.