类 Algorithms
java.lang.Object
net.apexes.commons.lang.Algorithms
- 作者:
- HeDYn
-
嵌套类概要
嵌套类 -
方法概要
修饰符和类型方法说明static voidcombination(int options, int select, Algorithms.IntArrayConsumer consumer) 计算“options 选 select”的全部组合。static voidpermutation(int options, Algorithms.IntArrayConsumer consumer) 对 options 个元素进行全排列(算法采用字典序法)。
-
方法详细资料
-
combination
计算“options 选 select”的全部组合。
算法思路是用一个数组的下标表示 1 到 options 个数,数组元素的值为1表示其下标代表的数被选中,为 0 则没选中。
首先初始化,将数组前 n 个元素置 1,表示第一个组合为前n个数。
然后从左到右扫描数组元素值的“10”组合,找到第一个“10”组合后将其变为“01”组合,同时将其左边的所有“1”全部移动到数组的最左端。 当“1”全部移动到最右端时,就得到了最后一个组合。
例如求5中选3的组合:
1 1 1 0 0 //0,1,2 1 1 0 1 0 //0,1,3 1 0 1 1 0 //0,2,3 0 1 1 1 0 //1,2,3 1 1 0 0 1 //0,1,4 1 0 1 0 1 //0,2,4 0 1 1 0 1 //1,2,4 1 0 0 1 1 //0,3,4 0 1 0 1 1 //1,3,4 0 0 1 1 1 //2,3,4
- 参数:
options- 备选元素数量select- 选择数量consumer- 组合结果消费者。为了提高性能,将共用一个数组对象传递组合结果,数组元素值为参与组合的备选元素下标。
-
permutation
对 options 个元素进行全排列(算法采用字典序法)。- 参数:
options- 参与全排列的元素数量consumer- 排列结果消费者。为了提高性能,将共用一个数组对象传递排列结果,数组元素值为参与排列的备选元素下标。
-