Just count and convert. I wrote something should help in an earlier answer here.
This should be a relatively easy problem to solve.
Essentially, you're merely computing the set of strings Σ^5 where Σ = { 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();
}
};
}
};
}
... which can be used as follows:
for (final String val : strings(3, 5)) {
System.out.println(val);
}
Basically, we generate the numbers in the interval [0, 3^5), where 3 is our radix and 5 our desired string length, and then convert the numbers into ternary form. 0 becomes 00000, 3^5 becomes 100000. You must also take care to not use too large a radix, otherwise the resulting String
will contain bad characters.
The solution here is to merely call strings(n, n)
. Note that, depending on how large your radix or desired digit lengths are, you may wish to instead use long
or even BigInteger
.
Also, since it relies on Integer.toString
, make sure you remember the following caveat...
If the radix is smaller than Character.MIN_RADIX
or larger than Character.MAX_RADIX
, then the radix 10
is used instead.
You can see the value for Character.MIN_RADIX
is 2
and MAX_RADIX
is 36
. If you use a radix outside of this range, it will default to 10
... you will need to write your own conversion with a custom extended character set for digits. The general form of such an itoa
function is as follows:
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);
}
Below is a working example for your usage (see result on 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();
}
}
... which produces:
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 ...