N Rats

Brain Teasers with Coding Study

Few companies ask the below brain teaser to the candidates during the interview.

You have 1000 wine bottles, one of which is poisoned. You want to determine which bottle is poisoned by feeding the wine to the rats. The poisoned wine takes 1 hour to work. How many rats are necessary to find the poisoned bottle in 1 hour?

But what if it is a coding challenge:

You have X wine bottles, one of which is poisoned. You want to determine which bottle is poisoned by feeding the wine to the rats. The poisoned wine takes Z hour to work. How many rats are necessary to find the poisoned bottle in Y hour? (Provided condition: Y is multiple of Z.)

Can you write a program which takes X, Y & Z as input and gives the solution?

The coding solution was originally published in my book “Brain Teasers with Coding For Data Scientist”. Puzzles from that book are published on this link. Also, check my puzzle books “Brain Teasers with Coding For Data Scientist 2: 9 New Computational Puzzles” and “Puzzles with Coding: Puzzles for Everyone” and “Computational Puzzles To Flex Your Brain: 50 original puzzles to sharpen computing mind and mathematical skills at Amazon. For purchasing my books or related queries, feel free to contact me. In these books, you will find interesting brain teasers those are suitable for coders as well as non-coders. Coding solutions are also provided with Python code. So, grab a copy of those books and jump into the world of fascinating and exciting brain teasers.

Solution:

General Formula :

Required number of rats = Log (Y/Z)+1 (X)

Where X = Number of wine bottles

Z = Hours for poison to effect

Y = Hours to find a poisoned bottle

Coding Solution:

import math
#X wine bottles
X = int(input("Enter X:"))
#Z hour time after which the poison works
Z = int(input("Enter Z:"))
#Y hour time to find the poisoned bottle
Y = int(input("Enter Y(Y should be multiple of Z):"))
T = Y/Z
print ("Number of rats required to find the poisoned bottle: ", end="")
print (math.ceil(math.log(X,T+1)))

Note: (Keeping non-coder readers in mind, code optimization may not be fully utilized.)

Test Output 1:
Enter X:1000
Enter Z:24
Enter Y(Y should be multiple of Z):48
Number of rats required to find the poisoned bottle: 7

Test Output 2:
Enter X:1000
Enter Z:24
Enter Y(Y should be multiple of Z):24
Number of rats required to find the poisoned bottle: 10