user2199158
user2199158

Reputation: 33

Incrementing values in array backwards

I want go through all combinations of values in array by incrementing it backwards.
So let's have an array

    int array[10] = {0,0,0,0,0,0,0,0,0,0};

I want to increment it this way: {0,0,0,0,0,0,0,0,0,1} > {0,0,0,0,0,0,0,0,0,2}...{p-1,p-1,p-1,p-1,p-1,p-1,p-1,p-1,p-1,p-1}.

For examples smaller array, p=3 : {0,0,0}>{0,0,1}>{0,0,2}>{0,1,0}>{0,1,1}>{0,1,2}...{2,2,2}

Array can be sizeof(int)*m big, where 1<=m<=10.

Can someone help me out with algorithm for that?

EDIT: Sorry, forgot about this..
Ok sorry for confusion but I have one more condition..

That array won't be in that form. It will be something like this example

    int array[10] = {0,0,0,0,0,0,0,0,0,0};
    int help[10] = {3,4,0,1,0,0,3,0,1,0};

and i want to get combination of values in array[help[]!=0], in this case array[0],array[1],array[3],array[6],array[8] so ->

    int array[10] = {0,0,0,0,0,0,0,0,0,0};
    int array[10] = {0,0,0,0,0,0,0,0,1,0};
    int array[10] = {0,0,0,0,0,0,0,0,2,0};
    int array[10] = {0,0,0,0,0,0,1,0,0,0};
    int array[10] = {0,0,0,0,0,0,1,0,1,0};
    int array[10] = {2,2,0,2,0,0,2,0,2,0};     

p=3
Something like that for() cycle will go i=0,1,3,6,8, where the values are i=help[i]!=0.

Upvotes: 0

Views: 166

Answers (3)

Valeri Atamaniouk
Valeri Atamaniouk

Reputation: 5163

Here is an example:

void increment(int array[], size_t size, int limit)
{
     do
     {
         if (++array[--size] != limit)
         {
             break;
         }
         array[size] = 0; // value overflow
     }
     while (size);
}

Usage:

int array[10];
memset(array, 0, sizeof(array));

increment(array, 10, 3);

Edit: algorithm with filter

void increment(int array[], int filter[], size_t size, int limit)
{
     do
     {
         if (!filter[--size])
         {
             // skip this position
             continue;
         }
         if (++array[size] != limit)
         {
             break;
         }
         array[size] = 0; // value overflow
     }
     while (size);
}

Upvotes: 2

K Scott Piel
K Scott Piel

Reputation: 4380

I see that the question has changed a bit, from incrementing an array backwards to adding one to a base(n) number... that's a different problem.

int base = 3;

for( int i = (sizeof( array ) / sizeof( array[0] ))-1; i >= 0; )
{
    if( ++array[i] < base )
        break;
    else
        array[i--] = 0;
}

Upvotes: 1

Charles Bretana
Charles Bretana

Reputation: 146499

this is equivalent to simply incrementing through the natural numbers, from 0 to (p+1) ^ arrayLength, in base p+1.

so for your example,

for (long i=0; i<4^10; i++)
{
   convert i to string in base (p+1), left- padding with 0s
   convert characters in string to comma separated array format and print 
}

Upvotes: 0

Related Questions