首页 > 编程语言 > 详细

java 字符数字组合算法

时间:2014-11-14 02:10:57      阅读:280      评论:0      收藏:0      [点我收藏+]

从指定集合中获取元素组合成不同的字符串.

?

  • 组合生成类(Combination.java)

?

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

?

/**

?*?

?* @author hymanz 506600909@qq.com

?*

?*/

public class Combination {

?

? ? private char[] base;

?

? ? public Combination(char[] base) {

? ? ? ? this.base = base;

? ? }

?

? ? public List<char[]> getCombinations(int length) {

?

? ? ? ? List<char[]> list = new ArrayList<char[]>();

? ? ? ? list.add(new char[length]);

?

? ? ? ? return compose(0, list);

? ? }

?

? ? private List<char[]> compose(int index, List<char[]> list) {

?

? ? ? ? if (index >= list.get(0).length) {

? ? ? ? ? ? return list;

? ? ? ? }

?

? ? ? ? for (int i = 0, size = list.size(); i < size; i++) {

? ? ? ? ? ? char[] item = list.get(i);

? ? ? ? ? ? for (int j = 0; j < base.length; j++) {

? ? ? ? ? ? ? ? if (j > 0) {

? ? ? ? ? ? ? ? ? ? item = copy(item);

? ? ? ? ? ? ? ? ? ? list.add(item);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? item[index] = base[j];

? ? ? ? ? ? }

? ? ? ? }

?

? ? ? ? return compose(++index, list);

? ? }

?

? ? private char[] copy(char[] item) {

? ? ? ? return Arrays.copyOf(item, item.length);

? ? }

?

}

?

  • 调用方式?

public class Main {

? ? public static void main(String[] args) {

? ? ? ??char[] base = {‘0‘, ‘1‘, ‘2‘, ‘3‘, ‘4‘, ‘5‘, ‘6‘, ‘7‘, ‘8‘, ‘9‘};

? ? ? ??

? ? ? ? Combination combination = new Combination(base);

? ? ? ? List<char[]> result = combination.getCombinations(3);

? ? ? ??

? ? ? ? for (char[] cs : result) {

? ? ? ? ? ? System.out.println( new String(cs));

? ? ? ? }

? ? }

}

?

?

?

?

java 字符数字组合算法

原文:http://piaohai.iteye.com/blog/2155724

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!