1
$\begingroup$

I have a list that looks like:

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

I want to replace duplicate values in each sublist by their value + 12:

{{-5,0,-8,-3},{0,3,-3,12},{3,-4,0,-7},{-4,-1,-7,8},{-1,4,-4,1},{4,-3,1,-6},{-3,0,-6,9},{0,2,-3,-1},{2,5,-1,14},{5,-2,2,-5}}

How can I do that?

*Duplicate values might not necessarily be at first and last position of each sublist.

$\endgroup$
1
  • 1
    $\begingroup$ Should {-3, 0, -3, -3} become {-3, 0, 9, 9} or {-3, 0, 9, 21}? $\endgroup$
    – Coolwater
    Commented Aug 23, 2019 at 14:22

2 Answers 2

2
$\begingroup$

A solution using Nearest:

list = {{-5,0,-8,-3}, {0,3,-3,0}, {3,-4,0,-7}, {-4,-1,-7,-4}, {-1,4,-4,1}, 
  {4,-3,1,-6}, {-3,0,-6,-3}, {0,2,-3,-1}, {2,5,-1,2}, {5,-2,2,-5}};
Map[
  MapAt[
    # + 12 &,
    #, Complement[ Array[List, Length@#], Nearest[#->"Index", #, 1] ]
  ] &, list
]
$\endgroup$
2
$\begingroup$
list = {{-5,0,-8,-3}, {0,3,-3,0}, {3,-4,0,-7}, {-4,-1,-7,-4}, {-1,4,-4,1}, 
  {4,-3,1,-6}, {-3,0,-6,-3}, {0,2,-3,-1}, {2,5,-1,2}, {5,-2,2,-5}};

Replace:

Replace[{a___, x_, b___, x_, c___}:> {a, x, b, x + 12, c}] /@ list

{{-5, 0, -8, -3}, {0, 3, -3, 12}, {3, -4, 0, -7}, {-4, -1, -7, 8}, {-1, 4, -4, 1}, {4, -3, 1, -6}, {-3, 0, -6, 9}, {0, 2, -3, -1}, {2, 5, -1, 14}, {5, -2, 2, -5}}

Memoization: Re-define f[x] to become g[x] (x + 12 in OP example) after first occurrence of x:

ClearAll[mapAtDuplicates]
mapAtDuplicates[g_] :=  Module[{f}, f[x_] := (f[x] = g[x]; x); f /@ #] &;

Map[mapAtDuplicates[# + 12 &]] @ list

{{-5, 0, -8, -3}, {0, 3, -3, 12}, {3, -4, 0, -7}, {-4, -1, -7, 8}, {-1, 4, -4, 1}, {4, -3, 1, -6}, {-3, 0, -6, 9}, {0, 2, -3, -1}, {2, 5, -1, 14}, {5, -2, 2, -5}}

Map[mapAtDuplicates[# + z &]] @ {{1, 1, 2, 3, 2, 1, 2}, {1, 2, 2, 3, 2, 4, 2, 2, 2}}

{{1, 1 + z, 2, 3, 2 + z, 1 + z, 2 + z},
{1, 2, 2 + z, 3, 2 + z, 4, 2 + z, 2 + z, 2 + z}}

$\endgroup$

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.