要求实现如下功能:
从a,b,c,d,e,f...字母中抽取任意3个字符,进行组合的算法。
比如:abc,abd,abe,abf,abg...bac,bad,bad,...类似的。要求有代码实现,谢谢,分不够再加。
从a,b,c,d,e,f...字母中抽取任意3个字符,进行组合的算法。
比如:abc,abd,abe,abf,abg...bac,bad,bad,...类似的。要求有代码实现,谢谢,分不够再加。
调试欢乐多
public class Sample {
char[] myChar = {
'a','b','c','d','e','f','g','h'
}; public void getResult(){
int count = 0; for(int i = 0; i<myChar.length; i++){
//first, add the head
StringBuffer buf = new StringBuffer();
buf.append(myChar[i]);
for(int j = 0; j < myChar.length; j++){
if(i != j){
//add the body
buf.append(myChar[j]);
for(int m = 0; m < myChar.length; m ++){
if(j != m && i != m){
//add the tail
buf.append(myChar[m]);
System.out.println(buf.toString());
count ++;
buf.deleteCharAt(2);
}
}
buf = new StringBuffer();
buf.append(myChar[i]);
}
} }
System.out.println("count = " + count);
} public static void main(String[] args) {
Sample s = new Sample();
s.getResult();
}
}原理很简单
把三个字母看做head,body,tail穷举一遍
这么做也行,只是最好能够按照递归的那种模式来搞。比如我可以随意设置取2个或者3个以及4个数,然后进行相互组合。
http://community.csdn.net/Expert/topic/4485/4485767.xml?temp=.5464899
class Combine {
public final static String[] CHARACHTER = {"a", "b", "c", "d", "e", "f"}; //so on
publoc final int AMOUNT = CHARACHTER.length;
public static ArrayList combine(int num, ArrayList sList) {
ArrayList ssList = new ArrayList();
String str;
if (sList == null) {
//do nothing
}
else if (num < 1) {
//do nothing
} else {
if (sList.size() == 0) {
for (int i=0; i<AMOUNT; i++) {
ssList.add(CHARACHTER[i]);
}
} else {
for (int i=0; i<AMOUNT; i++) {
for (int j=0; j<sList.size(); j++) {
str = String.valueOf(sList.get(j));
if (str.indexOf(CHARACHTER[i]) < 0) {
ssList.add(str+CHARACHTER[i]);
}
}
}
}
ssList = combine(num-1, ssList);
}
return ssList;
}
public static void main(String[] args) {
ArrayList result = combine(AMOUNT, new ArrayList());
for (int i=0; i<result.size; i++) {
System.out.println(result.get(i));
}
}
}
public class orderTest {
//单个字符串的长度
private static int loop = 4;
//整个字符串
private static String loopStr = "abcd";
//结果集
private static ArrayList loopResult = new ArrayList();
public static void main(String[] args){
//初始化
for(int i = 0; i < loopStr.length(); i++){
loopResult.add(loopStr.substring(i,i + 1));
}
//获得结果集
for(int i = 1; i < loop; i++){
loopMethod(i);
}
//测试结果集
int row = loopStr.length();
int col = loopResult.size()/loopStr.length();
for(int i = 0; i < row; i++){
for(int j = 0; j < col; j++){
System.out.print(loopResult.get(i * col + j) + " ");
}
System.out.println();
}
}
private static void loopMethod(int row){
ArrayList alResult = new ArrayList();
for(int i = 0; i < loopResult.size(); i++){
//未包含字符
String strParam = loopStr;
String strResult = (String)loopResult.get(i);
//去掉已存在的字符
for(int k = 0; k < strResult.length(); k++){
strParam = strParam.replaceAll(strResult.substring(k,k + 1),"");
}
//在末尾顺序追加未包含的字符,并加到结果集中
for(int j = 0; j < loopStr.length() - row; j++){
alResult.add(((String)loopResult.get(i))+strParam.substring(j,j + 1));
}
}
loopResult = alResult;
}
}
俺也写了一个,大家看看,测试过了