gpt4 book ai didi

java - 将所有可能的字符与星期几组合起来

转载 作者:行者123 更新时间:2023-12-02 01:33:43 28 4
gpt4 key购买 nike

我必须提取字符“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

最佳答案

我们可以使用双循环生成此输出。下面的逻辑是我们对第一个和最后一个字母以及打印的星期几使用单独的索引。我们使用 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

关于java - 将所有可能的字符与星期几组合起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55566787/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com