How to precalculate valid number of combinations instead of using while loop?

后端 未结 2 769
执念已碎
执念已碎 2021-01-28 11:12

Given List of datacenters which are dc1, dc2, dc3 and list of machines, h1, h2, h3, h4 as mentioned below -

Datacenters = dc1, dc2, dc3
Machines = h1, h2, h3, h         


        
2条回答
  •  被撕碎了的回忆
    2021-01-28 11:43

    You're talking math. The answer is (n choose k), where n is the number of machines, and k is the number of datacenters.

    The reason is the following: The ordering doesn't really matter, so we'll assume that the Datacenters are always arranged in the same order. For the first data center, we can pick any one of the n machines. For the second, we can pick any one of the machines, except for the one picked before, thus n * (n-1). The next data center will lead to n * (n-1) * (n-2) possible situations.

    Thus, if you had 10 machines, and 4 datacenters, you would have:

    10 * 9 * 8 * 7 possibile combinations.

    More info here: http://en.wikipedia.org/wiki/Combination

    If you want a function to do the work for you , it is in the Apache commons: http://commons.apache.org/proper/commons-math/apidocs/org/apache/commons/math3/util/ArithmeticUtils.html#binomialCoefficientDouble%28int,%20int%29

    However, if you are actually wanting to generate those combinations, then you need a for loop.

提交回复
热议问题