How does one write a Wolfram function which has a 25% chance of returning 1, a 50% chance of returning 2, and a 25% chance of returning 3?

Here is how the data structure might look like:

D = {(0.25, 1), (0.5, 2), (0.25, 3)}

So how do we write an

f[D_] := ...

with the property above? (Or if this is not the best/most idiomatic data structure for this type of problem, then feel free to dismiss it).


For a one-off call:

RandomChoice[{0.25, 0.5, 0.25} -> {1, 2, 3}]

To make a function as you request:

f[d_] := RandomChoice[d[[All, 1]] -> d[[All, 2]]]
f[{{0.25, 1}, {0.5, 2}, {0.25, 3}}]

Note a couple things: 1) D is a reserved keyword (for derivative). In general, avoid using capitalized variables. 2) A list needs to be created with braces {}, not parentheses ().


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.