生成具有正态分布属性的人物对象?
Generating people-objects with normally distributed attributes?
这个问题与我正在编写的视频游戏有关。
我正在尝试生成具有年龄、性别、宗教、收入等特征的人,以便每个属性以特定方式在人中分配。目前我正在使用一个地图,它存储对象(具有对应于特定特征的特定整数键)。
public class Person {
Map<Integer, Object> personalAttributes;
}
我还有一个 class 是一个州。
public class State {
Person[] personArray = new Person[200];
//Instantiates a bunch of Persons and puts the into the array
}
但是,我希望人们有 50/50 的性别、高斯年龄分布和自定义宗教分布。
这很重要,因为我希望能够对他们进行投票,并根据他们的不同特征获得回应。我该怎么做?
Random
class 在这里非常有用,因为它提供了一个 nextGaussian()
方法,该方法 returns 浮点数的正态分布,平均值为 0,标准差为1.0,您可以根据自己的最大和最小年龄按比例放大和截断。
对于 50/50 分布,您可以在迭代时在两种性别之间交替,或者您可以再次使用 Random
class 和 nextBoolean()
来确定性别伪随机。
对于自定义分布,我假设您希望一定比例的人口信奉每种宗教。只需在迭代时使用索引号来确定他们属于哪种宗教。例如,您可以让宗教 A 有 10% 的索引为 0 - 19,宗教 B 有 50% 的索引为 20 - 119,宗教 C 有 40%索引为 120 - 199。(如果您希望自定义分布改为使用概率,请参阅 this question)
所有这些加在一起可能看起来像这样:
Random rand = new Random();
Person[] people = new Person[200];
for (int i = 0; i < people.length; i++) {
Person p = new Person();
people[i] = p;
// Sex
p.setSex(rand.nextBoolean() ? "Male" : "Female");
// p.setSex(i % 2 == 0 ? "Male" : "Female");
// Age (normal distribution with min 0, max 100, and mean 50
int age = (int)(rand.nextGaussian() * 50);
while (Math.abs(age) > 50)
age = (int)(rand.nextGaussian() * 50);
p.setAge(age + 50);
// Religion
int maxA = (int) (people.length * .1),
maxB = (int) (people.length * .5) + maxA;
if (i < maxA)
p.setReligion("A");
else if (i < maxB)
p.setReligion("B");
else
p.setReligion("C");
}
// probably shuffle at the end so that religions aren't contiguous
这个问题与我正在编写的视频游戏有关。
我正在尝试生成具有年龄、性别、宗教、收入等特征的人,以便每个属性以特定方式在人中分配。目前我正在使用一个地图,它存储对象(具有对应于特定特征的特定整数键)。
public class Person {
Map<Integer, Object> personalAttributes;
}
我还有一个 class 是一个州。
public class State {
Person[] personArray = new Person[200];
//Instantiates a bunch of Persons and puts the into the array
}
但是,我希望人们有 50/50 的性别、高斯年龄分布和自定义宗教分布。
这很重要,因为我希望能够对他们进行投票,并根据他们的不同特征获得回应。我该怎么做?
Random
class 在这里非常有用,因为它提供了一个 nextGaussian()
方法,该方法 returns 浮点数的正态分布,平均值为 0,标准差为1.0,您可以根据自己的最大和最小年龄按比例放大和截断。
对于 50/50 分布,您可以在迭代时在两种性别之间交替,或者您可以再次使用 Random
class 和 nextBoolean()
来确定性别伪随机。
对于自定义分布,我假设您希望一定比例的人口信奉每种宗教。只需在迭代时使用索引号来确定他们属于哪种宗教。例如,您可以让宗教 A 有 10% 的索引为 0 - 19,宗教 B 有 50% 的索引为 20 - 119,宗教 C 有 40%索引为 120 - 199。(如果您希望自定义分布改为使用概率,请参阅 this question)
所有这些加在一起可能看起来像这样:
Random rand = new Random();
Person[] people = new Person[200];
for (int i = 0; i < people.length; i++) {
Person p = new Person();
people[i] = p;
// Sex
p.setSex(rand.nextBoolean() ? "Male" : "Female");
// p.setSex(i % 2 == 0 ? "Male" : "Female");
// Age (normal distribution with min 0, max 100, and mean 50
int age = (int)(rand.nextGaussian() * 50);
while (Math.abs(age) > 50)
age = (int)(rand.nextGaussian() * 50);
p.setAge(age + 50);
// Religion
int maxA = (int) (people.length * .1),
maxB = (int) (people.length * .5) + maxA;
if (i < maxA)
p.setReligion("A");
else if (i < maxB)
p.setReligion("B");
else
p.setReligion("C");
}
// probably shuffle at the end so that religions aren't contiguous