@param ― order - Total ordering over the elements.
@param ― items - Optional initial elements, in iteration order.
maxBinaryHeap,
constnumberOrder:Order<number>
A total order on number.
NaN is totally ordered as greater than every other number and equal
only to itself; 0 equals -0. Making the order total, rather than
returning 0 for every NaN comparison the way </> do, is what lets
heaps containing NaN keep a coherent invariant: with the partial rule,
NaN would compare equal to both 1 and 3 while 1 < 3, and a sift
could strand a smaller number behind it. NaN therefore drains last
from a min heap and first from a max heap.
Under this order -Infinity is the least element and NaN the greatest,
so the full chain reads -Infinity < -0 = 0 < 1 < Infinity < NaN.
numberOrder } from'knotkit/heap'
// Each candidate reaches some users; pick the two that reach the most users together.
const
constaudiences:string[][]
audiences= [
['ada', 'grace', 'alan'],
['grace', 'alan'],
['edsger', 'barbara'],
['ada', 'edsger'],
]
const
constreached:Set<string>
reached=new
var Set:SetConstructor
new <string>(iterable?:Iterable<string> |null|undefined) =>Set<string> (+1 overload)
Returns the elements of an array that meet the condition specified in a callback function.
@param ― predicate A function that accepts up to three arguments. The filter method calls the predicate function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the predicate function. If thisArg is omitted, undefined is used as the this value.
filter((
user: string
user) =>!
constreached:Set<string>
reached.
Set<string>.has(value: string): boolean
@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.
has(
user: string
user)).
Array<string>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length
interface
interfaceCandidate
Candidate {
readonly
Candidate.index: number
index:number
/** The gain when last computed: an upper bound, because gains only shrink as the set grows. */
readonly
Candidate.gain: number
The gain when last computed: an upper bound, because gains only shrink as the set grows.
NaN is totally ordered as greater than every other number and equal
only to itself; 0 equals -0. Making the order total, rather than
returning 0 for every NaN comparison the way </> do, is what lets
heaps containing NaN keep a coherent invariant: with the partial rule,
NaN would compare equal to both 1 and 3 while 1 < 3, and a sift
could strand a smaller number behind it. NaN therefore drains last
from a min heap and first from a max heap.
Under this order -Infinity is the least element and NaN the greatest,
so the full chain reads -Infinity < -0 = 0 < 1 < Infinity < NaN.
numberOrder, (
candidate: Candidate
candidate:
interfaceCandidate
Candidate) =>
candidate: Candidate
candidate.
Candidate.gain: number
The gain when last computed: an upper bound, because gains only shrink as the set grows.
gain)
const
constfrontier:BinaryHeap<{
index:number;
gain:number;
}>
frontier=
maxBinaryHeap<{
index:number;
gain:number;
}>(order:Order<{
index:number;
gain:number;
}>, items?:Iterable<{
index:number;
gain:number;
}> |undefined):BinaryHeap<{
index:number;
gain:number;
}>
Create a max binary heap: the largest element per order is at the root,
and pop extracts in descending order.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map((
_: string[]
_,
index: number
index) => ({
index: number
index,
gain: number
gain:
constgainOf: (index:number) =>number
gainOf(
index: number
index) })),
)
const
constpicks:number[]
picks:number[] = []
while (
constpicks:number[]
picks.
Array<T>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
@param ― order - Total ordering over the elements.
@param ― items - Optional initial elements, in iteration order.
maxBinaryHeap,
constnumberOrder:Order<number>
A total order on number.
NaN is totally ordered as greater than every other number and equal
only to itself; 0 equals -0. Making the order total, rather than
returning 0 for every NaN comparison the way </> do, is what lets
heaps containing NaN keep a coherent invariant: with the partial rule,
NaN would compare equal to both 1 and 3 while 1 < 3, and a sift
could strand a smaller number behind it. NaN therefore drains last
from a min heap and first from a max heap.
Under this order -Infinity is the least element and NaN the greatest,
so the full chain reads -Infinity < -0 = 0 < 1 < Infinity < NaN.
numberOrder } from'knotkit/heap'
import {
functionsplitmix32(seed:number): () =>number
Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by 0x9e3779b9. This constant equals
floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo
2^32. Because the increment is odd, it is coprime to 2^32. The resulting
Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from
the
search
for low avalanche bias. Its XOR-shifts and multiplications by odd integers
are invertible over 32-bit values. The mixer therefore preserves the full
period while diffusing nearby states across the output bits.
Math.imul and the bitwise operators keep the mixing steps in 32-bit
arithmetic. The final unsigned conversion produces an integer from 0 to
2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).
The SplitMix family was introduced by Steele, Lea, and Flood in
Draw an integer uniformly from 0..upperExclusive - 1.
Multiplying a source value by 2^32 produces one unsigned 32-bit draw. When
the requested range does not divide 2^32 evenly, a direct remainder would
make its lowest outcomes slightly more likely. Rejection sampling discards
the incomplete high end of the 32-bit range before taking the remainder, so
every returned integer has exactly the same number of source draws mapping
to it.
The source can be seeded or otherwise injected by the caller. Each value is
validated at the point it is consumed because a stateful source can become
invalid after earlier valid draws.
Consumes one source draw in the common case. The rejection region is always
smaller than upperExclusive, so fewer than half of all draws are rejected
and the expected number of draws is below two.
@param ― random - Function returning values in [0, 1).
@param ― upperExclusive - Exclusive upper bound, from 1 through 2^32.
@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is
not an integer in 1..2^32, or INVALID_SOURCE_VALUE when the source
returns a value outside [0, 1).
uniformInt } from'knotkit/prng'
const
constrandom: () =>number
random=
functionsplitmix32(seed:number): () =>number
Creates a deterministic 32-bit pseudorandom number generator.
Each call advances a private state by 0x9e3779b9. This constant equals
floor(2^32 / phi), where phi is the golden ratio. Addition wraps modulo
2^32. Because the increment is odd, it is coprime to 2^32. The resulting
Weyl sequence visits every 32-bit state once before it repeats.
The mixing function uses the constants 0x21f0aaad and 0x735a2d97 from
the
search
for low avalanche bias. Its XOR-shifts and multiplications by odd integers
are invertible over 32-bit values. The mixer therefore preserves the full
period while diffusing nearby states across the output bits.
Math.imul and the bitwise operators keep the mixing steps in 32-bit
arithmetic. The final unsigned conversion produces an integer from 0 to
2^32 - 1. Dividing by 2^32 maps that integer to [0, 1).
The SplitMix family was introduced by Steele, Lea, and Flood in
Draw an integer uniformly from 0..upperExclusive - 1.
Multiplying a source value by 2^32 produces one unsigned 32-bit draw. When
the requested range does not divide 2^32 evenly, a direct remainder would
make its lowest outcomes slightly more likely. Rejection sampling discards
the incomplete high end of the 32-bit range before taking the remainder, so
every returned integer has exactly the same number of source draws mapping
to it.
The source can be seeded or otherwise injected by the caller. Each value is
validated at the point it is consumed because a stateful source can become
invalid after earlier valid draws.
Consumes one source draw in the common case. The rejection region is always
smaller than upperExclusive, so fewer than half of all draws are rejected
and the expected number of draws is below two.
@param ― random - Function returning values in [0, 1).
@param ― upperExclusive - Exclusive upper bound, from 1 through 2^32.
@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is
not an integer in 1..2^32, or INVALID_SOURCE_VALUE when the source
returns a value outside [0, 1).
uniformInt(
constrandom: () =>number
random, 60)
returnnew
var Set:SetConstructor
new <number>(iterable?:Iterable<number> |null|undefined) =>Set<number> (+1 overload)
Draw an integer uniformly from 0..upperExclusive - 1.
Multiplying a source value by 2^32 produces one unsigned 32-bit draw. When
the requested range does not divide 2^32 evenly, a direct remainder would
make its lowest outcomes slightly more likely. Rejection sampling discards
the incomplete high end of the 32-bit range before taking the remainder, so
every returned integer has exactly the same number of source draws mapping
to it.
The source can be seeded or otherwise injected by the caller. Each value is
validated at the point it is consumed because a stateful source can become
invalid after earlier valid draws.
Consumes one source draw in the common case. The rejection region is always
smaller than upperExclusive, so fewer than half of all draws are rejected
and the expected number of draws is below two.
@param ― random - Function returning values in [0, 1).
@param ― upperExclusive - Exclusive upper bound, from 1 through 2^32.
@throws ― {PrngInvalidInputError} With code INVALID_BOUND when the bound is
not an integer in 1..2^32, or INVALID_SOURCE_VALUE when the source
returns a value outside [0, 1).
uniformInt(
constrandom: () =>number
random, 2_000)))
})
const
constreached:Set<number>
reached=new
var Set:SetConstructor
new <number>(iterable?:Iterable<number> |null|undefined) =>Set<number> (+1 overload)
Set<number>()
let
let evaluations:number
evaluations=0
const
constgainOf: (index:number) =>number
gainOf= (
index: number
index:number):number=> {
let evaluations:number
evaluations+=1
let
let gain:number
gain=0
for (const
constuser:number
userof
constaudiences:Set<number>[]
audiences[
index: number
index] ?? []) {
if (!
constreached:Set<number>
reached.
Set<number>.has(value: number): boolean
@returns ― a boolean indicating whether an element with the specified value exists in the Set or not.
has(
constuser:number
user)) {
let gain:number
gain+=1
}
}
return
let gain:number
gain
}
interface
interfaceCandidate
Candidate {
readonly
Candidate.index: number
index:number
/** The gain when last computed: an upper bound, because gains only shrink as the set grows. */
readonly
Candidate.gain: number
The gain when last computed: an upper bound, because gains only shrink as the set grows.
NaN is totally ordered as greater than every other number and equal
only to itself; 0 equals -0. Making the order total, rather than
returning 0 for every NaN comparison the way </> do, is what lets
heaps containing NaN keep a coherent invariant: with the partial rule,
NaN would compare equal to both 1 and 3 while 1 < 3, and a sift
could strand a smaller number behind it. NaN therefore drains last
from a min heap and first from a max heap.
Under this order -Infinity is the least element and NaN the greatest,
so the full chain reads -Infinity < -0 = 0 < 1 < Infinity < NaN.
numberOrder, (
candidate: Candidate
candidate:
interfaceCandidate
Candidate) =>
candidate: Candidate
candidate.
Candidate.gain: number
The gain when last computed: an upper bound, because gains only shrink as the set grows.
gain)
const
constfrontier:BinaryHeap<{
index:number;
gain:number;
}>
frontier=
maxBinaryHeap<{
index:number;
gain:number;
}>(order:Order<{
index:number;
gain:number;
}>, items?:Iterable<{
index:number;
gain:number;
}> |undefined):BinaryHeap<{
index:number;
gain:number;
}>
Create a max binary heap: the largest element per order is at the root,
and pop extracts in descending order.
Calls a defined callback function on each element of an array, and returns an array that contains the results.
@param ― callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array.
@param ― thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value.
map((
_: Set<number>
_,
index: number
index) => ({
index: number
index,
gain: number
gain:
constgainOf: (index:number) =>number
gainOf(
index: number
index) })),
)
const
constpicks:number[]
picks:number[] = []
while (
constpicks:number[]
picks.
Array<number>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
Remove and return the extreme element — the minimum for min kinds, the
maximum for max kinds, under the factory order. O(log n).
Property syntax for the same variance reason as
push
.
@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.
pop()
constpicks:number[]
picks.
Array<number>.push(...items: number[]): number
Appends new elements to the end of an array, and returns the new length of the array.
@param ― items New elements to add to the array.
push(
consttop: {
index:number;
gain:number;
}
top.
index: number
index)
for (const
constuser:number
userof
constaudiences:Set<number>[]
audiences[
consttop: {
index:number;
gain:number;
}
top.
index: number
index] ?? []) {
constreached:Set<number>
reached.
Set<number>.add(value: number): Set<number>
Appends a new element with a specified value to the end of the Set.
add(
constuser:number
user)
}
}
constpicks:number[]
picks.
Array<number>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length// 20
constreached:Set<number>
reached.
Set<number>.size: number
@returns ― the number of (unique) elements in Set.
size// 999
let evaluations:number
evaluations-
constaudiences:Set<number>[]
audiences.
Array<Set<number>>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length// 2853, after seeding the heap
constk:20
k*
constaudiences:Set<number>[]
audiences.
Array<Set<number>>.length: number
Gets or sets the length of the array. This is a number one higher than the highest index in the array.
length// 100000, re-scoring every candidate for every pick
Gains only shrink as the selection grows, so a stale gain is an upper bound: when the refreshed top still beats every other bound, it is the greedy choice without evaluating the rest. The algorithm page explains the guarantee and the measured savings.