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 ([email protected])
 *
 * 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 ([email protected])
 *
 * 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 ([email protected])
 *
 * 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 ([email protected])
 *
 * 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 ([email protected])
 *
 * 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;
  }
}

發佈了27 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章