user2161721
user2161721

Reputation: 164

How to generate combinations obtained by permuting 2 positions in Java

I have this problem, I need to generate from a given permutation not all combinations, but just those obtained after permuting 2 positions and without repetition. It's called the region of the a given permutation, for example given 1234 I want to generate :

2134

3214

4231

1324

1432

1243

the size of the region of any given permutation is , n(n-1)/2 , in this case it's 6 combinations .

Now, I have this programme , he does a little too much then what I want, he generates all 24 possible combinations :

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


}

the Question is how can I fix this programme to turn it into a programme that generates only the combinations wanted .

Upvotes: 0

Views: 212

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533500

How about something simple like

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

Upvotes: 1

Related Questions