I'm trying to write a program which takes as arguments a number of digits and a base, and counts upward through the numbers that have their nonzero digits in ascending order. For instance, in base 4 with 3 digits, it should print:
000 001 002 003 010 011 012 013 020 022 023 030 033 100 101 102 103 110 111 112 113 120 122 123 130 133 200 202 203 220 222 223 230 233 300 303 330 333
and in base 3 with 4 digits it should print:
0000 0001 0002 0010 0011 0012 0020 0022 0100 0101 0102 0110 0111 0112 0120 0122 0200 0202 0220 0222 1000 1001 1002 1010 1011 1012 1020 1022 1100 1101 1102 1110 1111 1112 1120 1122 1200 1202 1220 1222 2000 2002 2020 2022 2200 2202 2220 2222
I have done this successfully, but my algorithm seems unnecessarily complicated and time-consuming (time is very important for my application). Is there any way of either making it faster, or simplifying it if the speed cannot be improved?
Here is the program:
public static void count(int base, int size)
{
int[] array = new int[size];
print(array); // private print method prints out the array
int index = 0;
while (index < array.length)
{
if (array[index] < base - 1)
{
// check whether we need to increase array[index] by extra to maintain the order
if (array[index] == 0)
{
int i;
// search for the next nonzero digit
// this search seems to take unnecessary time; is there a faster alternative?
for (i = index + 1; i < array.length && array[i] == 0; i++);
// check whether there was, in fact, some later nonzero digit
if (i < array.length) array[index] = array[i];
else array[index] = 1;
}
else array[index]++;
print(array);
index = 0;
}
// carry over to the next digit
else array[index++] = 0;
}
}
counts upward through the numbers that have their nonzero digits in descending order
mean. - Qian Chen