- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Poor Pigs in C++
Suppose there are 1000 buckets, one of them is poisonous, others are filled with water. They all look similar. If a pig drinks the poison it will die within 15 minutes. What will be the minimum amount of pigs that we need to find out the poisonous bucket within one hour?
So now consider for the general case and devise an algorithm for this. So, the general case is that If there are n different buckets and a pig drinking poison will die within m minutes, how many pigs are needed to find poisonous bucket within p minutes? There is exactly one bucket with poison.
When the n = 1000, m = 15 and p = 60, then the output will be 5.
To solve this, we will follow these steps −
- ret := 0
- while (minutesToTest / minutesToDie + 1)^ret < buckets, do −
- (increase ret by 1)
- return ret
Let us see the following implementation to get better understanding −
Example
#include <bits/stdc++.h> using namespace std; class Solution { public: int poorPigs(int buckets, int minutesToDie, int minutesToTest) { int ret = 0; while(pow((minutesToTest / minutesToDie + 1), ret) < buckets) ret++; return ret; } }; main(){ Solution ob; cout << (ob.poorPigs(1000,15,60)); }
Input
1000 15 60
Output
5
Advertisements