Question

Let v = {x: x in {-1,0,1}} such that the dimension of|v| = 9

Every element x in vector v can take 3 possible values -1,0 or 1

How can I generate all the possible combinations of vector v ?


Example: v = {1,0,-1,0,0,1,1,1,0}, v = {-1,0,-1,1,0,0,1,1,0} etc...

Will i have 3^9 combinations?

thank you.

Was it helpful?

Solution

If you are using python, you can simply do that:

import itertools
v = itertools.product([-1,0,1], repeat=9)
# v will be a generator
# to have the whole list as tuples
list_v = list(v)

# Verify the number of combination
print len(list(v))

And it gives you: 19683, or 3^9

OTHER TIPS

The idea is this:

Your have a position for each element of v (9 in your case):

- - - - - - - - -

Each position can hold three different values (-1 | 0 | 1) and then the total number of combinations is equal to 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 * 3 = 3^9.

To generate such combinations only simulate this process, for example with for loops, e.g. for three positions:

values[] = {-1, 0, 1};
for (i = 0; i < 3; i++)
    for (j = 0; j < 3; j++)
        for (k = 0; k < 3; k++)
            print values[i], values[j], values[k]

In your case you need nine nested loops! An easier implementation will involve recursion but its sometimes more complicated to understand. Here is the idea anyway:

values[] = {-1, 0, 1};
void generate(int position)
{
    if (position == 0) {
        println();
        return;
    }

    for (int i = 0; i < 3; i++) {
        print(values[i], ", ");
        generate(position - 1);
    }
}

// call the function with
generate(9);

This another answer explains a little more how a recursive generator works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top