如何只循环一次组合? [英] How to loop through a combination only once?

查看:73
本文介绍了如何只循环一次组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历一个数组,但是遇到了这个问题. 当我遍历此数组时:

I am trying to loop through an array, however I am encountering this problem. As I loop through this array:

{1,2,3,4}

我遇到了这个问题:在开始时,我将得到1和4的组合,但是在中间位置,我将得到4和1的组合.我如何做到这一点,所以只接受唯一的关系?不能像{1,4}和{4,1}这样.

I am encountering this problem: During the start, I will get combinations of 1 and 4, however near the middle I will get a combination of 4 and 1. How can I make it so only unique relationships will be accepted? There cant be anything like {1,4} and {4,1}.

我正在使用Java,对此有一些答案,但是它们使用的语言仅是其他语言提供的.

I am using Java, there have been some answers to this however they use libraries only available in other languages.

不幸的是,我什至无法尝试解决问题.

I can't wrap my head around it to come up with even an attempt at a solution unfortunately.

这是遍历数组后的预期输出:

Here is the expected output after looping through the array:

{1, 2}
{1, 3}
{1, 4}
{2, 3}
{2, 4}
{3, 4}

但这是遍历数组时实际发生的事情:

But here is what actually happens when looping through the array:

{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),并且它们也不能相同.比较两个数字并查看它们是否相等,可以很容易地做到不相同,但是我对第一个要求有疑问.

So the two requirements is that the pair has to be a unique relationship (can't have 1,2 and 2,1) and they can't be the same either. Not being the same could easily be done by comparing the two numbers and seeing if they are equal, but I am having trouble with the first requirement.

推荐答案

更新后,我假设您正在寻找类似的东西

After your update I assume you are looking for something like this

int[] arr={1,2,3,4};
for (int i=0; i<arr.length; i++)
    for (int j=i+1; j<arr.length; j++)
        System.out.println("{"+arr[i]+","+arr[j]+"}");

输出:

{1,2}
{1,3}
{1,4}
{2,3}
{2,4}
{3,4}

这篇关于如何只循环一次组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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