6
$\begingroup$

Is there any way to get different values for different blanks with ReplaceAll[]? For example, I would like to do something like:

{_,_,_}/. _Blank -> RandomInteger[{1, 10}]

But, the output comes out as all the same random integer for each blank, such as:

{4, 4, 4}

Is there an efficient way to get an output that is more random, like:

{4, 7, 1}

,as shown above?

Thanks!

$\endgroup$
  • 3
    $\begingroup$ I suppose something like Replace[{_, _, _}, _ :> RandomInteger[{1, 10}], {1}] would do what you ask for, but why not just use RandomInteger[{1,10}, 3] instead? $\endgroup$ – Carl Woll Sep 13 '18 at 0:06
  • $\begingroup$ Thanks, that's a good idea - I should have been more specific though, because it wasn't just for {,,}, but also for variable lengths, such as {,}, or even {,{,}} and such $\endgroup$ – Jmeeks29ig Sep 13 '18 at 15:50
10
$\begingroup$

You can simply change the Rule -> to RuleDelayed :> to give

{_, _, _} /. _Blank :> RandomInteger[{1, 10}]

(*{5, 1, 3}*)
$\endgroup$
  • $\begingroup$ Awesome, thanks! $\endgroup$ – Jmeeks29ig Sep 13 '18 at 14:34
3
$\begingroup$

Just for variety: you can also temporarily redefine Blank as RandomInteger[{1,10}]& using Block:

Block[{Blank = RandomInteger[{1, 10}] &}, {_, _, x, y, _, z}]

{5, 7, x, y, 5, z}

$\endgroup$
  • $\begingroup$ Thanks, I appreciate it! $\endgroup$ – Jmeeks29ig Sep 13 '18 at 14:34

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.