I was curious to know, how do I implement probability in Java? For example, if the chances of a variable showing is 1/25, then how would I implement that? Or any other probability? Please point me in the general direction.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You’d use Random to generate a random number, then test it against a literal to match the probability you’re trying to achieve.
So given:
valwill have a 1/25 probability of being true (sincenextInt()has an even probability of returning any number starting at 0 and up to, but not including, 25.)You would of course have to
import java.util.Random;as well.As pointed out below, if you’re getting more than one random number it’d be more efficient to reuse the Random object rather than recreating it all the time:
..