java - 如何在Java中生成通过排列2个位置获得的组合

标签 java combinations permutation

我有这个问题,我需要从给定的排列生成不是所有组合,而是仅生成排列 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);
 }

关于java - 如何在Java中生成通过排列2个位置获得的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16245963/

相关文章:

python - 在不将可迭代(itertools.combinations)转换为列表的情况下改组组合

javascript - 在 Javascript 中查找重复对象或数组的更有效解决方案?

c++ - 计算排列的逆下降

python - 给定 N 项列表,如何生成长度为 LEN 的排列?

java - 使用 modInverse 计算大数的 C(n, k) 组合

java - Maven/Spring 私有(private)存储库设置

java - 安卓 : Sting returning with null pointer exception

java - 覆盖默认接口(interface)方法

java - Spring Boot 。使用@ConfigurationProperties注解的好处

mysql - 在 MySQL 中插入时检查和防止相似的字符串