admin
2020-12-19 37f89b3118620daa2277e227c2abdb574496ef56
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.ks;
 
import org.junit.jupiter.api.Test;
 
import java.util.*;
 
public class LuckyTest {
 
 
    @Test
    public void test() {
        Map<Long, Integer> map = new HashMap<>();
        int total = 0;
        int personCount = 1000000;
        for (int i = 0; i < personCount; i++) {
            map.put(10000L + i, i == 0 ? 0 : (int) (1 + 10 * Math.random()));
            total += map.get(10000L + i);
        }
        Set<Long> sets = choujiang(map, 100);
        int percent = total / personCount;
        int upCount = 0;
        for (Long uid : sets) {
            if (map.get(uid) > percent)
                upCount += 1;
            System.out.println(uid + "-" + map.get(uid) + "是否大于均值:" + (map.get(uid) > percent));
        }
        System.out.println("大于均值数量:" + upCount);
        System.out.println("数量:" + sets.size());
    }
 
    private Set<Long> choujiang(Map<Long, Integer> map, int number) {
 
        List<Long> mList = new ArrayList<>();
        for (Iterator<Long> its = map.keySet().iterator(); its.hasNext(); ) {
            Long uid = its.next();
            int c = map.get(uid);
            for (int i = 0; i < c; i++) {
                mList.add(uid);
            }
        }
 
        Set<Long> luckyUids = new HashSet<>();
        for (int i = 0; i < number; i++) {
            if(mList.size()==0)
                break;
            long startTime = System.currentTimeMillis();
            int p = (int) (mList.size() * Math.random());
            long uid = mList.get(p);
            luckyUids.add(uid);
 
            //移除列表右面的相同uid
            while (mList.size() > p && mList.get(p) == uid) {
                mList.remove(p);
            }
 
            //查询相同uid的列表左侧起点
            for (int j = p - 1; j >= 0; j--) {
                if (mList.get(j).longValue() != uid) {
                    p = j + 1;
                    break;
                } else if (j == 0) {
                    p = 0;
                }
            }
 
            //删除左侧相同uid
            while (mList.size() > p && mList.get(p) == uid) {
                mList.remove(p);
            }
 
            System.out.println("运行时间:" + (System.currentTimeMillis() - startTime));
        }
 
 
        System.out.println(luckyUids);
        return luckyUids;
    }
 
 
}