我正在尝试从java.i中所需的可能性的数组字符串列表中生成随机字符串能够生成随机字符串但不知道如何处理概率。我必须运行程序几乎25 - 30次
Probability for abc is 10%
for def is 60%
for ghi is 20%
for danny is 10%
但我无法做到这一点。
import java.util.*;
public class newyork
{
public static void main(String[]args) throws Exception
{
// othr fun
public static void abc()
{
//Strings to display
String [] random = {"abc","def", "ghi","danny"};
//Pick one by one
String no1= random[(int) (Math.random()*(random.length))];
String no2 = random[(int) (Math.random()*(random.length))];
String no3 = random[(int) (Math.random()*(random.length))];
//print randomly generated strings
System.out.println("Here you go : " + no1 + " " + no2 + " " + no3 + ");
}
答案 0 :(得分:2)
基本上,要使用概率,您会生成0到100之间的随机数,不包括100。
然后,依次测试每个字符串,添加概率:
String s;
if (number < 10) {s = "abc";}
else if (number < 70) { s = "def";}
else if (number < 90) {s = "ghi";}
else {s = "danny";}
答案 1 :(得分:2)
伪代码:
Generate a random integer n between 0 and 9
if (n==0) return "abc"
else if (n <= 6) return "def"
else if (n <= 8) return "ghi"
else return "danny"
有很多方法可以做到这一点
答案 2 :(得分:1)
这可能不是最佳解决方案:
int number = (int) Math.random() * 100;
String myString;
if(number <= 10)
myString = "abc";
else if(number <= 20)
myString = "danny";
else if(number <= 40)
myString = "ghi";
else
myString = "def";
所以从0:10返回abc,10:20返回danny,20:40返回ghi,40:100返回def。 这个解决方案对于多个字符串/百分比来说会很糟糕,我确信有更好的方法可以做到这一点,但是不记得了(这是我的舌尖。)