0

Let's say we have a vector of length 4, where every element can be a number from 0 to 9. For example: <1, 8, 0, 3>

Instead of simply looping over all 10^4 possible vectors, I want to loop in an specific order. So I want to start from <0, 0, 0, 0>, go to <1, 0, 0, 0>, then:

<2, 0, 0, 0>, <3, 0, 0, 0>, ..., <9, 0, 0, 0>, <0, 1, 0, 0>

and so on (notice the order in the last two). I cannot think of a way to write this for variable vector length.

Let's say we are in the ith iteration, having the ith vector in the lexicographic order I mentioned above. Having the ith vector is necessary for doing some process in the (i+1)th vector. This scheme saves compute over randomly looping over all possible vectors.

I haven't really found a non-brute force and memory efficient way to solve this problem. Specially considering that I should be able to support variable vector lengths and different ranges of numbers for entries.

Vicarious
  • 131
  • 18
  • 1
    The problem is not clear. Can you please be a little more specific? Can you post some code if you have it? Like code of a few real vectors of those you would like to work on. – Jeremy Then May 15 '19 at 20:24
  • @JeremyThen I don't have any codes. But the vectors I mentioned in the question are the exact ones I want to work on. The only difference is for vector length and the base that can be a number other than 10. – Vicarious May 15 '19 at 20:36

1 Answers1

1

So in this case you can think of each element as a number in base 10. The i'th element is i in base 10 with the digits arranged in reverse order. For instance:

int[] indexToElement(int index, int base) {
    String string = Integer.toString(index, base);
    int[] element = new int[string.length()];

    for (int i = 0; i < string.length(); ++i) {
        element[i] = Character.digit(string.charAt(string.length() - i - 1), base);
    }

    return element;
}
jspcal
  • 50,847
  • 7
  • 72
  • 76