Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Picking variables with a given propability

 
Olaf Olafson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi guys,

I have assigned a value of propability to a variable p of 20% (0,2)

then I have two other variables int a = 10 and int b = 5

How can I code it that way, that with 20% propability a is picked and with 80% propability
b is picked?


btw this is my first post, so hi to all of you. I am a beginner in java fooling around with some code ;)

br Olaf



 
Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15272
37
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch!

That is very easy: for example, generate a random floating-point number between 0 and 1 and if it is < 0.2, pick the first one, otherwise pick the other one.
 
Olaf Olafson
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hmm great, thanks!, does make sence! I´ll try to implement it ;)
 
Campbell Ritchie
Sheriff
Posts: 48910
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try it with the ? : operator.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic