Skip to main content
update methods and timings
Source Link
image_doctor
  • 10.3k
  • 23
  • 41

Perhaps if you like recursion this might seem more elegant, it certainly doesn't win on speed.

Recursive

NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
 NonPositive@First@# && Length@#[[2]] >= 1 &]

{1, {1950, 1950, 1950, 525, 0}}

Timing:

data = RandomInteger[{-1000, 10}, 100000];

AbsoluteTiming[
 NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
   NonPositive@First@# && Length@#[[2]] >= 1 &];]

{1.085087005087, Null}

rm -rf

AbsoluteTiming[
 With[{acc = Accumulate@dataacc=Accumulate@data}, 
   acc[[;; -#]]~Join~data[[-# + 1 ;;]] &@Tr@HeavisideTheta@acc];]&@Count[acc,_?Positive]];]

{0.026715024329, Null}

Rojo

AbsoluteTiming[
 Join[#, data[[Length@# + 1 ;;]]] &@
   Reap[Fold[If[NonPositive@#1, Sow[#1 + #2], Break[Null, Fold]] &, 0,
       data]][[-1, 1]];]

{0.104658, Null}

Perhaps if you like recursion this might seem more elegant, it certainly doesn't win on speed.

Recursive

NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
 NonPositive@First@# && Length@#[[2]] >= 1 &]

{1, {1950, 1950, 1950, 525, 0}}

Timing:

data = RandomInteger[{-1000, 10}, 100000];

AbsoluteTiming[
 NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
   NonPositive@First@# && Length@#[[2]] >= 1 &];]

{1.085087, Null}

AbsoluteTiming[
 With[{acc = Accumulate@data}, 
   acc[[;; -#]]~Join~data[[-# + 1 ;;]] &@Tr@HeavisideTheta@acc];]

{0.026715, Null}

Perhaps if you like recursion this might seem more elegant, it certainly doesn't win on speed.

Recursive

NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
 NonPositive@First@# && Length@#[[2]] >= 1 &]

{1, {1950, 1950, 1950, 525, 0}}

Timing:

data = RandomInteger[{-1000, 10}, 100000];

AbsoluteTiming[
 NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
   NonPositive@First@# && Length@#[[2]] >= 1 &];]

{1.005087, Null}

rm -rf

AbsoluteTiming[
 With[{acc=Accumulate@data},acc[[;; -#]]~Join~data[[-# + 1 ;;]] &@Count[acc,_?Positive]];]

{0.024329, Null}

Rojo

AbsoluteTiming[
 Join[#, data[[Length@# + 1 ;;]]] &@
   Reap[Fold[If[NonPositive@#1, Sow[#1 + #2], Break[Null, Fold]] &, 0,
       data]][[-1, 1]];]

{0.104658, Null}

Source Link
image_doctor
  • 10.3k
  • 23
  • 41

Perhaps if you like recursion this might seem more elegant, it certainly doesn't win on speed.

Recursive

NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
 NonPositive@First@# && Length@#[[2]] >= 1 &]

{1, {1950, 1950, 1950, 525, 0}}

Timing:

data = RandomInteger[{-1000, 10}, 100000];

AbsoluteTiming[
 NestWhile[{First@#~Plus~#[[2, 1]], Rest@#[[2]]} &, {0, data}, 
   NonPositive@First@# && Length@#[[2]] >= 1 &];]

{1.085087, Null}

AbsoluteTiming[
 With[{acc = Accumulate@data}, 
   acc[[;; -#]]~Join~data[[-# + 1 ;;]] &@Tr@HeavisideTheta@acc];]

{0.026715, Null}