RandomSample
RandomSample
RandomSample[ list, n ] randomly selects n different elements from a list.
Usages
RandomSample[ list, n ]
RandomSample[ list, n ] returns a list of n randomly chosen elements of list, where no element is chosen twice. Each time the exercise is generated, a new choice is made, so the outputs below are only examples.
| Example | in | out |
|---|---|---|
2 different elements. |
RandomSample[ {1, 2, 3, 4, 5}, 2 ] |
for example {5, 4} |
| All elements, in a random order. | RandomSample[ {1, 2, 3}, 3 ] |
for example {3, 1, 2} |
Note
RandomSample[ list, n ] does the same as RandomSelect[ list, n, AllowDuplicates=>False ]. For new scripts, RandomSelect is recommended.
Details
- Duplicates in the list: each position is chosen at most once. If the list contains the same element twice, the result can contain it twice:
RandomSample[ {a, a, b}, 2 ]can give{a, a}. - Zero elements:
RandomSample[ {1, 2, 3}, 0 ]returns{}.
| Invalid input | Result |
|---|---|
RandomSample[ {1, 2, 3}, 4 ] |
Error: the 2nd argument should no larger than the length of the 1st argument |
RandomSample[ {1, 2, 3}, 1.5 ] |
Error: the 2nd argument should be an integer |
RandomSample[ 5, 2 ] |
Error: the 1st argument should be a list |
RandomSample[ {1, 2, 3} ] |
Error: the number of arguments should be 2 |
See also: RandomSelect, Shuffle, RandomInt