8
$\begingroup$

I am trying to create a transformation rule that takes a list of non-negative integer values of any length, finds a non-zero entry in the list, adds 1 to all preceding numbers, subtracts 1 from the chosen non-zero entry, and keeps the subsequent values untouched.

As an example, {0,1,0,2,3,0} could be transformed into {1,0,0,2,3,0}, {1,2,1,1,3,0} or {1,2,1,3,2,0}.

I'm looking for a transformation rule, let's call it say desiredrule, such that ReplaceList[{0, 1, 0, 2, 3, 0}, desiredrule] yields those three lists above.

My (failed) attempt at this was along these lines:

ReplaceList[{0, 1, 0, 2, 3, 0}, {x___, y_ /; y > 0, z___} -> {x + 1, y - 1, z}]

which results in:

{{1, 0, 0, 2, 3, 0}, {2, 1, 3, 0}, {4, 2, 0}}

The key issue is obviously the x + 1 but I'm not sure how to correct this.

I know of other ways to achieve this same result without using ReplaceList; I know I could, for example, do the following:

transform[list_] := 
 Module[{nonzeropositions, numberoftransformations}, 
  nonzeropositions = Flatten@Position[list, x_ /; x > 0]; 
  numberoftransformations = Length[nonzeropositions]; 
  Table[list[[i]] + If[i < nonzeropositions[[j]], 1, 0] + 
    If[i == nonzeropositions[[j]], -1, 0], {j, 
    numberoftransformations}, {i, Length[list]}]]

But I'm specifically interested to learn how I could achieve this result via the transformation rule approach I outlined initially.

$\endgroup$

1 Answer 1

9
$\begingroup$
ReplaceList[{0, 1, 0, 2, 3, 0}, {x___, y_ /; y > 0, z___} :>  Flatten@{{x} + 1, y - 1, z}]
(*
  {{1, 0, 0, 2, 3, 0}, {1, 2, 1, 1, 3, 0}, {1, 2, 1, 3, 2, 0}}
*)
$\endgroup$
1
  • $\begingroup$ exactly what i was looking for. thank you. $\endgroup$
    – Royce
    Commented Dec 21, 2012 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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