File: LongHeapMap.java

package info (click to toggle)
bbmap 39.20%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,024 kB
  • sloc: java: 312,743; sh: 18,099; python: 5,247; ansic: 2,074; perl: 96; makefile: 39; xml: 38
file content (100 lines) | stat: -rwxr-xr-x 2,214 bytes parent folder | download | duplicates (4)
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package structures;

/**
 * Maintains a heap of unique values and counts.
 * @author Brian Bushnell
 * @date August 3, 2017
 *
 */
public class LongHeapMap implements LongHeapSetInterface {
	
	public LongHeapMap(int limit_){
		limit=limit_;
		heap=new LongHeap(limit, true);
		map=new LongHashMap(limit*2);
	}
	
	@Override
	public boolean add(long key){
		return increment(key, 1)>0;
	}
	
	@Override
	public int increment(long key, int incr){
		assert(incr>=1);
		assert(heap.size()==map.size());
		if(heap.hasRoom()){
			int value=map.increment(key, incr);
			if(value==incr){heap.add(key);}
			assert(heap.size()==map.size());
			return value;
		}
		
		final long bottom=heap.peek();
		if(key>bottom){
			int value=map.increment(key, incr);
			if(value==incr){
				map.remove(bottom);
				assert(map.size()<=limit);
				heap.add(key);
				assert(heap.size()<=limit);
				assert(heap.size()==map.size());
				return value;
			}
		}
		assert(heap.size()==map.size());
		return 0;
	}
	
	@Override
	public void clear(){
		assert(heap.size()==map.size()) : heap.size()+", "+map.size();
		if(heap.size()<1){
			assert(map.size()<1) : heap.size()+", "+map.size();
			return;
		}
		heap.clear();
		map.clear();
		assert(heap.size()==map.size());
	}
	
	public void add(LongHeapMap b){
		assert(heap.size()==map.size());
		final long[] keys=b.map.keys();
		final int[] values=b.map.values();
		final long invalid=b.map.invalid();
		
		for(int i=0; i<keys.length; i++){
			final long key=keys[i];
			final int value=values[i];
			assert((key==invalid)==(value==0));
			if(key!=invalid){
				increment(key, value);
			}
		}
		assert(heap.size()==map.size());
	}
	
	@Override
	public int size(){
		assert(heap.size()==map.size());
		return heap.size();
	}
	
	@Override
	public boolean contains(long key){return map.contains(key);}

	@Override
	public int capacity(){return heap.capacity();}
	@Override
	public boolean hasRoom(){return heap.hasRoom();}
	@Override
	public LongHeap heap(){return heap;}
	@Override
	public long peek(){return heap.peek();}
	
	final int limit;
	public LongHeap heap;
	public LongHashMap map;
	
}