如何只通过一次组合?
我试图循环一个数组,但我遇到了这个问题。 当我遍历这个数组时:
{1,2,3,4}
我遇到了这个问题:在开始时,我会得到1和4的组合,但是在中间附近我会得到4和1的组合。我怎样才能这样做,所以只接受独特的关系? 不能有{1,4}和{4,1}之类的东西。
我正在使用Java,但是它们有一些答案,但它们只使用其他语言版本的库。
不幸的是,我无法绕过它来想出解决方案。
这是循环遍历数组后的预期输出:
{1, 2} {1, 3} {1, 4} {2, 3} {2, 4} {3, 4}
但这是循环遍历数组时实际发生的事情:
{1, 1} {1, 2} {1, 3} {1, 4} {2, 1} {2, 2} {2, 3} {2, 4} {3, 1} {3, 2} {3, 3} {3, 4} {4, 1} {4, 2} {4, 3} {4, 4}
因此,两个要求是该对必须是一个独特的关系(不能有1,2和2,1),它们也不能相同。 通过比较两个数字并查看它们是否相等可以很容易地完成不一样的工作,但我遇到了第一个要求的问题。
更新后,我假设你正在寻找这样的东西
int[] arr={1,2,3,4}; for (int i=0; i
输出:
{1,2} {1,3} {1,4} {2,3} {2,4} {3,4}
如果您试图从第一组和第二组中找到所有可能的无序对,那么只需执行以下操作:
List pairs = new ArrayList (); for (int i : set1) { for (int j : set2) { pairs.add(new Pair(i, j)); } }
通常你循环遍历两个数组,如下所示:
for (int element1 : array1) { for (int element2 : array2) { ..... } }
public static void main(String[] args) { int[] array1 = new int[] {1,2,3,4}; int[] array2 = new int[] {5,6,7,8}; String[] result = new String[array1.length * array2.length]; int count = 0; for (int i : array1) { for (int j : array2) { result[count++] = "{" + i + ", " + j + "}"; } } for (String str : result) { System.out.println(str); } }
如果要避免重复对,请在外循环中的当前位置开始内循环。
for(int i = 0; i < array1.length; i++) { for(int j = i + 1; j < array2.length; j++) { //do stuff } }
您希望将一对对象视为可比较,然后创建一组对。 请注意,使用此解决方案,您需要将数组存储为对象(例如Integer)而不是基元(例如int)。 检查将原始long的数组转换为Longs列表以获取更多信息。
public class MyPair > implements Comparable> { public A first; //You may want to make these private and implement getters, setters, etc public A second; public MyPair(A f, A s) { first = f; second = s; } public int compareTo(MyPair o) { int cmp = first.compareTo(o.first); if(cmp == 0) cmp = second.compareTo(o.second); return cmp; } public String toString() { return "{"+first+","+second+"}"; } } public static void main(String[] args) { Integer[] x = new Integer[]{1,2,3,4}; Integer[] y = new Integer[]{5,6,7,8}; Set > mypairs = new HashSet >(); for(Integer f : x) { for(Integer s : y) { MyPair tmp = new MyPair (f,s); mypairs.add(tmp); } } for(MyPair pair : mypairs) { println(pair); } }