2 つの整数のみを格納するクラスがあります。
public class Item
{
private int from;
private int to;
public Item(int from, int to)
{
this.from = from;
this.to = to;
}
getters and setters
}
実行時に、これらのアイテムのリストを作成します。リストには 1 ~ 21 個の値が含まれます。次に、これらの値をループして、何らかの処理を行う必要があります。例えば:
public void validate()
{
List<Item> items = new ArrayList<Item>();
items.add(new Item(1,3));
items.add(new Item(11,13));
}
または:
public void validate()
{
List<Item> items = new ArrayList<Item>();
items.add(new Item(1,3));
items.add(new Item(11,13));
items.add(new Item(21,23));
}
次に、これらの値をループする必要があります。ループするレベル数がわからないので、ループをハードコードすることはできません。できれば、ループは次のようになります。
public void loop()
{
String str;
for(int i = 1; i < 3; i++)
{
str = "-" + i;
for(int j = 11; j < 13; j++)
{
str = str + "-" + j;
do stuff with str;
}
}
}
ここでテストする必要がある出力は次のようになります。
-1-11
-1-12
-1-13
-2-11
-2-12
-2-13
-3-11
-3-12
-3-13
2 番目の例は次のようになります。
public void loop()
{
String str;
for(int i = 1; i < 3; i++)
{
str = "-" + i;
for(int j = 11; j < 13; j++)
{
str = str + "-" + j;
for(k = 21; k < 32; k++)
{
str = str + "-" + k;
do stuff with str;
}
}
}
}
ここでテストする必要がある出力は次のようになります。
-1-11-21
-1-11-22
-1-11-23
-1-12-21
-1-12-22
...
-2-11-21
-2-11-22
...
-3 -13-21
ループがいくつあるかわからないので、再帰を使用する必要があると思います。しかし、再帰の内側のループで「str を使って何かをする」方法がわかりません。それは不可能だと思い始めています。
これは私がここで試していることのようなものです:
private void recursiveExplore(List<Item> items, int depth)
{
if (depth == 0) return;
for (Item item : items)
{
for (int i = item.getFromParameterId(); i < item.getToParameterId(); i++)
{
do stuff here?
}
recursiveExplore(items.subList(items.size() - depth, items.size()), depth - 1);
}
}
public void validate()
{
recursiveExplore(items, items.size());
}
どんな助けでも感謝します。
ETA SSCCE:
import java.util.ArrayList;
import java.util.List;
public class MyTest
{
private class Item
{
private int from;
private int to;
public Item(int from, int to)
{
this.from = from;
this.to = to;
}
public int getFrom()
{
return from;
}
public int getTo()
{
return to;
}
}
public void validate2()
{
List<Item> items = new ArrayList<Item>();
items.add(new Item(1, 3));
items.add(new Item(11, 13));
String str;
for (int i = items.get(0).getFrom(); i <= items.get(0).getTo(); i++)
{
for (int j = items.get(1).getFrom(); j <= items.get(1).getTo(); j++)
{
str = "-" + i + "-" + j;
System.out.println(str);
}
}
}
public void validate3()
{
List<Item> items = new ArrayList<Item>();
items.add(new Item(1, 3));
items.add(new Item(11, 13));
items.add(new Item(21, 23));
String str;
for (int i = items.get(0).getFrom(); i <= items.get(0).getTo(); i++)
{
for (int j = items.get(1).getFrom(); j <= items.get(1).getTo(); j++)
{
for (int k = items.get(2).getFrom(); k <= items.get(2).getTo(); k++)
{
str = "-" + i + "-" + j + "-" + k;
System.out.println(str);
}
}
}
}
public static void main(String[] args)
{
MyTest test = new MyTest();
test.validate2();
test.validate3();
}
}