Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * [permnorep2.c]
- * Gera permutacoes de tamanho n de um vetor
- * preenchido usando a entrada padrao.
- *
- * [Autor]
- * Marcos Paulo Ferreira (Daemonio)
- * undefinido gmail com
- * http://daemoniolabs.wordpress.com
- *
- *
- * Seg Set 26 08:03:02 BRT 2011
- */
- #include <stdio.h>
- #include <stdlib.h>
- /* Quantidade maxima de elementos. */
- #define MAX_E 30
- /* Tamanho maximo de cada elemento. */
- #define MAX_S 100
- /* 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) {
- /* vetor que representara cada permutacao. */
- int *num ;
- /* quantidade de elementos do vetor. */
- int n ;
- /* controle de loop. */
- int i, j ;
- /* Cria o vetor com MAX_E posicoes. */
- char vetor[MAX_E][MAX_S] ;
- /* Entrar com os elementos. */
- for(i=0; i < MAX_E; i++ ) {
- printf("Digite o elemento %d (fim para terminar): ", i+1) ;
- /* Leitura com scanf para facilitar.
- * Aconselho usar fgets para propositos gerais. */
- scanf("%s", &vetor[i]) ;
- if ( ! strcmp(vetor[i], "fim") ) {
- break ;
- }
- }
- /* Tamanho da entrada. */
- n = i ;
- if ( n == 0 ) {
- printf("n deve ser maior que zero.\n") ;
- return -1 ;
- }
- /* 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;
- }
- /* Inicio do algoritmo. */
- while ( num[n] == 0 ) {
- for(i=0; i < n; i++) {
- /* Mostra a permutacao na tela se
- * e somente se `num' nao contem
- * algarismos repetidos. */
- if ( eh_sem_repeticao(num, n) ) {
- for(j=0; j < n; j++) {
- printf("%s ", vetor[num[j]]) ;
- }
- putchar('\n') ;
- }
- /* 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]++ ;
- }
- }
- }
- free(num) ;
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement