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