我必须提取字符“ 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使字符组合在一起,但是我不能与日子相结合,我将非常感谢您的帮助。
循环while,数组和for。
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
答案 0 :(得分: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