You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现Brainfuck解释器:支持负数范围的索引溢出循环映射

实现方案

你需要的是带循环的区间映射函数,核心是解决JS原生取余运算符%对负数处理不符合预期的问题,同时规避除零错误。


原有方案的问题

  • 当lbound或ubound为0时直接触发除零错误
  • 用Math.round处理商的逻辑只在特定区间有效,无法适配任意正负区间
  • 没有统一的数学逻辑,上下溢出分开处理容易出现边界判断错误

最终实现代码

function wrapIndex(index, lbound, ubound) {
    // 校验区间合法性,从根源避免除零错误
    if (lbound >= ubound) {
        throw new Error('ubound must be greater than lbound')
    }
    const size = ubound - lbound
    // 偏移到0起点区间做正模运算后再映射回原区间
    const offset = index - lbound
    const positiveMod = ((offset % size) + size) % size
    return lbound + positiveMod
}

效果验证

和你给出的示例完全匹配:

  • lbound: 0, ubound: 10, index: 10 → 输出 0
  • lbound: 0, ubound: 10, index: 11 → 输出 1
  • lbound: -10, ubound: 0, index: -11 → 输出 -1
  • lbound: -5, ubound: 15, index: 16 → 输出 -4
  • lbound: 5, ubound: 15, index: 26 → 输出 6

原理解释

  1. 先计算区间总长度size = ubound - lbound,保证后续模运算的除数是正整数,避免除零错误
  2. 将输入索引减去左边界,得到相对于左边界的偏移量,把问题转换为[0, size)区间的循环映射
  3. 用((offset % size) + size) % size实现正模运算,不管偏移量是正还是负,最终结果都会落在0 ~ size-1的范围内
  4. 最后把模运算结果加回左边界,映射回原来的数值区间

内容的提问来源于stack exchange,提问作者kiroshiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 20:54:07