Debian Codegraph @

current/structures/IntLongHashMap.java

raw symbols SCIP
1 package structures;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.HashMap;
6 import java.util.Random;
7
8 import shared.KillSwitch;
9 import shared.Primes;
10 import shared.Shared;
11 import shared.Timer;
12 import shared.Tools;
13
14 /**
15 * @author Brian Bushnell
16 * @date December 12, 2017
17 *
18 */
19 public final class IntLongHashMap{
20
21 public static void main(String[] args){
22 Random randy2=Shared.threadLocalRandom();
23 IntLongHashMap map=new IntLongHashMap(20, 0.7f);
24 HashMap<Integer, Long> map2=new HashMap<Integer, Long>(20, 0.7f);
25 ArrayList<Integer> list=new ArrayList<Integer>();
26 ArrayList<Integer> list2=new ArrayList<Integer>();
27 // ArrayList<Integer> vals=new ArrayList<Integer>();
28 for(int i=0; i<1000; i++){
29 assert(!map.contains(i));
30 assert(!map2.containsKey(i));
31 list.add(Integer.valueOf(i));
32 }
33 for(int i=0; i<1000; i++){
34 int r=randy2.nextInt();
35 list2.add(r);
36 }
37
38 for(int x : list){
39 map.put(x, 2L*x);
40 map2.put(x, (2L*x));
41 assert(map.get(x)==(2L*x));
42 assert(map2.get(x)==(2L*x));
43 }
44
45 for(int x : list){
46 assert(map.get(x)==(2L*x));
47 assert(map2.get(x)==(2L*x));
48 map.remove(x);
49 map2.remove(x);
50 assert(!map.contains(x));
51 assert(!map2.containsKey(x));
52 }
53 assert(map.isEmpty());
54 assert(map2.isEmpty());
55
56 for(int x : list2){
57 map.put(x, (2L*x));
58 map2.put(x, (2L*x));
59 assert(map.get(x)==((2L*x)));
60 assert(map2.get(x)==((2L*x)));
61 }
62
63 for(int x : list2){
64 assert(map.get(x)==((2L*x)));
65 assert(map2.get(x)==((2L*x)));
66 map.remove(x);
67 map2.remove(x);
68 assert(!map.contains(x));
69 assert(!map2.containsKey(x));
70 }
71 assert(map.isEmpty());
72 assert(map2.isEmpty());
73
74 int count=4000000;
75 int runs=32;
76 IntList ll=new IntList(count);
77 for(int i=0; i<count; i++){ll.add(randy2.nextInt());}
78
79 Shared.printMemory();
80 Timer t=new Timer();
81 for(int k=0; k<2; k++){
82 System.err.println("LongHashMap:");
83 t.start();
84 for(int i=0; i<runs; i++){
85 // for(long x : ll.array){
86 // map.add(x);
87 // }
88 final int[] y=ll.array;
89 for(int z=0; z<count; z++){
90 final int key=y[z];
91 map.add(key);
92 map.contains(key);
93 map.remove(key);
94 map.add(key);
95 }
96 // for(long x : ll.array){
97 // map.remove(x);
98 // }
99 // map.clear();
100 // assert(map.isEmpty());
101 // System.err.println("Finished run "+i);
102 }
103 t.stop();
104 System.err.println(t);
105 Shared.printMemory();
106
107 // System.err.println("HashMap:");
108 // t.start();
109 // for(int i=0; i<runs; i++){
110 // for(long x : ll.array){
111 // map2.add(x);
112 // }
113 // for(long x : ll.array){
114 // map2.remove(x);
115 // }
116 // assert(map2.isEmpty());
117 //// System.err.println("Finished run "+i);
118 // }
119 // t.stop();
120 // System.err.println(t);
121 // Shared.printMemory();
122 }
123 t.stop();
124 }
125
126 /*--------------------------------------------------------------*/
127 /*---------------- Initialization ----------------*/
128 /*--------------------------------------------------------------*/
129
130 public IntLongHashMap(){
131 this(256);
132 }
133
134 public IntLongHashMap(int initialSize){
135 this(initialSize, 0.7f);
136 }
137
138 public IntLongHashMap(int initialSize, float loadFactor_){
139 invalid=randy.nextInt()|MINMASK;
140 assert(invalid<0);
141 assert(initialSize>0);
142 assert(loadFactor_>0 && loadFactor_<1);
143 loadFactor=Tools.mid(0.25f, loadFactor_, 0.90f);
144 resize(initialSize);
145 }
146
147 /*--------------------------------------------------------------*/
148 /*---------------- Public Methods ----------------*/
149 /*--------------------------------------------------------------*/
150
151 public void clear(){
152 if(size<1){return;}
153 Arrays.fill(keys, invalid);
154 Arrays.fill(values, 0);
155 size=0;
156 // assert(verify()); //123
157 }
158
159 public boolean contains(int key){
160 // assert(verify()); //123
161 return key==invalid ? false : findCell(key)>=0;
162 }
163
164 public boolean containsKey(int key){
165 return contains(key);
166 }
167
168 public long get(int key){
169 // assert(verify()); //123
170 long value=-1;
171 if(key!=invalid){
172 int cell=findCell(key);
173 if(cell>=0){value=values[cell];}
174 }
175 return value;
176 }
177
178 /**
179 * Increment this key's value by 1.
180 * @param key
181 * @return New value
182 */
183 public long add(int key){
184 return increment(key, 1);
185 }
186
187 /**
188 * Increment this key's value by incr.
189 * @param key
190 * @param incr
191 * @return New value
192 */
193 public long increment(int key, long incr){
194 // assert(verify()); //123
195 if(key==invalid){resetInvalid();}
196 int cell=findCellOrEmpty(key);
197 if(keys[cell]==invalid){
198 keys[cell]=key;
199 values[cell]=incr;
200 size++;
201 // assert(verify()); //123
202 if(size>sizeLimit){resize();}
203 // assert(verify()); //123
204 return incr;
205 }else{
206 values[cell]+=incr;
207 // assert(verify()); //123
208 return values[cell];
209 }
210 }
211
212 public void incrementAll(IntLongHashMap map) {
213 for(int i=0; i<map.keys.length; i++) {
214 if(map.keys[i]!=map.invalid) {
215 increment(map.keys[i], map.values[i]);
216 }
217 }
218 }
219
220 /**
221 * Map this key to value.
222 * @param key
223 * @param value
224 * @return true if the key was added, false if it was already contained.
225 */
226 public boolean put(int key, long value){
227 // assert(verify()); //123
228 if(key==invalid){resetInvalid();}
229 int cell=findCellOrEmpty(key);
230 if(keys[cell]==invalid){
231 keys[cell]=key;
232 values[cell]=value;
233 size++;
234 if(size>sizeLimit){resize();}
235 // assert(verify()); //123
236 return true;
237 }
238 assert(keys[cell]==key);
239 // assert(verify()); //123
240 return false;
241 }
242
243 /**
244 * Remove this key from the map.
245 * @param key
246 * @return Old value.
247 */
248 public long remove(int key){
249 // assert(verify()); //123
250 if(key==invalid){return -1;}
251 final int cell=findCell(key);
252 if(cell<0){return -1;}
253 assert(keys[cell]==key);
254 keys[cell]=invalid;
255 final long value=values[cell];
256 values[cell]=0;
257 size--;
258
259 rehashFrom(cell);
260 // assert(verify()); //123
261 return value;
262 }
263
264 public int size(){return size;}
265
266 public boolean isEmpty(){return size==0;}
267
268 /*--------------------------------------------------------------*/
269 /*---------------- String Methods ----------------*/
270 /*--------------------------------------------------------------*/
271
272 @Override
273 public String toString(){
274 return toStringListView();
275 }
276
277 public String toStringSetView(){
278 StringBuilder sb=new StringBuilder();
279 sb.append('[');
280 String comma="";
281 for(int i=0; i<keys.length; i++){
282 if(keys[i]!=invalid){
283 sb.append(comma+"("+i+", "+keys[i]+", "+values[i]+")");
284 comma=", ";
285 }
286 }
287 sb.append(']');
288 return sb.toString();
289 }
290
291 public String toStringListView(){
292 StringBuilder sb=new StringBuilder();
293 sb.append('[');
294 String comma="";
295 for(int i=0; i<keys.length; i++){
296 if(keys[i]!=invalid){
297 sb.append(comma+keys[i]);
298 comma=", ";
299 }
300 }
301 sb.append(']');
302 return sb.toString();
303 }
304
305 public int[] toArray(){
306 int[] x=KillSwitch.allocInt1D(size);
307 int i=0;
308 for(int key : keys){
309 if(key!=invalid){
310 x[i]=key;
311 i++;
312 }
313 }
314 return x;
315 }
316
317 public long[] toArray(long thresh){
318 int len=0;
319 // assert(verify());
320 for(int i=0; i<values.length; i++){
321 assert((values[i]==0)==(keys[i]==invalid)) : i+", "+values[i]+", "+keys[i]+", "+invalid+"\n"+toStringSetView();
322 assert((keys[i]<0)==((keys[i]==invalid))) : toStringSetView();
323 if(values[i]>=thresh){
324 assert(keys[i]>=0) : "\nNegative key ("+keys[i]+", "+values[i]+", "+i+") for thresh "+thresh+":\n"+toStringSetView();
325 len++;
326 }
327 }
328 long[] x=KillSwitch.allocLong1D(len);
329 for(int i=0, j=0; j<len; i++){
330 if(values[i]>=thresh){
331 x[j]=keys[i];
332 assert(keys[i]>=0) : "\nNegative key ("+keys[i]+", "+values[i]+", "+i+") for thresh "+thresh+":\n"+toStringSetView();
333 j++;
334 }
335 }
336 return x;
337 }
338
339 /*--------------------------------------------------------------*/
340 /*---------------- Private Methods ----------------*/
341 /*--------------------------------------------------------------*/
342
343 public boolean verify(){
344 if(keys==null){return true;}
345 int numValues=0;
346 int numFound=0;
347 for(int i=0; i<keys.length; i++){
348 final int key=keys[i];
349 final long value=values[i];
350
351 if(key==invalid){
352 if(value!=0){
353 assert(false) : i+", "+key+", "+value;
354 return false;
355 }
356 }else{
357 numValues++;
358 if(value<1){
359 assert(false) : i+", "+key+", "+value;
360 return false;
361 }
362 final int cell=findCell(key);
363 if(i==cell){
364 numFound++;
365 }else{
366 assert(false) : i+", "+key+", "+value+", "+cell+"\n"+((cell>=0) ? keys[cell]+", "+values[cell]+"\n" : "");
367 return false;
368 }
369 }
370 }
371 boolean pass=(numValues==numFound && numValues==size);
372 assert(pass) : numValues+", "+numFound+", "+size;
373 return pass;
374 }
375
376 private void rehashFrom(int initial){
377 if(size<1){return;}
378 final int limit=keys.length;
379 for(int cell=initial+1; cell<limit; cell++){
380 final long x=keys[cell];
381 if(x==invalid){return;}
382 rehashCell(cell);
383 }
384 for(int cell=0; cell<initial; cell++){
385 final long x=keys[cell];
386 if(x==invalid){return;}
387 rehashCell(cell);
388 }
389 }
390
391 private boolean rehashCell(final int cell){
392 final int key=keys[cell];
393 final long value=values[cell];
394 assert(key!=invalid);
395 if(key==invalid){resetInvalid();}
396 final int dest=findCellOrEmpty(key);
397 if(cell==dest){return false;}
398 assert(keys[dest]==invalid);
399 keys[cell]=invalid;
400 values[cell]=0;
401 keys[dest]=key;
402 values[dest]=value;
403 return true;
404 }
405
406 private void resetInvalid(){
407 final int old=invalid;
408 int x=invalid;
409 while(x==old || contains(x)){x=randy.nextInt()|MINMASK;}
410 assert(x<0);
411 invalid=x;
412 for(int i=0; i<keys.length; i++){
413 if(keys[i]==old){
414 assert(values[i]==0);
415 keys[i]=invalid;
416 }
417 }
418 }
419
420 private int findCell(final int key){
421 if(key==invalid){return -1;}
422
423 final int limit=keys.length, initial=(key&MASK)%modulus;
424 for(int cell=initial; cell<limit; cell++){
425 final long x=keys[cell];
426 if(x==key){return cell;}
427 if(x==invalid){return -1;}
428 }
429 for(int cell=0; cell<initial; cell++){
430 final long x=keys[cell];
431 if(x==key){return cell;}
432 if(x==invalid){return -1;}
433 }
434 return -1;
435 }
436
437 private int findCellOrEmpty(final int key){
438 assert(key!=invalid) : "Collision - this should have been intercepted.";
439
440 final int limit=keys.length, initial=(key&MASK)%modulus;
441 for(int cell=initial; cell<limit; cell++){
442 final long x=keys[cell];
443 if(x==key || x==invalid){return cell;}
444 }
445 for(int cell=0; cell<initial; cell++){
446 final long x=keys[cell];
447 if(x==key || x==invalid){return cell;}
448 }
449 throw new RuntimeException("No empty cells - size="+size+", limit="+limit);
450 }
451
452 private final void resize(){
453 assert(size>=sizeLimit);
454 resize(keys.length*2L+1);
455 }
456
457 private final void resize(final long size2){
458 // assert(verify()); //123
459 assert(size2>size) : size+", "+size2;
460 long newPrime=Primes.primeAtLeast(size2);
461 if(newPrime+extra>Integer.MAX_VALUE){
462 newPrime=Primes.primeAtMost(Integer.MAX_VALUE-extra);
463 }
464 assert(newPrime>modulus) : "Overflow: "+size+", "+size2+", "+modulus+", "+newPrime;
465 modulus=(int)newPrime;
466
467 final int size3=(int)(newPrime+extra);
468 sizeLimit=(int)(modulus*loadFactor);
469 final int[] oldKeys=keys;
470 final long[] oldValues=values;
471 keys=KillSwitch.allocInt1D(size3);
472 values=KillSwitch.allocLong1D(size3);
473 Arrays.fill(keys, invalid);
474
475 // System.err.println("Resizing "+(old==null ? "null" : ""+old.length)+" to "+size3);
476
477 if(size<1){return;}
478
479 size=0;
480 for(int i=0; i<oldKeys.length; i++){
481 int key=oldKeys[i];
482 if(key!=invalid){
483 put(key, oldValues[i]);
484 }
485 }
486 // assert(verify()); //123
487 }
488
489 /*--------------------------------------------------------------*/
490 /*---------------- Getters ----------------*/
491 /*--------------------------------------------------------------*/
492
493 public int[] keys() {return keys;}
494
495 public long[] values() {return values;}
496
497 public int invalid() {return invalid;}
498
499 /*--------------------------------------------------------------*/
500 /*---------------- Fields ----------------*/
501 /*--------------------------------------------------------------*/
502
503 private int[] keys;
504 private long[] values;
505 private int size=0;
506 /** Value for empty cells */
507 private int invalid;
508 private int modulus;
509 private int sizeLimit;
510 private final float loadFactor;
511
512 private static final Random randy=new Random(1);
513 private static final int MASK=Integer.MAX_VALUE;
514 private static final int MINMASK=Integer.MIN_VALUE;
515
516 private static final int extra=10;
517
518 }