public
Description: [DRAFT] Hyper Puzzle Warrior XVII Ultra - a "Super Puzzle Fighter II Turbo" clone.
Homepage:
Clone URL: git://github.com/orfjackal/puzzle-warrior.git
puzzle-warrior / src / main / java / net / orfjackal / puzzlewarrior / ShuffleBag.java
100644 76 lines (62 sloc) 1.707 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
76
package net.orfjackal.puzzlewarrior;
 
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
 
/**
* @author Esko Luontola
* @since 25.2.2008
*/
public class ShuffleBag<T> {
 
    private final Random random;
 
    /**
* Unused values are in the range {@code 0 <= index < cursor}.
* Used values are in the range {@code cursor <= index < values.size()}.
*/
    private final List<T> values = new ArrayList<T>();
    private int cursor = 0;
 
    public ShuffleBag() {
        this(new Random());
    }
 
    public ShuffleBag(Random random) {
        this.random = random;
    }
 
    public void add(T value) {
        values.add(value);
    }
 
    public T get() {
        if (values.size() == 0) {
            throw new IllegalStateException("bag is empty");
        }
        int grab = randomUnused();
        T value = values.get(grab);
        markAsUsed(grab);
        return value;
    }
 
    private int randomUnused() {
        if (cursor <= 0) {
            cursor = values.size();
        }
        return random.nextInt(cursor);
    }
 
    private void markAsUsed(int indexOfUsed) {
        cursor--;
        swap(values, indexOfUsed, cursor);
    }
 
    private static <T> void swap(List<T> list, int x, int y) {
        T tmp = list.get(x);
        list.set(x, list.get(y));
        list.set(y, tmp);
    }
 
    public void addMany(T value, int quantity) {
        for (int i = 0; i < quantity; i++) {
            add(value);
        }
    }
 
    public List<T> getMany(int quantity) {
        List<T> results = new ArrayList<T>(quantity);
        for (int i = 0; i < quantity; i++) {
            results.add(get());
        }
        return results;
    }
}