将所有可能的角色与一周中的几天结合起来

问题描述 投票:0回答:1

我必须提取字符“A,B,C,D,E,F,G”的所有组合,然后将其与一周中的几天组合,以便结果为:

Monday AB
Tuesday AC
Wednesday AD
Thursday AE
Friday AF
Saturday AG
Monday BA
Tuesday BC
Wednesday BD
....

Logrea使角色组合但我无法与日子结合,我将非常感谢帮助。

循环,阵列和。

public class daysP {

    public static void main(String[] args) 
    {
        String[] elements = "A,B,C,D,E,F,G".split(",");
        int r = elements.length; 
        combination(elements, "",2, r);
    }

    private static void combina(String[] elem, String act, int n, int r) {
        String[] di=new String[5];
        days[0]="Monday";
        days[1]="Tuesday ";
        days[2]="Wednesday";
        days[3]="Thursday";
        days[4]="Friday";
        days[5]="Saturday";

        if (n == 0) {            
            for (int x=0;x<7;)
            {   
                System.out.println(days[x]+act);x++;
            }
        } 
        else {
            for (int i = 0; i < r; i++) {
                if (!act.contains(elem[i]))
                    combina(elem, act + elem[i] + "", n - 1, r);
            }
        }
    }
}

预期的结果是:

Monday AB
Tuesday AC
Wednesday AD
Thursday AE
Friday AF
Saturday AG
Monday BA
Tuesday BC
Wednesday BD
..............

直到GF,这将是最后的组合

实际结果是:

MondayAB
Tuesday AB
java arrays string combinations permutation
1个回答
2
投票

我们可以用双循环生成这个输出。下面的逻辑是我们对第一个和最后一个字母使用单独的索引,以及打印的星期几。我们使用counter变量的mod来确定哪一天被打印出来,所以这个计数器会在你定义的一周中的六天中包围。

String[] days = new String[6];
days[0] = "Monday";
days[1] = "Tuesday";
days[2] = "Wednesday";
days[3] = "Thursday";
days[4] = "Friday";
days[5] = "Saturday";
int NUM_CHARS = 7;

int counter = 0;

for (int i=0; i < NUM_CHARS; ++i) {
    String first = Character.toString((char)(i + 65));
    for (int j=0; j < NUM_CHARS; ++j) {
        if (i == j) continue;
        String second = Character.toString((char)(j + 65));
        String day = days[counter % days.length];
        ++counter;

        System.out.println(day + " " + first + second);
    }
}

Monday AB
Tuesday AC
Wednesday AD
Thursday AE
Friday AF
Saturday AG
Monday BA
Tuesday BC
Wednesday BD
...
Thursday GD
Friday GE
Saturday GF
© www.soinside.com 2019 - 2024. All rights reserved.