前言
有100瓶酒,其中有一瓶是毒酒,最少用多少只老鼠,能找出这瓶毒酒
提示:以下是本篇文章正文内容,下面案例可供参考
代码如下(示例):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.mouse {
width: 10%;
height: auto;
margin: 10px;
cursor: pointer;
filter: grayscale(0);
transition: all .3s ease;
}
.choose {
filter: grayscale(1);
transition: all .3s ease;
}
.fat_group {
width: 100%;
display: grid;
grid-template-columns: repeat(10, 1fr);
}
.fat {
width: 100%;
height: auto;
transition: all .3s ease;
}
.confirm_btn {
width: 120px;
padding: 10px 0;
border: none;
outline: none;
background-color: #ff313f;
border-radius: 10px;
color: #fff;
}
</style>
</head>
<body>
<div class="check_group"></div>
<button onclick="confirm()" class="confirm_btn">确定</button>
<div class="fat_group"></div>
<script>
let total = 100;//设置一共有100桶酒
let length = getN(total);//获取老鼠数量
let convertArr = new Array(length).fill([]);
let confirmArr = [];
init();
function init() {
const wrap = document.querySelector('.check_group');
const fragFat = document.createDocumentFragment();
const fat = document.querySelector('.fat_group');
for (let i = 1; i <= total; i++) {
convert(i);
let img = document.createElement('img');
img.src = './fat.png';
img.className = 'fat';
fragFat.appendChild(img);
}
fat.appendChild(fragFat);
const frag = document.createDocumentFragment();
for (let j = 1; j <= length; j++) {
let img = document.createElement('img');
img.src = './mouse.png';
img.className = 'mouse';
img.onclick = function () {
document.querySelector('.fat.choose') && document.querySelector('.fat.choose').classList.remove('choose');
if (confirmArr.includes(j)) {
confirmArr.splice(confirmArr.indexOf(j), 1);
img.classList.remove('choose');
} else {
confirmArr.push(j);
img.classList.add('choose');
}
}
frag.appendChild(img);
}
wrap.appendChild(frag);
}
/**
* 递归求N=2的几次幂
*/
function getN(num, index = 0) {
if (num > 1) {
index++;
return getN(num / 2, index);
} else {
return index;
}
}
/**
* 递归将十进制数字转为二进制,并保存相关数据
*/
function convert(num, str = '', index = 0, numArr = []) {
if (num > 0) {
index++;
let n = Math.floor(num / 2);
let j = num % 2;
j && numArr.push(index);
str = j + str;
return convert(n, str, index, numArr);
} else {
str = str.padStart(length, '0');
numArr.forEach(s => {
let arr = convertArr[s - 1];
arr = arr.concat([str]);
convertArr[s - 1] = arr;
})
return str;
}
}
/**
* 获取毒酒编号
*/
function getStr(dieArr) {
let arr = new Array(length).fill('0');
dieArr.forEach(s => {
arr[length - s] = '1';
});
return arr.join('');
}
/**
* 二进制转十进制
*/
function getNumber(str) {
return parseInt(str, 2)
}
/**
* 选中小白鼠,得出对应的毒酒
*/
function confirm() {
let num = getNumber(getStr(confirmArr));
document.getElementsByClassName('fat')[num - 1].classList.add('choose');
confirmArr = [];
let imgs = document.getElementsByClassName('mouse');
for (let i = 0; i < imgs.length; i++) {
if (imgs[i].classList.contains('choose')) {
imgs[i].classList.remove('choose');
}
}
}
</script>
</body>
</html>