首页 > 解决方案 > 如何从 char 数组生成组合?

问题描述

如何从 char 数组生成组合?这是我的代码 https://anotepad.com/notes/icjsc5ct 我有一个包含 5 个字符的数组:a、b、c、d、e 我想生成 3 个字符的组合

  1. [a,b,c];
  2. [a, b, d];
  3. [b、c、d];
  4. [b、c、e];
  5. [c, d, e]

我的代码只能生成 3 个字符的 2 个组合:

  1. [a,b,c];
  2. [a, b, d];

我不知道如何增加 Array[0] 和 Array[1] 的索引;

public ArrayList< char[] > generate02( int r ) {

    ArrayList< char[] > combinationsList = new ArrayList<>();
    char[] data = new char[ r ];
    // initialize with lowest lexicographic combination
    for ( int i = 0; i < r; i++ ) {
        data[ i ] = CharArray01[ i ];
    }
    PrintData( CharArray01 );
    int n = CharArray01.length;
    while ( IndexInt( data[ r - 1 ] ) < n - 1 ) {
        int t01 = r - 1;
        System.out.println( " IndexInt( data[ r - 1 ] ) < n " );
        System.out.println( " data[ r - 1 ] ) = " + data[ t01 ]
                + ";  IndexInt( data[ r - 1 ] ) = "
                + IndexInt( data[ r - 1 ] )
                + ";  n = " + n );
        combinationsList.add( data.clone() );
        // generate next combination in lexicographic order
        int t02 = n - r + t01;
        while ( t01 != 0 && IndexInt( data[ t01 ] ) == t02 ) {
            t01--;
        }
        int k1 = IndexInt( data[ r - 1 ] );
        int k2 = k1 + 1;
        data[ r - 1 ] = IndexChar( k2 );
        System.out.println( " data[ r - 1 ] ) = " + data[ t01 ]
                + ";  IndexInt( data[ r - 1 ] ) = "
                + IndexInt( data[ r - 1 ] ) );
        System.out.println( "t01 = " + t01 + ";  n = " + n );
        int i = 0;
        for ( i = t01 + 1; i < r; i++ ) {
            int index02 = IndexInt( data[ i - 1 ] );
            int index03 = index02 + 1;
            data[ i ] = data[ index03 ];
        }
    }
    return combinationsList;
}
```

标签: javaalgorithmcharcombinations

解决方案


如果它是您正在寻找的解决方案/示例,我可以向您推荐我创建的 API,以便以内存有效的方式生成对象组合:https ://github.com/3venthorizo​​n/meta/blob/master/meta -mathics/src/main/java/com/devlambda/meta/mathics/CombinationGenerator.java

@Test
public void charComboTest() {
   List<Character> domain = Arrays.asList('a', 'b', 'c', 'd', 'e');
   CombinationGenerator<Character> combinations = new CombinationGenerator<>(domain, 3);
   while (combinations.hasNext()) {
      List<Character> combination = combinations.next();
      System.out.println(combination.stream().map(Object::toString)
            .collect(Collectors.joining(", ", "[", "]")));
   }
}

这将打印出以下结果:

[a, b, c]
[a, b, d]
[a, b, e]
[a, c, d]
[a, c, e]
[a, d, e]
[b, c, d]
[b, c, e]
[b, d, e]
[c, d, e]

推荐阅读