Debian Codegraph @

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