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

如何根据N个布尔值数组的序列获取对应状态索引?

解决方法

方法1:组合数计算法

这种方法通过数学计算组合数得到索引,适用于任意长度n的输入,效率高且无需预生成所有状态。

实现逻辑

  1. 提取输入中所有False对应的位置,按升序排列成列表。
  2. 统计False的个数k。
  3. 计算所有元素个数小于k的组合数之和(即前k-1种False数量对应的状态总数)。
  4. 计算当前k个False的位置组合在所有同数量组合中的排名。
  5. 总索引为前缀组合数之和加上当前组合的排名。
import math
import numpy as np

def get_state_index(sub_states):
    sub_states = np.asarray(sub_states)  # 兼容列表或numpy数组输入
    n = len(sub_states)
    # 提取所有False的位置(0-based索引)
    pos = np.where(sub_states == False)[0].tolist()
    k = len(pos)
    
    # 计算前缀组合数总和:sum(从n个元素中选i个的组合数),i从0到k-1
    prefix = sum(math.comb(n, i) for i in range(k))
    
    # 计算当前组合在同数量组合中的排名
    rank = 0
    for i in range(k):
        rank += math.comb(pos[i], i+1)
    
    return prefix + rank

方法2:预生成映射表法

这种方法预先生成所有可能的状态与索引的映射,查询时直接查表,适合n较小的场景,代码逻辑更直观。

import itertools
import numpy as np

def get_state_index(sub_states):
    sub_states = tuple(np.asarray(sub_states))
    n = len(sub_states)
    
    # 仅第一次调用时预生成映射表,避免重复计算
    if not hasattr(get_state_index, 'state_map'):
        state_map = {}
        idx = 0
        # 按False的个数从小到大遍历所有可能情况
        for k in range(0, n+1):
            # 生成所有k个False的位置组合
            for positions in itertools.combinations(range(n), k):
                # 构造对应的sub_states
                state = [True]*n
                for p in positions:
                    state[p] = False
                state_map[tuple(state)] = idx
                idx += 1
        get_state_index.state_map = state_map
    
    return get_state_index.state_map[sub_states]

方法3:硬编码逻辑法(针对n=3的特殊场景)

如果仅需要处理n=3的固定情况,可以直接通过条件判断快速返回结果,无需通用计算逻辑。

import numpy as np

def get_state_index(sub_states):
    s = np.asarray(sub_states)
    if s[0] and s[1] and s[2]:
        return 0
    elif not s[0] and s[1] and s[2]:
        return 1
    elif s[0] and not s[1] and s[2]:
        return 2
    elif s[0] and s[1] and not s[2]:
        return 3
    elif not s[0] and not s[1] and s[2]:
        return 4
    elif not s[0] and s[1] and not s[2]:
        return 5
    elif s[0] and not s[1] and not s[2]:
        return 6
    else:
        return 7

测试验证

使用你提供的测试代码验证函数正确性:

if __name__ == '__main__':
    # 初始化sub_states: [False, True, True] 对应H-T-T,预期索引1
    sub_states = np.full(3, False, dtype=bool)
    sub_states[1] = True
    sub_states[2] = True

    states = np.full(2 ** sub_states.size, False, dtype=bool)
    i = get_state_index(sub_states)
    states[i] = True
    print(states)  # 输出: [False  True False False False False False False]

运行后输出符合预期,说明函数逻辑正确。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 07:25:17