website/content.en/ChapterFour/0400~0499/0458.Poor-Pigs.md
There are buckets buckets of liquid, where exactly one of the buckets is poisonous. To figure out which one is poisonous, you feed some number of (poor) pigs the liquid to see whether they will die or not. Unfortunately, you only have minutesToTest minutes to determine which bucket is poisonous.
You can feed the pigs according to these steps:
Given buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to figure out which bucket is poisonous within the allotted time.
Example 1:
Input: buckets = 1000, minutesToDie = 15, minutesToTest = 60
Output: 5
Example 2:
Input: buckets = 4, minutesToDie = 15, minutesToTest = 15
Output: 2
Example 3:
Input: buckets = 4, minutesToDie = 15, minutesToTest = 30
Output: 2
Constraints:
There are buckets buckets of liquid, where exactly one bucket contains poison, and the rest contain water. They all look the same from the outside. To figure out which bucket contains poison, you can feed some pigs and determine it by observing whether the pigs die. Unfortunately, you only have minutesToTest minutes to determine which bucket of liquid is poisonous.
The rules for feeding pigs are as follows:
Given the number of buckets, buckets, minutesToDie, and minutesToTest, return the minimum number of pigs needed to determine which bucket is poisonous within the allotted time.
Use a mathematical method. Taking minutesToDie=15, minutesToTest=60, and 1 pig as an example, it can test 5 buckets.
So when minutesToDie and minutesToTest are fixed, one pig can determine at most base = minutesToTest / minutesToDie + 1 buckets
Assume the number of pigs is num, then pow(base, num) >= buckets. According to the rules of logarithms, taking logarithms on both sides gives: num >= Log10(buckets) / Log10(base)
package leetcode
import "math"
func poorPigs(buckets int, minutesToDie int, minutesToTest int) int {
base := minutesToTest/minutesToDie + 1
return int(math.Ceil(math.Log10(float64(buckets)) / math.Log10(float64(base))))
}