Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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.

share|improve this question
add comment

1 Answer

up vote 8 down vote accepted
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}}
*)
share|improve this answer
    
exactly what i was looking for. thank you. –  Royce Dec 21 '12 at 19:23
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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