在Java中动态生成2个列表的非重复排列对 [英] Generating non duplicate permutation pairs of 2 lists in Java on the fly

查看:193
本文介绍了在Java中动态生成2个列表的非重复排列对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在看很多关于Java排列的不同帖子,但是没有一个符合我的账单,所以我决定发帖。

I've been looking at a lot of different posts about permutations in Java, but none of them did fit my bill so I decided to post.

所以我有2 列表<整数> ,我需要生成所有排列对 没有重复,其中一个元素是pair在第一个列表中,第二个在第二个列表中。

So I have 2 List<Integer>, and I need to generate all permutation pairs with no duplicates where one element of the pair is in the first list and the second one in the second list.

例如,如果我有:

List<Integer> l1 = Arrays.asList(new Integer[] {1, 2, 3});
List<Integer> l1 = Arrays.asList(new Integer[] {2, 3, 4});

然后我想输出:

(1, 2), (1, 3), (1, 4), (2, 2), (2, 3), (2, 4), (3, 3), (3, 4)

注意(3,2)不在这里,因为我已经拥有( 2,3,

Note that (3, 2) is not here since I already have (2, 3)

我找不到任何库甚至远程关闭,我发现 guava Permutations 有类似的东西,但它似乎最近已经停产或其他什么。

I couldn't find any library to do something even remotely close, I found that guava had something similar with Permutations but it seems to have been discontinued recently or something.

另外,我想不必将列表存储在内存中,因为它可能非常大,我只需要一次迭代一对,所以我试图找到生成它们的方法即时。我正在考虑实现 Iterable< Pair> 但我似乎无法编写看起来效率高的东西。

Also, I would like to not have to store the list in memory as it can be quite large, I only need to iterate on the pairs one at a time, so I'm trying to find ways to generate them on the fly. I was thinking to implement an Iterable<Pair> but I can't seem to be able to write anything that looks efficient.

如果你知道那些已经做过这种非常有用的东西的图书馆了!

If you know libraries that already do this kind of stuff that would be very helpful as well !

推荐答案

怎么样

class Pair {
    private int x, y;

    Pair(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override public int hashCode() {
        int result = 1;
        result = 31 * result + x;
        result = 31 * result + y;
        return result;
    }

    @Override public boolean equals(Object obj) {
        if (this == obj)              return true;
        if (!(obj instanceof Pair))   return false;
        Pair tmp = (Pair) obj;
        return (tmp.x == x && tmp.y == y) || (tmp.x == y && tmp.y == x);
    }

    public String toString() {
        return "(" + x + "," + y + ")";
    }
}

class Testt {
    public static void main(String[] args) {
        List<Integer> l1 = Arrays.asList( 1, 2, 3 );
        List<Integer> l2 = Arrays.asList( 2, 3, 4 );

        Set<Pair> set = new HashSet<Pair>();
        for (int i : l1)
            for (int j : l2)
                set.add(new Pair(i, j));

        System.out.println(set);
    }
}

输出

[(1,2), (1,3), (1,4), (2,2), (2,3), (2,4), (3,3), (3,4)]

这篇关于在Java中动态生成2个列表的非重复排列对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆