Subversion Repositories SmartDukaan

Rev

Rev 32960 | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
32960 amit.gupta 1
package com.spice.profitmandi.service.order;
2
 
3
import java.util.NavigableMap;
4
import java.util.Random;
5
import java.util.TreeMap;
6
 
7
public class RandomCollection<E> {
8
    private final NavigableMap<Double, E> map = new TreeMap<>();
9
    private final Random random;
10
    private double total = 0;
11
 
12
    public RandomCollection() {
13
        this(new Random());
14
    }
15
 
16
    public RandomCollection(Random random) {
17
        this.random = random;
18
    }
19
 
20
    public RandomCollection<E> add(double weight, E result) {
21
        if (weight <= 0) return this;
22
        total += weight;
23
        map.put(total, result);
24
        return this;
25
    }
26
 
27
    public E next() {
28
        double value = random.nextDouble() * total;
29
        return map.higherEntry(value).getValue();
30
    }
33665 ranu 31
 
32
    public int size() {
33
        return map.size();
34
    }
32960 amit.gupta 35
}
36