import cn.hutool.core.lang.WeightRandom;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
public class RandomUtil extends cn.hutool.core.util.RandomUtil {
/**
* 根據(jù)權(quán)重列表生成固定總量的數(shù)組
*
* @param weightList 權(quán)重列表
* @param total 隨機(jī)列表數(shù)的總和
* @param fuDong 浮動(dòng)指數(shù)
* @return
*/
public static <T> Map<T, Integer> randomListFromWeight(List<WeightRandom.WeightObj<T>> weightList, Integer total, double fuDong) {
if (!(fuDong > 0 && fuDong < 1)) {
throw new IllegalArgumentException("浮動(dòng)指數(shù)必須在0~1之間");
}
Map<T, Integer> result = new HashMap<>();
// 將權(quán)重列表倒序排列,保證權(quán)重高的優(yōu)先取值
weightList.sort(new Comparator<WeightRandom.WeightObj>() {
@Override
public int compare(WeightRandom.WeightObj o1, WeightRandom.WeightObj o2) {
if (o1.getWeight() > o2.getWeight()) {
return -1;
} else if (o1.getWeight() < o2.getWeight()) {
return 1;
} else {
return 0;
}
}
});
// 統(tǒng)計(jì)權(quán)重總和
double sumWeight = weightList.stream().map(WeightRandom.WeightObj::getWeight).reduce((a, b) -> a + b).orElse(1.0 * weightList.size());
// 計(jì)算平均權(quán)重
double avgWeight = sumWeight / weightList.size();
// 計(jì)算平均值
double avg = 1.0 * total / weightList.size();
int before = 0;
for (int i = 0; i < weightList.size() - 1; i++) {
// 實(shí)際值 = 平均值 * 權(quán)重 / 平均權(quán)重
double countForWeight = avg * weightList.get(i).getWeight() / avgWeight;
double min = before + countForWeight * (1 - fuDong);
double max = before + countForWeight * (1 + fuDong);
min = min > total ? before : min;
max = max > total ? total : max;
int after = min < max ? (int) Math.round(RandomUtil.randomDouble(min, max)) : total;
result.put(weightList.get(i).getObj(), after - before);
before = after;
}
// 最后一個(gè)的值
result.put(weightList.get(weightList.size() - 1).getObj(), total - before);
return result;
}
}
權(quán)重隨機(jī)數(shù)列表
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
相關(guān)閱讀更多精彩內(nèi)容
- 一. 最直接的方式:用numpy.random模塊來(lái)生成隨機(jī)數(shù)組 1、np.random.rand 用于生成[0....
- 【蝴蝶效應(yīng)】 蝴蝶效應(yīng):上個(gè)世紀(jì)70年代,美國(guó)一個(gè)名叫洛倫茲的氣象學(xué)家在解釋空氣系統(tǒng)理論時(shí)說(shuō),亞馬遜雨林一只蝴蝶...
- 1.rand()函數(shù)只能生成0到1之間的隨機(jī)小數(shù),如果想要生成0到10,0到100就rand()*相應(yīng)的值。 2....
- 一般計(jì)算機(jī)的隨機(jī)數(shù)都是偽隨機(jī)數(shù),以一個(gè)真隨機(jī)數(shù)(隨機(jī)數(shù)種子)作為初始條件,然后用一定的算法不停迭代產(chǎn)生隨機(jī)數(shù)。Un...