class BinarySearchOnAnswer {
static smallestNumberSatisfyingCondition(low: number, high: number, condition: (x: number) => boolean): number {
while (low < high) {
const mid = Math.floor((low + high) / 2);
if (condition(mid)) {
high = mid; // try smaller or equal values
} else {
low = mid + 1; // increase low to discard mid
}
}
return low;
}
}
// Driver code
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const condition = (x: number) => x * x >= 20;
const result = BinarySearchOnAnswer.smallestNumberSatisfyingCondition(1, 9, condition);
console.log(result + "");loop until search space narrows to one value
const mid = Math.floor((low + high) / 2);
calculate middle guess
check if mid satisfies condition
high = mid; // try smaller or equal values
narrow search to left half including mid
discard mid and left half, search right half
return smallest value satisfying condition