该项目正在滚动一个 6 面骰子,并希望它在 90% 的时间内落在 6 上,而在 2% 的时间内落在 1-5 上。
这是主类Die
public class Die
{
//----------------------------------------------------------------------------------
// Instance Variables
//----------------------------------------------------------------------------------
protected int numSides;
protected Random myRandomNumGenerator;
//----------------------------------------------------------------------------------
//Constructors
//----------------------------------------------------------------------------------
/**
* Default constructor creates a 6-sided die.
*/
public Die()
{
numSides = 6;
myRandomNumGenerator = new Random();
}
/**
* This constructor takes in a single integer value and create a die with
* that number of sides.
*
* @param aNumSides Number of sides to create on the die.
*/
public Die(int aNumSides){
numSides = aNumSides;
myRandomNumGenerator = new Random();
}
//----------------------------------------------------------------------------------
//Class Methods
//----------------------------------------------------------------------------------
/**
* Getter for the number of sides on the die.
*
* @return The number of sides on the die.
*/
public int getNumOfSides()
{
return numSides;
}
/**
* Rolls the die to get a random value.
*
* @return A random value between 1 and the number of sides.
*/
public int roll()
{
return myRandomNumGenerator.nextInt(numSides) + 1;
}
}
这是一个子类,我需要在其中覆盖骰子中的 roll 方法,以将骰子加载到正确的值。
import java.util.Random;
public class LoadedDie extends Die{
protected double loadedPercentage;
protected int numSides;
protected int loadedValue;
protected Random ranNumGenerator;
public LoadedDie() {
loadedValue = 6;
loadedPercentage = .9;
}
public LoadedDie(int aNumSides, int aLoadedValue, double aLoadedPercentage) {
numSides = aNumSides;
loadedValue = aLoadedValue;
loadedPercentage = aLoadedPercentage;
}
public int roll() {
return ranNumGenerator.nextInt(numSides)+1;
}
}
我还没有弄清楚如何使随机数比其他数字更频繁地出现。 谢谢
最佳答案
您的要求重新措辞:
6 90% of the time
5 2%
4 2%
3 2%
2 2%
1 2%
因此,将其映射为 1-100 之间的随机数,而不是 1-6,这非常简单:
免责声明:我不是 Java 人员,无法验证它是否有效、是否可以更有效地编写等,但它说明了要点
int result = ranNumGenerator.nextInt(100);
if(result < 10) return (result % 5) + 1;
return 6;
关于java - 在java中滚动加权数字1-6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19417356/