假设我们面前有1000瓶水,其中一瓶含有毒药,任何小鼠在24小时内饮用这瓶水后会死亡。现在我们有10只小鼠可以用来测试这些水,目标是在最短时间内确定哪一瓶水是有毒的。
解决思路
- 10只老鼠 二进制表示 有 210 = 1024
- 999瓶水 + 1瓶药水 = 1000 < 1024
- 10只老鼠可以测出有毒药水
实现思路
- 首先,将每瓶药水从1 - 1000 编号
- 再将每一瓶编号转换为二进制,例如:
- 1 - 00 0000 0001
- 2 - 00 0000 0010
- ......
- 999 - 11 1110 0111
- 1000 - 11 1110 1000
- 每只老鼠对应每个位置 总计10位
- 将每只老鼠喂对应的水(或药)对应的位置为1,例如:
- 第一只老鼠 喂
00 0000 0001、00 0000 0011等 - 第二只老鼠 喂
00 0000 0010、00 0000 0011等 - ......
- 第一只老鼠 喂
- 等待
24h(扣题)后, 观察死亡老鼠编号 得出一串数字 - 用这串数字拼出二进制数字 最后转换为十进制,例如:
- 死亡的老鼠编号为 4, 7
- 则得出的二进制为 00 0100 1000
- 转换为十进制为 72
- 有毒的药水是编号为72的
代码实现
初始化药水 - 编号
/**
* 1000瓶药水的数组
*/
const waterBottles = Array.from({ length: 1000 }, (_, i) => i + 1
/*
* 随机设置一瓶有毒
*/
const index = Math.floor(Math.random() * 1000)
按照编号对应并喂给老鼠, 等待24h
找出死亡的老鼠
/**
* 找出死亡的老鼠
*/
function findDeadMouse() {
const indexB = index.toString(2).padStart(10, "0");
const deadMouse = indexB.split("");
return deadMouse.reduce((res, item, i) => {
if (item === "1") {
res.push(i + 1);
}
return res;
}, []);
}
/**
* 死亡老鼠的索引
*/
const deadMouseIndexList = findDeadMouse();
// 假设 [ 4, 6, 8, 9, 10 ]
根据死亡老鼠找出药水
/**
* 根据死亡老鼠找出药水索引
*/
function findWaterIndex() {
let list = [];
for (let i = 1; i <= 10; i++) {
if (deadMouseIndexList.includes(i)) {
list.push(1);
} else {
list.push(0);
}
}
return parseInt(list.join(""), 2);
}
const findIndex = findWaterIndex();
打印结果
console.log("死亡老鼠编号:", deadMouseIndexList);
console.log("有毒药水编号:", index);
console.log("推算的编号:", findIndex);
完整代码
/**
* 1000瓶药水的数组
*/
const waterBottles = Array.from({ length: 1000 }, (_, i) => i + 1);
/*
* 随机设置一瓶有毒
*/
const index = Math.floor(Math.random() * 1000);
/**
* 找出死亡的老鼠
*/
function findDeadMouse() {
const indexB = index.toString(2).padStart(10, "0");
const deadMouse = indexB.split("");
return deadMouse.reduce((res, item, i) => {
if (item === "1") {
res.push(i + 1);
}
return res;
}, []);
}
/**
* 死亡老鼠的索引
*/
const deadMouseIndexList = findDeadMouse();
/**
* 根据死亡老鼠找出药水索引
*/
function findWaterIndex() {
let list = [];
for (let i = 1; i <= 10; i++) {
if (deadMouseIndexList.includes(i)) {
list.push(1);
} else {
list.push(0);
}
}
return parseInt(list.join(""), 2);
}
const findIndex = findWaterIndex();
console.log("死亡老鼠编号:", deadMouseIndexList);
console.log("有毒药水编号:", index);
console.log("推算的编号:", findIndex);
同类型文章