0

我正在尝试从 java 中具有所需概率的数组字符串列表生成随机字符串。我能够生成随机字符串但不知道如何处理概率。我必须运行程序几乎 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 + ");
    } 
4

3 回答 3

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";}
于 2012-11-07T18:48:42.763 回答
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"

有很多方法可以做到这一点

于 2012-11-07T18:49:08.447 回答
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。这个解决方案对于多个字符串/百分比来说会很糟糕,我相信有更好的方法可以做到这一点,但不记得了(它在我的舌尖上。)

于 2012-11-07T18:49:01.117 回答