forked from pxu/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomKey.java
More file actions
75 lines (59 loc) · 1.53 KB
/
RandomKey.java
File metadata and controls
75 lines (59 loc) · 1.53 KB
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
import java.util.*;
public class RandomKey {
public static Random rand = new Random();
public static String getRandomKey(Map<String, Integer> map, int rid) {
System.out.println(rid);
System.out.println(map);
int pos = 0, id = 0;
Iterator it = map.entrySet().iterator();
String result = "";
while(pos <= rid && it.hasNext()) {
Map.Entry KV = (Map.Entry) it.next();
result = (String) KV.getKey();
int weight = (int) KV.getValue();
pos += weight;
}
return result;
}
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<> ();
map.put("apple", 10);
map.put("banana", 50);
map.put("peach", 30);
int range = 0;
for(int v: map.values()) range += v;
int rid = rand.nextInt(range);
String result = getRandomKey2(map, rid);
System.out.println(result);
}
static class Node {
String key;
int val;
public Node(String k, int v) {
this.key = k;
this.val = v;
}
}
public static String getRandomKey2(Map<String, Integer> map, int rid) {
System.out.println(rid);
System.out.println(map);
Node[] nr = new Node[map.size()];
int e = 0;
for(String k: map.keySet()) {
nr[e++] = new Node(k, map.get(k));
}
int[] sum = new int[map.size()];
sum[0] = nr[0].val;
for(int i=1; i<sum.length; ++i) {
sum[i] = sum[i-1] + nr[i].val;
}
int l = 0, r = sum.length-1;
while(l < r) {
int mid = (l+r)/2;
if(sum[mid]-sum[l]+nr[l].val < rid) l = mid + 1;
else if(sum[mid]-sum[l]+nr[l].val == rid) return nr[mid].key;
else r=mid;
}
return nr[l].key;
}
}