I want to write a function in Java that takes as input an integer and outputs every possible permutation of numbers up to that integer. For example:
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 it should output all 27 permutations of the digits of the numbers 0, 1, 2.
f(4) should output
0000 0001 0002 0003 0010 … 3330 3331 3332 3333
f(5) should output
00000 00001 … 44443 44444
I have been trying to solve this problem but cannot seem to work out how to do it and keep getting confused by how many loops I need. Does anyone know how to solve this problem? Thanks in advance.
Just count and convert. I wrote something should help in an earlier answer here.
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 uselongor evenBigInteger.Also, since it relies on
Integer.toString, make sure you remember the following caveat…You can see the value for
Character.MIN_RADIXis2andMAX_RADIXis36. If you use a radix outside of this range, it will default to10… you will need to write your own conversion with a custom extended character set for digits. The general form of such anitoafunction is as follows:Below is a working example for your usage (see result on ideone).
… which produces: