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$
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$
  • $\begingroup$ exactly what i was looking for. thank you. $\endgroup$ – Royce Dec 21 '12 at 19:23

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.