|
| 1 | +package algorithm.other; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * Created by boyce on 2014/9/4. |
| 7 | + */ |
| 8 | +public class BucketProblem { |
| 9 | + |
| 10 | + private static final int DEFAULT_CAPACITY = 10; |
| 11 | + private Bucket[] buckets; |
| 12 | + |
| 13 | + public BucketProblem(int capacity) { |
| 14 | + if (capacity <=0 ) |
| 15 | + throw new IllegalArgumentException(); |
| 16 | + |
| 17 | + this.buckets = new Bucket[capacity]; |
| 18 | + } |
| 19 | + |
| 20 | + public BucketProblem() { |
| 21 | + this(DEFAULT_CAPACITY); |
| 22 | + } |
| 23 | + |
| 24 | + public void add(int data) {} |
| 25 | + |
| 26 | + private static class Bucket { |
| 27 | + //bucket name |
| 28 | + private String name; |
| 29 | + |
| 30 | + //bucket elements |
| 31 | + private int[] elements; |
| 32 | + private int size; |
| 33 | + |
| 34 | + //bucket capacity |
| 35 | + private int capacity; |
| 36 | + |
| 37 | + //bucket remaining capacity |
| 38 | + private int remainingCapacity; |
| 39 | + |
| 40 | + private final static int ELEMENTS_LENGTH = 10; |
| 41 | + |
| 42 | + private Bucket(String name, int capacity) { |
| 43 | + this.name = name; |
| 44 | + this.capacity = capacity; |
| 45 | + this.remainingCapacity = this.capacity; |
| 46 | + this.elements = new int[ELEMENTS_LENGTH]; |
| 47 | + } |
| 48 | + |
| 49 | + private Bucket(String name) { |
| 50 | + this(name, 1); |
| 51 | + } |
| 52 | + |
| 53 | + private boolean add(int element) { |
| 54 | + if (element <= 0) return false; |
| 55 | + |
| 56 | + if (element > this.remainingCapacity) |
| 57 | + return false; |
| 58 | + |
| 59 | + if (this.size >= this.elements.length) |
| 60 | + this.ensureCapacity(1 << this.elements.length); |
| 61 | + |
| 62 | + this.elements[size++] = element; |
| 63 | + this.remainingCapacity -= element; |
| 64 | + |
| 65 | + return true; |
| 66 | + } |
| 67 | + |
| 68 | + private void ensureCapacity(int capacity) { |
| 69 | + int[] newTree = new int[capacity]; |
| 70 | + for (int i=0; i<this.elements.length; i++) |
| 71 | + newTree[i] = this.elements[i]; |
| 72 | + |
| 73 | + this.elements = newTree; |
| 74 | + } |
| 75 | + |
| 76 | + @Override |
| 77 | + public String toString() { |
| 78 | + return this.name + ": " + Arrays.toString(elements); |
| 79 | + } |
| 80 | + } |
| 81 | +} |
0 commit comments