gpt4 book ai didi

java - 动态 'for-loop' 结构

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:23:33 25 4
gpt4 key购买 nike

我无法理解以下内容,假设我有一个列表,每个列表都包含一个“将是”for 循环。每个继承都应该在彼此之内。

所以如果我有一个包含 3 个对象的列表,我想要

class Focus {
String focus;
List<String> values;

public Focus(String focus, String... values) {
this.focus = focus;
this.values = Lists.newArrayList(values);
}
}

List<Focus> focuses = new ArrayList<Focus>();
focuses.add(new Focus("Focus 1", "09", "14", "13", "12"));
focuses.add(new Focus("Focus 2", "94", "92"));
focuses.add(new Focus("Focus 3", "A", "B"));

String my_string = "";
for (Focus obj1 : list_obj_x) {
for (Focus obj2 : list_obj_xx) {
for (Focus obj3 : list_obj_xxx) {
my_string += obj1 + " " + obj2 + " " + obj3;
}
}
}

显然,对于列表,for 循环结构可以增长,而上述情况是不可能的。我需要一个动态结构来满足 my_string 的需要。即:

94    09    A
94 14 A
94 13 A
94 12 A
94 09 B
94 14 B
94 13 B
94 12 B
92 09 A
92 14 A
92 13 A
92 12 A
92 09 B
92 14 B
92 13 B
92 12 B

输出应该像上面那样。这是我到目前为止所拥有的:

int focusCount = focuses.size();
for (int i = (focusCount - 1); i >= 0; i--) {
Focus currentFocus = focuses.get(i);
List<String> currentFocusValues = currentFocus.values;

for (int cfv = 0; cfv < currentFocusValues.size(); cfv++) {
String currentFocusValue = currentFocusValues.get(cfv);

for (int j = (i - 1); j >= 0; j--) {
Focus previousFocus = focuses.get(j);
List<String> previousFocusValues = previousFocus.values;

for (int pfv = 0; pfv < previousFocusValues.size(); pfv++) {
String previousFocusValue = previousFocusValues.get(pfv);
System.out.println(currentFocusValue + " " + previousFocusValue);
}
}
}
}

它满足列表值的所有组合,但不是我想要的结构。

有人可以帮帮我吗?

最佳答案

最直接的方法可能是递归。在递归的每一步中,您一个一个地“确定”第 n 个列表的值,然后向下递归“列表的列表”直到到达末尾。

String[] values = new String[focuses.size()];
CreateCombinations(focuses, 0, values);

用递归的方法

private void CreateCombinations(List<Focus> focuses, int index, string[] values) {
Focus focus = focuses.get(index);
for (string v : focus.values) {
values[index] = v;
if (index < focuses.size() - 1) {
// there is at least one other focus
CreateCombinations(focuses, index+1, values);
} else {
// all values pinned down
StringBuilder sb = new StringBuilder(values[0]);
for (int i = 1; i < values.length; ++i) {
sb.append(" ").append(values[i]);
}
// now do whatever you like to do with sb.toString()...
}
}
}

当然,这可以进一步细化,但也许它足以作为您的起点。

关于java - 动态 'for-loop' 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9129116/

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