2

This is a Java program to generate and print all the possible "Anagrams" of a four digit number without using an array. Here is what I've been able to do so far:

import java.util.*;
class Anag {
  public static void main() {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();
    int d = n % 10;
    n = n / 10;
    int c = n % 10;
    n = n / 10;
    int b = n % 10;
    n = n / 10;
    int a = n;
    int w = a, x = b, y = c, z = d, co, i, j;
    System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
    for (i = 1; i <= 4; i++) {


      for (j = 1; j <= 3; j++) {


        if (j % 3 == 1) {
          co = w;
          w = x;
          x = co;
          System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
        }
        if (j % 3 == 2) {
          co = x;
          x = y;
          y = co;
          System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);
        }
        if (j % 3 == 0) {
          co = y;
          y = z;
          z = co;
          System.out.println(w * 1000 + x * 100 + y * 10 + z * 1);

        }

      }
    }
  }
}

Using the above code, I've been able to generate 12 "Anagrams", but I cannot figure out how to generate the remaining 12 (there should be 24 in total). Does anyone have any ideas?

Zachary Espiritu
  • 937
  • 7
  • 23
MrAP
  • 223
  • 4
  • 18
  • 2
    Just turn the number into a `String` and then [do this](http://stackoverflow.com/questions/4240080/generating-all-permutations-of-a-given-string). – azurefrog Jan 02 '16 at 21:18
  • Note that, in your current code, you're only calculating for i * j anagrams, or 4 * 3 = 12. – Zachary Espiritu Jan 03 '16 at 06:34

1 Answers1

2

The following algorithm should work for you. In short, you shiftrotate the number and for every 4 anagrams you swap first two digits, but after the 12th anagram you swap 1st and 3rd digit.

public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    int n = sc.nextInt();

    int d = n % 10;
    n = n / 10;
    int c = n % 10;
    n = n / 10;
    int b = n % 10;
    n = n / 10;
    int a = n;

    int t;
    for (int i = 0; i < 24; i++) {
        System.out.println(a * 1000 + b * 100 + c * 10 + d);
        if (i == 11) {
            t = a;
            a = c;
            c = t;
        }
        if (i % 4 == 3) {
            t = a;
            a = b;
            b = t;
        } else {
            t = a;
            a = b;
            b = c;
            c = d;
            d = t;
        }
    }
}
Kostas Kryptos
  • 4,081
  • 2
  • 23
  • 24