All files / hashes LinearHashing.js

0% Statements 0/244
0% Branches 0/53
0% Functions 0/22
0% Lines 0/233

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
import HashStructure from '@/algorithms/hashes/HashStructure';
import Color from '@/utils/Color';
import Action from '../../components/hashes/HashTableVerticalActions';
 
/**
 * Bucket. The object to hold the actual values.
 * @constructor
 */
function Bucket() {
  /**
   * The binary address of the bucket.
   * Only used for visualization.
   * @type {string}
   */
  this.index = undefined;
 
  /**
   * An array to store the values of this bucket.
   * @type {number[]}
   */
  this.values = [];
 
  /**
   * A nested Bucket object that holds the overflowing values.
   * @type {Bucket}
   */
  this.overflow = undefined;
}
 
function countOverflowBuckets(bucket) {
  if (!bucket.overflow) {
    return 0;
  }
  return 1 + countOverflowBuckets(bucket.overflow);
}
 
function getSpecificOverflowBucket(bucket, position) {
  if (position < 0) {
    return null;
  }
 
  let currentBucket = bucket;
  for (let i = 0; i < position; i += 1) {
    if (!currentBucket.overflow) {
      return null;
    }
    currentBucket = currentBucket.overflow;
  }
 
  return currentBucket;
}
 
/**
 * LinearHashing
 */
export default class LinearHashing extends HashStructure {
  /**
   * An array of Bucket objects to hold the values.
   * @type {Bucket[]}
   */
  buckets = [];
 
  /**
   * Initially addressable number of Buckets (in bits).
   * @type {number}
   */
  roundNumber = 1;
 
  /**
   * Bucket Size
   * @type {number}
   */
  MAX_BUCKET_SIZE;
 
  /**
   * Next To Split.
   * @type {number}
   */
  nextToSplit = 0;
 
  /**
   * Initialize an empty hash table.
   * @param {number} bucketSize
   */
 
  init(bucketSize) {
    const steps = [];
    this.buckets = [];
    this.MAX_BUCKET_SIZE = bucketSize;
    this.nextToSplit = 0;
 
    // fill the buckets array with as many buckets as should be initially addressable.
    for (let i = 0; i < 2 ** this.roundNumber; i += 1) {
      const bucket = new Bucket();
      // convert i to binary, only use the roundNumber rightmost bits
      bucket.index = i.toString(2)
        .slice(-Math.abs(this.roundNumber));
      this.buckets.push(bucket);
    }
    this.visualizeCreateTable(steps);
    this.visualizeUpdateInfoBoxes(steps, `Table initialized with bucket size: ${this.MAX_BUCKET_SIZE}`);
    return steps;
  }
 
  /**
   * The hash function is dependent on the length of the address space in bits (roundNumber).
   * @param {number} value
   */
  hash(value, steps) {
    // convert value to binary, only use the roundNumber rightmost bits
    let addressBinary = value.toString(2)
      .slice(-Math.abs(this.roundNumber));
    let addressDecimal = parseInt(addressBinary, 2);
 
    if (addressDecimal < this.nextToSplit) {
      // convert value to binary, only use the roundNumber-1 rightmost bits
      addressBinary = value.toString(2)
        .slice(-Math.abs(this.roundNumber + 1));
      addressDecimal = parseInt(addressBinary, 2);
    }
    this.visualizeHashCalculation(steps, value, addressBinary);
    return addressDecimal;
  }
 
  /**
   * Insert the given value into the hash table.
   * @param value
   */
  insert(value) {
    const steps = [];
    if (this.buckets.length === 0) {
      // Table not created
      return;
    }
 
    this.visualizeUpdateInfoBoxes(steps, `Inserting Value: ${value}`);
    // Calculate the address of the block where value should go
    let addressDecimal = this.hash(value, steps);
 
    if (this.buckets[addressDecimal].values.length < this.MAX_BUCKET_SIZE) {
      // free space in the designated bucket, put the value there, done.
      this.buckets[addressDecimal].values.push(value);
      this.addHighlightCalculatedCell(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal), Color.HASH_INSERT_SEARCH_COMPLETED);
      this.visualizeSimpleInsert(steps, addressDecimal);
      this.clearHighlighting(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal));
      return steps;
    }
    // designated bucket is full.
 
    // descend down in last overflow block
    // iterate over all overflow buckets until the last one is reached
    let currentBucket = this.buckets[addressDecimal];
    while (currentBucket.overflow !== undefined) {
      currentBucket = currentBucket.overflow;
    }
 
    if (currentBucket.values.length < this.MAX_BUCKET_SIZE) {
      // free space in current overflowing Bucket, put the value there, done.
      currentBucket.values.push(value);
      this.addHighlightCalculatedCell(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal), Color.HASH_INSERT_SEARCH_COMPLETED);
      this.visualizeSimpleInsert(steps, addressDecimal);
      this.clearHighlighting(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal));
      return steps;
    }
    // No overflow bucket or not enough space in the overflowing currentBucket, split.
    this.addHighlightCalculatedCell(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal), Color.HASH_COLLISION);
    this.visualizeUpdateInfoBoxes(steps, 'Bucket is overflowing, splitting on index next to split');
 
    const newOverflow = new Bucket();
    currentBucket.overflow = newOverflow;
    this.visualizeAddOverflowBucket(steps, addressDecimal);
    this.clearHighlighting(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal));
    newOverflow.values.push(value);
    this.addHighlightCalculatedCell(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal), Color.HASH_INSERT_SEARCH_COMPLETED);
    this.visualizeSimpleInsert(steps, addressDecimal);
    this.clearHighlighting(steps, addressDecimal, this.getLastPositionOfBucketValue(addressDecimal));
 
    const OLD_INDEXES = [];
    for (let i = 0; i < this.buckets.length; i += 1) {
      OLD_INDEXES.push(this.buckets[i].index);
    }
    // add new Bucket at the end and update vars
    currentBucket = this.buckets[this.nextToSplit];
    const newBucket = new Bucket();
    newBucket.index = `1${currentBucket.index}`;
    this.buckets.push(newBucket);
 
    // get all values from act row+overflows
    const vals = [];
    while (currentBucket !== undefined) {
      for (let i = 0; i < currentBucket.values.length; i += 1) {
        vals.push(currentBucket.values[i]);
      }
      currentBucket = currentBucket.overflow;
    }
 
    // delete all values overflows of act row
    currentBucket = this.buckets[this.nextToSplit];
    currentBucket.index = `0${currentBucket.index}`;
    this.visualizeAddBucket(steps, OLD_INDEXES);
    currentBucket.values = [];
    currentBucket.overflow = undefined;
    this.visualizeRemoveValuesOfBucketAndOverflow(steps, this.nextToSplit, vals);
 
    // roundNumber wird erhöht, wenn splitting für ursprünglichen Primärbereich einmal durchgeführt wurde:
    const previousRoundNumber = this.roundNumber;
    const previousNextToSplit = this.nextToSplit;
    this.nextToSplit += 1;
    if (this.nextToSplit === 2 ** this.roundNumber) {
      this.roundNumber += 1;
      this.nextToSplit = 0;
      this.visualizeUpdateInfoBoxes(steps, 'next to split is equals to 2 to the power of round number; increment round number reset next to split',
        previousRoundNumber, previousNextToSplit);
    } else {
      this.visualizeUpdateInfoBoxes(steps, 'next to split is smaller than 2 to the power of round number; increment next to split',
        previousRoundNumber, previousNextToSplit);
    }
 
    // redistribute
    for (let i = 0; i < vals.length; i += 1) {
      // Calculate the address/bucket/block where value should go
      addressDecimal = this.hash(vals[i], steps);
 
      // descend down in last overflow block
      currentBucket = this.buckets[addressDecimal];
      while (currentBucket.overflow !== undefined) {
        currentBucket = currentBucket.overflow;
      }
 
      if (currentBucket.values.length < this.MAX_BUCKET_SIZE) {
        currentBucket.values.push(vals[i]);
        this.visualizeSimpleInsert(steps, addressDecimal);
      } else {
        // overflow again?
        const overflowBlock = new Bucket();
        this.visualizeAddOverflowBucket(steps, addressDecimal);
        overflowBlock.values.push(vals[i]);
        currentBucket.overflow = overflowBlock;
        this.visualizeSimpleInsert(steps, addressDecimal);
      }
    }
    return steps;
  }
 
  remove(value) {
    const steps = [];
    if (this.buckets.length === 0) {
      return steps;
    }
 
    const addressDecimal = this.hash(value, steps);
 
    let currentBucket = this.buckets[addressDecimal];
    let previousBucket;
    const oldValues = this.getAllValuesOfBucketAndOverflow(addressDecimal);
 
    let found = false;
    let index = 0;
    let totalIndex = 0;
 
    while (!found) {
      for (let i = 0; i < this.MAX_BUCKET_SIZE; i += 1) {
        if (currentBucket.values[i] === value) {
          found = true;
          index = i;
          this.addHighlightCalculatedCell(steps, addressDecimal, totalIndex, Color.HASH_INSERT_SEARCH_COMPLETED);
          break;
        } else if (currentBucket.values[i] === undefined) {
          break;
        }
        this.addHighlightCalculatedCell(steps, addressDecimal, totalIndex, Color.HASH_COLLISION);
        this.clearHighlighting(steps, addressDecimal, totalIndex);
        totalIndex += 1;
      }
      if (!found) {
        previousBucket = currentBucket;
        currentBucket = currentBucket.overflow;
      }
      if (currentBucket === undefined) {
        // reached last overflow block, value not found.
        this.visualizeUpdateInfoBoxes(steps, `Tried to remove Value: ${value} but was not found`);
        return steps;
      }
    }
 
    // remove value
    this.visualizeRemove(steps, addressDecimal, totalIndex);
    this.visualizeUpdateInfoBoxes(steps, `Value: ${value} successfully removed`);
    currentBucket.values.splice(index, 1);
    this.clearHighlighting(steps, addressDecimal, totalIndex);
 
    // move all values to the left
    let { overflow } = currentBucket;
    if (overflow === undefined && currentBucket.values.length < 1 && previousBucket !== undefined) {
      previousBucket.overflow = undefined;
      this.visualizeRemoveOverflowBucket(steps, addressDecimal);
      return steps;
    }
 
    let removingLastOverflow = false;
 
    while (overflow !== undefined) {
      currentBucket.values.push(overflow.values[0]);
      overflow.values.splice(0, 1);
 
      // overflow now empty:
      if (overflow.values.length < 1) {
        if (overflow.overflow === undefined) {
          currentBucket.overflow = undefined;
          removingLastOverflow = true;
        } else {
          currentBucket.overflow = overflow.overflow;
        }
      }
      currentBucket = overflow;
      overflow = currentBucket.overflow;
    }
    this.visualizeUpdateValuesOfRow(steps, addressDecimal, oldValues);
    if (removingLastOverflow) this.visualizeRemoveOverflowBucket(steps, addressDecimal);
    return steps;
  }
 
  /**
   * Search for the given value in the hash table.
   * @param value
   */
  search(value) {
    const steps = [];
    if (this.buckets.length === 0) {
      return steps;
    }
 
    const addressDecimal = this.hash(value, steps);
 
    let currentBucket = this.buckets[addressDecimal];
 
    let found = false;
    let index = 0;
    let totalIndex = 0;
 
    while (!found) {
      for (let i = 0; i < this.MAX_BUCKET_SIZE; i += 1) {
        if (currentBucket.values[i] === value) {
          found = true;
          index = i;
          this.addHighlightCalculatedCell(steps, addressDecimal, totalIndex, Color.HASH_INSERT_SEARCH_COMPLETED);
          this.visualizeUpdateInfoBoxes(steps, `Value: ${value} was successfully found`);
          break;
        } else if (currentBucket.values[i] === undefined) {
          break;
        }
        this.addHighlightCalculatedCell(steps, addressDecimal, totalIndex, Color.HASH_COLLISION);
        this.clearHighlighting(steps, addressDecimal, totalIndex);
        totalIndex += 1;
      }
      if (!found) {
        currentBucket = currentBucket.overflow;
      }
      if (currentBucket === undefined) {
        this.visualizeUpdateInfoBoxes(steps, `Tried to find Value: ${value} but was not found`);
        break;
      }
    }
    this.clearHighlighting(steps, addressDecimal, totalIndex);
    return steps;
  }
 
  visualizeUpdateInfoBoxes(steps, text,
    previousRoundNumber = this.roundNumber, previousNextToSplit = this.nextToSplit) {
    steps.push({
      do: [{
        action: Action.UPDATE_INFO_BOX,
        roundNumber: this.roundNumber,
        nextToSplit: this.nextToSplit,
        bucketSize: this.MAX_BUCKET_SIZE,
        infoText: text,
      }],
      undo: [{
        action: Action.UPDATE_INFO_BOX,
        roundNumber: previousRoundNumber,
        nextToSplit: previousNextToSplit,
        bucketSize: this.MAX_BUCKET_SIZE,
        infoText: '',
      }],
    });
    return steps;
  }
 
  visualizeHashCalculation(steps, value, addressBinary) {
    const binaryValue = value.toString(2);
    steps.push({
      do: [{
        action: Action.SET_HASH_CALCULATION,
        value,
        binaryValue,
        addressBinary,
      }],
      undo: [{
        action: Action.SET_HASH_CALCULATION,
        value: null,
      }],
    });
    return steps;
  }
 
  visualizeRemoveValuesOfBucketAndOverflow(steps, bucketIndex, oldValues) {
    steps.push({
      do: [{
        action: Action.REMOVE_VALUES_OF_BUCKET_AND_OVERFLOW,
        row: bucketIndex,
      }],
      undo: [{
        action: Action.INSERT_VALUES_OF_BUCKET_AND_OVERFLOW,
        row: bucketIndex,
        values: oldValues,
      }],
    });
    return steps;
  }
 
  visualizeAddBucket(steps, oldIndexes) {
    const indexes = [];
    for (let i = 0; i < this.buckets.length; i += 1) {
      indexes.push(this.buckets[i].index);
    }
    steps.push({
      do: [
        {
          action: Action.ADD_BUCKETS,
          rows: 1,
          cols: this.MAX_BUCKET_SIZE,
        },
        {
          action: Action.SET_ROW_VALUE,
          bucketIndexes: indexes,
        },
      ],
      undo: [
        {
          action: Action.REMOVE_BUCKETS,
          rows: 1,
        },
        {
          action: Action.SET_ROW_VALUE,
          bucketIndexes: oldIndexes,
        },
      ],
    });
    return steps;
  }
 
  visualizeAddOverflowBucket(steps, bucketIndex) {
    steps.push({
      do: [{
        action: Action.ADD_OVERFLOW_BUCKET,
        row: bucketIndex,
        cols: this.MAX_BUCKET_SIZE,
      }],
      undo: [{
        action: Action.REMOVE_OVERFLOW_BUCKET,
        row: bucketIndex,
        cols: this.MAX_BUCKET_SIZE,
      }],
    });
    return steps;
  }
 
  visualizeRemoveOverflowBucket(steps, bucketIndex) {
    steps.push({
      do: [{
        action: Action.REMOVE_OVERFLOW_BUCKET,
        row: bucketIndex,
        cols: this.MAX_BUCKET_SIZE,
      }],
      undo: [{
        action: Action.ADD_OVERFLOW_BUCKET,
        row: bucketIndex,
        cols: this.MAX_BUCKET_SIZE,
      }],
    });
    return steps;
  }
 
  visualizeSimpleInsert(steps, bucketIndex) {
    let currentBucket = this.buckets[bucketIndex];
    let bucketNumber = currentBucket.values.length - 1;
 
    const amountOfOverflowBuckets = countOverflowBuckets(currentBucket);
    if (amountOfOverflowBuckets !== 0) {
      currentBucket = getSpecificOverflowBucket(currentBucket, amountOfOverflowBuckets);
      bucketNumber = this.getLastPositionOfBucketValue(bucketIndex);
    }
    steps.push({
      do: [{
        action: Action.INSERT_VALUE_AT_POS,
        row: bucketIndex,
        col: bucketNumber,
        value: currentBucket.values[currentBucket.values.length - 1],
      }],
      undo: [{
        action: Action.REMOVE_VALUE_AT_POS,
        row: bucketIndex,
        col: bucketNumber,
        value: null,
      }],
    });
    return steps;
  }
 
  visualizeUpdateValuesOfRow(steps, bucketIndex, oldValues) {
    steps.push({
      do: [{
        action: Action.UPDATE_VALUES_OF_ROW,
        row: bucketIndex,
        values: this.getAllValuesOfBucketAndOverflow(bucketIndex),
      }],
      undo: [{
        action: Action.INSERT_VALUES_OF_BUCKET_AND_OVERFLOW,
        row: bucketIndex,
        values: oldValues,
      }],
    });
    return steps;
  }
 
  visualizeRemove(steps, bucketIndex, bucketNumber) {
    const startBucket = this.buckets[bucketIndex];
    const overflowBucketNumber = Math.floor(bucketNumber / this.MAX_BUCKET_SIZE);
    const positionInOverflowBucket = bucketNumber % this.MAX_BUCKET_SIZE;
    steps.push({
      do: [{
        action: Action.REMOVE_VALUE_AT_POS,
        row: bucketIndex,
        col: bucketNumber,
        value: null,
      }],
      undo: [{
        action: Action.INSERT_VALUE_AT_POS,
        row: bucketIndex,
        col: bucketNumber,
        value: getSpecificOverflowBucket(startBucket, overflowBucketNumber).values[positionInOverflowBucket],
      }],
    });
    return steps;
  }
 
  clearHighlighting(steps, bucketIndex, bucketNumber) {
    steps.push({
      do: [{
        action: Action.SET_ROW_COLOR,
        row: bucketIndex,
        col: bucketNumber,
        color: Color.BASE_COLOR_HASH_TABLE,
      }],
      undo: [{
        action: Action.SET_ROW_COLOR,
        row: bucketIndex,
        col: bucketNumber,
        color: Color.BASE_COLOR_HASH_TABLE,
      }],
    });
    return steps;
  }
 
  addHighlightCalculatedCell(steps, bucketIndex, bucketNumber, color) {
    steps.push({
      do: [{
        action: Action.SET_ROW_COLOR,
        row: bucketIndex,
        col: bucketNumber,
        color,
      }],
      undo: [{
        action: Action.SET_ROW_COLOR,
        row: bucketIndex,
        col: bucketNumber,
        color: Color.BASE_COLOR_HASH_TABLE,
      }],
    });
    return steps;
  }
 
  // visualize the updated values in the infoBoxes (N, K, HashCalculation, FillRate)
  visualizeCreateTable(steps) {
    const indexes = [];
    for (let i = 0; i < this.buckets.length; i += 1) {
      indexes.push(this.buckets[i].index);
    }
    steps.push({
      do: [
        {
          action: Action.CREATE_LIST,
          rows: this.buckets.length,
          cols: this.MAX_BUCKET_SIZE,
        },
        {
          action: Action.SET_ROW_VALUE,
          bucketIndexes: indexes,
        },
      ],
      undo: [
        {
          action: Action.DELETE_LIST,
        },
        {
          action: Action.SET_ROW_VALUE,
          bucketIndexes: [],
        },
      ],
    });
    return steps;
  }
 
  getLastPositionOfBucketValue(bucketIndex) {
    const currentBucket = this.buckets[bucketIndex];
    const amountOfOverflowBuckets = countOverflowBuckets(currentBucket);
    return this.MAX_BUCKET_SIZE * amountOfOverflowBuckets
      + getSpecificOverflowBucket(currentBucket, amountOfOverflowBuckets).values.length - 1;
  }
 
  getAllValuesOfBucketAndOverflow(bucketIndex) {
    let currentBucket = this.buckets[bucketIndex];
    const values = [];
    while (currentBucket !== undefined) {
      for (let i = 0; i < currentBucket.values.length; i += 1) {
        values.push(currentBucket.values[i]);
      }
      currentBucket = currentBucket.overflow;
    }
    return values;
  }
}