# Replacing multiple instances of a symbol with different variables and assignments

I have an expression of the form:

expr=x+y+n+Sin[n]+n^2


I would like to replace each of the variables n with a different variable, like:

x+y+n1+Sin[n2]+n3^2


The order doesn't matter, but it matters that each n have a different name.

I can find the positions of the n's simply with:

pos=Position[expr,n]


and this returns a list of positions {{1}, {2, 1}, {5, 1}} as expected. I would then like to run through this list and make replacements in those positions. However, I don't want to have to do this by hand. Clearly I could do:

expr[[5,1]]=n3


but the real expression I have is many thousands of times larger.

I have tried using:

Apply[Part, Join[{expr}, pos[[3]]]]=n2


which would allow be to do this in a loop, or functionally, but this doesn't alter the element of the expression as I would like. I have tried playing with Hold in various places but it doesn't seem to work.

Anything simple that I am missing?

-
expr /. n :> Unique@n – Dr. belisarius Jan 9 '14 at 16:30
expr = x + y + n + Sin[n] + n^2; j = 0; expr /. n :> (j++; nn[j]) – Daniel Lichtblau Jan 9 '14 at 16:32
@DanielLichtblau the reason is that procedural code gets a penalty :D HNY BTW – Yves Klett Jan 9 '14 at 16:35
@Yves Klett I meant "beaten" in terms of "first to appear". But I agree his is the better method. Not faulting mine specifically for procedural usage but more because it has an unscoped global. – Daniel Lichtblau Jan 9 '14 at 16:40

You may do something like:

expr = x + y + n + Sin[n] + n^2;
{newExpr, {newVars}} = Reap[expr /. n :> Sow[Unique@n]];
{newExpr, newVars}
(*
{n$9881 + n$9882^2 + x + y + Sin[n$9883], {n$9881, n$9882, n$9883}}
*)

-
Hey, but that thing is worth lots of $! – Yves Klett Jan 9 '14 at 17:19 @Yves Use Unique["n"] to fix that. – Mr.Wizard Jan 9 '14 at 17:26 @Mr.Wizard Why do you want to fix that? Don't you like "$"? – Dr. belisarius Jan 9 '14 at 17:29
Yves complained about "\$" so I gave a solution. Also Unique["n"] gives results that match the OP's example. – Mr.Wizard Jan 9 '14 at 17:32
@Mr.Wizard Damn, my understanding was that Yves was trying to buy my answer. – Dr. belisarius Jan 9 '14 at 17:35