Java版排列组合工具类 - Java Permutation and Combination Tools - Go语言中文社区

Java版排列组合工具类 - Java Permutation and Combination Tools



( All code listed in this article is included in my personal lib, and the repo is hosted at: https://github.com/raistlic/LibRaistCommon )


最近在整理个人代码,有些觉得可能有用的,拿出来共享一下 大笑


先上用法示例代码:


问题一: 有三个字符串 "a", "b", "c",进行排列,列出共有多少种排列方式

public class PNCDemo {
  
  public static void main(String[] args) {
    
    System.out.println("===== demo permutation :");
    for(List<String> list : Permutation.of(Arrays.asList("a", "b", "c")))
      System.out.println(list);
  }
}
运行效果:

run:
===== demo permutation :
[a, b, c]
[a, c, b]
[b, a, c]
[b, c, a]
[c, a, b]
[c, b, a]
BUILD SUCCESSFUL (total time: 0 seconds)


问题二: 从五个数 1, 2, 3, 4, 5 中任取 3 个数,列出共有多少种取法

public class PNCDemo {
  
  public static void main(String[] args) {
    
    System.out.println("===== demo combination :");
    for(List<Integer> list : Combination.of(Arrays.asList(1, 2, 3, 4, 5), 3))
      System.out.println(list);
  }
}
运行效果:
run:
===== demo combination :
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
BUILD SUCCESSFUL (total time: 0 seconds)


问题三: 从五个数 1, 2, 3, 4, 5 中任取 3 个数进行排列,列出共有多少种排列方式

public class PNCDemo {
  
  public static void main(String[] args) {
    
    System.out.println("===== demo both :");
    for(List<Integer> list : Permutation.of(Arrays.asList(1, 2, 3, 4, 5), 3))
      System.out.println(list);
  }
}
运行效果:

run:
===== demo both :
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]
[1, 2, 4]
[1, 4, 2]
[2, 1, 4]
[2, 4, 1]
[4, 1, 2]
[4, 2, 1]
[1, 2, 5]
[1, 5, 2]
[2, 1, 5]
[2, 5, 1]
[5, 1, 2]
[5, 2, 1]
[1, 3, 4]
[1, 4, 3]
[3, 1, 4]
[3, 4, 1]
[4, 1, 3]
[4, 3, 1]
[1, 3, 5]
[1, 5, 3]
[3, 1, 5]
[3, 5, 1]
[5, 1, 3]
[5, 3, 1]
[1, 4, 5]
[1, 5, 4]
[4, 1, 5]
[4, 5, 1]
[5, 1, 4]
[5, 4, 1]
[2, 3, 4]
[2, 4, 3]
[3, 2, 4]
[3, 4, 2]
[4, 2, 3]
[4, 3, 2]
[2, 3, 5]
[2, 5, 3]
[3, 2, 5]
[3, 5, 2]
[5, 2, 3]
[5, 3, 2]
[2, 4, 5]
[2, 5, 4]
[4, 2, 5]
[4, 5, 2]
[5, 2, 4]
[5, 4, 2]
[3, 4, 5]
[3, 5, 4]
[4, 3, 5]
[4, 5, 3]
[5, 3, 4]
[5, 4, 3]
BUILD SUCCESSFUL (total time: 0 seconds)


话说算法这种东西,似乎天生适合写成“策略接口” ———— 夫算法者,策略者也。


第一个文件: 排列和组合都要用到的阶乘类(原类名没有改,去掉了与本题无关的部分)

/*
 * Copyright 2012 wuyou (raistlic@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.math.BigInteger;

/**
 * This class is intended to provide convenient facilities for 
 * frequently used maths calculations that {@code java.lang.Math} 
 * does not cover.
 * 
 * @date   08/08/2012
 */
public final class Calculator {
  
  private Calculator() {}
  
  private static final BigInteger[] FACT_RESULT_POOL = new BigInteger[1024];
  public static BigInteger factorial(int number) {
    
    if( number < 0 )
      throw new IllegalArgumentException();

    BigInteger result = null;

    if( number < FACT_RESULT_POOL.length )
      result = FACT_RESULT_POOL[number];

    if( result == null ) {

      result = BigInteger.ONE;
      for(int i = 2; i <= number; i++)
        result = result.multiply(BigInteger.valueOf(i));
      if( number < FACT_RESULT_POOL.length )
        FACT_RESULT_POOL[number] = result;
    }
    return result;
  }
}

第二个文件: 一个定义了“组合算法”需要做的事情的——策略接口


/*
 * Copyright 2012 wuyou (raistlic@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.math.BigInteger;

/**
 * The strategy interface for implementing the combination algorithm.
 *
 * @date   07/08/2012
 */
public interface CombinationAlgorithm {
  
  public int getMaxSupportedSize();
  
  public BigInteger getCombinationCount(int numberOfElements, int numberToPick);
  
  public void fetchCombination(Object[] source, Object[] target, BigInteger ordinal);
}

第三个文件: 组合的工具类,及一个集成在内部的默认算法实现,其中“组合算法”作为一个“可拆换的零件”,可以作为静态工厂方法的参数


/*
 * Copyright 2012 wuyou (raistlic@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

/**
 * This class is to fulfill the needs of getting combinations from a 
 * collection.
 * 
 * It basically provides the functionalities of :
 *   1 - enquiry the number of combination count : c(m, n)
 *   2 - given an ordinal number i, fetch the i-th combination of c(m, n)
 *       as a read-only list.
 *   3 - convenient for-each iteration of all the combinations
 * 
 * This class is NOT thread safe.
 * 
 * This class re-uses one array to fetch the combination, so if the user 
 * want to keep the i-th combination result, make a copy.
 *
 * @date   07/08/2012
 * @author raistlic
 */
public class Combination<E> implements Iterable<List<E>> {
  
  public static final CombinationAlgorithm DEFAULT_ALGORITHM = 
          AlgorithmVER01.INSTANCE;
  
  public static <E> Combination<E> of(Collection<E> elements,
                                      int numberToPick) {
    
    return of(elements, numberToPick, DEFAULT_ALGORITHM);
  }
  
  public static <E> Combination<E> of(Collection<E> elements, 
                                      int numberToPick,
                                      CombinationAlgorithm algorithm) {
    
    if( elements == null )
      throw new NullPointerException();
    
    if( numberToPick < 0 || numberToPick > elements.size() )
      throw new IllegalArgumentException(
              "Invalid number of elements to pick : " + numberToPick + 
              " out of " + elements.size());
    
    if( algorithm == null )
      algorithm = DEFAULT_ALGORITHM;
    
    return new Combination<E>(elements, numberToPick, algorithm);
  }
  
  @SuppressWarnings("unchecked")
  private E[] elements, picked;
  private CombinationAlgorithm algorithm;
  private BigInteger count;
  private Combination(Collection<E> elements, 
                      int numberToPick,
                      CombinationAlgorithm algorithm) {
    
    assert elements != null;
    assert numberToPick >= 0;
    assert numberToPick <= elements.size();
    assert algorithm != null;
    
    this.elements = (E[])elements.toArray();
    this.picked = (E[])new Object[numberToPick];
    this.algorithm = algorithm;
    this.count = this.algorithm.getCombinationCount(
            this.elements.length, numberToPick);
  }
  
  public BigInteger getCombinationCount() {
    
    return count;
  }
  
  public List<E> getCombination(BigInteger ordinal) {
    
    algorithm.fetchCombination(elements, picked, ordinal);
    return Arrays.asList(picked);
  }

  @Override
  public Iterator<List<E>> iterator() {
    
    return new OrdinalIterator();
  }
  
  private class OrdinalIterator implements Iterator<List<E>> {
    
    private BigInteger ordinal;
    private OrdinalIterator() {
      
      ordinal = ZERO;
    }
    
    @Override
    public boolean hasNext() {
      
      return ordinal.compareTo(getCombinationCount()) < 0;
    }

    @Override
    public List<E> next() {
      
      List<E> result = getCombination(ordinal);
      ordinal = ordinal.add(ONE);
      return result;
    }

    @Override
    public void remove() {
      
      throw new UnsupportedOperationException();
    }
  }
  
  private static enum AlgorithmVER01 implements CombinationAlgorithm {

    INSTANCE;
    
    @Override
    public int getMaxSupportedSize() {

      return MAX_SUPPORT;
    }

    @Override
    public BigInteger getCombinationCount(int numberOfElements, int numberToPick) {

      if( numberOfElements < 0 )
        throw new IllegalArgumentException(
                "Invalid number of elements : " + numberOfElements);

      if( numberOfElements > getMaxSupportedSize() )
        throw new IllegalArgumentException(
                "Number of elements out of range : " + numberOfElements);

      if( numberToPick < 0 || numberToPick > numberOfElements )
        throw new IllegalArgumentException(
                "Invalid number to pick : " + numberToPick);

      if( numberToPick == 0 || numberToPick == numberOfElements)
        return ONE;
      else
        return Calculator.factorial(numberOfElements).divide(
                   Calculator.factorial(numberToPick).multiply(
                   Calculator.factorial(numberOfElements - numberToPick)));
    }

    @Override
    public void fetchCombination(Object[] source, 
                                 Object[] target,
                                 BigInteger ordinal) {

      for(int i=0, si=0; i<target.length; i++, si++) {

        if( ordinal.compareTo(ZERO) > 0 ) {

          BigInteger cLeft = getCombinationCount(
                  source.length - si - 1, target.length - i - 1);
          while( ordinal.compareTo(cLeft) >= 0 ) {

            si++;
            ordinal = ordinal.subtract(cLeft);
            if( ordinal.compareTo(ZERO) == 0 )
              break;
            cLeft = getCombinationCount(
                    source.length - si - 1, target.length - i - 1);
          }
        }
        target[i] = source[si];
      }
    }

    private static final int MAX_SUPPORT = 1024;
  }
}

第四个文件: 定义了“排列算法”要做的事情的 ——策略接口


/*
 * Copyright 2012 wuyou (raistlic@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.math.BigInteger;

/**
 * The strategy interface for implementing the permutation algorithm.
 *
 * @date   07/08/2012
 */
public interface PermutationAlgorithm {
  
  public int getMaxSupportedSize();
  
  public BigInteger getPermutationCount(int numberOfElements);
  
  public void fetchPermutation(Object[] elements, BigInteger ordinal);
}

第五个文件: 排列的工具类,以及一个集成在内部的默认算法实现,同样的,排列及组合算法可以作为静态工厂方法的参数


/*
 * Copyright 2012 wuyou (raistlic@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import static java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;

/**
 * This class is to fulfill the needs of getting permutations from a 
 * collection.
 * 
 * It basically provides the functionalities of :
 *   1 - enquiry the number of permutation count : p(m, n)
 *   2 - given an ordinal number i, fetch the i-th permutation result
 *       as a read-only list.
 *   3 - convenient for-each iteration of all the permutations
 * 
 * This class is NOT thread safe.
 * 
 * This class re-uses one array to fetch each enquiry, so if the user 
 * want to keep the i-th permutation result, make a copy.
 * 
 * @date   07/08/2012
 * @author raistlic
 */
public class Permutation<E> implements Iterable<List<E>>{
  
  public static final PermutationAlgorithm DEFAULT_PERMUTATION_ALGORITHM = 
          AlgorithmVER01.INSTANCE;
  public static final CombinationAlgorithm DEFAULT_COMBINATION_ALGORITHM =
          Combination.DEFAULT_ALGORITHM;
  
  public static <E> Permutation<E> of(Collection<E> elements) {
    
    return of(elements, elements.size());
  }
  
  public static <E> Permutation<E> of(Collection<E> elements,
                                      int numberToPick) {
    
    return of(elements, numberToPick, DEFAULT_PERMUTATION_ALGORITHM);
  }
  
  public static <E> Permutation<E> of(Collection<E> elements,
                                      PermutationAlgorithm pAlgorithm) {
    
    return of(elements, elements.size(), pAlgorithm);
  }
  
  public static <E> Permutation<E> of(Collection<E> elements,
                                      int numberToPick,
                                      PermutationAlgorithm pAlgorithm) {
    
    return of(elements, numberToPick, pAlgorithm, DEFAULT_COMBINATION_ALGORITHM);
  }
  
  public static <E> Permutation<E> of(Collection<E> elements,
                                      int numberToPick,
                                      PermutationAlgorithm pAlgorithm,
                                      CombinationAlgorithm cAlgorithm) {
    
    if( elements == null )
      throw new NullPointerException();
    
    if( pAlgorithm == null )
      throw new NullPointerException();
    
    if( elements.size() > pAlgorithm.getMaxSupportedSize() )
      throw new IllegalArgumentException(
              "Element collection size not supported by the permutation algorithm.");
    
    return new Permutation<E>(elements, numberToPick, pAlgorithm, cAlgorithm);
  }
  
  @SuppressWarnings("unchecked")
  private E[] elements, picked;
  private PermutationAlgorithm pAlgorithm;
  private CombinationAlgorithm cAlgorithm;
  private BigInteger cCount, pCount;
  private BigInteger count;
  private int numberToPick;
  private Permutation(Collection<E> elements, 
                      int numberToPick,
                      PermutationAlgorithm pAlgorithm,
                      CombinationAlgorithm cAlgorithm) {
    
    assert elements != null;
    assert pAlgorithm != null;
    assert cAlgorithm != null;
    assert numberToPick >= 0;
    assert numberToPick <= elements.size();
    
    this.elements = (E[])elements.toArray();
    this.picked = (E[])new Object[numberToPick];
    this.pAlgorithm = pAlgorithm;
    this.cAlgorithm = cAlgorithm;
    this.numberToPick = numberToPick;
    
    this.cCount = this.cAlgorithm.getCombinationCount(this.elements.length, 
                                                      this.numberToPick);
    this.pCount = this.pAlgorithm.getPermutationCount(this.numberToPick);
    this.count = this.cCount.multiply(this.pCount);
  }
  
  public BigInteger getPermutationCount() {
    
    return count;
  }
  
  public List<E> getPermutation(BigInteger ordinal) {
    
    if( ordinal == null )
      throw new NullPointerException();
    
    if( ordinal.compareTo(ZERO) < 0 || ordinal.compareTo(count) >= 0 )
      throw new IllegalArgumentException(
              "Ordinal value out of range : " + ordinal);
    
    if( numberToPick == elements.length ) {
      
      System.arraycopy(elements, 0, picked, 0, elements.length);
    }
    else {
      
      cAlgorithm.fetchCombination(elements, picked, ordinal.divide(pCount));
      ordinal = ordinal.mod(pCount);
    }
    pAlgorithm.fetchPermutation(picked, ordinal);
    return Arrays.asList(picked);
  }
  
  @Override
  public Iterator<List<E>> iterator() {
    
    return this.new OrdinalIterator();
  }
  
  private class OrdinalIterator implements Iterator<List<E>> {
    
    private BigInteger ordinal;
    private OrdinalIterator() {
      
      this.ordinal = ZERO;
    }

    @Override
    public boolean hasNext() {
      
      return ordinal.compareTo(count) < 0;
    }

    @Override
    public List<E> next() {
      
      List<E> result = getPermutation(ordinal);
      ordinal = ordinal.add(ONE);
      return result;
    }

    @Override
    public void remove() {
      
      throw new UnsupportedOperationException();
    }
  }
  
  private static enum AlgorithmVER01 implements PermutationAlgorithm {

    INSTANCE;
    
    @Override
    public int getMaxSupportedSize() {

      return MAX_SUPPORT;
    }

    @Override
    public BigInteger getPermutationCount(int numberOfElements) {

      if( numberOfElements < 0 )
        throw new IllegalArgumentException(
                "Invalid number of elements : " + numberOfElements);

      if( numberOfElements > getMaxSupportedSize() )
        throw new IllegalArgumentException(
                "Number of elements out of range : " + numberOfElements);

      return Calculator.factorial(numberOfElements);
    }

    @Override
    public void fetchPermutation(Object[] elements, BigInteger ordinal) {

      for(int i=0; i<elements.length-1; i++) {

        int left = elements.length - i - 1;
        BigInteger leftCount = Calculator.factorial(left);
        int curr = ordinal.divide(leftCount).intValue();
        ordinal = ordinal.mod(leftCount);
        if( curr > 0 ) {

          Object temp = elements[curr + i];
          for(int j = curr + i; j > i; j--)
            elements[j] = elements[j - 1];
          elements[i] = temp;
        }
      }
    }
    
    private static final int MAX_SUPPORT = 1024;
  }
}

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/raistlic/article/details/7844812
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-05-11 22:42:22
  • 阅读 ( 1922 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢