【问题标题】:Java: Combination of elements in array in couplesJava:数组中元素的组合
【发布时间】:2014-01-14 23:37:27
【问题描述】:

我有一个元素数组(偶数),我想将它们的所有可能组合成对。

如果数组是

String[] test = new String[4]; 
String[] test= {"e1","e2","e3","e4"};

输出应该是:

Combination1 e1-e2 , e3-e4
Combination2 e1-e3 , e2-e4
Combination3 e1-e4 , e2-e3
Combination4 e4-e1 , e3-e2
Combination5 e3-e1 , e4-e2
Combination6 e2-e1 , e4-e3

【问题讨论】:

  • 请展示你的尝试?
  • 如果您在组合之后,那么e1-e2e2-e1 的组合相同,并且应该只有 3 个结果输出。如果你在排列之后,那么它们就不一样了,应该有 24 个结果输出(e1-e2,e3-e4e1-e2,e4-e3e2-e1,e3-e4e2-e1,e4-e3 等)。你追求的是排列还是组合?
  • 我尝试了不同的“for”循环,但没有任何效果(我是初学者)。我显然正在寻找排列,对误解感到抱歉。输出应该和我在问题中写的一样。
  • 编辑(应该是 12 而不是 24):如果你在排列之后 [...] 应该有 12 个结果输出(e1-e2,e3-e4e1-e2,e4-e3e2-e1,e3-e4,@987654332 @等)。

标签: java arrays combinations


【解决方案1】:

Link to previous answer


String[] test = {"e1","e2","e3","e4"};

for (int i = 0; i < test.length; i++) {

    for (int j = i + 1; j < test.length; j++) {

        System.out.print(test[i] + " - " + test[j]);

        boolean foundExtra = false;

        for (int k = 0; k < test.length && !foundExtra; k++)
        {
            if (k != j && k != i)
            {
                for (int l = 0; l < test.length; l++)
                {
                    if (l != k && l != j && l != i)
                    {
                        System.out.println(" , " + test[k] + " - " + test[l]);
                        foundExtra = true;
                        break;
                    }
                }
            }
        }
    }
}

会给出输出:

e1 - e2 , e3 - e4
e1 - e3 , e2 - e4
e1 - e4 , e2 - e3
e2 - e3 , e1 - e4
e2 - e4 , e1 - e3
e3 - e4 , e1 - e2

这不是您在问题中提出的输出,但从您的运动队评论来看,我相信这是您想要的输出。

不要害怕循环 - 我一次尝试了这个,因为我认为它很容易扔掉。

我在想什么:找到所有组合,就像我之前的答案一样。我就是这样开始的。接下来我做的事情(4 个循环中的最后 2 个 - kl)是检查剩下的 other 团队。

所以循环遍历所有元素,检查 ij 是否尚未使用,然后是 k。然后,再次循环遍历所有元素,检查 ijk 是否尚未使用,则为 l

【讨论】:

  • 谢谢,这与我尝试排除 i!=j 检查的方法几乎相同。现在的问题是如何在不重复元素的情况下将它们分组。
  • 我的意思是重复排列组中的元素。就像在您的输出中,排列 1 只能与排列 5 或排列 8 分组。这就像一场体育锦标赛,每组 2 个排列代表每支球队必须与另一支球队一起比赛的一轮。输出必须显示所有轮次。 (每支球队在主场和客场比赛两次,因此显然是排列而不是组合)
  • @user3189770 哦,好吧,我现在明白了。我会试试的。
  • 您先生是真正的 MVP。非常感谢
【解决方案2】:

写两个for循环:

for (int i =0; i < test.length; i++) {
    for (int j = i + 1; j < test.length; j++) {
       // code to print a[i] - a[j]
    }
 }

【讨论】:

    【解决方案3】:

    这应该适用于任何偶数个元素的数组(并且是通用的,因此也适用于字符串以外的其他东西):

    import java.lang.reflect.Array;
    import java.util.ArrayList;
    import java.util.LinkedList;
    
    public class Q2112634 {
    
        public static class Pair<X> {
            final X first;
            final X second;
    
            public Pair( final X one, final X two){
                first = one;
                second = two;
            }
    
            public String toString(){
                return first.toString() + "-" + second.toString(); 
            }
    
            public String toReverseString(){
                return second.toString() + "-" + first.toString(); 
            }
        }
    
        @SuppressWarnings("unchecked")
        public static <X> void getCombinations( final ArrayList<Pair<X>[]> combinations, final LinkedList<Pair<X>> pairs, final LinkedList<X> list ) {
    //      System.out.println(list.size());
            final X first = list.removeFirst();
            for ( int i = 0; i < list.size(); ++i ) {
                final X second = list.remove( i );
                final Pair<X> p = new Pair<X>( first, second );
                pairs.addLast( p );
                if ( list.size() == 0 )
                {
                    combinations.add( pairs.toArray( (Pair[]) Array.newInstance( p.getClass(), pairs.size() ) ) );
                }
                else
                {
                    getCombinations( combinations, pairs, list );
                }
                list.add( i, second );
                pairs.removeLast();
            }
            list.addFirst( first );
        }
    
        static <E> String arrayToString( E[] arr ) {
            if ( arr.length == 0 )
                return "";
            final StringBuffer str = new StringBuffer();
            str.append( arr[0].toString() );
            for ( int i = 1; i < arr.length; ++i )
            {
                str.append( ',' );
                str.append( arr[i].toString() );
            }
            return str.toString();
        }
    
        public static void main(String[] args) {
            String[] test = { "e1", "e2", "e3", "e4" };
    
            int num_combinations = 1;
            for ( int i = test.length - 1; i > 1; i = i - 2 )
                num_combinations *= i;
    
            final ArrayList<Pair<String>[]> combinations = new ArrayList<Pair<String>[]>( num_combinations );
            final LinkedList<String> strings = new LinkedList<String>();
            for ( String s : test )
                strings.add( s );
    
            getCombinations( combinations, new LinkedList<Pair<String>>(), strings );
    
            System.out.println( "-----Combinations-----" );
            int i = 1;
            for ( Pair<String>[] combination: combinations ){
                System.out.println( "Combination " + (i++) + " " + arrayToString( combination ) );
            }
    
            System.out.println( "-----Permutations-----" );
            i = 1;
            for ( Pair<String>[] combination: combinations ){
                for ( int j = 0; j < Math.pow( 2, combination.length ); ++j )
                {
                    System.out.print( "Permutation " + (i++) + " " );
                    for ( int k = 0; k < combination.length; ++k )
                    {
                        if ( k > 0 )
                            System.out.print(',');
                        if ( (j & ( (int) Math.pow( 2, k ) ) ) == 0 )
                            System.out.print( combination[k].toString() );
                        else
                            System.out.print( combination[k].toReverseString() );
                    }
                    System.out.println();
                }
            }
        }
    }
    

    输出

    -----Combinations-----
    Combination 1 e1-e2,e3-e4
    Combination 2 e1-e3,e2-e4
    Combination 3 e1-e4,e2-e3
    -----Permutations-----
    Permutation 1 e1-e2,e3-e4
    Permutation 2 e2-e1,e3-e4
    Permutation 3 e1-e2,e4-e3
    Permutation 4 e2-e1,e4-e3
    Permutation 5 e1-e3,e2-e4
    Permutation 6 e3-e1,e2-e4
    Permutation 7 e1-e3,e4-e2
    Permutation 8 e3-e1,e4-e2
    Permutation 9 e1-e4,e2-e3
    Permutation 10 e4-e1,e2-e3
    Permutation 11 e1-e4,e3-e2
    Permutation 12 e4-e1,e3-e2
    

    【讨论】:

      【解决方案4】:

      试试这个:

      String[] test= {"e1","e2","e3","e4"};
      int count=1;
      for(int i=0; i<test.length/2; i++)
          for(int k=0, j=0; k<test.length; k++,j++) {
              if(i==k) k++; if(j==i+test.length/2) j++;
              System.out.print("Permutatation "+count+": ");
              System.out.println(test[i]+"-"+test[k]+", "+test[i+test.length/2]+"-"+test[j]);
              count++;
          }
      

      输出:

      Permutatation 1: e1-e2, e3-e1
      Permutatation 2: e1-e3, e3-e2
      Permutatation 3: e1-e4, e3-e4
      Permutatation 4: e2-e1, e4-e1
      Permutatation 5: e2-e3, e4-e2
      Permutatation 6: e2-e4, e4-e3
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-09-22
        • 1970-01-01
        • 2013-05-15
        • 2021-12-02
        • 1970-01-01
        • 1970-01-01
        • 2017-08-24
        • 1970-01-01
        相关资源
        最近更新 更多