Last active
November 21, 2021 09:42
-
-
Save burdiuz/926adea5176e31eda9079dd4948337df to your computer and use it in GitHub Desktop.
Adjacency matrix implemented using UInt8Array -- every bit represents an edge
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getPosition = (rowLength) => (col, row) => row * rowLength + col; | |
const getSlotIndex = (rowLength) => { | |
const pos = getPosition(rowLength); | |
return (col, row) => pos(col, row) >> 3; | |
}; | |
const getInSlotPosition = (rowLength) => { | |
const pos = getPosition(rowLength); | |
return (col, row) => pos(col, row) % 8; | |
}; | |
const setBitAt = (slot, index, value) => { | |
const bit = 1 << (index - 1); | |
return value ? slot | bit : slot & (0xff ^ bit); | |
}; | |
const getSlotCount = (size) => (size >> 3) + 1; | |
const iterateOver = (bam, callback) => { | |
const { list, size } = bam; | |
const { length } = list; | |
const slotsPerRow = getSlotCount(size); | |
let row = 0; | |
let col = 0; | |
for (let index = 0; index < length; index++) { | |
const slot = list[index]; | |
//const col = (index % slotsPerRow) << 3; | |
for (let pos = 0; pos < 8; pos++) { | |
callback((slot >> pos) & 1, col + pos, row, bam); | |
col++; | |
} | |
if (col >= size) { | |
row++; | |
col = 0; | |
index = slotsPerRow * row - 1; | |
} | |
} | |
}; | |
class BitAdjacencyMatrix { | |
constructor(size) { | |
this.size = size; | |
const rowLength = getSlotCount(size); | |
this.list = new Uint8Array(Math.ceil(rowLength ** 2 / 8)); | |
this.getPosition = getPosition(rowLength); | |
this.getSlotIndex = getSlotIndex(rowLength); | |
this.getInSlotPosition = getInSlotPosition(rowLength); | |
} | |
get(col, row) { | |
const slot = this.list[this.getSlotIndex(col, row)]; | |
const prevPos = this.getInSlotPosition(col, row) - 1; | |
return (slot >> prevPos) & 1; | |
} | |
set(col, row, value) { | |
const index = this.getSlotIndex(col, row); | |
const pos = this.getInSlotPosition(col, row); | |
const slot = this.list[index]; | |
this.list[index] = setBitAt(slot, pos, value); | |
} | |
getSlot(index) { | |
return this.list[index]; | |
} | |
setSlot(index, value) { | |
this.list[index] = value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment