Java根据概率(权重)排序

原理:依次将权重叠加,构建各元素命中区间,然后利用random.nextInt(int)在总的区间内生成随机整数,落在指定区间内即为命中。命中者不参与下一轮命中事件,同时命中者自身、后面的元素、以及总和均减少本轮命中值,继续下一轮,直至所有区间被命中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
public class App
{
public static void main( String[] args ) throws Exception
{
Channel[] channels = new Channel[4];
channels[0] = new Channel();
channels[0].setName("Alipay");
channels[0].setWeight(100);
channels[1] = new Channel();
channels[1].setName("WxPay");
channels[1].setWeight(90);
channels[2] = new Channel();
channels[2].setName("BankPay");
channels[2].setWeight(80);
channels[3] = new Channel();
channels[3].setName("CashPay");
channels[3].setWeight(70);

Channel[] newChannels = sortWithProbability(channels);
for (int i = 0; i < newChannels.length; i++) {
System.out.println(newChannels[i].getName());
}
}

private static Channel[] sortWithProbability(Channel[] channels) {
Channel[] newChannels = new Channel[channels.length];
int[] weights = new int[channels.length];
weights[0] = channels[0].getWeight();
for (int i = 1; i < channels.length; i++) {
weights[i] = weights[i-1] + channels[i].getWeight();
}
int sum = weights[channels.length - 1];
for (int i = 0; i < weights.length; i++) {
System.out.print(weights[i] + " ");
}
System.out.println();

Random random = new Random();
int index = 0;
for (int i = 0; i < channels.length; i++) {
int weight = random.nextInt(sum);
System.out.print("第" + i + "次: " + weight);
int hit = 0;
for (int j = 0; j < weights.length; j++) {
if (weight < weights[j]) {
hit = j;
System.out.println(", 命中: " + j);
newChannels[index++] = channels[j];
sum -= channels[j].getWeight();
break;
}
}
for (int j = hit; j < weights.length; j++) {
weights[j] -= channels[hit].getWeight();
}
}
return newChannels;
}
}

@Data
class Channel {
private String name;
private int weight;
}
1
2
3
4
5
6
7
8
9
100 190 270 340 
第0次: 158, 命中: 1
第1次: 207, 命中: 3
第2次: 25, 命中: 0
第3次: 40, 命中: 2
WxPay
CashPay
Alipay
BankPay

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :