5
$\begingroup$

I have a list of numbers. Each time the absolute difference between two consecutive numbers exceeds a threshold from this position up to the end, the list should be increased by increase.

My solution:

list = {3, 7, 3, 0, 2, 7, 8, 7, 9, 3, 6, 2, 3, 8, 9, 1, 3, 8, 5, 5};

threshold = 5;
increase = 10;

diffList = Abs[Differences[list]]

{4, 4, 3, 2, 5, 1, 1, 2, 6, 3, 4, 1, 5, 1, 8, 2, 5, 3, 0}

pos = Flatten@Position[diffList, n_ /; n >= threshold]

{5, 9, 13, 15, 17}

modifiedList = list;

Do[
  modifiedList[[pos[[i]] + 1 ;; All]] = modifiedList[[pos[[i]] + 1 ;; All]] + increase;
  , {i, 1, Length@pos}
  ];

(* desired resulting list *)

modifiedList

{3, 7, 3, 0, 2, 17, 18, 17, 19, 23, 26, 22, 23, 38, 39, 41, 43, 58, 55, 55}

Show[
 ListLinePlot[{list, modifiedList}, InterpolationOrder -> 0, 
  PlotLabels -> {"list", "modifiedList"}],
 Graphics[{Dashed, 
     Line[{{pos[[#]] + 1, 0}, {pos[[#]] + 1, Max@modifiedList}}]}] & /@
   Range[Length@pos]
 ]

enter image description here

Question: How can I replace the Do loop or can you propose another solution?

$\endgroup$
5
$\begingroup$
list = {3, 7, 3, 0, 2, 7, 8, 7, 9, 3, 6, 2, 3, 8, 9, 1, 3, 8, 5, 5};

threshold = 5;
increase = 10;

Breaking into steps:

inc = (increase Boole[# >= threshold]) & /@ Abs@Differences@list

{0, 0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10, 0, 10, 0, 10, 0, 0}

acc = {0}~Join~Accumulate@inc

{0, 0, 0, 0, 0, 10, 10, 10, 10, 20, 20, 20, 20, 30, 30, 40, 40, 50, 50, 50}

list + acc

{3, 7, 3, 0, 2, 17, 18, 17, 19, 23, 26, 22, 23, 38, 39, 41, 43, 58, 55, 55}

% == modifiedList

True

$\endgroup$
4
$\begingroup$
i = 0;
Prepend[MapThread[(If[#2 >= threshold, i += increase];
    #1 + i) &, {Rest@list, diffList}], First[list]]

{3, 7, 3, 0, 2, 17, 18, 17, 19, 23, 26, 22, 23, 38, 39, 41, 43, 58, 55, 55}

$\endgroup$
3
$\begingroup$
l2 = list + Accumulate[increase UnitStep[Join[{0}, diffList] - threshold]];

l3 = Join @@ MapIndexed[# + increase (#2[[1]] - 1) &, Split[list, Abs@Subtract@## < 5 &]];

l2  == l3 == modifiedList

True

$\endgroup$

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.