如何在Google表格中为非空行生成指定范围且含限定重复数的随机数?
Google表格自定义函数:带重复上限的随机数分配
以下是直接可用的Google Apps Script自定义函数,能解决你的需求:
函数代码
打开Google表格,点击「扩展程序」→「Apps脚本」,新建脚本文件,替换默认代码为以下内容:
function assignRandomNumbers(dataRange, minCell, maxCell, maxRepeatCell) { // 获取输入参数的实际值 const dataValues = dataRange.flat(); const min = minCell[0][0]; const max = maxCell[0][0]; const maxRepeat = maxRepeatCell[0][0]; // 筛选出非空行的索引 const nonEmptyIndices = dataValues.map((val, idx) => val !== "" ? idx : null).filter(idx => idx !== null); const totalNeeded = nonEmptyIndices.length; // 生成符合重复上限的随机数池 let numberPool = []; for (let num = min; num <= max; num++) { // 每个数字添加maxRepeat次,直到池的数量足够 const addCount = Math.min(maxRepeat, totalNeeded - numberPool.length); if (addCount <= 0) break; numberPool = numberPool.concat(Array(addCount).fill(num)); } // 打乱随机数池(Fisher-Yates洗牌算法) for (let i = numberPool.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [numberPool[i], numberPool[j]] = [numberPool[j], numberPool[i]]; } // 构建结果数组,空行留空 const result = Array(dataValues.length).fill(""); nonEmptyIndices.forEach((idx, poolIdx) => { result[idx] = numberPool[poolIdx]; }); // 返回二维数组适配表格输出 return result.map(val => [val]); }
使用方法
假设你的表格布局是:
- B2:B81:包含包的列(其中20行为空)
- C1:随机数最小值(比如1)
- D1:随机数最大值(比如31)
- E1:每个随机数的最大重复次数(比如2)
在你想输出随机数的列(比如C2)的第一个单元格输入:
=assignRandomNumbers(B2:B81, C1, D1, E1)
按回车后,函数会自动填充整列,空行对应位置保持为空。
关键逻辑说明
- 先筛选所有非空行的位置,避免给空行分配数值
- 生成随机数池时,确保每个数字最多出现指定的重复次数,同时总数量匹配非空行的总数
- 使用Fisher-Yates洗牌算法打乱数池,保证随机分布的公平性
- 最后将打乱后的数对应填充到非空行的位置,空行留空
内容的提问来源于stack exchange,提问作者tuner2000i
相关产品推荐
相关产品推荐

