Poor Pigs - Problem
๐ท The Poor Pigs Problem
You work in a laboratory where there are buckets buckets of liquid, and exactly one of them is poisonous. Your mission is to identify which bucket contains the poison using the minimum number of pigs possible.
The Testing Process:
- You have
minutesToTestminutes total to find the poisonous bucket - Each pig takes
minutesToDieminutes to die after consuming poison - You can feed multiple buckets to the same pig simultaneously
- You can feed the same bucket to multiple pigs
- After feeding, you must wait
minutesToDieminutes to see results - You can repeat this process until time runs out
Goal: Return the minimum number of pigs needed to guarantee finding the poisonous bucket within the time limit.
Example: With 1000 buckets, 15 minutes to die, and 60 minutes to test, you can conduct 4 tests (60/15 = 4). Each pig can have 5 states (alive after 0, 1, 2, 3, or 4 tests). Since 5ยณ = 125 < 1000 < 5โด = 625, you need at least 4 pigs.
Input & Output
example_1.py โ Basic Case
$
Input:
buckets = 1000, minutesToDie = 15, minutesToTest = 60
โบ
Output:
5
๐ก Note:
We can conduct 60/15 = 4 tests. Each pig can have 5 states (die after test 1, 2, 3, 4, or never die). With 4 pigs: 5^4 = 625 < 1000, so we need 5 pigs where 5^5 = 3125 โฅ 1000.
example_2.py โ Single Bucket
$
Input:
buckets = 1, minutesToDie = 1, minutesToTest = 1
โบ
Output:
0
๐ก Note:
With only 1 bucket, there's no poison to find, so 0 pigs are needed.
example_3.py โ Limited Time
$
Input:
buckets = 4, minutesToDie = 15, minutesToTest = 15
โบ
Output:
2
๐ก Note:
Only 1 test possible (15/15 = 1). Each pig has 2 states (die or survive). With 2 pigs: 2^2 = 4 buckets can be distinguished.
Constraints
- 1 โค buckets โค 1000
- 1 โค minutesToDie โค minutesToTest โค 100
- minutesToTest is always divisible by minutesToDie
Visualization
Tap to expand
Understanding the Visualization
1
Calculate Test Rounds
Determine how many complete test cycles fit in the time limit
2
Determine States
Each pig can die after round 1, 2, 3... or never die (poison-free)
3
Encode Buckets
Map each bucket to a unique combination of pig death timings
4
Apply Formula
Use logarithms to find minimum pigs needed
Key Takeaway
๐ฏ Key Insight: This problem brilliantly demonstrates how information theory and multi-dimensional encoding can dramatically reduce resource usage - from potentially needing 1000 pigs to just 5!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code