VIII: The Programmatic Side of Mathematica: Sampling With Replacement

Arrays. I can declare an array and return an arbitrary element from it:

S := {2,4,6,8,10}

I can also do the same things for an anonymous array:


In both cases, I request the third element of the array in double square brackets, and Mathematica returns with the number 6. I can request a random element as was shown in previour posts, but it would be better to name the array:


The above statement returns a random element from an array without needing to know the length of the array. I could include it in my bag of tricks, since it would resemble sampling, especially if I sample a certain number of times.

Sampling with replacement means picking an element e from a set S without removing it. With sets, that amounts to just choosing elements from a set while allowing repetition. We don’t even need numbers. What about letters? Let’s re-define the set S thusly:


Now, let’s define a function called “pick[n]” which chooses some quantity of letters from S by passing the number of choices to it as “n”:


That’s a lot of nested brackets. But recall that the Table[] function generated a set of size n by executing the function in the first parameter n times, and returning the result as an array. But here, the function is passed into the Random[] function, which determines the array index of the element chosen from S. So, two calls to pick returned these for me:


So, as you can see, we have repetition.

Published by


I am Paul King, a math and science teacher. I help maintain the MIT FAQ Archive along with Nick Bolach. I am also the maintainer of the FAQ for