( 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