5
$\begingroup$
list = {
  {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, 
  {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, 
  {0, 1, 1}, {1, 1, 0}, {1, 1, 0}, 
  {1, 0, 1}, {1, 0, 1}, {1, 0, 1},
  {1, 0, 1} ,{1, 0, 1},{1, 0, 1}
};

The list always has two 1s and one zero. I want to replace the 0s (position 1, 2 or 3 within element) that change to 1 in next element, with minus 1. This would give list2 below.

list2 = {
  {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, 
  {0, 1, 1}, {0, 1, 1}, {0, 1, 1}, 
  {**-1**, 1, 1}, {1, 1, 0}, {1, 1, **-1**}, 
  {1, 0, 1}, {1, 0, 1}, {1, 0, 1},
  {1, 0, 1} ,{1, 0, 1},{1, 0, 1}
};
$\endgroup$
6
$\begingroup$
list = {{0, 1, 1}, {1, 1, 0}, {1, 1, 0}, {1, 0, 1}, {1, 0, 1}};

Join[Subtract @@@ Partition[list, 2, 1] /. {1 -> 0}, {{0, 0, 0}}] + list

{{-1, 1, 1}, {1, 1, 0}, {1, 1, -1}, {1, 0, 1}, {1, 0, 1}}

$\endgroup$
  • $\begingroup$ Thanks that work perfectly! I am still deciphering fully how it works, but excellent idea to add the original list as the zeros don't change the minus one! Thanks again! $\endgroup$ – SPIL Dec 7 '16 at 14:49
  • $\begingroup$ OK I think I've upvote/accepted now. $\endgroup$ – SPIL Dec 7 '16 at 16:27
3
$\begingroup$

A replacement-based approach, with minimal pre- and post-processing of the list:

list = {{0, 1, 1}, {1, 1, 0}, {1, 1, 0}, {1, 0, 1}, {1, 0, 1}};
Transpose@list /. {a___, 0, 1, b___} :> {a, -1, 1, b} // Transpose
(* {{-1, 1, 1}, {1, 1, 0}, {1, 1, -1}, {1, 0, 1}, {1, 0, 1}} *)
$\endgroup$
  • $\begingroup$ Thanks that is useful, with minimal pre- and post-processing, there is less risk of something going awry. $\endgroup$ – SPIL Dec 9 '16 at 16:50

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.