gpt4 book ai didi

java - 通过生成随机数根据百分比随机选择表格

转载 作者:行者123 更新时间:2023-12-01 14:48:25 24 4
gpt4 key购买 nike

我正在开发一个项目,其中不同的数据库中有两个具有不同架构的表。这意味着我有两个不同的连接参数用于使用 JDBC 连接这两个表-

假设下面是 config.property 文件,其中 table1.percentage 表示 80% 的时间 table1 将被选取,并且 20% 的时间 table2 将根据随机数进行选择。

TABLES: table1 table2

#For Table1
table1.percentage: 80

#For Table2
table2.percentage: 20

下面的方法将读取上面的config.property文件并为每个表创建一个ReadTableConnectionInfo对象。

private static HashMap<String, ReadTableConnectionInfo> tableList = new HashMap<String, ReadTableConnectionInfo>();

private static void readPropertyFile() throws IOException {

prop.load(Read.class.getClassLoader().getResourceAsStream("config.properties"));

tableNames = Arrays.asList(prop.getProperty("TABLES").split(" "));

for (String arg : tableNames) {

ReadTableConnectionInfo ci = new ReadTableConnectionInfo();

double percentage = Double.parseDouble(prop.getProperty(arg + ".percentage"));

ci.setPercentage(percentage);

tableList.put(arg, ci);
}
}

下面是 ReadTableConnectionInfo 类,它将保存特定表的所有表连接信息

public class ReadTableConnectionInfo {

public String percentage;

public double getPercentage() {
return percentage;
}

public void setPercentage(double percentage) {
this.percentage = percentage;
}
}

现在,在我的运行方法中,每个线程必须生成随机数,然后根据每个表的百分比决定需要使用哪个表。

private static Random random = new SecureRandom();


@Override
public run() {
...


while ( < 60 minutes) {
double randomNumber = random.nextDouble() * 100.0;
ReadTableConnectionInfo tableInfo = selectRandomConnection(randomNumber);

// do query...
}
}


//Any problem with the below method?
private ReadTableConnectionInfo selectRandomConnection(double randomNumber) {
double limit = 0;
for (ReadTableConnectionInfo ci : tableLists.values()) {
limit += ci.getPercentage();
if (randomNumber < limit) {
return ci;
}
}
throw new IllegalStateException();
}

问题陈述:-

我的 selectRandomConnection 方法有什么问题吗?因为每个线程工作 60 分钟,并且在这 60 分钟内每次只选择 table1

我正在寻找的是它应该选择 table180% 时间和它应该选择 20% 的时间表2

最佳答案

如果您希望 A 在 80% 的情况下被选中,而 B 在 20% 的情况下被选中,则平均而言,只需选择 0(含)和 100(不含)之间的随机数即可。如果数量 < 80,则选择 A,否则选择 B。

就这么简单。

关于java - 通过生成随机数根据百分比随机选择表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15147017/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com