Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * [permat.c]
- * Gera permutacoes de um vetor e as salva
- * numa matriz.
- *
- * [Autor]
- * Marcos Paulo Ferreira (Daemonio)
- * undefinido gmail com
- * http://daemoniolabs.wordpress.com
- *
- * Seg Set 26 19:41:16 BRT 2011
- */
- #include <stdio.h>
- #include <stdlib.h>
- /* Funcao que retorna verdadeiro se
- * `num' nao contem algarismos repetidos
- * e zero caso contrario. */
- char eh_sem_repeticao(int *num, int r) {
- int i, j ;
- for(i=0; i < r; i++) {
- for(j=0; j < r && i != j; j++) {
- if(num[i] == num[j]) {
- return 0;
- }
- }
- }
- return 1 ;
- }
- int main(int argc, char **argv) {
- int *num ;
- int n ;
- int i, j ;
- int vetor[121][5] ;
- int index_matriz ;
- /* Valores que serao permutados. Adicionei
- * eles diretamente para economizar linhas
- * de codigo.*/
- vetor[0][0] = 1 ;
- vetor[0][1] = 7 ;
- vetor[0][2] = 8 ;
- vetor[0][3] = 2 ;
- vetor[0][4] = 3 ;
- /* tamanho da entrada. */
- n = 5 ;
- /* Aloca espaco para o vetor num. Lembre-se
- * que o vetor `num' representa um numero
- * na base n com n algarismos. */
- num = (int *)calloc(n+1, sizeof(int)) ;
- if ( num == NULL ) {
- perror("malloc") ;
- return -1;
- }
- /* Indice da permutacao na matriz. A primeira
- * permutacao tem indice 1, pois o indice 0
- * eh usado para armazenar a entrada. */
- index_matriz = 1 ;
- /* Inicio do algoritmo. */
- while ( num[n] == 0 ) {
- for(i=0; i < n; i++) {
- /* Copia permutacoes sem repeticao
- * para o vetor[][] */
- if ( eh_sem_repeticao(num, n) ) {
- for(j=0; j < n; j++) {
- vetor[index_matriz][j] = vetor[0][num[j]] ;
- }
- /* Incrementa o indice da permutacao. */
- index_matriz++ ;
- }
- /* incrementa o algarismo menos
- * significativo. */
- num[0]++ ;
- }
- /* distribui os vai-uns. */
- for(i=0; i < n; i++) {
- if(num[i] == n) {
- num[i] = 0;
- num[i+1]++ ;
- }
- }
- }
- /* Mostra as pemutacoes na tela. */
- for(i=1; i < index_matriz; i++) {
- for(j=0; j < 5; j++) {
- printf("%d ", vetor[i][j]) ;
- }
- putchar('\n') ;
- }
- free(num) ;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement