如何根据键值生成数组值的组合
我正在从文件输入以下内容。字符串索引键和值数组
SL [1,3]
SW [5,7]
PL [11,12]
PW [16]
我正在尝试生成以下组合键和值
例如(关键):
(SL,SW) : < 1,5 > < 1,7 > < 3,5 > < 3,7 >
(SL,PL): < 1,11 > < 1,12 > < 3,11 > < 3,12 >
(SL,PW): < 1,16 > < 3,16 >
(SW,PL): < 5,11 > < 5,12 > < 7,11 > < 7,12 >
(SW,PW): < 5,16 > < 7,16 >
(PL,PW): < 11,16 > < 12,16 >
Consider combination of three attributes:
(SL,SW,PL): < 1,5,11 > < 1,5,12 > < 1,7,11 > < 1,7,12 > < 3,5,11 > < 3,5,12 > < 3,7,11 > < 3,7,12 >
(SL,SW,PW): < 1,5,16 > < 1,7,16 > < 3,5,16 > < 3,7,16 >
(SL,PL,PW): < 1,11,16 > < 1,12,16 > < 3,11,16 > < 3,12,16 >
(SW,PL,PW): < 5,11,16 > < 5,12,16 > < 7,11,16 > < 7,12,16 >
到目前为止我只能为按键创建组合。但是包括SL SL也是我不需要的,而且我还需要获得我之前提到的值的组合。
public void GenCombinations(String[] str_arr) {
for (int i = 0; i < str_arr.length; i++) {
System.out.print(str_arr[i] + " ");
}
/*COMBINATIONS OF LENGTH ONE*/
for (int i = 0; i < str_arr.length; i++) {
System.out.println(str_arr[i]);
}
/*COMBINATIONS OF LENGTH TWO*/
for (int i = 0; i < str_arr.length; i++) {
for (int j = 0; j < str_arr.length; j++) {
System.out.println(str_arr[i] + " " + str_arr[j]);
}
}
/*COMBINATIONS OF LENGTH THREE*/
for (int i = 0; i < str_arr.length; i++) {
for (int j = 0; j < str_arr.length; j++) {
for (int k = 0; k < str_arr.length; k++) {
System.out.println(str_arr[i] + " " + str_arr[j] + " " + str_arr[k]);
}
}
}
}
当前输出
SL
SW
PL
PW
SL SL
SL SW
SL PL
SL PW
.
.
.
如何达到所需的输出以获得值的组合以及键组合?
请建议。
答案 0 :(得分:0)
您可以检查索引:
for(int i = 0; i < str_arr.length; i++) {
for(int j = 0; j < str_arr.length; j++) {
if (i != j) {
System.out.println(str_arr[i] + " " + str_arr[j]);
}
}
}
,或者进行字符串比较:
for(int i = 0; i < str_arr.length; i++) {
for(int j = 0; j < str_arr.length; j++) {
if (!str_arr[i].equals(str_arr[j]) {
System.out.println(str_arr[i] + " " + str_arr[j]);
}
}
}
答案 1 :(得分:0)
如何初始化j = i+1
和k = j+1
?
public void GenCombinations(String[] str_arr){
/*COMBINATIONS OF LENGTH TWO*/
for(int i=0;i<str_arr.length;i++)
{
for(int j=i+1;j<str_arr.length;j++)
{
System.out.println(str_arr[i]+" "+str_arr[j]);
}
}
/*COMBINATIONS OF LENGTH THREE*/
for(int i=0;i<str_arr.length;i++)
{
for(int j=i+1;j<str_arr.length;j++)
{
for(int k=j+1;k<str_arr.length;k++)
{
System.out.println(str_arr[i]+" "+str_arr[j]+" "+str_arr[k]);
}
}
}
}
编辑:如果要生成所有组合,可能需要递归执行
private static void GenCombinations(String[] head, String[] tail, int headIndex, int tailIndex) {
if (headIndex == head.length) {
System.out.println(Arrays.toString(head));
return;
}
if (tailIndex >= tail.length)
return;
// Either take tail[tailIndex] to head[headIndex]
head[headIndex] = tail[tailIndex];
GenCombinations(head, tail, headIndex+1, tailIndex+1);
// Or don't take it, and try the next element to put in head[headIndex]
GenCombinations(head, tail, headIndex, tailIndex+1);
}
private static void GenCombinations(String[] str_arr, int num) {
GenCombinations(new String[num], str_arr, 0, 0);
}
private static void GenCombinations(String[] str_arr) {
for (int i = 1; i <= str_arr.length; i++)
GenCombinations(str_arr, i);
}