algorithm: add autoBisect
This commit is contained in:
@@ -23,3 +23,29 @@ export function binSearch(begin: number, end: number, beforeHalf: boolean[]): [n
|
|||||||
|
|
||||||
return [begin, half, end];
|
return [begin, half, end];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function autoBisect(
|
||||||
|
begin: number,
|
||||||
|
end: number,
|
||||||
|
check: (
|
||||||
|
begin: number,
|
||||||
|
end: number,
|
||||||
|
index: number
|
||||||
|
) => Promise<boolean>) {
|
||||||
|
|
||||||
|
// Try to find the first index where check() predicates to true.
|
||||||
|
// Assume check() is true at first, for range [begin, end)
|
||||||
|
let index = 0;
|
||||||
|
while (end - begin > 1) {
|
||||||
|
const mid = Math.floor((end - begin) / 2) + begin;
|
||||||
|
if (await check(begin, mid, index)) {
|
||||||
|
// Shrink half range.
|
||||||
|
end = mid;
|
||||||
|
} else {
|
||||||
|
begin = mid;
|
||||||
|
}
|
||||||
|
index++;
|
||||||
|
}
|
||||||
|
|
||||||
|
return begin;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user