Debian Codegraph @

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