int main(void) { int i, j, pid; int segmento1, segmento2, segmento3, *p; int **mat1, **mat2, **mat3; segmento1 = alocaMatriz(MAT_WIDTH, MAT_HEIGHT); segmento2 = alocaMatriz(MAT_WIDTH, MAT_HEIGHT); segmento3 = alocaMatriz(MAT_WIDTH, MAT_HEIGHT); mat1 = (int * *) shmat(segmento1, 0, 0); preencheMatriz(mat1, MAT_WIDTH, MAT_HEIGHT); mat2 = (int * *) shmat(segmento2, 0, 0); preencheMatriz(mat2, MAT_WIDTH, MAT_HEIGHT); mat3 = (int * *) shmat(segmento3, 0, 0); printf("Matriz 1: \n"); imprimeMatriz(mat1, MAT_WIDTH, MAT_HEIGHT); printf("\nMatriz 2: \n"); imprimeMatriz(mat2, MAT_WIDTH, MAT_HEIGHT); for(i = 0; i < MAT_HEIGHT; i++) { pid = fork(); if(pid == 0) { for(j = 0; j < MAT_WIDTH; j++) { mat3[i][j] = mat1[i][j] + mat2[i][j]; } exit(0); } waitpid(-1, NULL, 0); } printf("\nMatriz 3: \n"); imprimeMatriz(mat3, MAT_WIDTH, MAT_HEIGHT); shmdt(mat1); shmctl(segmento1, IPC_RMID, 0); shmdt(mat2); shmctl(segmento2, IPC_RMID, 0); shmdt(mat3); shmctl(segmento3, IPC_RMID, 0); return 0; }
int main() { int l = 3, c = 4; int mat[][MAX] = { {1, 2, 3}, {4, 5, 6, 7}, {8, 9} }; printf("antes:\n"); imprimeMatriz(mat, l, c); multiplicaEscalar(mat, l, c, 2); printf("\n\ndepois:\n"); imprimeMatriz(mat, l, c); }
int main(){ int n; // numero de linhas e colunas da matriz scanf("%d", &n); int i,j; char ch; int **A = (int**)malloc(sizeof(int)*n); for (i=0; i<n; i++){ A[i] = (int*)malloc(sizeof(int)*n); } for (i=0; i<n; i++){ for (j=0; j<n; j++) scanf("%d", &A[i][j]); //do {scanf("%c", &ch);} while (ch!='\n'); // "limpa" os caracteres que estejam sobrando no final de cada linha //(nao eh necessario caso o arquivo matriz.txt esteja bem definido) } imprimeMatriz(A,n); printf("\n"); // Imprime Matriz: for (i=0; i<n; i++){ for (j=0; j<n; j++) printf("%d ", A[i][j]); printf("\n"); } system("pause"); return 0; }
void resolveMatrizTS(double **m,int n, int v []) { double *x; int tipo,i; x = malloc(sizeof(double)*n); if(x==NULL){ printf("Erro ao alocar Matriz. Falta de memoria!\n"); return; } tipo = sretro(m,n,x); printf("\tO SL \202 %s\n\n", tipo==0?"Determinado":tipo==1?"Indeterminado":"Incompativel"); if(tipo!=2){ for(i=0;i<n;i++){ printf("x[%d] = %10.3lf ", v[i]+1,x[i]); } printf("\n\n"); imprimeMatriz(m, n, n + 1); } }
int main(){ srand((unsigned) time(NULL)); //para alterar o preenchimento da matriz matriz *m = iniciaMatriz(); setor *jogador = iniciaSetor(); pilha *p = iniciaPilha(); preencheMatrizCom01(m); imprimeMatriz(m); comecaJogo(jogador); printf("Posição do jogador : x = %d y = %d\n", getXJogador(jogador), getYJogador(jogador)); while(!fimDeJogo(jogador)){ mover(jogador, m, p); } if(getXJogador(jogador) == 9&& getYJogador(jogador) == 9) //jogo bem sucedido imprimeMatriz(m); //imprime o caminho free(m); free(jogador); free(p); return 0; }
// Imprime o grafo void imprimeGrafo(Grafo G){ //Imprime número de cidades printf("%d\n",G.N); imprimeMatriz(G.matrizAdj); for (int i = 0; i < G.N; i++){ printf("%d ",G.Vol[i]); } printf("\n"); };
int main(int argc, char *argv[]){ // Inicializa matriz e a posição central do cursor textbackground(CORFUNDO); inicializaMatriz(m); posLin = (int)TAM_MATRIZ/2; posCol = (int)TAM_MATRIZ/2; int tecla; // Inicia a lógica do jogo while(1){ imprimeMatriz(m); destaca(posLin,posCol); imprimeStatus(); if(pontuacao == 1) imprimeFimdejogo; if(fimDeJogo) imprimeFimdejogo(); tecla = getch(); if(tecla == DIRECIONAL){ switch(getch()){ case CIMA: moveCursor(CIMA); break; case DIREITA: moveCursor(DIREITA); break; case BAIXO: moveCursor(BAIXO); break; case ESQUERDA: moveCursor(ESQUERDA); break; } } else { switch(tecla){ case ENTER: verifica(); break; case ESPACO: sugestao(); break; case ESC: return; } } gotoxy(TAM_MATRIZ*2+1,TAM_MATRIZ); } return 0; }
int main(){ int n/*intersecções*/, m/*numRuas*/, i, j, v, w, p; // scanf("%d %d", &n, &m); Fila* vertices; // vertices = filaConstrutor(); scanf("%d%d", &n,&m); for (i = 1; i <= n; ++i){ for (j = 1; j <= m; ++j){ scanf("%d ", &matrix[i][j]); // printf("%d ", matrix[i][j]); } //printf("\n"); } imprimeMatriz(n,m,matrix); return 0; }
int main(int argc, char const *argv[]) { int linha, coluna, i, j; int **n0, **n1; char controle = 'a'; char output[10] = "saida.txt"; FILE *entrada; entrada = fopen("dados.txt", "r"); if (entrada == NULL) { printf("Erro de abertura do arquivo.\n"); return -1; } fscanf(entrada, "%d %d", &linha, &coluna); alocaMatriz(&n0, linha, coluna); alocaMatriz(&n1, linha, coluna); for (i = 0; i < linha; i++) { for (j = 0; j < coluna; j++) { fscanf(entrada, "%d", &n0[i][j]); } } fclose(entrada); while (toupper(controle) != 'N') { system("clear"); imprimeMatriz(n0, linha, coluna); printf("Você gostaria de continuar executando a evolução das " "gerações?\nDigite 's' se gostaria e 'n' se não gostaria.\n"); scanf(" %c", &controle); if (toupper(controle) == 'S') { novaGeracao(n0, n1, linha, coluna); copiaMatriz(n0, n1, linha, coluna); } } imprimeConway(output, linha, coluna, n0); liberaMatriz(n0, linha); liberaMatriz(n1, linha); return 0; }
int main(void) { int *m; int nlin, ncol; int i, j; /* peço o número de linhas e colunas */ printf("Entre o numero de linhas e colunas: "); scanf("%d %d", &nlin, &ncol); /* leitura da matriz */ m = leitura(nlin, ncol); /* imprimo a matriz */ imprimeMatriz(m, nlin, ncol); /* desaloco a matriz */ free(m); }
int main (int argc, char* argv[]) { std::ifstream fichResultado; int totales[DIMENSIONES][DIMENSIONES]; int totalesOriginal[DIMENSIONES], totalesResultado[DIMENSIONES]; for(int i = 0; i < DIMENSIONES; i++) { totalesOriginal[i] = totalesResultado[i] = 0; for(int j = 0; j < DIMENSIONES; j++) totales[i][j] = 0; } if ( !seguridad(argc, argv, fichResultado) ) return 0; std::string tipoOriginal, tipoResultado; long posicionTest = 0; char basura; while( !fichResultado.eof() ) { std::string pertenece, perteneceEuclidea; if (posicionTest != 0) fichResultado.seekg(posicionTest, fichResultado.beg); leerDato(tipoOriginal, tipoResultado, fichResultado); std::cout << "Original: " << tipoOriginal << ", y Resultado: " << tipoResultado << std::endl; construyeMatriz(totales, totalesOriginal, totalesResultado, tipoOriginal, tipoResultado); posicionTest = fichResultado.tellg(); fichResultado >> basura; } fichResultado.close(); imprimeMatriz(totales, totalesOriginal, totalesResultado); return 1; }
int main() { system("title Trabalho de Estrutura de Dados I"); system("color 0F"); system("chcp 1252 > chcp.txt"); system("cls"); listaMatriz *mA, *mB, *mC; listaMatriz *matSoma, *matMult; int op,ok = 0; char nome[MAX_TAM]; while(op != 6) { printf("\t\tExercicio 02"); printf("\n\n\n"); printf(" 1 - Abre Matriz\n"); printf(" 2 - Imprimi Matriz\n"); printf(" 3 - Soma Matriz\n"); printf(" 4 - Multiplica Matriz\n"); printf(" 5 - Apaga Matriz\n"); printf(" 6 - Sair\n\n"); printf("Opção: "); scanf("%d",&op); switch (op) { case 1 : system("cls"); printf("Forneça o Nome do 1º Arquivo:\n"); scanf("%s",&nome); mA = lerMatriz(nome); printf("Forneça o Nome do 2º Arquivo:\n"); scanf("%s",&nome); mB = lerMatriz(nome); system("PAUSE"); ok = 1; break; case 2 : system("cls"); if(!ok) { printf("Matrizes Nao Inicializadas Corretamente\n\n"); system("PAUSE"); break; } else { printf("Matriz 1\n"); imprimeMatriz(mA); printf("\nMatriz 2\n"); imprimeMatriz(mB); system("PAUSE"); break; } case 3 : system("cls"); if(!ok) { printf("Matrizes Nao Inicializadas Corretamente\n\n"); system("PAUSE"); break; } else { printf("Soma da Matriz 1 Com a Matriz 2\n\n"); printf("Matriz 1\n"); imprimeMatriz(mA); printf("\n"); printf("Matriz 2\n"); imprimeMatriz(mB); printf("\n"); printf("Resultado\n"); matSoma = somaMatriz(mA, mB); imprimeMatriz(matSoma); system("PAUSE"); break; } case 4 : system("cls"); if(!ok) { printf("Matrizes Nao Inicializadas Corretamente\n\n"); system("PAUSE"); break; } else { printf("Multiplicação da Matriz 1 Com a Matriz 2\n\n"); printf("Matriz 1\n"); imprimeMatriz(mA); printf("\n"); printf("Matriz 2\n"); imprimeMatriz(mB); printf("\n"); printf("Resultado\n"); matMult = multiplicaMatriz(mA,mB); imprimeMatriz(matMult); system("PAUSE"); break; } case 5 : system("cls"); if(!ok) { printf("Matrizes Nao Inicializadas Corretamente\n\n"); system("PAUSE"); break; } else { if(apagaMatriz(mA)) printf("Matriz 1 Apagada Com Sucesso!"); else printf("Erro, Nao Existe Matriz a Ser apagada."); if(apagaMatriz(mB)) printf("\nMatriz 2 Apagada Com Sucesso!\n\n"); else printf("\nErro, Nao Existe Matriz a Ser apagada.\n\n"); system("PAUSE"); break; } } system("cls"); } system("PAUSE"); return 0; }
int main(){ // Variable declaration. double *optim_point_N, *optim_point_lbfgs, *optim_point_slm_lbfgs; double precision; int length; // Print options // menu(); /* * ############################################################### * Test Functions * ############################################################### */ if(run_functions){ // Size of point. length = 100; // Print results easy. optim_point_N = NGC(test_func1, length, 10, 1e-1, verbose, 100, 1, .0001); imprimeTit("Problem 1 minimum (NCG):"); imprimeMatriz(optim_point_N, 1, length); // Print results hard. optim_point_N = NGC(test_func2, length, 10, 1e-1, verbose, 100, 1, .0001); imprimeTit("Problem 2 minimum (NCG):"); imprimeMatriz(optim_point_N, 1, length); // Print result easy. optim_point_lbfgs = LBFGS(test_func1, length, 20, 1e-6, verbose); imprimeTit("Problem 1 minimum (LBFGS):"); imprimeMatriz(optim_point_lbfgs, 1, length); // Print results hard. optim_point_lbfgs = LBFGS(test_func2, length, 20, 1e-6, verbose); imprimeTit("Problem 2 minimum (LBFGS):"); imprimeMatriz(optim_point_lbfgs, 1, length); // Print result easy. optim_point_slm_lbfgs = SLM_LBFGS(test_func1, length, 20, 1e-4, 10, verbose); imprimeTit("Problem 1: minimum (SLM-LBFGS):"); imprimeMatriz(optim_point_slm_lbfgs, 1, length); // Print results hard. optim_point_slm_lbfgs = SLM_LBFGS(test_func2, length, 20, 1e-4, 10, verbose); imprimeTit("Problem 2: minimum (SLM-LBFGS):"); imprimeMatriz(optim_point_slm_lbfgs, 1, length); } /* * ############################################################### * Test Logistic * ############################################################### */ if(run_logistic){ length = MAX_FILE_COLS; // READ FILE readFile(); // RUNNING NGC MODEL imprimeTit("RUNNING NGC MODEL"); // Test logistic. // ADD THIS CONFIGURATIONS TO CODE optim_point_N = NGC(logistic, length, 20, 1e-2, verbose, 10, 1000, .0001); imprimeTit("Logistic minimum (NCG):"); imprimeMatriz(optim_point_N, 1, length); // Prediction error. precision = class_precision(optim_point_N, length, 0); printf("\n"); imprimeTit("Classification Precision:"); printf("%.5lf \n", precision); /**/ /* // RUNNING LBFGS MODEL imprimeTit("RUNNING LBFGS MODEL"); // Test multinomial logistic. optim_point_N = LBFGS(logistic, length, min(length, 15), 1e-5, verbose); imprimeTit("Multinomial Logistic minimum (LBFGS):"); imprimeMatriz(optim_point_N, 1, length); // Prediction error. precision = class_precision(optim_point_N, length, 0); printf("\n"); imprimeTit("Classification Precision (LBFGS):"); printf("%.5lf \n", precision); */ // RUNNING SLM-LBFGS MODEL /* imprimeTit("RUNNING SLM-LBFGS MODEL"); // Test multinomial logistic. optim_point_N = SLM_LBFGS(logistic, length, 2, 1e-2, 5, verbose); imprimeTit("Multinomial Logistic minimum (SLM-LBFGS):"); imprimeMatriz(optim_point_N, 1, length); // Prediction error. precision = class_precision(optim_point_N, length, 0); printf("\n"); imprimeTit("Classification Precision (SLM_LBFGS):"); printf("%.5lf \n", precision); */ } return 0; }
int main(int argc, char **argv) { int alterou=1,i,j,vizinhos,transicoes,complementos; /* le ficheiro de input - verificar nargs */ if(argc != 2) { alterou = 0; printf("#ERRO: Insira uma imagem\n"); } else { carregaImagemPBM(argv[1]); } /* Processamento - iniciar timer */ double time = omp_get_wtime(); while(alterou) { alterou = 0; /* Primeira passagem */ #pragma omp parallel #pragma omp for reduction for(i=1; i<linhas-1; i++) { for(j=1; j<colunas-1; j++) { /* Se o pixel for diferente de zero */ if(mat[i][j]) { /* vizinhos */ vizinhos = mat[i][j+1] + mat[i+1][j+1] + mat[i+1][j] + mat[i+1][j-1] + mat[i][j-1] + mat[i-1][j-1] + mat[i-1][j] + mat[i-1][j+1]; if(vizinhos >= 2 && vizinhos <= 6) { /* transicçoes */ transicoes = trans(mat[i+1][j+1],mat[i][j+1]) + trans(mat[i+1][j],mat[i+1][j+1]) + trans(mat[i+1][j-1],mat[i+1][j]) + trans(mat[i][j-1],mat[i+1][j-1]) + trans(mat[i-1][j-1],mat[i][j-1]) + trans(mat[i-1][j],mat[i-1][j-1]) + trans(mat[i-1][j+1],mat[i-1][j]) + trans(mat[i][j+1],mat[i-1][j+1]); if(transicoes == 1) { /* complementos */ complementos = comp(mat[i+1][j]) + comp(mat[i][j-1]) + comp(mat[i][j+1]) * comp(mat[i-1][j]); if(complementos == 1) { //#pragma omp atomic mat[i][j] -= 1; alterou = 1; } } } } } } /* Segunda passagem */ #pragma omp for for(i=1; i<linhas-1; i++) { for(j=1; j<colunas-1; j++) { /* Se o pixel for diferente de zero */ if(mat[i][j]) { /* vizinhos */ vizinhos = mat[i][j+1] + mat[i+1][j+1] + mat[i+1][j] + mat[i+1][j-1] + mat[i][j-1] + mat[i-1][j-1] + mat[i-1][j] + mat[i-1][j+1]; if(vizinhos >= 2 && vizinhos <= 6) { /* transicçoes */ transicoes = trans(mat[i+1][j+1],mat[i][j+1]) + trans(mat[i+1][j],mat[i+1][j+1]) + trans(mat[i+1][j-1],mat[i+1][j]) + trans(mat[i][j-1],mat[i+1][j-1]) + trans(mat[i-1][j-1],mat[i][j-1]) + trans(mat[i-1][j],mat[i-1][j-1]) + trans(mat[i-1][j+1],mat[i-1][j]) + trans(mat[i][j+1],mat[i-1][j+1]); if(transicoes == 1) { /* complementos */ complementos = comp(mat[i][j+1]) + comp(mat[i-1][j]) + comp(mat[i+1][j]) * comp(mat[i][j-1]); if(complementos == 1) { //#pragma omp atomic mat[i][j] -= 1; alterou = 1; } } } } } } } /* Terminar timer */ time = omp_get_wtime() - time; printf("Tempo: %lf\n",time); /* escreve a matriz no ficheiro de output */ imprimeMatriz(); return 0; }
void main(int argc, char *argv[]) { char prefixo_arquivo_out[MAX_NAME - 4]; int imagem[MAXLINHA][MAXCOLUNA]; int linhas, colunas, maiorValor, check, larguraJanela, k, limiteValido = 0; const char comandos[] = "nrvhedmz123xctgCas"; char comando = 0; int flag = 0; if (argc < 2) { printf("Usage: %s <arquivo entrada>\n", argv[0]); exit(0); } if (le_pgm(argv[1], imagem, &linhas, &colunas, &maiorValor)) { printf("Arquivo %s.pgm carregado com sucesso.\n", argv[1]); } else { exit(0); } strcpy(prefixo_arquivo_out, argv[1]); void menu(); while (comando != 's') { printf("Digite um comando: "); scanf(" %c", &comando); if (!strchr (comandos, comando)) { printf("Comando invalido\n"); continue; } for (int i = 4; i < 11; i++) { if (comando == comandos[i]) { larguraJanela = 0; while (larguraJanela < JANELA_MIN || larguraJanela > JANELA_MAX) { printf("Digite o tamanho da janela: "); scanf("%d", &larguraJanela); if (larguraJanela < JANELA_MIN || larguraJanela > JANELA_MAX) { printf("Tamanho invalido. A janela deve ser entre %d e %d.\n", JANELA_MIN); } } } } if (comando == '1' || comando == '2' || comando == '3') { printf("Informe o valor de k: "); scanf("%d", &k); } if (comando = 'n') negativo(imagem, linhas, colunas); if (comando = 'r') rotacao(imagem, &linhas, &colunas); if (comando = 'v') rebatimentoVertical(imagem, linhas, colunas); if (comando = 'h') rebatimentoHorizontal(imagem, linhas, colunas); if (comando = 'e') filtroErosao(imagem, linhas, colunas, larguraJanela); if (comando = 'd') filtroDilatacao(imagem, linhas, colunas, larguraJanela); if (comando = 'm') filtroMediana(imagem, linhas, colunas, larguraJanela); if (comando = 'z') filtroMedia(imagem, linhas, colunas, larguraJanela); if (comando = '1') filtroBorda1(imagem, linhas, colunas, larguraJanela, k); if (comando = '2') filtroBorda2(imagem, linhas, colunas, larguraJanela, k); if (comando = '3') filtroBorda3(imagem, linhas, colunas, larguraJanela, k); if (comando = 'a') menu(); if (comando == 'c') { check = 0; while (!check) { printf("Digite o nome do arquivo de entrada: "); scanf("%s", argv[1]); if ((check = le_pgm(argv[1], imagem, &linhas, &colunas, &maiorValor))) printf("Arquivo %s.pgm carregado com sucesso.\n\n", argv[1]); } strcpy(prefixo_arquivo_out, argv[1]); flag = 0; } if (comando == 't') { imprimeMatriz(imagem, linhas, colunas); printf("\n"); } if (comando == 'x') { int xsup, ysup, xinf, yinf; printf("Informe x superior: "); scanf("%d", &xsup); printf("Informe y superior: "); scanf("%d", &ysup); printf("Informe x inferior: "); scanf("%d", &xinf); printf("Informe y inferior: "); scanf("%d", &yinf); if (xsup < 0 || ysup < 0 || xinf >= linhas || yinf >= colunas || xsup > xinf || ysup > yinf) limiteValido = 0; else limiteValido = 1; if (limiteValido) { corte(imagem, &linhas, &colunas, xsup, ysup, xinf, yinf); if (!flag) { strcat(prefixo_arquivo_out, "-"); flag = 1; } strncat(prefixo_arquivo_out, &comando, 1); printf("Operacao realizada com sucesso.\n"); } else { printf("Limites invalidos\n\n"); } } if (comando == 'g') { grava_pgm(prefixo_arquivo_out, imagem, linhas, colunas, maiorValor); printf("%s.pgm\n", prefixo_arquivo_out); printf("Arquivo %s.pgm gravado com sucesso.\n", prefixo_arquivo_out); } if (comando == 'C') { int c[MAXLINHA][MAXCOLUNA]; int linhasC, colunasC, maiorValorC; char prefixo_arquivo_c[MAX_NAME - 4]; posicao erro; check = 0; while (!check) { printf("Digite o nome do arquivo com a imagem a ser comparada: "); scanf("%s", prefixo_arquivo_c); check = le_pgm(prefixo_arquivo_c, c, &linhasC, &colunasC, &maiorValorC); } erro = compara(imagem, c, linhas, linhasC, colunas, colunasC); if (erro.linha == -2 && erro.coluna == -2) { printf("As matrizes sao iguais\n"); } else if (erro.linha == -1 && erro.coluna == -1) { printf("As matrizes tem dimensoes diferentes\n"); } else { printf("As matrizes tem valores diferentes na posicao %d, %d\n", erro.linha, erro.coluna); } } for (int i = 0; i < 11; i++) { if (comando == comandos[i]) { if (flag == 0) { strcat(prefixo_arquivo_out, "-"); flag = 1; } strncat(prefixo_arquivo_out, &comando, 1); printf("Operacao realizada com sucesso.\n"); } } } return; }
int main(int argc, char **argv) { int nLinhas, nColunas, i, j, aleatorio, aux; int nDestroyers, nPatrulhas, nPortaAvioes; jogador jogadores[NUM_JOGADORES]; coordenada coord_ataque; printf("Entre com a dimensao do tabuleiro (quadrado): "); scanf("%d", &nLinhas); nColunas = nLinhas; do { printf("\n------------------\n"); printf("Tamanho dos navios:\n"); printf("Destroyer = 4, Patrulha = 2, Porta-avioes = 5\n"); printf("------------------\n"); printf("Entre com o numero de destroyers, patrulhas e porta avioes (separados por espaco): "); scanf("%d %d %d", &nDestroyers, &nPatrulhas, &nPortaAvioes); aux = checaInput(nDestroyers, nPatrulhas, nPortaAvioes, nLinhas, nColunas); if(aux == 0) printf("\nAVISO: o tabuleiro nao suporta a quantidade de navios desejada! Entre com novos valores.\n"); }while(!aux); srand(time(NULL)); // Inicializacao dos jogadores e posicionamento dos navios for(i = 0; i < NUM_JOGADORES; ++i) { jogadores[i].nLinhas = nLinhas; jogadores[i].nColunas = nColunas; jogadores[i].nDestroyers = nDestroyers; jogadores[i].nPatrulhas = nPatrulhas; jogadores[i].nPortaAvioes = nPortaAvioes; jogadores[i].totalNavios = nDestroyers + nPatrulhas + nPortaAvioes; jogadores[i].nNaviosDestruidos = 0; jogadores[i].ganhou = 0; jogadores[i].id_jogador = i; jogadores[i].destroyers = alocaDestroyers(jogadores[i].nDestroyers); jogadores[i].patrulhas = alocaPatrulhas(jogadores[i].nPatrulhas); jogadores[i].porta_avioes = alocaPortaAvioes(jogadores[i].nPortaAvioes); jogadores[i].tabuleiro = alocaTabuleiro(jogadores[i].nLinhas, jogadores[i].nColunas); if(jogadores[i].tabuleiro == NULL) return -1; jogadores[i].matrizControle = alocaMatriz(jogadores[i].nLinhas, jogadores[i].nColunas); if(jogadores[i].matrizControle == NULL) return -1; // Posicionamento dos navios if(i == 0) { do { printf("\nDeseja posicionar os navios de maneira aleatoria? (0 - NAO, 1 - SIM): "); scanf("%d", &aleatorio); if(aleatorio != 0 && aleatorio != 1) printf("Opcao invalida!\n"); }while(aleatorio != 1 && aleatorio != 0); } else aleatorio = 1; // o posicionamento dos navios da máquina é sempre feito de forma aleatória // Coloca os navios de maneira aleatoria no tabuleiro if(aleatorio) { printf("Posicionando destroyers do JOGADOR %d...\n", i); for(j = 0; j < jogadores[i].nDestroyers; ++j) { do { jogadores[i].destroyers[j].coord_ini.x = rand() % jogadores[i].nLinhas; jogadores[i].destroyers[j].coord_ini.y = rand() % jogadores[i].nColunas; jogadores[i].destroyers[j].coord_fim.x = rand() % jogadores[i].nLinhas; jogadores[i].destroyers[j].coord_fim.y = rand() % jogadores[i].nColunas; }while(posicionaNavio(jogadores[i].tabuleiro, jogadores[i].destroyers[j], jogadores[i].nLinhas, jogadores[i].nColunas) == -1); } printf("Posicionando patrulhas do JOGADOR %d...\n", i); for(j = 0; j < jogadores[i].nPatrulhas; ++j) { do { jogadores[i].patrulhas[j].coord_ini.x = rand() % jogadores[i].nLinhas; jogadores[i].patrulhas[j].coord_ini.y = rand() % jogadores[i].nColunas; jogadores[i].patrulhas[j].coord_fim.x = rand() % jogadores[i].nLinhas; jogadores[i].patrulhas[j].coord_fim.y = rand() % jogadores[i].nColunas; }while(posicionaNavio(jogadores[i].tabuleiro, jogadores[i].patrulhas[j], jogadores[i].nLinhas, jogadores[i].nColunas) == -1); } printf("Posicionando porta-avioes do JOGADOR %d...\n", i); for(j = 0; j < jogadores[i].nPortaAvioes; ++j) { do { jogadores[i].porta_avioes[j].coord_ini.x = rand() % jogadores[i].nLinhas; jogadores[i].porta_avioes[j].coord_ini.y = rand() % jogadores[i].nColunas; jogadores[i].porta_avioes[j].coord_fim.x = rand() % jogadores[i].nLinhas; jogadores[i].porta_avioes[j].coord_fim.y = rand() % jogadores[i].nColunas; }while(posicionaNavio(jogadores[i].tabuleiro, jogadores[i].porta_avioes[j], jogadores[i].nLinhas, jogadores[i].nColunas) == -1); } } else { printf("Posicionando destroyers do JOGADOR %d...\n", i); for(j = 0; j < jogadores[i].nDestroyers; ++j) { do { printf("Entre com as coordenadas (X, Y) da proa (frente) do navio seperadas por espaco: "); scanf("%d %d", &jogadores[i].destroyers[j].coord_ini.x, &jogadores[i].destroyers[j].coord_ini.y); printf("Entre com as coordenadas (X, Y) da popa (traseira) do navio seperadas por espaco: "); scanf("%d %d", &jogadores[i].destroyers[j].coord_fim.x, &jogadores[i].destroyers[j].coord_fim.y); }while(posicionaNavio(jogadores[i].tabuleiro, jogadores[i].destroyers[j], jogadores[i].nLinhas, jogadores[i].nColunas) == -1); if(i == 0) { system(CLEAR); imprimeTabuleiro(jogadores[i].tabuleiro, jogadores[i].nLinhas, jogadores[i].nColunas); } } printf("Posicionando patrulhas do JOGADOR %d...\n", i);; for(j = 0; j < jogadores[i].nPatrulhas; ++j) { do { printf("Entre com as coordenadas (X, Y) da proa (frente) do navio seperadas por espaco: "); scanf("%d %d", &jogadores[i].patrulhas[j].coord_ini.x, &jogadores[i].patrulhas[j].coord_ini.y); printf("Entre com as coordenadas (X, Y) da popa (traseira) do navio seperadas por espaco: "); scanf("%d %d", &jogadores[i].patrulhas[j].coord_fim.x, &jogadores[i].patrulhas[j].coord_fim.y); }while(posicionaNavio(jogadores[i].tabuleiro, jogadores[i].patrulhas[j], jogadores[i].nLinhas, jogadores[i].nColunas) == -1); if(i == 0) { system(CLEAR); imprimeTabuleiro(jogadores[i].tabuleiro, jogadores[i].nLinhas, jogadores[i].nColunas); } } printf("Posicionando porta-avioes do JOGADOR %d...\n", i); for(j = 0; j < jogadores[i].nPortaAvioes; ++j) { do { printf("Entre com as coordenadas (X, Y) da proa (frente) do navio seperadas por espaco: "); scanf("%d %d", &jogadores[i].porta_avioes[j].coord_ini.x, &jogadores[i].porta_avioes[j].coord_ini.y); printf("Entre com as coordenadas (X, Y) da popa (traseira) do navio seperadas por espaco: "); scanf("%d %d", &jogadores[i].porta_avioes[j].coord_fim.x, &jogadores[i].porta_avioes[j].coord_fim.y); }while(posicionaNavio(jogadores[i].tabuleiro, jogadores[i].porta_avioes[j], jogadores[i].nLinhas, jogadores[i].nColunas) == -1); if(i == 0) { system(CLEAR); imprimeTabuleiro(jogadores[i].tabuleiro, jogadores[i].nLinhas, jogadores[i].nColunas); } } } } i = 1; int controle; printf("\nO jogo vai comecar!\n"); do { ++i; do { if(i % NUM_JOGADORES == 0) { //system(CLEAR); //coord_ataque.x = rand() % nLinhas; //coord_ataque.y = rand() % nColunas; printf("\n\nTabuleiro dos navios\n"); imprimeTabuleiro(jogadores[JOG_1].tabuleiro, jogadores[JOG_1].nLinhas, jogadores[JOG_1].nColunas); printf("\n\nMatriz de controle\n"); imprimeMatriz(jogadores[JOG_1].matrizControle, jogadores[JOG_1].nLinhas, jogadores[JOG_1].nColunas); printf("\n\n"); printf("Digite as coordendas (X, Y) separadas por espaco do seu ataque: "); scanf("%d %d", &coord_ataque.x, &coord_ataque.y); printf("\n"); } else { coord_ataque.x = rand() % nLinhas; coord_ataque.y = rand() % nColunas; } printf("Jogador %d:\n", (i % NUM_JOGADORES) + 1); controle = joga(&jogadores[i % NUM_JOGADORES], &jogadores[(i + 1) % NUM_JOGADORES], coord_ataque); printf("\n"); }while(controle == -1); } while(controle != 0); if(jogadores[JOG_1].ganhou) printf("Voce ganhou.\n"); else printf("Voce perdeu.\n"); // Libera memoria for(i = 0; i < NUM_JOGADORES; ++i) { desalocaDestroyers(jogadores[i].destroyers); desalocaPatrulhas(jogadores[i].patrulhas); desalocaPortaAvioes(jogadores[i].porta_avioes); desalocaMatriz(jogadores[i].matrizControle, jogadores[i].nLinhas, jogadores[i].nColunas); desalocaTabuleiro(jogadores[i].tabuleiro, jogadores[i].nLinhas, jogadores[i].nColunas); } return 0; }
int main (int argc, char **argv) { int **tabuleiro, **grauJogadaBranca, **grauJogadaPreta; int m, n, vitP, vitB,tam = 14; int corPreta, corBranca, modoVerboso, eJogada, troca = 0; forcaJogada jog; posicao proximaJogada; proximaJogada = malloc (sizeof (pos) ); jog = malloc (sizeof (jogada) ); grauJogadaBranca = criaMatriz (tam, tam); grauJogadaPreta = criaMatriz (tam, tam); tabuleiro = criaMatriz(tam, tam); if (argc > 3) return 0; if (argc == 3) if (argv[2][0] == 'd') modoVerboso = 1; else modoVerboso = 0; if (argc == 2) modoVerboso = 0; if (argv[1][0] == 'b') { corBranca = 1; corPreta = 0; } else if (argv[1][0] == 'p') { corBranca = 0; corPreta = 1; } else { return 0; } zeraMatriz(tabuleiro, tam, tam, -2); zeraMatriz(grauJogadaBranca, tam, tam, -1); zeraMatriz(grauJogadaPreta, tam, tam, -1); vitB = checaVitoria(tabuleiro, corBranca, tam); vitP = checaVitoria(tabuleiro, corPreta, tam); while (vitP == 0 && vitB == 0) { scanf("%d %d", &m,&n); if (m == tam/2 && n == tam/2 && troca == 0) { corBranca = corPreta; corPreta = 1; troca = 1; } else { troca = 1; } while (casaLivre (tabuleiro, tam, m, n) == 0) { scanf("%d %d", &m,&n); } tabuleiro[m][n] = corBranca; /* Calcular jogada da maquina */ zeraMatriz(grauJogadaPreta, tam, tam, -1); grauJogadaPreta = jogadaLivre (tabuleiro, tam, grauJogadaPreta, corPreta); eJogada = existeJogada (grauJogadaPreta, tam); if (eJogada == 1) { grauJogadaPreta = grauJogada(tabuleiro, tam, grauJogadaPreta, corPreta); jog = jogadaMaisForte (grauJogadaPreta, tam); if (jog -> qnt > 1) { proximaJogada = sorteiaJogada (tabuleiro, grauJogadaPreta, tam, jog -> forca, jog -> qnt); } else { /* Só uma casa com aquela força de ocorrencia */ proximaJogada = buscaForcaMatriz(tabuleiro, tam, grauJogadaPreta, jog -> forca); /* Fazer a busca Matriz */ } printf("%d %d\n", proximaJogada -> lin, proximaJogada -> col); tabuleiro[proximaJogada -> lin][proximaJogada -> col] = corPreta; if (modoVerboso == 1) imprimeMatriz(tabuleiro, tam, tam); } vitP = checaVitoria(tabuleiro, corPreta, tam); printf("\n vitP = %d",vitP); fflush(stdout); vitB = checaVitoria(tabuleiro, corBranca, tam); printf("\n vitB = %d",vitB); fflush(stdout); } if (vitB == 1) { printf("b ganhou\n"); return 0; } if (vitP == 1){ printf("p ganhou\n"); return 0; } return 0; }
int main(){ int i = 0, j = 0, opcao = 0, qtdVert=0, qtdAres =0, grau = 0; int opcao1 = 0, vertDel = 0, opcao2 =0, direcionado = 0, dd = 0; int **p = NULL; printf("Quais das opcoes tu desejas?\n"); printf("1 - Matriz de adjacencia\n"); printf("2 - Matriz de incidencia\n"); scanf("%i", &opcao); //----------------------------------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------ADJACENCIA----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------------------- switch(opcao){ case 1: while(opcao1 != 9){ printf("Quais das opcoes tu desejas?\n"); printf("1 - Gerar matriz de adjacencia\n"); printf("2 - Adicionar relacoes\n"); printf("3 - Imprimir matriz de adjacencia\n"); printf("4 - Zerar matriz de adjacencia\n"); printf("5 - Adicionar um vertice\n"); printf("6 - Remover um vertice\n"); printf("7 - Gerar grafo complementar\n"); printf("8 - Grau dos vertices\n"); printf("9 - Sair\n"); scanf("%i", &opcao1); switch(opcao1){ case 1: printf("Quantos vertices?\n"); scanf("%i",&qtdVert); p = geraMatriz(qtdVert); break; case 2: relacaoes(p); break; case 3: imprimeMatriz(qtdVert ,p); break; case 4: zeraMatriz(qtdVert ,p); break; case 5: qtdVert++; p = adicionaVertice(qtdVert, p); break; case 6: printf("Qual vertice tu desejas excluir?\n"); scanf("%i", &vertDel); vertDel--; removeVertice(qtdVert, vertDel, p); break; case 7: grafoComplementar(qtdVert, p); break; case 8: printf("Qual vertice do queres saber o grau?\n"); scanf("%i", &grau); printf("\n"); mostraGrau(grau, qtdVert, p); break; case 9: return 0; } } //----------------------------------------------------------------------------------------------------------------------------------------------------------- //------------------------------------------------------------INCIDENCIA----------------------------------------------------------------------------------------------- //----------------------------------------------------------------------------------------------------------------------------------------------------------- case 2: while(opcao2 != 8){ printf("Quais das opcoes tu desejas?\n"); printf("1 - Gerar matriz de incidencia\n"); printf("2 - Adicionar relacoes\n"); printf("3 - Imprimir matriz de incidencia\n"); printf("4 - Zerar matriz de incidencia\n"); printf("5 - Adicionar um vertice\n"); printf("6 - Remover um vertice\n"); printf("7 - Grau do vertice\n"); printf("8 - Sair\n"); scanf("%i", &opcao2); switch(opcao2){ case 1: printf("Quantos vertices?\n"); scanf("%i",&qtdVert); printf("Quantas arestas?\n"); scanf("%i",&qtdAres); p = geraMatrizIncidencia(qtdVert, qtdAres); break; case 2: printf("O grafo é direcionado? 1 para nao e 2 para sim\n"); scanf("%d", &direcionado); switch(direcionado){ case 1: relacaoIncidencia(p); break; case 2: relacaoIncidenciaDirecionada(p); break; } case 3: imprimeMatrizIncidencia (qtdAres,qtdVert,p); break; case 4: zeraMatrizIncidencia (qtdAres,qtdVert,p); break; case 5: qtdVert++; p = adicionaVerticeIncidencia(qtdVert, p); break; case 6: printf("Qual vertice tu desejas excluir?\n"); scanf("%i", &vertDel); vertDel--; removeVerticeIncidencia(qtdAres, vertDel, p); break; case 7: printf("Qual vertice do queres saber o grau?\n"); scanf("%i", &grau); printf("\n"); mostraGrauIncidencia(grau, qtdAres, p); break; case 8: return 0; } } } printf("\n"); printf("\n"); return 0; }
int main (int argc, char *argv[]){ double *A; // Matriz A double *B; // Matriz B double *C; // Matriz C double timetick; //El tamano de la matriz sera n= N*r , donde N y r se reciben //por parametro se tendran N*N bloques de r*r cada uno if (argc < 4){ printf("\n Falta un parametro "); printf("\n 1. Cantidad de bloques por dimension "); printf("\n 2. Dimension de cada bloque "); printf("\n 3. 0/1 para imprimir/no imprimir resultados "); return 0; } int N = atoi(argv[1]); int r = atoi(argv[2]); int imprimir=atoi(argv[3]); int n = N*r; //dimension de la matriz int sizeMatrix=n*n; //cantidad total de datos matriz int sizeBlock=r*r; //cantidad total de datos del bloque int i; A= (double *)malloc(sizeMatrix*sizeof(double)); //aloca memoria para A B= (double *)malloc(sizeMatrix*sizeof(double)); //aloca memoria para B C= (double *)malloc(sizeMatrix*sizeof(double)); //aloca memoria para C crearMatriz(A, sizeMatrix); //Inicializa A crearIdentidad(B,sizeBlock,sizeMatrix,N,r); //Inicializa B como matriz identidad timetick = dwalltime(); producto(A,B,C,r,N,sizeMatrix,sizeBlock); printf("Tiempo en segundos %f \n", dwalltime() - timetick); //tiempo if (imprimir ==1){ printf("\n\n A (como esta almacenada): \n" ); imprimeVector(A, sizeMatrix); printf("\n\n B (como esta almacenada): \n" ); imprimeVector(B,sizeMatrix); printf("\n\n A: \n" ); imprimeMatriz(A,N,r); printf(" \n\n B: \n" ); imprimeMatriz(B,N,r); printf("\n\n C: \n" ); imprimeMatriz(C,N,r); } printf(" \n\n Realizando comprobacion ... \n" ); for (i=0;i<sizeMatrix ;i++ ) { if (A[i]!=C[i]) { printf("\n Error %f", C[i] ); } } //imprimir tiempo free(A); free(B); free(C); return 0; } //FIN MAIN
int main(int argc, char **argv) { int alterou=1,i,j,vizinhos,transicoes,complementos; int p2,p3,p4,p5,p6,p7,p8,p9; /* le ficheiro de input - verificar nargs */ if(argc != 2) { alterou = 0; printf("#ERRO: Insira uma imagem\n"); } else { carregaImagemPBM(argv[1]); } /* Processamento - iniciar timer */ double time = omp_get_wtime(); while(alterou) { alterou = 0; /* Primeira passagem */ for(i=1; i<linhas-1; i++) { for(j=1; j<colunas-1; j++) { /* Se o pixel for diferente de zero */ if(mat[i][j]) { p2 = mat[i-1][j]; p3 = mat[i-1][j+1]; p4 = mat[i][j+1]; p5 = mat[i+1][j+1]; p6 = mat[i+1][j]; p7 = mat[i+1][j-1]; p8 = mat[i][j-1]; p9 = mat[i-1][j-1]; /* vizinhos */ vizinhos = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9; if(vizinhos >= 2 && vizinhos <= 6) { /* transicçoes */ transicoes = trans(p3,p2) + trans(p4,p3) + trans(p5,p4) + trans(p6,p5) + trans(p7,p6) + trans(p8,p7) + trans(p9,p8) + trans(p2,p9); if(transicoes == 1) { /* complementos */ complementos = comp(p4) + comp(p6) + comp(p8) * comp(p2); if(complementos == 1) { mat[i][j] = 0; if(!alterou) { alterou = 1; } } } } } } } /* Segunda passagem */ for(i=1; i<linhas-1; i++) { for(j=1; j<colunas-1; j++) { /* Se o pixel for diferente de zero */ if(mat[i][j]) { p2 = mat[i-1][j]; p3 = mat[i-1][j+1]; p4 = mat[i][j+1]; p5 = mat[i+1][j+1]; p6 = mat[i+1][j]; p7 = mat[i+1][j-1]; p8 = mat[i][j-1]; p9 = mat[i-1][j-1]; /* vizinhos */ vizinhos = p2 + p3 + p4 + p5 + p6 + p7 + p8 + p9; if(vizinhos >= 2 && vizinhos <= 6) { /* transicçoes */ transicoes = trans(p3,p2) + trans(p4,p3) + trans(p5,p4) + trans(p6,p5) + trans(p7,p6) + trans(p8,p7) + trans(p9,p8) + trans(p2,p9); if(transicoes == 1) { /* complementos */ complementos = comp(p2) + comp(p8) + comp(p4) * comp(p6); if(complementos == 1) { mat[i][j] = 0; if(!alterou) { alterou = 1; } } } } } } } } /* Terminar timer */ time = omp_get_wtime() - time; printf("Tempo: %lf\n",time); /* escreve a matriz no ficheiro de output */ imprimeMatriz(); return 0; }