Compute rank of a combination?

前端 未结 7 1393
灰色年华
灰色年华 2020-11-30 06:07

I want to pre-compute some values for each combination in a set of combinations. For example, when choosing 3 numbers from 0 to 12, I\'ll compute some value for each one:

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 06:28

    What you want are called combinadics. Here's my implementation of this concept, in Python:

    def nthresh(k, idx):
      """Finds the largest value m such that C(m, k) <= idx."""
      mk = k
      while ncombs(mk, k) <= idx:
        mk += 1
      return mk - 1
    
    
    def idx_to_set(k, idx):
      ret = []
      for i in range(k, 0, -1):
        element = nthresh(i, idx)
        ret.append(element)
        idx -= ncombs(element, i)
      return ret
    
    
    def set_to_idx(input):
      ret = 0
      for k, ck in enumerate(sorted(input)):
        ret += ncombs(ck, k + 1)
      return ret
    

提交回复
热议问题