有没有一种快速的方法可以产生一组笛卡尔的力量?
例如,如果集合为{1,2},则{1,2} x {1,2} = {(1,1),(1,2),(2,1),(2) ,2)}。如何为任何给定的力量生成它?
谢谢。
答案 0 :(得分:1)
我想用 power ,你的意思是这个集合与自身结合的频率是多少?所以权力3将是:
{1, 2} x {1, 2} x {1, 2} = (({1, 2} x {1, 2}) x {1, 2})
所以你可以递归地解决它,组合一次,然后组合结果......
如果您愿意,可以将我的Iterator for Lists of Lists调整为List of List,并构建一个interator: import java.util。*;
class CartesianIterator <T> implements Iterator <List <T>> {
private final List <List <T>> lilio;
private int current = 0;
private final long last;
public CartesianIterator (final List <Set <T>> llo) {
// transform Set<T> to List <T>, because we need an index later
List <List <T>> llt = new ArrayList <List <T>> ();
for (Set <T> st : llo)
{
List <T> lt = new ArrayList <T> ();
for (T t: st)
lt.add (t);
llt.add (lt);
}
lilio = llt;
long product = 1L;
for (List <T> lio: lilio)
product *= lio.size ();
last = product;
}
public boolean hasNext () {
return current != last;
}
public List <T> next () {
++current;
return get (current - 1, lilio);
}
public void remove () {
++current;
}
private List<T> get (final int n, final List <List <T>> lili) {
switch (lili.size ())
{
case 0: return new ArrayList <T> (); // no break past return;
default: {
List <T> inner = lili.get (0);
List <T> lo = new ArrayList <T> ();
lo.add (inner.get (n % inner.size ()));
lo.addAll (get (n / inner.size (), lili.subList (1, lili.size ())));
return lo;
}
}
}
}
class CartesianIterable <T> implements Iterable <List <T>> {
private List <Set <T>> lilio;
public CartesianIterable (List <Set <T>> llo) {
lilio = llo;
}
public Iterator <List <T>> iterator () {
return new CartesianIterator <T> (lilio);
}
}
public class SetItTest
{
public static void main ( String [] args )
{
Set <Integer> si = new HashSet<Integer> ();
si.add (1);
si.add (2);
List <Set<Integer>> ls = new ArrayList <Set<Integer>> ();
ls.add (si);
ls.add (si);
ls.add (si);
CartesianIterable <Integer> ci = new CartesianIterable <Integer> (ls);
for (List <Integer> li : ci)
{
for (int i : li)
System.out.print (i + " ");
System.out.println ();
}
}
}
输出: java SetItTest
1 1 1
2 1 1
1 2 1
2 2 1
1 1 2
2 1 2
1 2 2
2 2 2
答案 1 :(得分:1)
如果您可以使用外部库,Guava有Sets.cartesianProduct(Set<E>...)
,那么您可以这样做:
Set<Integer> set = ImmutableSet.of(1, 2);
Set<List<Integer>> = Sets.cartesianProduct(set, set);
// returns {[1, 1], [1, 2], [2, 1], [2, 2]} as desired
(披露:我向Guava捐款。)
答案 2 :(得分:0)
这就是生成具有元素X和Y(您的情况1和2)的n长度数组。 代码如下:
1 - 第一个元素(X) 2 - 秒元素(Y) ... 等等。 然后生成长度为n的1,2,...,n的所有字符串。 例: 11,12,21,22. // n = 2 111,112,121,122,211,212,221,222 // n = 3 切换回原始元素,用实际元素替换1,2,... n。
我很确定某些库已经实现了这个功能。
答案 3 :(得分:0)
您可以尝试使用两个向量v1 = {x1 ... xn},v2 = {y1 ... yn}
public List producto(List a, List b) {
List producto = new ArrayList();
for (String s1 : a);
for (String s2 : b) {
List duo = new ArrayList();
duo.add(s1);
duo.add(s2);
producto.add(duo);
}
}
return producto;
}