package dianamingq;
import java.io.*;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class test2 {
public static void main(String[] args) throws IOException {
//带权重的随机点名器
//首先是要读取文件信息
BufferedReader br = new BufferedReader(new FileReader("ttt.txt"));
String s ;
ArrayList<student> a1 = new ArrayList<student>();
while ((s=br.readLine())!=null)
{
String[] st= s.split("-");
//用集合将他们拿出来,用student来存储
a1.add(new student(st[0],st[1],st[2],st[3]));
}
br.close();
//计算权重和,然后再相加求各个数值在数轴的占比
int sum=0;
for (int i = 0; i < a1.size(); i++) {
sum+=a1.get(i).getWeight();
}
//然后把所有数据的权重除以总权重。得到他们再数值中的位置,定义一个数组记录
Double []arr1 = new Double[a1.size()];
for (int i = 0; i < arr1.length; i++) {
if(i!=0){
arr1[i]=a1.get(i).weight/sum+arr1[i-1];}else{
arr1[i]=a1.get(i).weight/sum;
}
}
//此时随机点名,生成一个0到1的随机数,在哪个区间,就点哪个人的名字
Random ran = new Random();
Double ran1 = ran.nextDouble(1e10+1)/1e10;
System.out.println(ran1);
//使用二分查找,就能确定应该插入那个位置
int index = -Arrays.binarySearch(arr1,ran1) -1; //该方法返回的是-index-1,我们要获得index
//这个时候返回的就是我们要点的名字的索引了
System.out.println(a1.get(index).getName());
//要求是点到一次名字,他的权重就要减半
a1.get(index).setWeight(a1.get(index).getWeight()/2);
System.out.println(a1);
BufferedWriter bw = new BufferedWriter(new FileWriter("ttt.txt"));
//接下来把集合写回去
//改写student的tostring方法,使其变成想要的格式
for (student student : a1) {
bw.write(student.toString());
bw.newLine();
}
bw.close();
}
}
package dianamingq;
public class student {
String name;
String gender;
int age;
double weight;
public student() {
}
public student(String name, String gender, String age, String weight) {
this.name = name;
this.gender = gender;
this.age = Integer.parseInt(age);
this.weight = Double.parseDouble(weight);
}
/**
* 获取
* @return name
*/
public String getName() {
return name;
}
/**
* 设置
* @param name
*/
public void setName(String name) {
this.name = name;
}
/**
* 获取
* @return gender
*/
public String getGender() {
return gender;
}
/**
* 设置
* @param gender
*/
public void setGender(String gender) {
this.gender = gender;
}
/**
* 获取
* @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+"-"+gender+"-"+age+"-"+weight;
}
}
带权重的随机点名
最新推荐文章于 2024-10-06 20:16:20 发布