Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: indices stack overflow #3

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 21 additions & 15 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,28 +173,34 @@ export function doubleHashing (n: number, hashA: number, hashB: number, size: nu
* @param seed - The seed used
* @return A array of indexes
* @author Arnaud Grall
* @author Simon Woolf (SimonWoolf)
*/
export function getDistinctIndices (element: HashableInput, size: number, number: number, seed?: number): Array<number> {
if (seed === undefined) {
seed = getDefaultSeed()
}
function getDistinctIndicesBis (n: number, elem: HashableInput, size: number, count: number, indexes: Array<number> = []): Array<number> {
if (indexes.length === count) {
return indexes
} else {
const hashes = hashTwice(elem, true, seed! + size % n)
const ind = doubleHashing(n, hashes.first, hashes.second, size)
if (indexes.includes(ind)) {
// console.log('generate index: %d for %s', ind, elem)
return getDistinctIndicesBis(n + 1, elem, size, count, indexes)
} else {
// console.log('already found: %d for %s', ind, elem)
indexes.push(ind)
return getDistinctIndicesBis(n + 1, elem, size, count, indexes)
}

const indexes = new Set<number>()
let n = 0
let hashes = hashTwice(element, true, seed)

while (indexes.size < number) {
const ind = hashes.first % size
if (!indexes.has(ind)) {
indexes.add(ind)
}

hashes.first = (hashes.first + hashes.second) % size
hashes.second = (hashes.second + n) % size
n++

if (n > size) {
seed++
hashes = hashTwice(element, true, seed)
}
}
return getDistinctIndicesBis(1, element, size, number)

return [...indexes.values()]
}

/**
Expand Down