Advertisement
daemonio

Untitled

Oct 9th, 2015
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.09 KB | None | 0 0
  1. /*
  2.  * [combr2.c]
  3.  * Programa que gera combinações de tamanho r de
  4.  * números em um vetor fixo.
  5.  *
  6.  * [Uso]
  7.  * $ gcc -o combr2 combr2.c
  8.  * $ ./combr2
  9.  *   3    <-- digite o r
  10.  *
  11.  * Fri Oct  9 08:13:23 BRT 2015
  12.  */
  13.  
  14. #include <stdio.h>
  15. #include <string.h>
  16.  
  17. /* Tamanho máximo da entrada */
  18. #define MAX_INPUT 31
  19.  
  20. int main() {
  21.     unsigned MAX, MASK, NUM ;
  22.     int i, j, r, k ;
  23.  
  24.     /* Coloque aqui seus números. MAXIMO=31 numeros. */
  25.     int input[]={
  26.         6, 14, 22, 4, 77, 99, 6, 33,
  27.         11, 34, 56, 78, 90,
  28.         NULL};
  29.  
  30.     int str[MAX_INPUT] ;
  31.  
  32.     int l = 0;
  33.     for(i=0; input[i]!=NULL;i++) l++;
  34.  
  35.     printf("Digite o r: ") ;
  36.     scanf("%d", &r) ;
  37.  
  38.     /* Manda o bit 1 para a n-ésima posição.
  39.      * Os bits são invertidos para que a posição n
  40.      * esteja com o bit zero, a fim de marcar
  41.      * o final do processo.
  42.      */
  43.     MAX = ~(1 << l) ;
  44.  
  45.     /* Primeiro número é o 1. */
  46.     NUM = 1;
  47.  
  48.     putchar('\n') ;
  49.  
  50.     /* Quando o número alcançar MAX, o loop
  51.      * será encerrado.
  52.      */
  53.     while ( MAX & NUM ) {
  54.         /* Conta os bits 1's. */
  55.         MASK = 1 ;
  56.         k = 0 ;
  57.         while ( MAX & MASK ) {
  58.             if ( NUM & MASK ) k++ ;
  59.             MASK = MASK << 1 ;
  60.         }
  61.  
  62.         /* Monta o resultado somente se
  63.          * a quantidade de bits k é igual
  64.          * a r. */
  65.         if ( k == r ) {
  66.             MASK = 1 ;
  67.             i = j = 0 ;
  68.  
  69.             while ( MAX & MASK ) {
  70.                 /* Verdadeiro se NUM tem um bit 1
  71.                  * na posição indicada por MASK. */
  72.                 if ( NUM & MASK ) {
  73.                     /* Gera a combinação em str */
  74.                     str[i] = input[j] ;
  75.                     i++ ;
  76.                 }
  77.                 j++ ;
  78.                 /* Desloca a máscara */
  79.                 MASK = MASK << 1 ;
  80.             }
  81.             /* As combinações estão no vetor[]. Aqui mostramos cada
  82.              * elemento como número */
  83.             for(l=0;l<i;l++)printf("%d ", str[l]); putchar('\n') ;
  84.         }
  85.  
  86.         NUM++ ;
  87.     }
  88.  
  89.     return 0;
  90. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement