用js写个算法算出筐里最少有多少个鸡蛋?
function minEggsInBasket(brokenEggs, unbrokenEggs) {
/**
* Calculates the minimum number of eggs that could have been in a basket,
* given the number of broken and unbroken eggs.
*
* Args:
* brokenEggs: The number of broken eggs.
* unbrokenEggs: The number of unbroken eggs.
*
* Returns:
* The minimum number of eggs that could have been in the basket, or 0 if
* the input is invalid (e.g., negative numbers).
*/
if (brokenEggs < 0 || unbrokenEggs < 0) {
return 0; // Invalid input
}
return brokenEggs + unbrokenEggs;
}
// Example usage:
let broken = 5;
let unbroken = 7;
let minEggs = minEggsInBasket(broken, unbroken);
console.log("Minimum eggs in the basket:", minEggs); // Output: 12
broken = 0;
unbroken = 10;
minEggs = minEggsInBasket(broken, unbroken);
console.log("Minimum eggs in the basket:", minEggs); // Output: 10
broken = -2; // Invalid input
unbroken = 5;
minEggs = minEggsInBasket(broken, unbroken);
console.log("Minimum eggs in the basket:", minEggs); // Output: 0
// For more advanced scenarios (though not asked for in the question):
/**
* If you had a percentage of broken eggs and the total number of unbroken eggs,
* you could estimate the original total like this:
*/
function estimateOriginalTotal(brokenPercentage, unbrokenEggs) {
if (brokenPercentage < 0 || brokenPercentage > 1 || unbrokenEggs < 0) {
return 0; // Invalid input
}
if (brokenPercentage === 1) {
return Infinity; // Avoid division by zero if all eggs are broken. This signifies that there could have been infinitely many eggs.
}
return Math.round(unbrokenEggs / (1 - brokenPercentage));
}
let brokenPercent = 0.25; // 25% broken
let unbrokenCount = 75;
let estimatedTotal = estimateOriginalTotal(brokenPercent, unbrokenCount);
console.log("Estimated original total:", estimatedTotal); // Output: 100
brokenPercent = 1; // 100% broken
estimatedTotal = estimateOriginalTotal(brokenPercent, unbrokenCount);
console.log("Estimated original total:", estimatedTotal); // Output: Infinity
This code provides both the direct calculation of the minimum number of eggs (which is simply the sum of broken and unbroken eggs) and also a function to estimate the original total if you have a percentage of broken eggs and the count of unbroken eggs. The second function handles edge cases like invalid input and the scenario where all eggs are broken (resulting in an infinite possible original total).