4
$\begingroup$

I want to write a function that will randomly select an element in a list of arbitrary length and operate on it. For example, if I have

L = RandomInteger[100, {10}]

and want to reduce the value of a random element by 1, I can do this with e.g.

R = RandomInteger[{1, Length[L]}]
F[L_, R_] := ReplacePart[L, R -> L[[R]] - 1]
F[L, R] 

But if I include the random number (RN) generation in the function like this

F = ReplacePart[#,RandomInteger[{1,Length[#]}] -> #[[RandomInteger[{1, Length[#]}]]]- 1] &
F[L]

it generates two different RNs and so doesn't work as intended. Is there some way to generate a RN within the function and then use the result repeatedly within the same function?

$\endgroup$
0

1 Answer 1

4
$\begingroup$

You have to generate your random index only once, for example using With (or Module):

F = With[{ind = RandomInteger[{1, Length[#]}]}, 
 ReplacePart[#, ind -> #[[ind]] - 1]] &
$\endgroup$
0

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.