Java:在x%的情况下做一些事情
我需要几行Java代码,它们随机运行命令x%的时间。
伪代码:
boolean x = true 10% of cases. if(x){ System.out.println("you got lucky"); }
如果你的意思是代码被执行的次数 ,那么你想要一些代码块内的东西,执行整个块的次数是10%,你可以这样做:
Random r = new Random(); ... void yourFunction() { float chance = r.nextFloat(); if (chance <= 0.10f) doSomethingLucky(); }
当然0.10f
代表10%,但你可以调整它。 像每个PRNG算法一样,这通过平均使用来工作。 除非你的yourFunction()
被称为合理的次数,否则你不会接近10%。
你只需要这样的东西:
Random rand = new Random(); if (rand.nextInt(10) == 0) { System.out.println("you got lucky"); }
这是一个衡量它的完整示例:
import java.util.Random; public class Rand10 { public static void main(String[] args) { Random rand = new Random(); int lucky = 0; for (int i = 0; i < 1000000; i++) { if (rand.nextInt(10) == 0) { lucky++; } } System.out.println(lucky); // you'll get a number close to 100000 } }
如果你想要34%的东西,你可以使用rand.nextInt(100) < 34
。
以您的代码为基础,您可以这样做:
if(Math.random() < 0.1){ System.out.println("you got lucky"); }
FYI Math.random()
使用Random
的静态实例
你可以使用随机 。 您可能想要播种它,但默认值通常就足够了。
Random random = new Random(); int nextInt = random.nextInt(10); if (nextInt == 0) { // happens 10% of the time... }
你可以试试这个:
public class MakeItXPercentOfTimes{ public boolean returnBoolean(int x){ if((int)(Math.random()*101) <= x){ return true; //Returns true x percent of times. } } public static void main(String[]pps){ boolean x = returnBoolean(10); //Ten percent of times returns true. if(x){ System.out.println("You got lucky"); } } }
你必须首先定义“时间”,因为10%是一个相对的衡量标准……
例如,x每5秒为真。
或者你可以使用一个随机数生成器,从1到10均匀采样,如果他采样“1”,总会做一些事情。
你总是可以生成一个随机数(默认情况下它在0到1之间,我相信)并检查它是否是<= .1,再次这不是均匀的随机数....
public static boolean getRandPercent(int percent) { Random rand = new Random(); return rand.nextInt(100) <= percent; }