实验1:
function shuffle(target) { var j, x, i = target.length; for (; i > 0; j = parseInt(Math.random() * i), x = target[--i], target[i] = target[j], target[j] = x) {} return target } function removeAt(target, index) { return !!target.splice(index, 1).length } var bingo1 = 0 var bingo2 = 0 for (var i = 0; i < 10000; i++) { var arr = shuffle([0, 0, 1]); var index = parseInt(Math.random() * 3); if (arr[index]) bingo1++ } for (var i = 0; i < 10000; i++) { var arr = shuffle([0, 0, 1]); var index = parseInt(Math.random() * 3); var errIndex = 0 // 主持人删掉一个错误答案 for (var j = 0; j < arr.length; j++) { if (arr[j] == 0 && j != index) { errIndex = j arr[j] = 'x' break; } }
// 遍历所有答案,如果用户选择的是错的,那根据强制交换的约定,就是一定是对的。 for (var k = 0; k < arr.length; k++) { if (arr[k] == 0 && k == index) { bingo2++ } } } console.log(bingo1, bingo2);
更简单的实验:
function shuffle(target) { var j, x, i = target.length; for (; i > 0; j = parseInt(Math.random() * i), x = target[--i], target[i] = target[j], target[j] = x) {} return target } function removeAt(target, index) { return !!target.splice(index, 1).length } var bingo1 = 0 var bingo2 = 0 for (var i = 0; i < 10000; i++) { var arr = shuffle([0, 0, 1]); var index = parseInt(Math.random() * 3); if (arr[index]) bingo1++ if (!arr[index]) bingo2++ } console.log(bingo1, bingo2);