Skip to main content
5 of 11
added 379 characters in body
Dominic van Essen
  • 36.4k
  • 2
  • 22
  • 60

R, 33 bytes

(Or 26 bytes in R>=4.1 using ‘\’ instead of ‘function’)

function(x)sample(y<-c(0,x),1,,y)

Try it online!

The 4th argument of R’s ‘sample’ function is ‘prob’=“a vector of probability weights for obtaining the elements of the vector being sampled”.

——

R, 29 bytes

(Or 22 bytes in R>=4.1 using ‘\’ instead of ‘function’)

function(x)sample(rep(x,x),1)

Try it online!

Only valid for integer input.

——

R, 25 bytes

(Or 18 bytes in R>=4.1 using ‘\’ instead of ‘function’)

function(x)sample(x,1,,x)

Try it online!

This simpler version of the first solution may unfortunately fail if the input vector has only 1 element (due to a ‘convenience’ feature of ‘sample’ which changes its behaviour in this case…).

Dominic van Essen
  • 36.4k
  • 2
  • 22
  • 60