Untitled
unknown
javascript
4 years ago
794 B
14
Indexable
function attempts(eggs, floors) {
if (eggs == 1) {
return floors;
}
if (floors == 1) {
return 1;
}
let floorsLeft = Math.floor(floors / 2);
return 1 + attempts(eggs - 1, floorsLeft);
}
function attemptsUsingMath(eggs, floors) {
let eggsForBinarySearch = Math.log2(floors);
if (eggs > eggsForBinarySearch) {
return Math.ceil(eggsForBinarySearch);
}
if (eggsForBinarySearch > eggs) {
let attemptsForBinarySearch = eggs - 1;
let partsAfterBinarySearch = 2 ** attemptsForBinarySearch;
let floorsPerPartAfterBinarySearch = Math.ceil(floors / partsAfterBinarySearch);
let attemptsForLastPart = floorsPerPartAfterBinarySearch - 1;
return attemptsForLastPart + attemptsForBinarySearch;
}
}Editor is loading...