本帖最后由 cat73 于 2016-8-25 08:42 编辑
[Java] 纯文本查看 复制代码 public final class Main {
public static void main(final String[] args) {
Main.traverse(ArrayUtil.box("1234".toCharArray()), 0, chars -> Log.debug(new String(ArrayUtil.unBox(chars), 1, 3)));
}
/**
* 遍历几个元素的所有可能的组合
*
* @param array 元素列表
* @param index 请传 0
* @param out 结果输出的接口
*/
public static <T> void traverse(final T[] array, final int index, final TraverseOut<T> out) {
if (index == array.length - 1) {
out.invoke(array);
} else {
for (int index2 = index; index2 < array.length; index2++) {
ArrayUtil.swap(array, index, index2);
Main.traverse(array, index + 1, out);
ArrayUtil.swap(array, index, index2);
}
}
}
/**
* 遍历结果输出的接口
*
* @author cat73
*/
@FunctionalInterface
public static interface TraverseOut<T> {
void invoke(T[] t);
}
}
- [00:00:00] [DEBUG]: 1234
- [00:00:00] [DEBUG]: 1243
- [00:00:00] [DEBUG]: 1324
- [00:00:00] [DEBUG]: 1342
- [00:00:00] [DEBUG]: 1432
- [00:00:00] [DEBUG]: 1423
- [00:00:00] [DEBUG]: 2134
- [00:00:00] [DEBUG]: 2143
- [00:00:00] [DEBUG]: 2314
- [00:00:00] [DEBUG]: 2341
- [00:00:00] [DEBUG]: 2431
- [00:00:00] [DEBUG]: 2413
- [00:00:00] [DEBUG]: 3214
- [00:00:00] [DEBUG]: 3241
- [00:00:00] [DEBUG]: 3124
- [00:00:00] [DEBUG]: 3142
- [00:00:00] [DEBUG]: 3412
- [00:00:00] [DEBUG]: 3421
- [00:00:00] [DEBUG]: 4231
- [00:00:00] [DEBUG]: 4213
- [00:00:00] [DEBUG]: 4321
- [00:00:00] [DEBUG]: 4312
- [00:00:00] [DEBUG]: 4132
- [00:00:00] [DEBUG]: 4123
复制代码
|