带权重的随机算法(Weighted Random Algorithm)是一种在给定一组具有不同权重的选项时,根据权重随机选择一个选项的算法。这种算法常用于需要按照某种分布来选择元素的情况,比如负载均衡、随机化测试、游戏中的随机事件等。 比如游戏抽奖,抽中最好奖品的概率会随着抽奖次数的增加而增加。 以下我们来举一个学生点名的例子,用以理解带权重的随机算法。 点名要求如下:1,最初每个学生被点到名的概率一样 2,每次被点到名下次再被点到的概率减半 首先我们创建学生类:
package IoStream.Case;
public class Student
{
private String name;
private String sex;
private int age;
private double weight;
public Student()
{
}
public Student(String name, String sex, int age, double weight)
{
this.name = name;
this.sex = sex;
this.age = age;
this.weight = weight;
}
/**
* 获取
* @return name
*/
public String getName()
{
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name)
{
this.name = name;
}
/**
* 获取
* @return sex
*/
public String getSex()
{
return sex;
}
/**
* 设置
* @param sex
*/
public void setSex(String sex)
{
this.sex = sex;
}
/**
* 获取
* @return age
*/
public int getAge()
{
return age;
}
/**
* 设置
* @param age
*/
public void setAge(int age)
{
this.age = age;
}
/**
* 获取
* @return weight
*/
public double getWeight()
{
return weight;
}
/**
* 设置
* @param weight
*/
public void setWeight(double weight)
{
this.weight = weight;
}
public String toString()
{
return name + "-" + sex + "-" + age + "-" + weight;
}
}
按以下格式随便编一些名字 姓名-性别-年龄-权重
王二麻子-男-25-1.0
李大脚-男-32-1.0
张小花-女-29-1.0
刘铁柱-男-40-1.0
陈香菜-女-22-1.0
杨胖胖-男-35-1.0
赵香蕉-女-28-1.0
周拜金-男-45-1.0
吴饼干-女-30-1.0
黄三炮-男-27-1.0
许大嘴-女-31-1.0
马小胖-男-29-1.0
朱二傻-女-24-1.0
冯大头-男-38-1.0
陶小贝-女-33-1.0
林铁蛋-男-42-1.0
钟哈哈-男-26-1.0
梁小笨-女-39-1.0
徐二白-男-34-1.0
袁矮子-女-28-1.0
蔡懒虫-男-23-1.0
秦二愣子-女-37-1.0
邓大傻-男-41-1.0
魏二呆-女-29-1.0
潘短腿-男-36-1.0
曾二百斤-女-31-1.0
赖大胃-男-27-1.0
丁小懒-女-33-1.0
姚二白-男-30-1.0
文二脑-女-25-1.0
下面为带权重的随机算法
package IoStream.Case;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
public class Random_roll_call_with_weight
{
public static void main(String[] args) throws IOException
{
//1将文件中的数据放入列表
ArrayList list = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(".\\roll.txt"));
String info;
while ((info = br.readLine()) != null){
String[] split = info.split("-");
Student student = new Student(split[0],split[1],Integer.parseInt(split[2]),Double.parseDouble(split[3]));
list.add(student);
}
//System.out.println(list);
//2计算总权重
double weight = 0;
int index = 0;
for (Student student : list)
{
weight = weight + student.getWeight();
}
//System.out.println(weight);
//3计算每一个权重占比
double[] arr = new double[list.size()];
for (Student student : list)
{
arr[index] = student.getWeight()/weight;
index++;
}
//System.out.println(Arrays.toString(arr));
//4计算每一个权重占比范围
for (int i = 1; i |