簡體   English   中英

如何從字符數組生成組合?

[英]How to generate combinations from char array?

如何從字符數組生成組合? 我在算法方面很弱,這是我的代碼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]

我的代碼只能生成 2 個 3 個字符的組合:

  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;
}

如果它是您正在尋找的解決方案/示例,我可以向您推薦我創建的 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]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM