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.
Answer this question, and write an algorithm for the follow-up general case.
Follow-up:
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.
1 2 3 4 5
publicclassSolution { publicintPoorPigs(int buckets, int minutesToDie, int minutesToTest) { } }
[TestMethod] publicvoid PoorPigsTest_5桶水_1小時_毒發時間15分鐘_最少需要1隻豬來測試() { //arrange var sut = new Solution(); var bukets = 5; var minutesToDie = 15; var minutesToTest = 60;
var expected = 1; //act var actual = sut.PoorPigs(bukets, minutesToDie, minutesToTest);
//assert actual.Should().Be(expected);
}
1 2 3 4 5 6 7 8 9 10 11 12 13 14
publicintPoorPigs(int buckets, int minutesToDie, int minutesToTest) { var OnePigCanTestBukets = (minutesToTest / minutesToDie) + 1;
var Pigs = 0; double TotalCanTestBukets = 0; while (TotalCanTestBukets < buckets) { Pigs++; TotalCanTestBukets = Math.Pow(OnePigCanTestBukets, Pigs); }
return Pigs; }
案例二
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
[TestMethod] publicvoid PoorPigsTest_6桶水_1小時_毒發時間15分鐘_最少需要2隻豬來測試() { //arrange var sut = new Solution(); var bukets = 6; var minutesToDie = 15; var minutesToTest = 60;
var expected = 2; //act var actual = sut.PoorPigs(bukets, minutesToDie, minutesToTest);
//assert actual.Should().Be(expected);
}
直接通過單元測試
#解析
LeetCode測試發生錯誤
補上案例
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
[TestMethod] publicvoid PoorPigsTest_1桶水_1分鐘測試時間_毒發時間1分鐘_最少需要0隻豬來測試() { //arrange var sut = new Solution(); var bukets = 1; var minutesToDie = 1; var minutesToTest = 1;
var expected = 0; //act var actual = sut.PoorPigs(bukets, minutesToDie, minutesToTest);
//assert actual.Should().Be(expected);
}
一桶水根本不需要測試,所以修改一下Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
publicintPoorPigs(int buckets, int minutesToDie, int minutesToTest) { var Pigs = 0; if (buckets <= 1) { return Pigs; }