我有一个字符串列表列表[每个元素都在括号中],需要获取字符串列表,每个字符串表示每个列表中一个元素的元素组合。需要获得所有组合
[+9, +4, +a]
[+i*o -k*z +(m+n+f+5)][+i*o +(m+n+f+5) -k*z][+(m+n+f+5) +i*o -k*z]
[+h*i/o +6*l/8]
[+b/c/r +(a*b*x*y+1)][+(a*b*x*y+1)+b/c/r]
需要获得
[+9, +4, +a][+i*o -k*z +(m+n+f+5)][+h*i/o +6*l/8][+b/c/r +(a*b*x*y+1)]
[+9, +4, +a][+i*o -k*z +(m+n+f+5)][+h*i/o +6*l/8][+(a*b*x*y+1)+b/c/r]
[+9, +4, +a][+i*o +(m+n+f+5) -k*z][+h*i/o +6*l/8][+b/c/r +(a*b*x*y+1)]
[+9, +4, +a][+i*o +(m+n+f+5) -k*z][+h*i/o +6*l/8][+(a*b*x*y+1)+b/c/r]
[+9, +4, +a][+(m+n+f+5) +i*o -k*z][+h*i/o +6*l/8][+b/c/r +(a*b*x*y+1)]
[+9, +4, +a][+(m+n+f+5) +i*o -k*z][+h*i/o +6*l/8][+(a*b*x*y+1)+b/c/r]
任何帮助表示赞赏 感谢
答案 0 :(得分:2)
使用番石榴Sets.cartesianProduct
:
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import java.util.List;
import java.util.Set;
public class Foo {
public static void main(String[] args)
{
final Set<String> s1 = ImmutableSet.of("[+9, +4, +a]");
final Set<String> s2 = ImmutableSet.of("[+i*o -k*z +(m+n+f+5)]","[+i*o +(m+n+f+5) -k*z]","[+(m+n+f+5) +i*o -k*z]");
final Set<String> s3 = ImmutableSet.of("[+h*i/o +6*l/8]");
final Set<String> s4 = ImmutableSet.of("[+b/c/r +(a*b*x*y+1)]","[+(a*b*x*y+1)+b/c/r]");
@SuppressWarnings("unchecked")
final Set<List<String>> cartesianProducts = Sets.cartesianProduct(s1, s2, s3, s4);
for (final List<String> cartesianProduct : cartesianProducts) {
System.out.println(Joiner.on("").join(cartesianProduct));
}
}
}
输出:
[+9, +4, +a][+i*o -k*z +(m+n+f+5)][+h*i/o +6*l/8][+b/c/r +(a*b*x*y+1)]
[+9, +4, +a][+i*o +(m+n+f+5) -k*z][+h*i/o +6*l/8][+b/c/r +(a*b*x*y+1)]
[+9, +4, +a][+(m+n+f+5) +i*o -k*z][+h*i/o +6*l/8][+b/c/r +(a*b*x*y+1)]
[+9, +4, +a][+i*o -k*z +(m+n+f+5)][+h*i/o +6*l/8][+(a*b*x*y+1)+b/c/r]
[+9, +4, +a][+i*o +(m+n+f+5) -k*z][+h*i/o +6*l/8][+(a*b*x*y+1)+b/c/r]
[+9, +4, +a][+(m+n+f+5) +i*o -k*z][+h*i/o +6*l/8][+(a*b*x*y+1)+b/c/r]
答案 1 :(得分:0)
我将如何做到这一点。这是未经测试的。
List<List<Object>> lists = ...;
int max = combinationCount(lists);
for (int i = 0; i < max; ++i)
{
System.out.println(combination(lists, i));
}
使用:
public static int combinationCount(List<List> l)
{
int r = 1;
for (List i : l) r *= i.size();
return r;
}
和
public static List combination(List<List> l, int index)
{
List r = new ArrayList(l.size());
for (int i = 0; i < l.size(); ++i)
{
List k = l.get(i);
int m = index % k.size();
index /= k.size();
r.add(k.get(m));
}
return r;
}