最近,我在我的一个项目组中遇到了一个要求,我需要从不同类型的变量创建集合。这是一个例子: 我有一个(比如说)字符串列表,其中每个字符串都与一个类型相关联。所以列表有:[var11:Type1,var12:Type1,var21:Type2,var31:Type3,var32:Type3,var33:Type3]。
现在,我想创建一个函数:
public List<String> getSetsWithTypes(String[] types) {
// Iterate through types and create sets
}
所以,如果我用以下方法调用该函数:
1. types = {&#34; Type1&#34;,&#34; Type2&#34;},必须返回:
["var11:var21", "var12:var21"]
2。 types = {&#34; Type1&#34;,&#34; Type3&#34;},必须返回:
["var11:var31", "var11:var32", "var11:var33", "var12:var31", "var12:var32", "var12:var33"]
3。 types = {&#34; Type1&#34;,&#34; Type2&#34;,&#34; Type3&#34;},必须返回:
["var11:var21:var31", "var11:var21:var32", "var11:var21:var33", "var12:var21:var31"...and so on]
这些类型本质上是动态的,也是变量的数量 任何帮助都表示赞赏,并提前感谢。
答案 0 :(得分:0)
所以,我找到了解决这个问题的方法。这是解释: 例如,我们有:
Types : Type1 | Type 2 | Type 3 | Type 4 |
Number of vars : 2 | 3 | 1 | 2 |
Toggle rate : 6 | 2 | 2 | 1 |
切换率T(i)= N(i + 1)* N(i + 2)* ... * N(n),在我们的例子中n = 4且N(i)=类型的vars数岛
/* Assumptions: Each type has it's own column, so variable index
at column 4 will always be for Type 4.
*/
int currentColumn = numberOfTypes.length;
while (--currentColumn > -1) {
// For each currentCol calculate combination
// numberOfVariablesAtCurrentCol = typeSize[colPointer]
// if there are more than 1 variables of certain type
if (typeSize[currentColumn] > 1) {
// Toggle rate is the integer value after which the var index would change for any column
final int toggleRate = findToggleRate(params, currentColumn);
int currentTogglePos = 1, varIndex = 0;
for (int currentRow = 0; currentRow < rows; currentRow++) {
variableCombination[currentRow][currentColumn] = varIndex;
// Reset currentTogglePos, if needed
if (++currentTogglePos > toggleRate) {
currentTogglePos = 1;
// Reset varIndex, if required, only at toggle boundary
if (++varIndex >= typeSize[currentColumn])
varIndex = 0;
}
}
}
}
所以,我最终得到的是:
Types : Type1 | Type 2 | Type 3 | Type 4 |
Number of vars : 2 | 3 | 1 | 2 |
Toggle rate : 6 | 2 | 2 | 1 |
---------------------------------------------------
VariableIndex : 0 0 0 0
Every col gives: 0 0 0 1
it's type : 0 1 0 0
0 1 0 1
0 2 0 0
0 2 0 1
1 0 0 0
1 0 0 1
1 1 0 0
1 1 0 1
1 2 0 0
1 2 0 1
嗯,这是我能想到的唯一方法。如果有更有效的方式,请建议。