类 Algorithms

java.lang.Object
net.apexes.commons.lang.Algorithms

public final class Algorithms extends Object
作者:
HeDYn
  • 方法详细资料

    • combination

      public static void combination(int options, int select, Algorithms.IntArrayConsumer consumer)

      计算“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

      public static void permutation(int options, Algorithms.IntArrayConsumer consumer)
      对 options 个元素进行全排列(算法采用字典序法)。
      参数:
      options - 参与全排列的元素数量
      consumer - 排列结果消费者。为了提高性能,将共用一个数组对象传递排列结果,数组元素值为参与排列的备选元素下标。