我正在尝试从 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 + ");
}
最佳答案
伪代码:
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"
有很多方法可以做到这一点
关于java - 从具有一定概率的字符串列表生成随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13276014/