现在,据我所知,实际随机变量是一个将值映射到它们的概率的函数。我不认为你应该返回一个函数,所以我已经抓住了这个:最接近我猜你应该做的事情:
import java.util.*;
import java.lang.*;
class RandomVar
{
TreeMap<Double, Integer> variables;
public RandomVar()
{
variables = new TreeMap<Double, Integer>();
int count = Main.RandGen.nextInt(15);
double probabilityLeft = 1.0;
for (int i = 0 ; i < count - 1; i++)
{
int toPut = Main.RandGen.nextInt(100);
while (variables.containsValue(toPut)) toPut = Main.RandGen.nextInt(100);
double prob = probabilityLeft * Main.RandGen.nextDouble();
variables.put(prob, toPut);
}
int toPut = Main.RandGen.nextInt(100);
while (variables.containsValue(toPut)) toPut = Main.RandGen.nextInt(100);
double prob = probabilityLeft;
variables.put(prob, toPut);
}
public int getValue()
{
double rand = Main.RandGen.nextDouble();
double sum = 0;
for (double prob : variables.keySet()) //keySet() is sorted ascending
{
if (prob >= rand)
return variables.get(prob);
}
return variables.get(variables.lastKey());
}
//Shows probabilities of values
public void test()
{
for (double key : variables.keySet())
System.out.println(key + " :: " + variables.get(key));
}
}
class Main
{
public static Random RandGen = new Random();
public static void main (String[] args)
{
RandomVar rv = new RandomVar();
rv.test();
System.out.println("------------------------------");
for (int i = 0; i < 40 ; i++)
System.out.print(rv.getValue() + ", ");
}
}
这是一个非常糟糕的解决方案,基本上是一个允许您以一组(随机)概率返回值的类。我仍然不知道这是否是您教授想要的...