Generate all possible array combinations in C - Optimal Graph Colouring

随声附和 提交于 2019-12-08 09:29:23

问题


I need to generate arrays with all possible combinations, like this question I've found here:

Combinatorics: generate all "states" - array combinations

I'm doing a simple work of optimal Graph Coloring, so, I'm trying to generate all possible color combinations (the array represents the color for each node). This code is working but, is also doing unnecessary work. In this situation, [1, 1, 2] is the same thing of [2, 2, 1], I don't need to test if this is a valid graph again.

I can't think of anything, but first I would like to know if there's a simple code for doing what I want to.

For now, my code is something like this:

void generatearray(int array[], int array_size, int idx){

    int i;

    if(idx == array_size){
        putchar('\n');
        for(i = 0; i < array_size; i++) printf("%i ", array[i]);

    }
    else for(i = 0; i <= 3; i++){
        array[idx] = i;
        generatearray(array, array_size, idx+1);
    }

}

And it will print:

    [0, 0, 0]
    [0, 0, 1]
    [0, 0, 2]
    [0, 0, 3]
    [0, 1, 0]
    [0, 1, 1]
    ...
    [3, 3, 0]
    [3, 3, 1]
    [3, 3, 2]
    [3, 3, 3]

回答1:


Try this:

void generatearray( int array[], int array_size, int idx = 0, int fixed = 0 )
{
   int i;

   if ( idx == array_size )
   {
       putchar('\n');
       for( i = 0; i < array_size; i++ ) printf( "%i ", array[i] );

   } else {

       for( i = 0; i <= 3; i++ )
       {
          if ( fixed == i )
          {
             fixed++;
             array[idx] = i;
             return generatearray( array, array_size, idx + 1, fixed );
          }
          array[idx] = i;
          generatearray( array, array_size, idx + 1, fixed );
       }
   }
}

int arr[6];
generatearray( arr, 6 );

Old broken answer:

void generatearray(int array[], int array_size, int idx){

   int i;

   if(idx == array_size){
       putchar('\n');
       for(i = 0; i < array_size; i++) printf("%i ", array[i]);

   }
   else if ( idx == 0 ) {
       array[idx] = 0;
       generatearray(array, array_size, idx+1);
   } else {
       for(i = 0; i <= 3; i++){
       array[idx] = i;
       generatearray(array, array_size, idx+1);
       }

   }
}


来源:https://stackoverflow.com/questions/16444084/generate-all-possible-array-combinations-in-c-optimal-graph-colouring

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!