java中的一般循环生成所有可能的字符串

时间:2015-10-30 20:45:30

标签: java

我很难自己创建一些通用for循环(我的代码在java中)。想象一下,我有 M 个字符串的arraylists,每个arraylist s_i 都有 x_i 成员。我想生成所有可能的字符串,使得字符串的第一部分来自第一组,字符串的第二部分来自第二组,并且......

例如,下面有3个列表(在编程时未知):

|s_0| = x_0 = 3: [a1, a2, a3]

|s_1| = x_1 = 5: [b1, b2, b3, b4, b5]

|s_2| = x_2 = 2: [c1, c2]

我想生成这些字符串(顺序并不重要):

字符串:["a1 b1 c1", "a1 b1 c2", "a1 b2 c1", ...., "a3 b5 c2"]

1 个答案:

答案 0 :(得分:1)

You can use Guava Sets. For example this will give all combinations AAA, AAB,...,CCC.

final Set<String> set = new HashSet<>();
set.add("A");
set.add("B");
set.add("C");
final Set<List<String>> sets = Sets.cartesianProduct(set, set, set);

In your case you will have to pass s_0, s_1, s_2 for the parameters.