RandomInt
RandomInt
RandomInt[ {min, max} ] randomly selects one or more integers from a range.
Usages
RandomInt[ {min, max} ]
RandomInt[ {min, max} ] returns a random integer from min to max, including min and max. Each time the exercise is generated, a new number is chosen, so the outputs below are only examples.
| Example | in | out |
|---|---|---|
A random integer from 1 to 5. |
RandomInt[ {1, 5} ] |
for example 4 |
RandomInt[ {min, max}, n ]
RandomInt[ {min, max}, n ] returns a list of n random integers from min to max. The list may contain the same number more than once; use the option AllowDuplicates to prevent this.
| Example | in | out |
|---|---|---|
3 random integers from 1 to 5. |
RandomInt[ {1, 5}, 3 ] |
for example {5, 3, 3} |
| The range and the number can be script variables. | x := 3 |
for example r = {3, 7} |
Options
AllowDuplicates
If set to False, every number is drawn at most once. Default: True.
| Syntax | Example | out |
|---|---|---|
RandomInt[ {min, max}, n, AllowDuplicates=>False ] |
RandomInt[ {1, 10}, 5, AllowDuplicates=>False ] |
for example {3, 4, 9, 10, 1} |
Exclude
Numbers that must not be drawn. The value can be a single number or a list of numbers.
| Syntax | Example | out |
|---|---|---|
RandomInt[ {min, max}, Exclude=>{m1, m2, ...} ] |
RandomInt[ {-5, 5}, Exclude=>{0, 1} ] |
for example 4 |
RandomInt[ {min, max}, n, Exclude=>m ] |
RandomInt[ {-5, 5}, 4, Exclude=>0 ] |
for example {-1, 2, 3, 4} |
Details
- Order of the range: if
minis larger thanmax, they are swapped:RandomInt[ {5, 1} ]works likeRandomInt[ {1, 5} ]. - Non-integer bounds are rounded inwards:
RandomInt[ {1.5, 4.5} ]chooses from2,3and4. - Zero numbers:
RandomInt[ {1, 5}, 0 ]returns{}. - Older notation:
RandomInt[ min, max ], without the list, still works but should not be used in new scripts.
| Invalid input | Result |
|---|---|
RandomInt[ {1, 5, 7} ] |
Error: the number range should have format {min, max} |
RandomInt[ {1, x} ] |
Error: The minimum and maximum of the range must be numerical |
RandomInt[ {1, 3}, 4, AllowDuplicates=>False ] |
Error: the given range contains fewer valid elements than the number requested |
RandomInt[ {1, 5}, -1 ] |
Left unevaluated. |
Warning
- If
Excluderemoves every number in the range, such asRandomInt[ {1, 2}, Exclude=>{1, 2} ], the script stops with an internal error. nshould be an integer:RandomInt[ {1, 5}, 2.5 ]silently returns2numbers.- Unknown options are ignored without an error, so check the spelling of
AllowDuplicatesandExclude.
See also: RandomSelect, RandomSample, Shuffle