The number in the database is 2, 3, 4, etc. In Java and the output of all permutations

I want to write a function in Java that takes an integer as a value and prints out every possible permutation of numbers to that integer. For instance:

F (1)

0

f (2) should output:

00 01 10 11

f (3) should output:

000 001 002 010 011 012 020 021 022 100 .... 220 221 222

That is, he must print all 27 permutations of the digits of the numbers 0, 1, 2.

f (4) should be displayed 0000 0001 0002 0003 0010 ... 3330 3331 3332 3333

f (5) should be displayed 00000 00001 ... 44443 44444

I am trying to solve this problem, but I can’t figure out how to do it, and be confused by how many cycles I need. Does anyone know how to solve this problem? Thanks in advance.

+5
source share
1

. -, .

.

, Σ ^ 5 Σ = {0, 1, 2}.

static Iterable<String> strings(final int radix, final int digits) {
  return new Iterable<String>() {

    public Iterator<String> iterator() {
      return new Iterator<String>() {

        private final String pad;
        {
          final StringBuilder buf = new StringBuilder(digits);
          for (int n = digits; n >= 0; --n) {
            buf.append('0');
          }
          pad = buf.toString();
        }

        private final int hi = (int) Math.pow(radix, digits);
        private int cursor;

        public boolean hasNext() {
          return cursor < hi;
        }

        public String next() {
          final String rsl = Integer.toString(cursor++, radix);
          return pad.substring(0, digits - rsl.length()) + rsl;
        }

        public void remove() {
          throw new UnsupportedOperationException();
        }
      };
    }
  };
}

..., :

for (final String val : strings(3, 5)) {
  System.out.println(val);
}

, [0, 3 ^ 5), 3 - 5 - , ternary. 0 00000, 3 ^ 5 100000. , , String .


, strings(n, n). , , , long BigInteger.

, Integer.toString, , ...

, Character.MIN_RADIX , Character.MAX_RADIX, 10.

Character.MIN_RADIX 2 MAX_RADIX - 36. , 10... . itoa :

    private static final char[] ALPHABET = { '0', '1', '2', '3', ... };

    public static String itoa(int value, final int radix, int width) {
      final char[] buf = new char[width];
      while (width > 0) {
        buf[--width] = ALPHABET[value % radix];
        value /= radix;
      }
      return new String(buf);
    }

(. ideone).

static Iterable<String> f(final int n) {
  return strings(n, n);
}

public static void main(final String[] argv) {
  for (int n = 1; n <= 5; ++n) {
    for (final String string : f(n)) {
      System.out.printf("%s ", string);
    }
    System.out.println();
  }
}

... :

0

00 01 10 11

000 001 002 010 011 012 020 021 022 100 101 102 110 111...

0000 0001 0002 0003 0010 0011 0012 0013 0020 0021 0022 0023 0030...

00000 00001 00002 00003 00004 00010 00011 00012 00013 00014 00020 00021 00022...

+3

All Articles