java实现1000桶酒,1桶有毒,最少需要10只小白鼠
有1000桶酒,其中1桶有毒。而一旦喝了,毒性会在1周后发作。现在我们用小白鼠做实验,要在1周后找出那桶毒酒,问最少需要多少小白鼠。
代码如下:
public static int[] WINE = new int[1000];
static {
for (int i = 0; i < 1000; i++) {
//假设有毒的是999号
if (i == 998) {
WINE[i] = 1;
} else {
WINE[i] = 0;
}
}
}
代码如下:
public static void main(String[] args) throws Exception {
//①计算需要多少只小白鼠
int mouseCnt = 1;
int wineCnt = WINE.length;
while (wineCnt > 1) {
wineCnt /= 2;
mouseCnt++;
}
System.out.println("至少需要小白鼠" + mouseCnt + "只");
//准备好活小白鼠,0代表活着,1代表死了
int[] mouses = new int[mouseCnt];
for (int i = 0; i < mouseCnt; i++) {
mouses[i] = 0;
}
//②给小白鼠喂酒
for (int j = 0; j < WINE.length; j++) {
int wine = WINE[j];
int wineNum = j + 1;
//获取需要喂酒的小白鼠编号
ArrayList<Integer> mouseIndex = getMouseIndex(wineNum, mouseCnt);
for (Integer index : mouseIndex) {
//如果酒有毒,那就毒死它
if (wine == 1) {
mouses[index] = 1;
}
}
}
//③看一眼小白鼠的状态
StringBuilder mouseStatus = new StringBuilder();
for (int mouse : mouses) {
mouseStatus.append(mouse);
}
System.out.println("所有小白鼠状态:" + mouseStatus);
//④将小白鼠状态换算为毒酒的编号
int poisonousWine = 0;
for (int x = mouses.length - 1; x >= 0; x--) {
poisonousWine = (poisonousWine << 1) | mouses[x];
}
System.out.println("毒酒的编号是:" + poisonousWine);
}
代码如下:
/**
* @param wineNum 酒的编号
* @param mouseCnt 小白鼠数量
* @return 需要喂酒的小白鼠编号
*/
private static ArrayList<Integer> getMouseIndex(int wineNum, int mouseCnt) {
ArrayList<Integer> mouseIndex = new ArrayList<>();
for (int i = 0; i < mouseCnt; i++) {
if ((wineNum & (1 << i)) != 0) {
mouseIndex.add(i);
}
}
return mouseIndex;
}
至少需要小白鼠10只
所有小白鼠状态:1110011111
毒酒的编号是:999
Process finished with exit code 0
手撸不易,如果您觉得我的文章对您有所帮助,欢迎您的打赏,您的支持将鼓励我继续创作更多优质内容。