豬的故事
There are 1000 buckets, one and only one of them contains poison, the rest are filled with water. They all look the same. If a pig drinks that poison it will die within 15 minutes. What is the minimum amount of pigs you need to figure out which bucket contains the poison within one hour.
If there are n buckets and a pig drinking poison will die within m minutes, how many pigs (x) you need to figure out the "poison" bucket within p minutes? There is exact one bucket with poison.
解:
最開始天真的以為豬是一次喝一桶,后來想到二分法,讓n只豬每次喝buckets/n桶水旦委,然后確定哪塊有毒搁进,然后接下去疏咐。惕蹄。箍土。
/**
* @param {number} buckets
* @param {number} minutesToDie
* @param {number} minutesToTest
* @return {number}
*/
var poorPigs = function(buckets, minutesToDie, minutesToTest) {
if(buckets == 1) return 0;
var pigs = 1;
var times = Math.floor(minutesToTest / minutesToDie);
while(buckets/Math.pow(pigs + 1, times) > 1){
pigs += 1;
}
return pigs;
};
然而,豬是會死的后频,所以二分法不靠譜。暖途。卑惜。。驻售。這道題的難度竟然是easy??露久。。欺栗。毫痕。。迟几。
求助別人消请,使用定位法。
如果有兩頭豬瘤旨,有四次嘗試機會梯啤,我們可以發(fā)現25桶里的毒藥,使用5×5的矩陣來安排:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
使用一只豬一行一行的嘗試存哲,另外一只豬一列一列的嘗試因宇,就可以確定哪行有毒哪列有毒了,因為有排除的方法祟偷,所以是五維的察滑。依次類推,有三只豬的話修肠,就可以構建5×5×5的矩陣贺辰。。。
所以饲化,n只豬可以尋找5的n次方桶水莽鸭。
/**
* @param {number} buckets
* @param {number} minutesToDie
* @param {number} minutesToTest
* @return {number}
*/
var poorPigs = function(buckets, minutesToDie, minutesToTest) {
if(buckets == 1) return 0;
var pigs = 1;
var times = Math.ceil(minutesToTest / minutesToDie);
while((times+1) ** pigs < buckets) pigs += 1;
return pigs;
};