MATLAB, 30 bytes
@(a)datasample(repelem(n,n),1)
This assumes MATLAB R2015a or newer and with the Statistics & Machine Learning toolbox installed.
See the explanation below for how repelem
is used. The difference between this shorter one and the one below is that the S&ML toolbox includes the function datasample
which can be used to take one or more elements from an array at random (with uniform probability) which allows an anonymous function to be used, stripping away the input/disp
calls.
MATLAB, 49 bytes
n=input('');a=repelem(n,n);disp(a(randi(nnz(a))))
This code assumes that MATLAB R2015a or newer is used as that is when the repelem
function was introduced. repelem
is a function which takes two parameters, the first is an array of numbers to be replicated, and the second is an array of how many times the corresponding element should be replicated. Essentially the function performs run-length decoding by providing the number and the run-length.
By providing the same input to both inputs of repelem
we end up with an array which consists of n times more of element n if that makes sense. If you provided [1 2 3]
you would get [1 2 2 3 3 3]
. If you provided [1 2 4 2]
you would get [1 2 2 4 4 4 4 2 2]
. By doing this it means that if we select an element with uniform probability (randi(m)
gives a random integer from 1 to m with uniform probability), each element n has an n times higher probability of being selected. In the first example of [1 2 3]
, 1
would have a 1/6 chance, 2
would have a 2/6 chance and 3
would have a 3/6 chance.
As a side note, because repelem
is not available yet for Octave, I can't give a TIO link. Additionally because Octave can't be used there is a big character penalty as input()
and disp()
need to be used as an anonymous function is not possible. If Octave supported repelem
, the following could be used:
@(n)a(randi(nnz(a=repelem(n,n))))
That would have saved 16 bytes, but it was not to be.