場景描述:
我有個測試同僚,要測試一個接口,這個接口有多個參數,而且有的參數取值有多個.
比如參數method,可以取值["a","b","c"],并且個數不确定,即method,可以取值ab,也可是是abc
如何擷取排列組合的所有值呢?
之前咱們是求排列組合的取值個數,現在要求取值
首先我們考慮正常的情況:
我們有n個盒子,分别放置n個元素
第一回:我們從n個裡面選擇一個:有n種可能
第二回:我們從n-1個裡面選擇一個:有n-1種可能
第三回:我們從n-2個裡面選擇一個:有n-2種可能
第四回:我們從n-3個裡面選擇一個:有n-3種可能
……
最後我們隻有一個可選

直接上代碼:直接上代碼:
/***
* @param base :[a,b,c,d]
* @param times
* @param remaining : 剩餘要選擇的個數
* @return
*/
public static void assemble(list<string> result, stringbuffer buffer, string base[], int times, int remaining, boolean issort) {
if (remaining <= 1) {
buffer.append(base[base.length - 1]);
if(times==0||times==base.length-remaining+1){
addelementbysort(result, buffer, issort);
}
} else {
for (int i = 0; i < remaining; i++) {
stringbuffer buffertmp = new stringbuffer(buffer);
buffertmp.append(base[base.length - 1 - i]);
if(times==0||times==base.length-remaining+1){
addelementbysort(result, buffertmp, issort);
}
assemble(result, buffertmp, systemhwutil.aheadelement(base, base.length - 1 - i), times, remaining - 1, issort);
}
}
參數說明:
參數名 含義 舉例
base
樣本
[a,b,c,d]
remaining
剩餘可選擇的樣本個數
times
組合的個數
工具類完整代碼:
package com.common.util;
import com.string.widget.util.valuewidget;
import java.util.arraylist;
import java.util.list;
/**
* created by huangweii on 2016/1/23.
*/
public class assembleutil {
/***
* @param base :[a,b,c,d]
* @param times
* @param remaining : 剩餘要選擇的個數
* @return
*/
public static void assemble(list<string> result, stringbuffer buffer, string base[], int times, int remaining, boolean issort) {
if (remaining <= 1) {
buffer.append(base[base.length - 1]);
if(times==0||times==base.length-remaining+1){
addelementbysort(result, buffer, issort);
}
} else {
for (int i = 0; i < remaining; i++) {
stringbuffer buffertmp = new stringbuffer(buffer);
buffertmp.append(base[base.length - 1 - i]);
if(times==0||times==base.length-remaining+1){
addelementbysort(result, buffertmp, issort);
}
assemble(result, buffertmp, systemhwutil.aheadelement(base, base.length - 1 - i), times, remaining - 1, issort);
}
}
* @param base
* @param issort : 是否對"acb"進行排序,<br />排序結果:"abc"
public static list<string> assemble(string base[], int times, boolean issort) {
// set<string> result = new hashset<string>();
list<string> result = new arraylist<string>();
assembleutil.assemble(result, new stringbuffer(), base, times, base.length, true);
return result;
public static void addelementbysort(list<string> result, stringbuffer buffer, boolean issort) {
string str = buffer.tostring();
if (issort) {
str = valuewidget.sortstr(str);
if (result.size() == 0 || (!result.contains(str))) {
result.add(str);
* 參數的取值個數,ab和ba算一種
*
* @param argcount
public static int getassemblesum(int argcount) {
int sum = 0;
for (int i = 0; i < argcount; i++) {
int count = i + 1;//參數組合的個數
sum += (systemhwutil.factorial(argcount, count) / systemhwutil.arrayarrange(count));
return sum;
}