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}
S[[3]]
6```

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

```{2,4,6,8,10}[[3]]
6```

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:

`S[[Random[Integer,{1,Length[S]}]]]`

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:

`S:={a,b,c,d,e,f,g,h,i,j,k,l}`

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”:

`pick[n_]:=Table[S[[Random[Integer,{1,Length[S]}]]],{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:

```pick[4]
{b,e,a,d}
pick[4]
{h,g,h,d}```

So, as you can see, we have repetition.