Compute rank of a combination?

前端 未结 7 1391
灰色年华
灰色年华 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:49

    You can try using the lexicographic index of the combination. Maybe this page will help: http://saliu.com/bbs/messages/348.html

    This MSDN page has more details: Generating the mth Lexicographical Element of a Mathematical Combination.

    To be a bit more specific:

    When treated as a tuple, you can order the combinations lexicographically.

    So (0,1,2) < (0,1,3) < (0,1,4) etc.

    Say you had the number 0 to n-1 and chose k out of those.

    Now if the first element is zero, you know that it is one among the first n-1 choose k-1.

    If the first element is 1, then it is one among the next n-2 choose k-1.

    This way you can recursively compute the exact position of the given combination in the lexicographic ordering and use that to map it to your number.

    This works in reverse too and the MSDN page explains how to do that.

提交回复
热议问题