求用16面量子骰子实现文本随机分词的JavaScript或离散数学方案
cleromancy SPA 分区选择实现方案
核心逻辑
本质是基于16进制的层级定位:每次投116的骰子相当于取1位16进制数,用于定位当前层级的16个分区,每次拆分后选中对应分区继续拆分,直到分区内词数在116区间即可停止,不需要复杂的离散数学知识,直接按流程实现即可。
前置约定
- 提前将文本库整理为纯数组格式,每个元素对应一个词,不需要在代码中做任何字符串处理,完全符合你的要求
- 量子骰子单次返回值为116的整数,代码中会统一转为015的索引用于数组定位
- 建议提前将文本库总词数
n调整为16的整数次幂(比如256、4096、65536),避免拆分时出现小数,应用层无需额外处理边界
JavaScript实现代码
动态调用量子随机数版本
每次拆分自动调用你封装的量子骰子接口拿结果:
/** * @param {Array} wordLib 提前整理好的词数组,每个元素是单个词 * @param {Function} getQuantumDiceResult 你封装的量子随机数获取方法,调用一次返回1~16的整数 * @returns {Array} 最终选中的1~16个词的分区 */ function getCleromancyPartition(wordLib, getQuantumDiceResult) { let currentPartition = wordLib // 拆分直到分区大小符合要求 while (currentPartition.length > 16) { const perPartitionSize = currentPartition.length / 16 // 取量子骰子结果转成分区索引 const partitionIndex = getQuantumDiceResult() - 1 // 计算选中分区的起止位置 const start = partitionIndex * perPartitionSize const end = start + perPartitionSize // 更新当前分区 currentPartition = currentPartition.slice(start, end) } return currentPartition }
传入预生成骰子结果版本
如果已经提前生成好了多次骰子的结果列表,可以用这个版本:
/** * @param {Array} wordLib 提前整理好的词数组 * @param {Array} diceResultList 预生成的骰子结果数组,每个元素是1~16的整数 * @returns {Array} 最终选中的1~16个词的分区 */ function getCleromancyPartitionByDiceList(wordLib, diceResultList) { let currentPartition = wordLib let diceIndex = 0 while (currentPartition.length > 16) { const perPartitionSize = currentPartition.length / 16 const partitionIndex = diceResultList[diceIndex] - 1 const start = partitionIndex * perPartitionSize const end = start + perPartitionSize currentPartition = currentPartition.slice(start, end) diceIndex++ } return currentPartition }
非16整数次幂词库兼容方案
如果不想调整词库大小凑16的整数次幂,修改拆分逻辑即可,最后一个分区装剩下的所有词:
while (currentPartition.length > 16) { // 向下取整计算每个分区的大小 const perPartitionSize = Math.floor(currentPartition.length / 16) const partitionIndex = getQuantumDiceResult() - 1 const start = partitionIndex * perPartitionSize // 最后一个分区直接取到数组末尾,避免剩余词丢失 const end = partitionIndex === 15 ? currentPartition.length : start + perPartitionSize currentPartition = currentPartition.slice(start, end) }
内容的提问来源于stack exchange,提问作者DubiousTunic
相关产品推荐
相关产品推荐

