Skip to content

Pick the k items that cover the most

Lazy greedy keeps every candidate in a max heap keyed by its last known gain and re-evaluates only the top.

import {
function mapInputOrder<A, B>(order: Order<A>, f: (b: B) => A): Order<B>

Derive an Order<B> from an Order<A> by mapping each B to an A with f before comparing.

@example

const byAge = mapInputOrder(numberOrder, (user: { age: number }) => user.age)

mapInputOrder
,
function maxBinaryHeap<A>(order: Order<A>, items?: Iterable<A>): BinaryHeap<A>

Create a max binary heap: the largest element per order is at the root, and pop extracts in descending order.

@example

const heap = maxBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 50

@param ― order - Total ordering over the elements.

@param ― items - Optional initial elements, in iteration order.

maxBinaryHeap
,
const numberOrder: 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
const audiences: string[][]
audiences
= [
['ada', 'grace', 'alan'],
['grace', 'alan'],
['edsger', 'barbara'],
['ada', 'edsger'],
]
const
const reached: Set<string>
reached
= new
var Set: SetConstructor
new <string>(iterable?: Iterable<string> | null | undefined) => Set<string> (+1 overload)
Set
<string>()
const
const gainOf: (index: number) => number
gainOf
= (
index: number
index
: number): number => (
const audiences: string[][]
audiences
[
index: number
index
] ?? []).
Array<string>.filter(predicate: (value: string, index: number, array: string[]) => unknown, thisArg?: any): 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
) => !
const reached: 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
interface Candidate
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.

gain
: number
}
const
const byGain: Order<Candidate>
byGain
=
mapInputOrder<number, Candidate>(order: Order<number>, f: (b: Candidate) => number): Order<Candidate>

Derive an Order<B> from an Order<A> by mapping each B to an A with f before comparing.

@example

const byAge = mapInputOrder(numberOrder, (user: { age: number }) => user.age)

mapInputOrder
(
const numberOrder: 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
, (
candidate: Candidate
candidate
:
interface Candidate
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
const frontier: 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.

@example

const heap = maxBinaryHeap(numberOrder, [30, 1, 50, 20])
heap.peek() // 50

@param ― order - Total ordering over the elements.

@param ― items - Optional initial elements, in iteration order.

maxBinaryHeap
(
const byGain: Order<Candidate>
byGain
,
const audiences: string[][]
audiences
.
Array<string[]>.map<{
index: number;
gain: number;
}>(callbackfn: (value: string[], index: number, array: string[][]) => {
index: number;
gain: number;
}, thisArg?: any): {
index: number;
gain: number;
}[]

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
:
const gainOf: (index: number) => number
gainOf
(
index: number
index
) })),
)
const
const picks: number[]
picks
: number[] = []
while (
const picks: 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.

length
< 2) {
const
const top: {
index: number;
gain: number;
}
top
=
const frontier: BinaryHeap<{
index: number;
gain: number;
}>
frontier
.
BinaryHeap<{ index: number; gain: number; }>.peek: () => {
index: number;
gain: number;
}

Return the extreme element without removing it. O(1).

Property syntax for the same variance reason as

push

.

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

peek
()
const
const fresh: number
fresh
=
const gainOf: (index: number) => number
gainOf
(
const top: {
index: number;
gain: number;
}
top
.
index: number
index
)
if (
const fresh: number
fresh
<
const top: {
index: number;
gain: number;
}
top
.
gain: number
gain
) {
const frontier: BinaryHeap<{
index: number;
gain: number;
}>
frontier
.
BinaryHeap<{ index: number; gain: number; }>.replaceRoot: (value: {
index: number;
gain: number;
}) => {
index: number;
gain: number;
}

Return the current root and replace it with the supplied value, preserving size. O(log n).

@throws ― {HeapInvalidInputError} With code EMPTY when the heap is empty.

replaceRoot
({ ...
const top: {
index: number;
gain: number;
}
top
,
gain: number
gain
:
const fresh: number
fresh
}) // stale bound: lower it and look again
continue
}
const frontier: BinaryHeap<{
index: number;
gain: number;
}>
frontier
.
BinaryHeap<{ index: number; gain: number; }>.pop: () => {
index: number;
gain: number;
}

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
()
const picks: 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
(
const top: {
index: number;
gain: number;
}
top
.
index: number
index
)
for (const
const user: string
user
of
const audiences: string[][]
audiences
[
const top: {
index: number;
gain: number;
}
top
.
index: number
index
] ?? []) {
const reached: Set<string>
reached
.
Set<string>.add(value: string): Set<string>

Appends a new element with a specified value to the end of the Set.

add
(
const user: string
user
)
}
}
const picks: number[]
picks
// [0, 2]
const reached: Set<string>
reached
.
Set<string>.size: number

@returns ― the number of (unique) elements in Set.

size
// 5

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.

Modules: knotkit/heap · API reference