Node.js中如何将含1个正确值的4个固定值随机分配给4个变量?
在Node.js中随机分配正确/错误答案到变量的实现方案
核心思路
先将正确答案与错误答案合并为一个数组,通过Fisher-Yates洗牌算法打乱数组顺序(保证真正的随机性),再将打乱后的数组元素分别赋值给四个变量。
具体实现代码
// 定义正确答案和错误答案集合 const correctAnswer = "正确选项"; const wrongAnswers = ["错误选项A", "错误选项B", "错误选项C"]; // Fisher-Yates洗牌函数:实现数组的公平随机打乱 function shuffleArray(array) { const shuffled = [...array]; // 复制原数组避免修改原数据 for (let i = shuffled.length - 1; i > 0; i--) { const randomIndex = Math.floor(Math.random() * (i + 1)); // 交换当前元素与随机位置元素 [shuffled[i], shuffled[randomIndex]] = [shuffled[randomIndex], shuffled[i]]; } return shuffled; } // 合并并打乱答案数组 const shuffledOptions = shuffleArray([...wrongAnswers, correctAnswer]); // 分配给四个变量 const option1 = shuffledOptions[0]; const option2 = shuffledOptions[1]; const option3 = shuffledOptions[2]; const option4 = shuffledOptions[3]; // 验证结果 console.log({ option1, option2, option3, option4 });
封装复用的版本
如果需要多次生成随机选项,可以封装成函数:
function getRandomizedOptions(correct, wrongs) { if (wrongs.length !== 3) { throw new Error("需要传入3个错误答案"); } const allOptions = [...wrongs, correct]; const shuffled = shuffleArray(allOptions); return { option1: shuffled[0], option2: shuffled[1], option3: shuffled[2], option4: shuffled[3] }; } // 使用示例 const quizOptions = getRandomizedOptions("Paris", ["London", "Berlin", "Madrid"]); console.log(quizOptions);
为什么不用array.sort(() => Math.random() - 0.5)?
这种方式的随机排序并不公平,某些元素的位置概率会失衡,而Fisher-Yates算法是经过验证的公平洗牌方案,能保证每个元素出现在任意位置的概率均等。
内容的提问来源于stack exchange,提问作者batman
相关产品推荐
相关产品推荐

