簡體   English   中英

如何生成通過置換Java中的2個位置獲得的組合

[英]How to generate combinations obtained by permuting 2 positions in Java

我有這個問題,我需要從給定的排列中生成所有組合,而不是生成所有組合,而只是生成排列2個位置且沒有重復的組合。 這稱為給定排列的區域,例如給定的1234,我想生成:

2134

3214

4231

1324

1432

1243

任何給定排列的區域的大小為n(n-1)/ 2,在這種情況下為6個組合。

現在,我有了這個程序,他做的比我想要的要多,他生成所有24種可能的組合:

public class PossibleCombinations {


    public static void main(String[] args) {

        Scanner s=new Scanner(System.in);
        System.out.println("Entrer a mumber");
       int n=s.nextInt();

        int[] currentab = new int[n];
        // fill in the table 1 TO N 
        for (int i = 1; i <= n; i++) {
            currentab[i - 1] = i;
        }

        int total = 0;

        for (;;) {
            total++;

            boolean[] used = new boolean[n + 1];
            Arrays.fill(used, true);

            for (int i = 0; i < n; i++) {
                System.out.print(currentab[i] + " ");
            }

            System.out.println();

            used[currentab[n - 1]] = false;

            int pos = -1;
            for (int i = n - 2; i >= 0; i--) {              
                used[currentab[i]] = false;

                if (currentab[i] < currentab[i + 1]) {
                    pos = i;
                    break;
                }
            }

            if (pos == -1) {
                break;
            }               

            for (int i = currentab[pos] + 1; i <= n; i++) {
                if (!used[i]) {
                    currentab[pos] = i;
                    used[i] = true;
                    break;
                }
            }

            for (int i = 1; i <= n; i++) {
                if (!used[i]) {
                    currentab[++pos] = i;
                }
            }
        }

        System.out.println(total);
    }       


}

問題是如何解決該程序,使其變成僅生成所需組合的程序。

簡單的東西怎么樣

public static void printSwapTwo(int n) {
    int count = 0;
    StringBuilder sb = new StringBuilder();
    for(int i = 0; i < n - 1;i++)
       for(int j = i + 1; j < n; j++) {
          // gives all the pairs of i and j without repeats 
          sb.setLength(0);
          for(int k = 1; k <= n; k++) sb.append(k);
          char tmp = sb.charAt(i);
          sb.setCharAt(i, sb.charAt(j));
          sb.setCharAt(j, tmp);
          System.out.println(sb);
          count++;
       }
    System.out.println("total=" + count+" and should be " + n * (n - 1) / 2);
 }

暫無
暫無

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

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