language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <time.h> #include <stdio.h> #include <stdlib.h> int main() { struct tm *tm_ptr; time_t raw_time; (void) time(&raw_time); tm_ptr = gmtime(&raw_time); printf("Raw time is %ld\n", raw_time); printf("\n"); printf("gmtime() provides:\n"); printf("date: %04d/%02d/%02d\n", tm_ptr->tm_year+1900, tm_ptr->tm_mon+1, tm_ptr->tm_mday); printf("time: %02d:%02d:%02d\n", tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec); printf("\n"); tm_ptr = localtime(&raw_time); printf("localtime() provides:\n"); printf("date: %04d/%02d/%02d\n", tm_ptr->tm_year+1900, tm_ptr->tm_mon+1, tm_ptr->tm_mday); printf("time: %02d:%02d:%02d\n", tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec); printf("\n"); char * ctime_str; ctime_str = ctime(&raw_time); printf("ctime() provides:\n"); printf("%s\n", ctime_str); char * asctime_str; asctime_str = asctime(tm_ptr); printf("asctime() provides:\n"); printf("%s\n", asctime_str); exit(0); }
C
#ifndef _18_HASH_TABLE #define _18_HASH_TABLE #define HTABLE 0 #define LRU 1 typedef struct _ht_list_node { //struct _htable_node *prev; struct _htable_node *next; } ht_list_node; typedef struct _lru_list_node { struct _htable_node *prev; struct _htable_node *next; } lru_list_node; typedef struct _htable_node { int key; ht_list_node ht_list_node; lru_list_node lru_list_node; } htable_node; typedef struct _htable { ht_list_node *hash_table; int size; //htable_node lru; //int count; } htable; typedef struct _lru_object { htable_node lru; int count; int max_size; htable *ht; } lru_object; void ht_list_insert(ht_list_node *p_cur, htable_node *node); void ht_list_del(ht_list_node *prev, ht_list_node *cur); int ht_list_delete(ht_list_node *head, int key); htable_node* ht_list_find(ht_list_node *head, int key); int ht_list_traverse(ht_list_node *head); int htable_hash(htable *htable, int key); htable* htable_create(int size); int htable_destroy(htable *htable); htable_node* htable_find(htable *htable, int key); htable_node* htable_add_new(htable *htable, int key); int htable_add(htable *htable, htable_node *ht_node); int htable_delete(htable *htable, int key); void htable_traverse(htable *htable); void lru_list_init(htable_node *head); void lru_list_insert(htable_node *p_cur, htable_node *p_elem); void lru_list_delete(htable_node *cur); int lru_list_traverse(htable_node *lru_head); lru_object* lru_object_create(int lru_size, int hash_table_size); int lru_object_destroy(lru_object *lru); htable_node* lru_object_get(lru_object *lru, int key); htable_node* lru_object_access(lru_object *lru, int key); int lru_object_delete(lru_object *lru, htable_node *ht_node); int lru_object_eliminate(lru_object *lru); int lru_object_traverse(lru_object *lru); #endif
C
#include <stdio.h> int main() { int i, f, l, m, n, s, a[100]; printf("Enter number of elements\n"); scanf("%d", &n); printf("Enter %d integers\n", n); for (i = 0; i < n; i++) scanf("%d", &a[i]); printf("Enter value to find\n"); scanf("%d", &s); f = 0; l = n - 1; m = (f+l)/2; while (f <= l) { if (a[m] < s) f = m + 1; else if (a[m] == s) { printf("%d found at location %d.\n", s, m+1); break; } else l = m - 1; m = (f + l)/2; } if (f > l) printf("Not found! %d isn't present in the list.\n", s); return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define MAXSTRING 10001 void print_array(int array[],int size) { int i; for (i=0;i<size;i++) { printf("%d ",array[i]); } printf("\n\n"); } int palindrome(char *str, int length) { int a = 0; int b = length - 1; while (b > a) { if (str[a++] != str[b--]) { return 0; } } return 1; } void find_palindromes_left(char *s, int length, int results[]) { char hold; int x, y; for (x=0;x<length;x++) { results[x] = 1; } for (x=0;x<length;x++) { for (y=length-1;y>x;y--) { if (s[y] == s[x]) { hold = s[y+1]; s[y+1] = '\0'; /* Temporarily end the string after y */ if (palindrome(&(s[x]),y-x+1)) { s[y+1] = hold; /* Undo the temporary end-of-string */ results[x] = y-x+1; break; } else { s[y+1] = hold; } } } } } void find_palindromes_right(char *s, int length, int results[]) { char hold; int x, y; for (x=0;x<length;x++) { results[x] = 1; } for (y=length-1;y>0;y--) { for (x=0;x<y;x++) { if (s[y] == s[x]) { hold = s[y+1]; s[y+1] = '\0'; /* Temporarily end the string after y */ if (palindrome(&(s[x]),y-x+1)) { s[y+1] = hold; /* Undo the temporary end-of-string */ results[y] = y-x+1; break; } else { s[y+1] = hold; } } } } } void save_if_best( char *candidate, int candidate_length, char *best, int *best_length) { /* Note that we assume here that candidate_length >= (*best_length) */ if ((candidate_length > (*best_length)) || (strcmp(candidate,best) < 0)) { //printf(" A NEW BEST!\n"); strcpy(best,candidate); (*best_length) = candidate_length; } } void reverse_string(char *target, char *source, int length) { int i; /* loop counter */ for(i=0;i<length;i++) { target[length-i-1] = source[i]; } target[length] = '\0'; } int main() { int params; char s1[MAXSTRING]; char s2[MAXSTRING]; int s1_palindromes[MAXSTRING]; int s2_palindromes[MAXSTRING]; int s1_length; int s2_length; char left_bookend[MAXSTRING]; char right_bookend[MAXSTRING]; int bookend_length; int total_bookend_length; int body_length; char best[MAXSTRING+MAXSTRING]; int best_length; char teststring[MAXSTRING+MAXSTRING]; int teststring_length; int i, n, x, y, a, b; /* Loop counters */ /* Read in the number of pairs we'll consider */ i = scanf("%i",&params); for (n=0;n<params;n++) { /* Read in the pair */ i = scanf("%s",s1); i = scanf("%s",s2); s1_length = strlen(s1); s2_length = strlen(s2); //printf("s1 == \"%s\"\n",s1); //printf("s2 == \"%s\"\n",s2); /* Initialize our best result */ best[0] = '\0'; best_length = 0; /* Find all palindromes in s1 (left-indexed) and s2 (right-indexed) */ find_palindromes_left(s1,s1_length,s1_palindromes); //print_array(s1_palindromes,strlen(s1)); find_palindromes_right(s2,s2_length,s2_palindromes); //print_array(s2_palindromes,strlen(s2)); for (x=0;x<s1_length;x++) { if (best_length <= (s1_length - x + s2_length)) { for (y=x;y<s1_length;y++) { /* Set up the bookend data */ bookend_length = y-x+1; total_bookend_length = bookend_length * 2; strncpy(left_bookend,&(s1[x]),bookend_length); left_bookend[bookend_length] = '\0'; //printf("Left bookend (%d,%d) = \"%s\"\n",x,y,left_bookend); reverse_string(right_bookend,left_bookend,bookend_length); /* See if any right bookends are found */ if (strstr(s2,right_bookend)) { //printf(" Right bookend = \"%s\"\n",right_bookend); /* Try the body from s1 */ if (y != (s1_length-1)) { body_length = s1_palindromes[y+1]; /* Ignore this body if the resulting string would be too small */ if ((total_bookend_length + body_length) >= best_length) { /* Build the test string */ teststring_length = total_bookend_length + body_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),&(s1[y+1]),body_length); strncpy(&(teststring[bookend_length+body_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (body from s1): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } else /* No body available from s1 - try just the bookends */ { /* Ignore this body if the resulting string would be too small */ if (total_bookend_length >= best_length) { /* Build the test string */ teststring_length = total_bookend_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (no body): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } } else /* No right bookend was found */ { /* If a right bookend was not found for x at a given length nothing will be found with a greater length */ break; } } } } /* for */ for (b=s2_length-1;b>=0;b--) { if (best_length <= (s1_length + b + 1)) { for (a=b;a>=0;a--) { /* Set up the bookend data */ bookend_length = b-a+1; total_bookend_length = bookend_length * 2; strncpy(right_bookend,&(s2[a]),bookend_length); right_bookend[bookend_length] = '\0'; //printf("Right bookend (%d,%d) = \"%s\"\n",a,b,right_bookend); reverse_string(left_bookend,right_bookend,bookend_length); /* See if any left bookends are found */ if (strstr(s1,left_bookend)) { //printf(" Left bookend = \"%s\"\n",left_bookend); /* Try the body from s2 */ if (a != 0) { body_length = s2_palindromes[a-1]; /* Ignore this body if the resulting string would be too small */ if ((total_bookend_length + body_length) >= best_length) { /* Build the test string */ teststring_length = total_bookend_length + body_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),&(s2[a-body_length]),body_length); strncpy(&(teststring[bookend_length+body_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (body from s2): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } else /* No body available from s2 - try just the bookends */ { /* Ignore this body if the resulting string would be too small */ if (total_bookend_length >= best_length) { /* Build the test string */ teststring_length = total_bookend_length; strcpy(teststring,left_bookend); strncpy(&(teststring[bookend_length]),right_bookend,bookend_length); teststring[teststring_length] = '\0'; //printf(" Teststring (no body): \"%s\"\n",teststring); /* Compare test string with the best we've seen */ save_if_best(teststring,teststring_length,best,&best_length); } } } else /* No left bookend was found */ { /* If a left bookend was not found for b at a given length nothing will be found with a greater length */ break; } } } } /* for */ if (best_length) printf("%s\n",best); else printf("-1\n"); } }
C
#include <stdio.h> #define MAX(x, y) ((x)>(y) ? (x) : (y)) int main(void) { int i, s; printf(" Է: "); scanf_s("%d %d", &i, &s); printf(" ū : %d \n", MAX(i, s)); return 0; }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> struct student{ char id[15]; char name[100]; float marks; int rank; int flag; }; struct student arr[50]; struct student sorted[50]; void readdata(struct student arr[50]) {int i; for(i=0;i<50;i++) {scanf("%[^,]",arr[i].id);getchar();scanf("%[^,]",arr[i].name);getchar(); scanf("%f",&arr[i].marks);getchar(); } } void rankig(struct student sorted[50],struct student arr[50]) {int count=0,i; for(i=0;i<50;i++) arr[i].flag=1; int temp_rank; float temp=10000000,max=-1;int ranks=1,j,index; for(count=0;count<50;count++) { max=-1; for(j=0;j<50;j++) if(arr[j].marks>max && arr[j].flag==1) {max=arr[j].marks;index=j;} arr[index].flag=0; strcpy(sorted[count].id,arr[index].id); strcpy(sorted[count].name,arr[index].name); sorted[count].marks=max; if(temp==max) {sorted[count].rank=temp_rank; temp_rank=ranks;} else {temp_rank=ranks; sorted[count].rank=ranks;ranks++;} temp=max; } } void print(struct student sorted[50]) { int i; for(i=0;i<50;i++) {printf("%s ",sorted[i].name); printf("%s ",sorted[i].id); printf("%f ",sorted[i].marks); printf("%d ",sorted[i].rank); printf("\n"); } } int main() {readdata(arr); rankig(sorted,arr); print(sorted); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <time.h> // Bibliotecas para socket #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <fcntl.h> // for open #include <unistd.h> // for close #include <arpa/inet.h> #include <dirent.h> #include <netdb.h> #define LEN 4096 // Tamanho da mensagem a ser lida #define TAM 10 char mensagem[1] = {'C'}, ult_ac, atq[2]; int pontuacao = 0; struct sockaddr_in6 local, remoto; void traduz_linha_coluna(int *l, int *c){ for(int i = 0; i < 10; i++) if(atq[0] == 'A'+i) *l = 0 + i; *c = atq[1] - '0'; } void traduz_linha(int *l, char *l1){ for(int i = 0; i < 10; i++) if(*l == 0) *l1 = 'A' + i; } void seleciona_aleatorio(int oceano_rival[TAM][TAM]) { int l, c; while(1){ l = rand() % 10; c = rand() % 10; if(oceano_rival[l][c] == 0) break; } for(int i = 0; i < 10; i++) if (l == i) atq[0] = 'A' + i; for(int i = 0; i < 10; i++) if (c == i) atq[1] = '0' + i; } void escolhe_campo_ataque(int oceano_rival[TAM][TAM]) { int l1, c1, h1; char buf[1], aux; if(ult_ac == 'A') { traduz_linha_coluna(&l1, &c1); if(c1 + 1 <= 9 && oceano_rival[l1][c1+1] != 1) { // Tem como ir para direita sprintf(buf,"%i",c1+1); atq[1] = buf[0]; } else if (c1 - 1 >= 0 && oceano_rival[l1][c1-1] != 1){ // esquerda sprintf(buf,"%i",c1-1); atq[1] = buf[0]; } else if (l1-1>=0 && oceano_rival[l1-1][c1] != 1) { // baixo h1 = c1 - 1; traduz_linha(&h1, &aux); atq[0] = aux; } else if (l1+1<=9 && oceano_rival[l1+1][c1] != 1) { // cima h1 = c1 + 1; traduz_linha(&h1, &aux); atq[0] = aux; } else seleciona_aleatorio(oceano_rival); } else seleciona_aleatorio(oceano_rival); } void envia_mensagem(char buffer[], int oceano_rival[TAM][TAM]) { escolhe_campo_ataque(oceano_rival); strcat(buffer, atq); strcat(buffer, mensagem); //printf("Enviado: %s\n", buffer); } // Constroi matriz inicial para jogo void inicializa_oceano(int oceano[TAM][TAM]){ for(int i = 0; i < TAM; i++) for(int j = 0; j < TAM; j++) oceano[i][j] = 0; } // Cria um posicionamento randomico int posiciona_navio(int t, int oceano[TAM][TAM]){ int c = 0, l = 0, d = 0; srand(time(NULL)); d = rand() % 2; if(d == 0){ // se quero na horizontal c = rand() % (10 - t); l = rand() % 10; for(int i = c; i < t + c; i++) if(oceano[l][i] != 0) return 1; for(int i = c; i < t + c; i++) oceano[l][i] = t; } else { // se quero na vertical c = rand() % 10; l = rand() % (10 - t); for(int i = l; i < t + l; i++) if(oceano[i][c] != 0) return 1; for(int i = l; i < t + l; i++) oceano[i][c] = t; } return 0; } // Chama funcao para criar as posicoes aleatorias void cria_posicoes(int oceano[TAM][TAM]) { printf("Aguarde... Posicionando o porta aviao\n"); while(posiciona_navio(5, oceano)); printf("Aguarde... Posicionando navios tanque\n"); for(int i = 0; i < 2; i++) while(posiciona_navio(4, oceano)); printf("Aguarde... Posicionando contra torpedeiros\n"); for(int i = 0; i < 3; i++) while(posiciona_navio(3, oceano)); printf("Aguarde... Posicionando submarinos\n"); for(int i = 0; i < 4; i++) while(posiciona_navio(2, oceano)); } // Atualiza a minha matriz de oceano com o ataque void oceano_recebe_ataque(int oceano[TAM][TAM], int linha, int coluna){ int posicao_atacada = oceano[linha][coluna]; if(posicao_atacada == 0){ // Se for 0 nao atacou e errou: -1 strcpy(mensagem, "E"); oceano[linha][coluna] = -1; } else if(posicao_atacada == -1) // Se for -1: atacou e errou strcpy(mensagem, "E"); else if(posicao_atacada == 1) // Se for 1: atacou e acertou strcpy(mensagem, "E"); else{ // Se for ! de 0, acertou: 1 strcpy(mensagem, "A"); oceano[linha][coluna] = 1; } } // Atualiza a minha matriz de oceano com o ataque void oceano_rival_ataque(int oceano_rival[TAM][TAM], char flag){ int linha = 0, coluna = 0; if(atq[0] == 'A') linha = 0; if(atq[0] == 'B') linha = 1; if(atq[0] == 'C') linha = 2; if(atq[0] == 'D') linha = 3; if(atq[0] == 'E') linha = 4; if(atq[0] == 'F') linha = 5; if(atq[0] == 'G') linha = 6; if(atq[0] == 'H') linha = 7; if(atq[0] == 'I') linha = 8; if(atq[0] == 'J') linha = 9; coluna = atq[1] - '0'; if(flag == 'A') { oceano_rival[linha][coluna] = 1; pontuacao += 1; } else if (flag == 'E') oceano_rival[linha][coluna] = -1; else if (flag == 'C') {} else printf("Erro no ataque\n"); } // Traduz a mensagem enviada pelo cliente void mensagem_cliente(char ataque[], int oceano[TAM][TAM], int oceano_rival[TAM][TAM]){ int linha = 0, coluna = 0; char flag = 0; //printf("Recebido: %s\n", ataque); if(ataque[0] == 'A') linha = 0; if(ataque[0] == 'B') linha = 1; if(ataque[0] == 'C') linha = 2; if(ataque[0] == 'D') linha = 3; if(ataque[0] == 'E') linha = 4; if(ataque[0] == 'F') linha = 5; if(ataque[0] == 'G') linha = 6; if(ataque[0] == 'H') linha = 7; if(ataque[0] == 'I') linha = 8; if(ataque[0] == 'J') linha = 9; coluna = ataque[1] - '0'; flag = ataque[2]; ult_ac = ataque[2]; oceano_recebe_ataque(oceano, linha, coluna); oceano_rival_ataque(oceano_rival, flag); } int main(int argc, char *argv[]){ int sockfd, cliente, len = sizeof(remoto), porta; char buffer[4096]; if(argc == 2) { porta = atoi(argv[1]); sockfd = socket(AF_INET6, SOCK_STREAM, 0); if(sockfd == -1){ perror("socket "); exit(1); } bzero((char *) &local, sizeof(local)); local.sin6_flowinfo = 0; local.sin6_family = AF_INET6; local.sin6_addr = in6addr_any; local.sin6_port = htons(porta); if(bind(sockfd,(struct sockaddr*)&local, sizeof(local))==-1){ perror("bind "); exit(1); } listen(sockfd, 1); if((cliente = accept(sockfd,(struct sockaddr*)&remoto, &len)) == - 1){ perror("accept "); exit(1); } char ataque[2]; int oceano[TAM][TAM]; int oceano_rival[TAM][TAM]; int flag = 0; char mensagem_fim[1] = {'Z'}; inicializa_oceano(oceano); inicializa_oceano(oceano_rival); cria_posicoes(oceano); while(flag == 0){ envia_mensagem(buffer, oceano_rival); if(send(cliente, buffer, strlen(buffer), 0)){ while(1){ if((recv(cliente,buffer,LEN,0)) > 0) { // recebeu mensagem if(buffer[0] == 'Z') { printf("O cliente ganhou!\n"); close(cliente); flag = 1; break; } if(pontuacao == 30) { memset(buffer, 0x0, LEN); strcat(buffer, mensagem_fim); send(cliente, buffer, strlen(buffer), 0); flag = 1; break; } mensagem_cliente(buffer, oceano, oceano_rival); memset(buffer, 0x0, LEN); break; } } } } close(cliente); close(sockfd); printf("Servidor encerrado!\n"); } else printf("\nPadrao de entrada: PORTA.\n"); return 0; }
C
// // Created by Unknow on 18/11/2020. // #include "cli_menu.h" int menu(char **xml_path, char **dtd_path) { char *temp = *xml_path; *xml_path = strtrim_space(*xml_path); if (temp) { free(temp); } temp = *dtd_path; *dtd_path = strtrim_space(*dtd_path); if (temp) { free(temp); } while (!check_file_exist_and_extension(*xml_path, "xml")) { printf("Please enter xml file path (relative or absolute) :\n"); if (*xml_path) { free(*xml_path); } *xml_path = get_user_input_trimmed_file_path(); } while (!check_file_exist_and_extension(*dtd_path, "dtd")) { printf("Please enter dtd file path (relative or absolute) :\n"); if (*dtd_path) { free(*dtd_path); } *dtd_path = get_user_input_trimmed_file_path(); } return 1; } char *get_user_input_trimmed_file_path() { char *buffer = calloc(sizeof(char), 501); fflush(stdin); fgets(buffer, 500, stdin); //remove end '\n' from user input char *return_char = strchr(buffer, '\n'); if (return_char) { *return_char = '\0'; } else { buffer[500] = '\0'; } char *trimmed_string = strtrim_space(buffer); free(buffer); return trimmed_string; } int check_file_exist_and_extension(char *trimmed_file_path, const char *extension) { return verif_file_extension(trimmed_file_path, extension) && file_exist(trimmed_file_path); } int verif_file_extension(char *trimmed_file_path, const char *extension) { if (!trimmed_file_path) { return 0; } printf("Testing '"); change_console_color(blue); printf("%s", trimmed_file_path); reset_console_color(); printf("' file extension... Should be '"); change_console_color(green); printf("%s", extension); reset_console_color(); printf("'\n"); sprintf(menu_message, "Testing '%s' file extension, should be '%s'", trimmed_file_path, extension); logIt(menu_message, 1); if (trimmed_file_path == NULL) { return 0; } char *bname = basename(trimmed_file_path); char *verif = strrchr(bname, '.'); if (!verif || verif == bname) { change_console_color(red); printf("File '%s' don't have extension !\n\n", bname); sprintf(menu_message, "File '%s' don't have extension !\n", bname); logIt(menu_message, 1); reset_console_color(); return 0; } int return_code = !strcmp(verif + 1, extension); if (!return_code) { change_console_color(red); printf("Wrong file extension, expected '%s' but founded '%s' !\n\n", extension, (verif + 1)); sprintf(menu_message, "Wrong file extension, expected '%s' but founded '%s' !\n", extension, (verif + 1)); logIt(menu_message, 1); reset_console_color(); } else { change_console_color(green); printf("Extension is valid !\n\n"); sprintf(menu_message, "Extension is valid !\n"); logIt(menu_message, 1); reset_console_color(); } return return_code; } int file_exist(char *trimmed_file_path) { if (!trimmed_file_path) { return 0; } printf("Testing if '"); change_console_color(blue); printf("%s", trimmed_file_path); reset_console_color(); printf("' exists...\n"); sprintf(menu_message, "Testing if '%s' exists...\n", trimmed_file_path); logIt(menu_message, 1); FILE *fp = fopen(trimmed_file_path, "r"); if (!fp) { change_console_color(red); printf("File don't exist !\n\n"); sprintf(menu_message, "File don't exist !\n"); logIt(menu_message, 1); reset_console_color(); return 0; } change_console_color(green); printf("File exists !\n\n"); sprintf(menu_message, "File exist !\n"); logIt(menu_message, 1); reset_console_color(); fclose(fp); return 1; }
C
/*! \file Blackjack.c \author Clément BELLEIL \version 1.0 \date 9 décembre 2020 \brief TP_09 Blackjack */ #include "Blackjack.h" int NouvelleManche(int nbjoueur, Joueur liste_j[7]) { int int_i; int int_choix; int int_valretour; for(int_i=1;int_i<nbjoueur+1;int_i++) { if (liste_j[int_i].int_pot==0) { printf("\n%s Votre pot est à 0 ... la partie s'arrête !\n",liste_j[int_i].char_nom); return(PARTIE_TERMINEE); } } printf("\n Voulez vous continuer ?\n"); printf("1 - Oui on continue !\n"); printf("2 - Non on arrête !\n"); int_valretour=scanf("%d",&int_choix); while ((int_valretour!=1)||(int_choix>2)||(int_choix==0)) { viderBuffer(); printf("Je ne suis pas sur d'avoir compris, veuillez resaisir votre choix : \n"); int_valretour=scanf("%d",&int_choix); } return(int_choix); } int verifGagne(int numJoueur,Joueur liste_j[7],Carte Jeu[TAILLE]) { int int_i; int int_valtot; int_valtot=0; for (int_i=0;int_i<liste_j[numJoueur].int_nbCartes;int_i++) { if ((liste_j[numJoueur].Jeu_joueur[int_i].int_valeur==1)&&(int_valtot+11<=21)) { //As compte pour 11 si cela arrange le joueur ... int_valtot=int_valtot+11; } else { int_valtot=int_valtot+liste_j[numJoueur].Jeu_joueur[int_i].int_valeur; // ... ou pour 1 si le joueur dépasse 21 } } if ((int_valtot==21)&&(liste_j[numJoueur].int_nbCartes==2)) { // BUCHE ET AS return(-1); } else if (int_valtot>=22) { return(0); } else { return (int_valtot); } } int TourDeJeu(int numJoueur,Joueur liste_j[7],Carte Jeu[TAILLE]) { int int_valretour; int int_choix; if((verifGagne(numJoueur,liste_j,Jeu)==-1)||(verifGagne(numJoueur,liste_j,Jeu)==0)) { //On verifie d'abord qu'il n'a pas fait blackjack avec les 2 cartes return(TOUR_FINI); } printf("\n%s C'est à votre tour\n",liste_j[numJoueur].char_nom); printf(" Souhaitez vous tirer une carte ? ou bien rester ?\n"); printf("1 - Carte !\n"); printf("2 - Je reste !\n"); int_valretour=scanf("%d",&int_choix); while ((int_valretour!=1)||(int_choix>2)||(int_choix==0)) { viderBuffer(); printf("Je ne suis pas sur d'avoir compris, veuillez resaisir votre choix : \n"); int_valretour=scanf("%d",&int_choix); } while (int_choix==1) { demandeCarte(numJoueur,liste_j[numJoueur].int_nbCartes,liste_j,Jeu); if(verifGagne(numJoueur,liste_j,Jeu)==0) { //On verifie que le joueur n'a pas bust return(TOUR_FINI); } printf(" Voulez vous retirer une carte, ou non ?\n"); printf(" 1 - Carte !\n"); printf(" 2 - Je reste !\n"); int_valretour=scanf("%d",&int_choix); } return(TOUR_FINI); } int demandeCarte(int numJoueur,int int_numCarte,Joueur liste_j[7],Carte Jeu[TAILLE]) { //Tire carte et affiche jeu_joueur int int_i; printf(" Vous avez décider de tirer une carte, votre jeu est maintenant le suivant :\n"); distribCarte(numJoueur,int_numCarte,liste_j,Jeu); for (int_i=0;int_i<int_numCarte+1;int_i++) { printf(" Carte %d-> Couleur : %d, Valeur : %d\n",int_i+1,liste_j[numJoueur].Jeu_joueur[int_i].int_couleur,liste_j[numJoueur].Jeu_joueur[int_i].int_valeur); } liste_j[numJoueur].int_nbCartes=liste_j[numJoueur].int_nbCartes+1; return(0); } int distribCarte(int numJoueur,int numCarte,Joueur liste_j[7], Carte Jeu[TAILLE]) { int int_rand; int_rand=rand()%(TAILLE); while ((Jeu[int_rand].bool_distrib)==1) { //Si la carte a déjà été distribué, on en "retire" une. int_rand=rand()%(TAILLE); } Jeu[int_rand].bool_distrib=1; // Carte est distribuée liste_j[numJoueur].Jeu_joueur[numCarte]=Jeu[int_rand]; return(0); } int initJoueur(int nbtour,int numJoueur,Joueur liste_j[7],Carte Jeu[TAILLE]) { //7 joueurs max size_t nb1; int int_valretour; if (nbtour==1) { // Si c'est le premier tour, on "initialise" les profils if (numJoueur!=1) { viderBuffer(); } if (numJoueur!=0) { liste_j[numJoueur].char_nom=NULL; printf("Veuillez saisir le nom du joueur %d :\n",numJoueur); getline(&liste_j[numJoueur].char_nom, &nb1, stdin); liste_j[numJoueur].int_pot=200; // POT INITIAL DE CHAQUE JOUEUR (ARBITRAIRE) printf("Veuillez saisir votre mise pour ce tour (Pot : %d) : ",liste_j[numJoueur].int_pot); // Mise demandée pour le tour int_valretour=scanf("%d",&liste_j[numJoueur].int_mise); while ((liste_j[numJoueur].int_mise>liste_j[numJoueur].int_pot)||(int_valretour!=1)||(liste_j[numJoueur].int_mise==0)) { viderBuffer(); printf("Veuillez resaisir votre mise pour ce tour (Pot : %d) : ",liste_j[numJoueur].int_pot); int_valretour=scanf("%d",&liste_j[numJoueur].int_mise); } } liste_j[numJoueur].int_nbCartes=0; distribCarte(numJoueur,0,liste_j,Jeu); distribCarte(numJoueur,1,liste_j,Jeu); liste_j[numJoueur].int_nbCartes=2; return(0); } else { // Si ce n'est pas le premier tour, on a juste besoin de savoir la mise de chacun des joueurs pour le tour if (numJoueur!=1) { viderBuffer(); } if (numJoueur!=0) { printf("%s Veuillez saisir votre mise pour ce tour (Pot : %d) : ",liste_j[numJoueur].char_nom,liste_j[numJoueur].int_pot); // Mise demandée pour le tour int_valretour=scanf("%d",&liste_j[numJoueur].int_mise); while ((liste_j[numJoueur].int_mise>liste_j[numJoueur].int_pot)||(int_valretour!=1)||(liste_j[numJoueur].int_mise==0)) { viderBuffer(); printf(" Veuillez resaisir votre mise pour ce tour (Pot : %d) : ",liste_j[numJoueur].int_pot); int_valretour=scanf("%d",&liste_j[numJoueur].int_mise); } } liste_j[numJoueur].int_nbCartes=0; distribCarte(numJoueur,0,liste_j,Jeu); distribCarte(numJoueur,1,liste_j,Jeu); liste_j[numJoueur].int_nbCartes=2; return(0); } } int Blackjack(int nbjoueur,int nbtour) { srand(time(NULL)); int int_i; int int_j; Carte Jeu[TAILLE]; Joueur liste_j[7]; //INITIALISATION DES JOUEURS ET DE LEUR MAIN, ET DE CELLE DU BANQUIER (J0) initJeu(Jeu); for(int_i=1;int_i<nbjoueur+1;int_i++) { initJoueur(nbtour,int_i,liste_j,Jeu); } initJoueur(nbtour,0,liste_j,Jeu); //AFFICHAGE JEU INIT for (int_i=1;int_i<nbjoueur+1;int_i++) { // Pour chaque joueur, on affiche son jeu initial. printf("\n%s Vos deux cartes initiales sont les suivantes :\n",liste_j[int_i].char_nom); for (int_j=0;int_j<2;int_j++) { printf(" Carte %d-> Couleur : %d, Valeur : %d\n",int_j+1,liste_j[int_i].Jeu_joueur[int_j].int_couleur,liste_j[int_i].Jeu_joueur[int_j].int_valeur); } } printf("\nLa première carte du banquier est la suivante :\n"); //On montre les cartes du banquier avant de demander aux joueurs de jouer printf(" Carte %d-> Couleur : %d, Valeur : %d\n",1,liste_j[0].Jeu_joueur[0].int_couleur,liste_j[0].Jeu_joueur[0].int_valeur); printf(" Sa deuxième est face cachée\n"); //TOUR DE JEU JOUEURS for (int_i=1;int_i<nbjoueur+1;int_i++) { TourDeJeu(int_i,liste_j,Jeu); } //TOUR DE JEU BANQUIER printf("\nFinalement, les cartes du banquier sont :\n"); for (int_i=0;int_i<2;int_i++) { printf(" Carte %d-> Couleur : %d, Valeur : %d\n",int_i+1,liste_j[0].Jeu_joueur[int_i].int_couleur,liste_j[0].Jeu_joueur[int_i].int_valeur); } while ((verifGagne(0,liste_j,Jeu)<=16)&&(verifGagne(0,liste_j,Jeu)>0)) { //IL TIRE A 16 ET RESTE A 17 TANT QU'IL A PAS DE BLACKJACK demandeCarte(0,liste_j[0].int_nbCartes,liste_j,Jeu); } //RESULTAT for (int_i=1;int_i<nbjoueur+1;int_i++) { if ((verifGagne(int_i,liste_j,Jeu)==-1)&&(verifGagne(0,liste_j,Jeu)==21)) { //Joueur a fait un blackjack et le banquier a fait 21 en 3 cartes ou plus printf("\nBLACKJACK ! le joueur %d remporte le double de sa mise car le banquier a fait 21 !\n",int_i); liste_j[int_i].int_pot=liste_j[int_i].int_pot+2*liste_j[int_i].int_mise; printf(" Son pot est désormais de : %d\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; } else if (verifGagne(int_i,liste_j,Jeu)==-1) { //Joueur a fait un blackjack printf("\nBLACKJACK ! le joueur %d remporte sa mise !\n",int_i); liste_j[int_i].int_pot=liste_j[int_i].int_pot+liste_j[int_i].int_mise; printf(" Son pot est désormais de : %d\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; } else if (verifGagne(0,liste_j,Jeu)==-1 ){ //Banquier a fait un blackjack printf("\nBLACKJACK POUR LE BANQUIER! le joueur %d perd sa mise !\n",int_i); liste_j[int_i].int_pot=liste_j[int_i].int_pot-liste_j[int_i].int_mise; printf(" Son pot est désormais de : %d\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; } else if (verifGagne(0,liste_j,Jeu)==0) { //Banquier a bust printf("\nBUST POUR LE BANQUIER ! le joueur %d remporte sa mise !\n",int_i); liste_j[int_i].int_pot=liste_j[int_i].int_pot+liste_j[int_i].int_mise; printf(" Son pot est désormais de : %d\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; } else if (verifGagne(int_i,liste_j,Jeu)==0) { //Joueur a bust printf("\nBUST ! le joueur %d perd sa mise car sa valeur totale est supérieure à 21...\n",int_i); liste_j[int_i].int_pot=liste_j[int_i].int_pot-liste_j[int_i].int_mise; printf(" Son pot est désormais de : %d\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; }else if ((verifGagne(0,liste_j,Jeu))>(verifGagne(int_i,liste_j,Jeu))) { //Banquier a gagné printf("\n%s Vous perdez votre mise ... la valeur totale du banquier est %d alors que la votre est %d\n",liste_j[int_i].char_nom,verifGagne(0,liste_j,Jeu),verifGagne(int_i,liste_j,Jeu)); liste_j[int_i].int_pot=liste_j[int_i].int_pot-liste_j[int_i].int_mise; printf(" Votre pot est désormais de %d\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; } else if ((verifGagne(0,liste_j,Jeu))<(verifGagne(int_i,liste_j,Jeu))) { //Joueur a gagné printf("\n%s Vous remportez votre mise ! la valeur totale du banquier est %d alors que la votre est %d !\n",liste_j[int_i].char_nom,verifGagne(0,liste_j,Jeu),verifGagne(int_i,liste_j,Jeu)); liste_j[int_i].int_pot=liste_j[int_i].int_pot+liste_j[int_i].int_mise; printf(" Votre pot est désormais de %d !\n",liste_j[int_i].int_pot); liste_j[int_i].int_mise=0; } else { // Egalité printf("\nEGALITE, les mises sont conservées. On peut passer au tour suivant !\n\n"); } } // TOUR SUIVANT return(NouvelleManche(nbjoueur,liste_j)); } int mainBlackjack(int int_nbjoueur) { int int_nbtour; int_nbtour=1; printf("### JEU DE BLACKJACK ###\n"); while (Blackjack(int_nbjoueur,int_nbtour)==1) { int_nbtour++; } printf(" Au revoir ! \n"); return(PARTIE_TERMINEE); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* render.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cmelara- <cmelara-@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/22 20:20:39 by cmelara- #+# #+# */ /* Updated: 2019/01/29 13:26:54 by cmelara- ### ########.fr */ /* */ /* ************************************************************************** */ #include "wolf3d.h" void render_background(t_engine *engine) { SDL_Rect rect; rect.w = WINDOW_WIDTH; rect.h = WINDOW_HEIGHT / 2; rect.x = 0; rect.y = 0; SDL_FillRect(engine->surface, &rect, 0x587399); rect.y = WINDOW_HEIGHT / 2; SDL_FillRect(engine->surface, &rect, 0x2c2c2c); } void render_walls(t_engine *engine) { int x; t_col column; x = 0; while (x < WINDOW_WIDTH) { raycast(engine, engine->player, x); engine->ray->wall_height = (int)(WINDOW_HEIGHT / engine->ray->wall_dist); column.start = (int)(WINDOW_HEIGHT / 2 - engine->ray->wall_height / 2); column.start = (column.start < 0) ? 0 : column.start; column.end = (int)(WINDOW_HEIGHT / 2 + engine->ray->wall_height / 2); column.end = (column.end >= WINDOW_HEIGHT) ? WINDOW_HEIGHT - 1 : column.end; draw_column(engine, x, column, engine->ray); x++; } } void render_hud(t_engine *engine) { SDL_Rect rect; rect.w = 512; rect.h = 512; rect.x = (int)(WINDOW_WIDTH / 2) - rect.w / 2; rect.y = WINDOW_HEIGHT - rect.h; SDL_BlitScaled(engine->gun, NULL, engine->surface, &rect); } void render(t_engine *engine) { render_background(engine); render_walls(engine); render_hud(engine); update_screen(engine); }
C
/* vim: tabstop=4 shiftwidth=4 noexpandtab * This file is part of ToaruOS and is released under the terms * of the NCSA / University of Illinois License - see LICENSE.md * Copyright (C) 2018 K. Lange * * hexify - Convert binary to hex. * * This is based on the output of xxd. * Does NOT a hex-to-bin option - something to consider. */ #include <stdio.h> #include <ctype.h> void print_line(unsigned char * buf, unsigned int width, unsigned int sizer, unsigned int offset) { fprintf(stdout, "%08x: ", sizer); for (unsigned int i = 0; i < width; ) { if (i >= offset) { fprintf(stdout, " "); } else { fprintf(stdout, "%02x", buf[i]); } i++; if (i == width) break; /* in case of odd width */ if (i >= offset) { fprintf(stdout, " "); } else { fprintf(stdout, "%02x ", buf[i]); } i++; } fprintf(stdout, " "); for (unsigned int i = 0; i < width; i++) { if (i >= offset) { fprintf(stdout, " "); } else { if (isprint(buf[i])) { fprintf(stdout, "%c", buf[i]); } else { fprintf(stdout, "."); } } } fprintf(stdout, "\n"); } int main(int argc, char * argv[]) { FILE * f; unsigned int width = 16; /* TODO make configurable */ if (argc > 1) { f = fopen(argv[1], "r"); if (!f) return 1; } else { f = stdin; } unsigned int sizer = 0; unsigned int offset = 0; unsigned char buf[width]; while (!feof(f)) { unsigned int r = fread(buf+offset, 1, width-offset, f); offset += r; if (offset == width) { print_line(buf, width, sizer, offset); offset = 0; sizer += width; } } if (offset != 0) { print_line(buf, width, sizer, offset); } return 0; }
C
#include "stack.h" #define SIZE 512 /* _Bool stack(u64 in, u64* out, _Bool push, _Bool pop) { static u64 stack[SIZE]; static u16 ptr = 0; _Bool result = 1; if (push && ptr < SIZE) { stack[ptr++] = in; } else if (pop && ptr > 0) { *out = stack[--ptr]; } else result = 0; return result; } */ _Bool stack(u64 in, u64* out, _Bool push, _Bool pop) { static u64 stack[SIZE]; static u16 push_ptr = 0; static u16 pop_ptr = 0; _Bool result = 1; if (push && push_ptr < SIZE) { pop_ptr = push_ptr; stack[push_ptr++] = in; } else if (pop && push_ptr > 0) { push_ptr = pop_ptr; *out = stack[pop_ptr--]; } else result = 0; return result; }
C
using static System.Console; namespace exercicio32 { public class exercicio32 { public static void Main(string[] args) { int[] numeros = new int[args.Length]; for (int i = 0; i < args.Length; i++) { int numero; if (int.TryParse(args[i], out numero)) { numeros[i] = numero; } else { WriteLine("Dado inválido! Digite apenas números separados por espaço"); } } Write("Vetor: "); for (int i = 0; i < args.Length; i++) { Write($"{numeros[i]} "); } OrdernaVetor(numeros); WriteLine("\nVetor Ordenado: "); for (int i = 0; i < args.Length; i++) { Write($"{numeros[i]} "); } } public static void OrdernaVetor(int[] vetor) { for (int i = 0; i < vetor.Length; i++) { for (int j = 0; j < vetor.Length - 1; j++) { if (vetor[j] > vetor[j + 1]) { int temp = vetor[j + 1]; vetor[j + 1] = vetor[j]; vetor[j] = temp; } } } } } } //http://pt.stackoverflow.com/q/182249/101
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> void set_read(int* lpipe) { dup2(lpipe[0], STDIN_FILENO); close(lpipe[0]); // we have a copy already, so close it close(lpipe[1]); // not using this end } void set_write(int* rpipe) { dup2(rpipe[1], STDOUT_FILENO); close(rpipe[0]); // not using this end close(rpipe[1]); // we have a copy already, so close it } void fork_and_chain(int* lpipe, int* rpipe) { if(!fork()) { if(lpipe) // there's a pipe from the previous process set_read(lpipe); // else you may want to redirect input from somewhere else for the start if(rpipe) // there's a pipe to the next process set_write(rpipe); // else you may want to redirect out to somewhere else for the end // blah do your stuff // and make sure the child process terminates in here // so it won't continue running the chaining code } } int main(){ // two pipes: one from the previous in the chain, one to the next in the chain int lpipe[2], rpipe[2]; // create the first output pipe pipe(rpipe); // first child takes input from somewhere else fork_and_chain(NULL, rpipe); // output pipe becomes input for the next process. lpipe[0] = rpipe[0]; lpipe[1] = rpipe[1]; // chain all but the first and last children for(i = 1; i < N - 1; i++) { pipe(rpipe); // make the next output pipe fork_and_chain(lpipe, rpipe); close(lpipe[0]); // both ends are attached, close them on parent close(lpipe[1]); lpipe[0] = rpipe[0]; // output pipe becomes input pipe lpipe[1] = rpipe[1]; } // fork the last one, its output goes somewhere else fork_and_chain(lpipe, NULL); close(lpipe[0]); close(lpipe[1]); }
C
/*! \file main.c \brief Main program of the serial solar system simulator. \author Peter C. Chapin <PChapin@vtc.vsc.edu> LICENSE This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <stdio.h> #include <stdlib.h> #include <mpi.h> #include "global.h" #include "Initialize.h" #include "Timer.h" #define STEPS_PER_YEAR 8766 // Number of hours in a year. int main( int argc, char **argv ) { Timer stopwatch; long long total_steps = 0; int total_years = 0; int return_code = EXIT_SUCCESS; int my_rank; MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &my_rank ); initialize_object_arrays( ); Timer_initialize( &stopwatch ); Timer_start( &stopwatch ); while (1) { time_step( ); total_steps++; // Print out a message after 100 steps just to give the user something to see. if( total_steps % 100 == 0 && my_rank == 0 ) printf( "STEP %4lld\n", total_steps ); if( total_steps % STEPS_PER_YEAR == 0 ) { total_years++; if( total_years % 10 == 0 && my_rank == 0 ) { printf( "Years simulated = %d\r", total_years ); fflush( stdout ); } // For now, stop the simulation after 1 year. if( total_years == 1 ) break; } } Timer_stop( &stopwatch ); if( my_rank == 0 ) { dump_dynamics( ); printf( "Time elapsed = %ld milliseconds\n", Timer_time( &stopwatch ) ); } MPI_Finalize( ); return return_code; }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> struct transition { char car;//caractère étiquetant la transition. -1 si c'est une epsilon transition int arr;//état d'arrivée de la transition struct transition *suiv; }; typedef struct transition *TRANSITION ; typedef struct{ int sigma; // Le nombre de lettre de l'alphabet, les lettres de l'alphabet étant les minuscules. Ce qui limite donc à 26 int Q; // Le nombre d'états qui sont numérotés de 0 à Q-1. 0 étant l'état initial int *F; // Un tableau monodimensionnel de taille Q qui indique pour chaque état s'il est final ou non TRANSITION *T; //Un tableau de taille Q donnant pour chaque état la liste des transitions depuis cet état }AUTOMATE; ////////////////////Liste des fonctions de manipulation d'automates fournies //////////////////////////////////// TRANSITION copie_liste(TRANSITION T, int decalage, int conserve_epsilon);//copie une liste de transitions, en ajoutant décalage au numero de l'état d'arrivée //si conserve_epsilon == 0, ne conserve pas les epsilon transitions AUTOMATE automate_creer (int Q); // Création d'un automate de taille Q, sans états finaux et sans transitions AUTOMATE automate_copier(AUTOMATE A, int conserve_epsilon);//créé une copie fraiche de l'automate A //si conserve_epsilon == 0, ne conserve pas les epsilon transitions void automate_ajouter_transition (AUTOMATE A, int dep, char car, int arr); // Ajoute la transition (dep,car,arr) à l'automate (ne fait rien si elle existe) //void automate_supprimer_transition (AUTOMATE A, int dep, char car, int arr); // Ne fait rien si elle n'existe pas void automate_ajouter_final (AUTOMATE A, int q); //ajoute l'état q aux états finaux //void automate_supprimer_final (AUTOMATE A, int q); //supprime l'état q des états finaux void automate_liberer_memoire(AUTOMATE A);// libère la mémoire allouée dynamiquement pour l'automate void automate_ecrire (AUTOMATE A, char* nomfic); // Ecrit un automate dans un fichier sous la forme : /* Q F T F_1 F_2 F_3 ... F_F dep_1 car_1 arr_1 dep_2 car_2 arr_2 ... dep_T car_T arr_T Q : nombre d'états F : nombre d'états finaux T : nombres de transitions F_i : les numéros des états finaux dep_j car_j arr_J : une transition */ AUTOMATE automate_lire (char* nomfic); // Lit un automate depuis un fichier sous la forme précédente AUTOMATE automate_supprimer_epsilon(AUTOMATE A);//renvoie un automate sans epsilon transition qui reconnait le // même langage que A //////////////////////////// Fonction à programmer vous même ///////////////////////////////////////////////// AUTOMATE automate_une_lettre(char car);//renvoie l'automate qui reconnait le mot constitué de la lettre car ou epsilon si car = -1 AUTOMATE automate_epsilon();//renvoie l'automate qui reconnait le mot epsilon AUTOMATE automate_concatenation(AUTOMATE A, AUTOMATE B);//renvoie un automate qui reconnaît la concaténation des //langages reconnus par A et B AUTOMATE automate_disjonction(AUTOMATE A, AUTOMATE B);//renvoie un automate qui reconnaît la disjonction des //langages reconnus par A et B AUTOMATE automate_etoile(AUTOMATE A);//renvoie un automate qui reconnaît l'étoile de Kleene du langage du langage reconnu par A AUTOMATE automate_determiniser(AUTOMATE A);//renvoie un automate déterministe qui reconnait le même langage que A AUTOMATE automate_transpose(AUTOMATE A); AUTOMATE automate_minimal(AUTOMATE A);
C
#include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include "../array/array.h" #include "stack.h" #include "../errors.h" void init_stack(stack * s) { if (s->_array != NULL) { printf("Can't init twice for stack!\n"); exit(ERR_INIT_TWICE); } s->_array = new_array(); if(s->_array->_data != NULL){ printf("haha\n"); } init_array(s->_array); s->_top_idx = 0; } void release_stack(stack * s) { release_array(s->_array); //先释放内部的 free(s->_array); //再释放其本身,谁申请,谁释放 s->_array = NULL; s->_top_idx = 0; } void push_stack(stack * s, int v) { int ns = need_resize_before_add(s->_array); if (ns != -1) { resize_array(s->_array, ns, 0, s->_top_idx); } add_array_item(s->_array, s->_top_idx++, v); } static void check_data_avaliable(int num) { if (num <= 0) { printf("not data ever\n"); exit(ERR_NO_DATA); } } int pop_stack(stack * s) { check_data_avaliable(get_array_datanum(s->_array)); int v = del_array_item(s->_array, --(s->_top_idx)); int ns = need_resize_after_remove(s->_array); if (ns != -1) { resize_array(s->_array, ns, 0, s->_top_idx); } return v; } int get_stack_top(stack * s) { check_data_avaliable(get_array_datanum(s->_array)); return get_array_item(s->_array,s->_top_idx-1); } int get_stack_datanum(stack * s) { return s->_top_idx; } int get_stack_size(stack * s) { return s->_array->_size; }
C
#include "extras.h" int ft_execute_d(t_data *d, t_inst i) { if (!st_push(d->ih, i)) return (0); if (!ft_execute(i, d->a, d->b)) return (0); return (1); } int ft_free_data(t_data *d) { st_free(d->a); st_free(d->b); st_free(d->mem); st_free(d->ih); return (0); } void *ft_dummy_sum(int n) { n++; return (0); } int ft_is_num_int(const char *str) { int i; i = 0; if (str[0] == '-') i++; while (str[i]) if (str[i] >= 48 && str[i] <= 57) i++; else return (0); return (ft_str_is_int(str)); } int ft_check_argv(int argc, char **argv) { int i; i = 1; if (argc <= 1) { write(2, "Error\n", 6); return (0); } while (i < argc) { if (!ft_is_num_int(argv[i])) { write(2, "Error\n", 6); return (0); } i++; } return (1); }
C
#include<stdio.h> void main() { int a[100],b,i,c,d,e,f,k; printf("enter the value "); scanf("%d",&c); printf("enter the value "); for(b=1;b<=c;b++) scanf("%d", &a[b]); for(d=1;d<=c;d++) { if(a[d]>f) f=a[d]; } printf("the maximum value %d",f); for(d=1;d<=c;d++) { if(a[d]<f) f=a[d]; } printf("\nthe minimum value %d",f); }
C
#include <xeroskernel.h> #include <i386.h> /*----------------------------------------------------------------------------------- * Tests for mem.c. * * List of functions that are called from outside this file: * - run_mem_test * - Runs the test suite for mem.c *----------------------------------------------------------------------------------- */ extern unsigned long freemem_aligned; extern unsigned long hole_start_aligned; extern unsigned long hole_end_aligned; extern unsigned long max_addr_aligned; /*----------------------------------------------------------------------------------- * Runs the test suite for mem.c. *----------------------------------------------------------------------------------- */ void run_mem_test(void) { kprintf("Testing memory management...\n"); // Test: kmeminit initializes with 2 free blocks assert_equal(get_free_list_length(), 2); // Test: kmalloc rejects 0 assert_equal((int) kmalloc(0), 0); // Test: kmalloc rejects negative assert_equal((int) kmalloc(-1), 0); // Test: kmalloc rejects size larger than maximum allocatable memory // https://stackoverflow.com/questions/3472311/what-is-a-portable-method-to-find-the-maximum-value-of-size-t size_t max_size = (size_t) - 1; // Upper bound of size_t is (2^32 - 1) in this system assert_equal((int) kmalloc(max_size), 0); // Test: kfree rejects NULL assert_equal(kfree(NULL), 0); // Test: kfree rejects address not on paragraph boundary assert_equal(kfree((void *) 10), 0); // kmalloc and kfree tests unsigned long *p1 = (unsigned long *) kmalloc(16); unsigned long *p2 = (unsigned long *) kmalloc(16); unsigned long *p3 = (unsigned long *) kmalloc(16); unsigned long *p4 = (unsigned long *) kmalloc(16); assert_equal(get_free_list_length(), 2); // Test: kfree merges adjacent free blocks assert_equal(kfree(p1), 1); assert_equal(get_free_list_length(), 3); assert_equal(kfree(p2), 1); assert_equal(get_free_list_length(), 3); assert_equal(kfree(p4), 1); assert_equal(get_free_list_length(), 3); assert_equal(kfree(p3), 1); assert_equal(get_free_list_length(), 2); // Test: Cannot free block twice assert_equal(kfree(p4), 0); // Test: Allocate all available free memory unsigned long *p5 = (unsigned long *) kmalloc(hole_start_aligned - freemem_aligned - 16); unsigned long *p6 = (unsigned long *) kmalloc(max_addr_aligned - hole_end_aligned - 16); assert_equal((int) kmalloc(1), 0); assert_equal(get_free_list_length(), 0); assert_equal(kfree(p5), 1); assert_equal(get_free_list_length(), 1); assert_equal(kfree(p6), 1); assert_equal(get_free_list_length(), 2); // Test: kmalloc aligns on paragraph boundary // Need 16 bytes for header, then 10 bytes to satisfy request unsigned long *p7 = (unsigned long *) kmalloc(10); assert_equal((unsigned long) p7, freemem_aligned + 16); // 26 bytes was allocated, so next header starts at 32 and next block starts at 48 unsigned long *p8 = (unsigned long *) kmalloc(10); assert_equal((unsigned long) p8, freemem_aligned + 48); }
C
#include "ft_printf.h" void flags_init(t_options *structure) { structure->flag = -1; structure->width = 0; structure->precision = -1; structure->zero = 0; structure->type = '\0'; } int type(char format, va_list ap, t_options *structure) { int if_error; if_error = 0; if (format == (structure->type = 'c')) charr(ap, structure); else if (format == (structure->type = 'd')) if_error = intt(ap, structure); else if (format == (structure->type = 'i')) if_error = intt(ap, structure); else if (format == (structure->type = 's')) string(ap, structure); else if (format == (structure->type = 'u')) if_error = unsigned_int(ap, structure); else if (format == (structure->type = 'p')) if_error = pointer(ap, structure); else if (format == (structure->type = '%')) percent(structure); else if (format == (structure->type = 'X')) if_error = hex(ap, structure); else if (format == (structure->type = 'x')) if_error = hex(ap, structure); if (if_error) return (if_error); return (0); } void flag(const char **format, t_options *structure) { while (*(*format + 1) == '-' || *(*format + 1) == '0') { if (*(*format + 1) == '-') structure->flag = 1; if (*(*format + 1) == '0' && structure->flag != 1) structure->flag = 0; (*format)++; } } void width(const char **format, t_options *structure, va_list ap) { if (ft_isdigit(*(*format + 1))) { structure->width = ft_atoi(*format + 1); while (ft_isdigit(*(*format + 1))) (*format)++; } else if (*(*format + 1) == '*') { structure->width = va_arg(ap, int); if (structure->width < 0) { structure->width = structure->width * -1; structure->flag = 1; } (*format)++; } } void prec(const char **format, t_options *structure, va_list ap) { if (*(*format + 1) == '.') { structure->precision = 0; (*format)++; if (ft_isdigit(*(*format + 1))) { structure->precision = ft_atoi(*format + 1); while (ft_isdigit(*(*format + 1))) (*format)++; } else if (*(*format + 1) == '*') { structure->precision = va_arg(ap, int); (*format)++; } } if (structure->precision < 0) structure->precision = -1; }
C
/*13. Escriba una función que reciba un entero y devuelva su factorial. */ #include <stdio.h> int getFactorial(int x){ int aux = 1; for(;x > 1;x--){ aux*=x; } return aux; } int main() { int n = 2; printf("Factorial de %d: %d\n", n, getFactorial(n)); return 0; }
C
// print the square of a number. #include<stdio.h> int main(int argc, char const *argv[]) { float square(float b); // Make sure this matches the definition. int main() { float a, y; printf("enter a number?\n"); scanf("%f", &a); y = square( a ); printf("%f", y); } }
C
#include<stdio.h> #include<string.h> int main() { int i=0,j=0,k=0,l=0; char inp[50]={0},part1[50]={0},part2[50]={0}; printf("Enter production in the form A-> Aa1|Aa2|...|b1|b2..\nA-> "); gets(inp); inp[strlen(inp)]='\0'; if(inp[0]=='A') { abc:for(i++,j=0;inp[i]!='|';i++,l++) part1[l]=inp[i]; part1[l]='A'; part1[++l]='\''; part1[++l]='|'; part1[++l]='\0'; j=0; do { k=i+1; if(inp[k]=='A') { i++; goto abc; } else { for(i++;inp[i]!='|'&&inp[i];i++,j++) part2[j]=inp[i]; if(inp[i]=='|') { part2[j]='A'; part2[++j]='\''; part2[++j]='|'; j++; } } } while(inp[i]); part2[j]='A'; part2[++j]='\''; part2[++j]='\0'; printf("A-> %s",part2); printf("\nA'-> %s",part1); printf("e\n"); } else printf("No LR\n"); return 0; }
C
/* main.c Autor: Orlando Enrico Liz Silvério Silva */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "matriz.h" int main(int argc, const char * argv[]) { int N=0, M=0; int i=0, n1=0, n2=0; char op[4]; //ponteiros para ler e escrever em arquivos de //entrada e saída FILE *fpr, *fpw; if(argc == 3){ fpr = fopen(argv[1], "r"); if(fscanf(fpr, "%d %d", &N, &M)!=2){ printf("Erro de leitura de N e/ou M\n"); } //aborta o programa se N e M possuirem valores //fora dos limites especificados if((N<1 || N>1000000) || (M<1 || M>10000000)) return 0; int *V = (int *) malloc((N+1)*sizeof(int)); Matrix matrix; criaMatriz(&matrix, N+1); //vetor começa da posição 1, não 0 for(i=1; i<=N; i++){ if(fscanf(fpr, "%d", &V[i])!=1){ printf("Erro de leitura nos elementos do vetor\n"); } } //processa a matriz com as tuplas correspondentes aos intervalos //possíveis processaMatriz(&matrix, V, N); fpw = fopen(argv[2], "w"); for(i=0; i<M; i++){ if(fscanf(fpr, "%s %d %d", op, &n1, &n2)<=0){ printf("Erro de leitura nas operacoes\n"); } //execução das operações if(strcmp(op, "Add")==0){ addMatriz(&matrix, V, N, n1, n2); }else{ if(strcmp(op, "Sub")==0){ subMatriz(&matrix, V, N, n1, n2); }else{ if(strcmp(op, "Min")==0){ fprintf(fpw, "%d\n", matrix.data[n1-1][n2-1].min); }else{ if(strcmp(op, "Max")==0){ fprintf(fpw, "%d\n", matrix.data[n1-1][n2-1].max); }else{ if(strcmp(op, "Sum")==0){ fprintf(fpw, "%d\n", matrix.data[n1-1][n2-1].sum); } } } } } } fclose(fpw); fclose(fpr); freeMatrix(&matrix); }else{ printf("Erro de entrada\n"); } return 0; }
C
#include <stdlib.h> #include <stdio.h> void exportGPIOFile(char* fileName, int pin) { printf("Called %s, %d", fileName, pin); FILE *pfile = fopen(fileName, "w"); if (pfile == NULL) { printf("ERROR: Unable to open the file.\n"); exit(1); } fprintf(pfile, "%d", pin); fclose(pfile); } int main() { exportGPIOFile("/sys/class/gpio/export", 30); return 0; }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #define MAX_ROW 1000 typedef struct element { char *string; int frequency; struct element *next; } element; // Insertion is SORTED ALPHABETICALLY! element *storeWord(element *list, char *word) { for(int i = 0; i < strlen(word); ++i) word[i] = tolower(word[i]); if(list == NULL) { element *e = malloc(sizeof(element)); e->string = strdup(word); e->frequency = 1; e->next = NULL; return e; } element *parent = NULL; element *cursor = list; while(cursor != NULL) { int result = strcmp(word, cursor->string); if(result == 0) { ++cursor->frequency; return list; } else if(result > 0) // Word comes after the current string: continue searching... { parent = cursor; cursor = cursor->next; } else // Word comes before the current string but no match has been found: need to insert! { element *e = malloc(sizeof(element)); e->string = strdup(word); e->frequency = 1; e->next = cursor; if(parent == NULL) // No parent -> word is the parent of the first element -> head insertion return e; else { parent->next = e; return list; } } } // If we reached here, it means that the word is not present in the list and comes after every word: tail insertion element *e = malloc(sizeof(element)); e->string = strdup(word); e->frequency = 1; e->next = NULL; parent->next = e; return list; } int main(void) { FILE *input = fopen("input.txt", "r"); if(input == NULL) { fprintf(stderr, "ERROR: Failed to open file!\n"); exit(1); } element *list = NULL; char word[MAX_ROW + 1]; while(fscanf(input, "%s", word) != EOF) list = storeWord(list, word); element *current = list; while(current != NULL) { element *next = current->next; printf("%s %d\n", current->string, current->frequency); free(current->string); free(current); current = next; } }
C
// vim: set tabstop=2 softtabstop=2 shiftwidth=2 expandtab : /* * Copyright (c) 2017, Ryan V. Bissell * All rights reserved. * * SPDX-License-Identifier: MIT * See the enclosed "LICENSE.forge" file for exact license terms. */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include "fibgen.h" void usage(char* name) { fprintf(stderr, "USAGE: %s <number>\n", name); } int main(int argc, char** argv) { unsigned long n; char *endptr; if (argc != 2) { usage(argv[0]); exit(EXIT_FAILURE); } errno = 0; n = strtoul(argv[1], &endptr, 10); if (errno || *endptr || !*argv[1]) { fprintf(stderr, "Bad number given.\n"); usage(argv[0]); exit(EXIT_FAILURE); } if (n > 40) { fprintf(stderr, "I see you gave a number higher than 40.\n" "I also like to live dangerously.\n"); exit(EXIT_FAILURE); } fibgen(n); exit(EXIT_SUCCESS); }
C
#include<stdio.h> #include "date.h" int compare(struct date d1,struct date d2) { if(d1.day==d2.day && d1.month==d2.month && d1.year==d2.year) return 0; else if ((d1.year>d2.year)||(d1.year==d2.year && d1.month>d2.month)||(d1.year==d2.year && d1.month==d2.month && d1.day>d2.day)) return 1; else return -1; }
C
#ifndef ROBOTMAP_H #define ROBOTMAP_H #include "WPILib.h" /** * The RobotMap is a mapping from the ports sensors and actuators are wired into * to a variable name. This provides flexibility changing wiring, makes checking * the wiring easier and significantly reduces the number of magic numbers * floating around. */ // For example to map the left and right motors, you could define the // following variables to use with your drivetrain subsystem. //const int LEFTMOTOR = 1; //const int RIGHTMOTOR = 2; // If you are using multiple modules, make sure to define both the port // number and the module. For example you with a rangefinder: //const int RANGE_FINDER_PORT = 1; //const int RANGE_FINDER_MODULE = 1; enum Side { Right, Left, }; enum End { Front, Rear, }; const int MotorChannels[][2] = { { 8, // Right front 9, // Right rear }, { 6, // Left front 7, // Left rear } }; #endif
C
#include <stdlib.h> #include <stdio.h> #include <math.h> // Determine which version of GLUT to load #if defined(__APPLE_CC__) #include <GLUT/glut.h> #else #include <GL/glut.h> #endif /* Compilation command: gcc -framework GLUT -framework OpenGL main.c -o main */ // STRUCTS // Struct to represent RGB float values typedef struct { float r; float g; float b; } RGBf; // Struct to represent 3-dimensional vectors typedef struct { float x; float y; float z; } Vector; // Struct to represent a sphere typedef struct { float r; Vector c; RGBf color; } Sphere; // Struct to represent a ray typedef struct { Vector direction; Vector origin; } Ray; // RGB OPERATIONS // Create an RGBf with the given values RGBf newRGB(float red, float green, float blue) { RGBf result; result.r = red; result.g = green; result.b = blue; return result; } // Convert int RGB values (on a [0,255] scale) to float RGB values (normalize it) void setPixelRGB(float red, float green, float blue, RGBf* out) { out->r = red / 255; out->b = blue / 255; out->g = green / 255; } // Same as above, but takes in an RGBf that hasn't been normalized void setPixelColor(RGBf pixelColor, RGBf* pixel) { pixel->r = pixelColor.r / 255; pixel->g = pixelColor.g / 255; pixel->b = pixelColor.b / 255; } // Scale a color by a constant float value RGBf scaleRGB(RGBf rgb, float value) { return newRGB(rgb.r * value, rgb.g * value, rgb.b * value); } // Add two colors together RGBf addRGB(RGBf a, RGBf b) { return newRGB(a.r + b.r, a.g + b.g, a.b + b.b); } // VECTOR OPERATIONS // Create a new Vector with the given values Vector newVector(float x, float y, float z) { Vector result; result.x = x; result.y = y; result.z = z; return result; } // Compute the magnitude of a vector float mag(Vector v) { return sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } // Compute the dot product of two vectors float dot(Vector a, Vector b) { return (a.x * b.x) + (a.y * b.y) + (a.z * b.z); } // Scale a vector by a constant value Vector scaleVector(float value, Vector v) { return newVector(v.x * value, v.y * value, v.z * value); } // Compute the cross-product of two vectors Vector cross(Vector a, Vector b) { return newVector(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x); } // Compute the addition of two vectors Vector addVector(Vector a, Vector b) { return newVector(a.x + b.x, a.y + b.y, a.z + b.z); } // Compute a vector produced by substracting a vector from another Vector minusVector(Vector a, Vector b) { return addVector(a, scaleVector(-1,b)); } // GLOBAL VARIABLES unsigned int window_width = 512, window_height = 512; unsigned int numSpheres = 3; float pixels[512*512*3]; Sphere spheres[3]; Vector e; float d = 10; float lightI = 1; // Light Intensity Vector lightDir; // Light direction (unit vector) Ray ray; RGBf bgColor; RGBf specColor; // The color of the specular highlight unsigned int specPow = 20; float ambientLightI = 0.2; // Ambient light intensity // Variable to represent image plane float l = -10, r = 10; float b = -10, t = 10; // Basis vectors, must be unit vectors Vector w; Vector u; Vector v; void init() { bgColor = newRGB(100, 100, 100); // The viewpoint, e e = newVector(5, 0, 0); // Calculate basis vectors Vector up = newVector(0, 1, 0); // Vector representing global up Vector viewDirection = newVector(-1, 0, 0); // The view direction (which way we're looking) w = scaleVector(-1/mag(viewDirection), viewDirection); // The view direction is -w Vector upCrossW = cross(up, w); u = scaleVector(1/mag(upCrossW), upCrossW); v = cross(w, u); // Variable for the ray ray.origin = e; ray.direction = scaleVector(-1, w); // Variables for diffuse shading lightDir = newVector(0, 1, 1); lightDir = scaleVector(1/mag(lightDir),lightDir); // Initialize specular color specColor = newRGB(250, 250, 250); // Create Spheres spheres[0].r = 1; spheres[0].c = newVector(0, 1, 1); spheres[0].color = newRGB(255, 0, 0); spheres[1].r = 1; spheres[1].c = newVector(0, 1, -1); spheres[1].color = newRGB(0, 0, 255); spheres[2].r = 1; spheres[2].c = newVector(0, -0.75, 0); spheres[2].color = newRGB(0, 255, 0); } float calcIntersection(Ray ray, Sphere sphere) { // Compute discriminate // (d . (e - c))^2 - (d.d) * ((e-c).(e-c) - r^2) Vector eMinusC = minusVector(ray.origin, sphere.c); float d2 = dot(ray.direction, ray.direction); float discriminate = dot(ray.direction, eMinusC); discriminate *= discriminate; discriminate -= (d2 * (dot(eMinusC, eMinusC) - pow(sphere.r, 2.0))); if (discriminate >= 0) { // Solve quadratic for t // t = -d . (e-c) +- discriminate / d.d float t = dot(scaleVector(-1, ray.direction), eMinusC); float t1 = (t + sqrt(discriminate)) / d2; float t2 = (t - sqrt(discriminate)) / d2; if (t1 > 0 && t2 > 0) { if (t1 < t2) { return t1; } else { return t2; } } else if (t1 > 0) { return t1; } else if (t2 > 0) { return t2; } else { return -1; } } else { return -1; } } RGBf castShadowRay(Vector p) { // Calculate ray from point to light source Ray ray; ray.origin = p; ray.direction = scaleVector(-1, lightDir); float t; // See if ray hits any objects for (int i=0; i<numSpheres; i++) { if ((t = calcIntersection(ray, spheres[i])) > 0.001) { return newRGB(-50, -50, -50); } } return newRGB(0, 0, 0); } RGBf castReflectRay(Vector p, Vector n, Ray ray) { Ray reflectRay; reflectRay.origin = p; reflectRay.direction = scaleVector(1/mag(ray.direction), ray.direction); reflectRay.direction = minusVector(reflectRay.direction, scaleVector(2 * dot(reflectRay.direction,n), n)); for (int i=0; i<numSpheres; i++) { if (calcIntersection(reflectRay, spheres[i]) > 0.001) { return spheres[i].color; } } return newRGB(0,0,0); } Ray computeViewingRay(int i, int j) { Ray viewingRay; float us = l + (r-l) * (i+0.5) / window_width; float vs = b + (t-b) * (j+0.5) / window_height; viewingRay.origin = e; viewingRay.direction = addVector(scaleVector(-1*d, w), addVector(scaleVector(us, u), scaleVector(vs, v))); return viewingRay; } RGBf diffuse(Vector n, RGBf surfaceColor) { // Diffuse coloring // Calculate pixel color = lightIntensity * surfaceColor * max(0,n.l); float nl = dot(n, lightDir); float max = (nl > 0) ? nl : 0; float scale = lightI * max; return scaleRGB(surfaceColor, scale); } RGBf specular(Ray ray, Vector n) { // h = (v+l) / mag(v+l) Vector viewingRay = scaleVector(1/mag(ray.direction), ray.direction); Vector h = addVector(viewingRay, lightDir); h = scaleVector(1/mag(h),h); float nh = dot(n,h); float max = (nh > 0) ? nh : 0; max = pow(max, specPow); float scale = max * lightI; printf("%f\n", nh); return scaleRGB(specColor, scale); } RGBf ambient(float intensity, RGBf color) { return scaleRGB(color, ambientLightI); } RGBf shading(Ray ray, Vector p, Vector n, Sphere sphere) { RGBf pixelColor; pixelColor = diffuse(n, sphere.color); pixelColor = addRGB(pixelColor, specular(ray, n)); pixelColor = addRGB(pixelColor, ambient(ambientLightI, sphere.color)); pixelColor = addRGB(pixelColor, castShadowRay(p)); pixelColor = addRGB(pixelColor, castReflectRay(p, n, ray)); return pixelColor; } RGBf castRay(Ray ray) { RGBf pixelColor = bgColor; float t = -1; float lastT = 9999; for (int i=0; i<numSpheres; i++) { t = calcIntersection(ray, spheres[i]); if (t > 0 && t < lastT) { // Compute point of intersection Vector p = addVector(ray.origin, scaleVector(t, ray.direction)); // Compute surface normal, n = (p-c)/R Vector n = scaleVector(1/spheres[i].r, minusVector(p, spheres[i].c)); //Evaluate shading model pixelColor = shading(ray, p, n, spheres[i]); // Update last-t value lastT = t; } } return pixelColor; } // Display method generates the image void display(void) { // Reset drawing window glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Ray-tracing loop, for each pixel for (int i=0; i<window_height; i++) { for (int j=0; j<window_width; j++) { // Compute viewing ray Ray viewingRay = computeViewingRay(i,j); // Get color from casting that ray into scene RGBf pixelColor = castRay(viewingRay); // Update pixel color to result from ray setPixelColor(pixelColor, &pixels[(j*window_width*3) + (i*3)]); } } // Draw the pixel array glDrawPixels(window_width, window_height, GL_RGB, GL_FLOAT, pixels); // Reset buffer for next frame glutSwapBuffers(); } void reshape(int width, int height) { glViewport(0, 0, width, height); } void idle(void) { glutPostRedisplay(); } int main(int argc, char** argv) { glutInit(&argc, argv); init(); glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH); glutInitWindowSize(window_width, window_height); glutCreateWindow("CAP 4730 | Final Project | Advanced Ray-Tracer"); glutDisplayFunc(display); glutReshapeFunc(reshape); glutIdleFunc(idle); glutMainLoop(); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include "list.h" #define TETA 0.5 #define NUMBER_OF_CORES 3 struct core{ struct Task task; bool busy; bool faulty; }; int time = -1; struct core cores[NUMBER_OF_CORES]; int number_of_cores = NUMBER_OF_CORES; int number_of_Tasks; struct Node * list; struct Node * ready_list; struct Node * get_list(struct Node * head){ FILE* file = fopen("/home/zahra/Uni/OS/project1/tasks.txt","r"); if(file==NULL)perror("tasks.txt"); int i,r,c,d; head = NULL; for (i=0; 0<fscanf(file,"%d%d%d",&r,&c,&d) ;i++ ) { struct Task t; t.r=r; t.c=c; t.d=d; t.ad=t.r+t.d; //t->p=0; t.u=(float)t.c/(float)t.d; t.id = i+1; t.execution_count=1;t.success=false; head=add_task(head,t); } // struct Node * h=head; printf("first list : \n"); for (;h;h=h->next)printf("r: %d ad: %d\n", h->task.r, h->task.ad); // fclose(file); number_of_Tasks = i; return head; } void update_tc(struct Task * t){ float f = (float) 1.2 * t->c; int i = (int) f; if(f>i)t->c = i+1; else t->c = i; } struct Node * update_ready_list(){ struct Node * l = list; for(; time>=l->task.r; l=l->next){ ready_list = add_to_ready(ready_list,l->task); list = rmv(list,list->task); if (!(l->next))break; } return ready_list; } void update_cores(){ for(int i=0; i<number_of_cores; i++){ if(cores[i].busy) { if ( time - cores[i].task.s >= cores[i].task.c ) {//execution finished printf("--- time : %d -----------\n",time); printf("Task %d finished executing on core %d \n", cores[i].task.id, i); //cores[i].task = NULL; cores[i].busy = false; cores[i].faulty = false; } } } } bool core_fault (int core){ int r =rand()%number_of_cores; if (r == core) return true; if (cores[core].busy){ cores[core].faulty = true; cores[core].task.success = false; } return false; } bool execute(struct Task task,int core){ task.s = time; cores[core].task = task; cores[core].busy = true; if(core_fault(core)) { cores[core].faulty = true; return false;//add to ready list and inc execution_count } task.success = true; return true; } int find_idle_core(){ int i; for (i=0; i<number_of_cores; i++) // if (!(cores[i].Task)){ if (!(cores[i].busy)) { return i;//i'th core is idle } return -1; } int min_execution_time() {//finds the minimum remained execution time int min = 0; if(cores[0].busy){ min = cores[0].task.c - (time - cores[0].task.s);//execution time - progress } for(int i=1; i<number_of_cores; i++) { if(cores[i].busy) { if (min > (cores[i].task.c - (time - cores[i].task.s))) min = (cores[i].task.c - (time - cores[i].task.s)); } } return min; } int find_busy_core() { for (int i = 0; i < number_of_cores; i++) { if (cores[i].busy) return i; } return -1; } void finish(){ int inc = min_execution_time(); if(inc == 0 )return; else { time += inc; update_cores(); } } void print_list(){ struct Node * l=list; printf("list:\n"); for(;l;l=l->next)printf("id: %d, r: %d, ad: %d\n",l->task.id, l->task.r, l->task.ad); } void print_ready(){ struct Node * f=ready_list; printf("readylist:\n"); for(;f;f=f->next)printf("id: %d, r: %d, ad: %d\n",f->task.id, f->task.r, f->task.ad); } int main() { int inc = 1; list = NULL; list = get_list(list); int executed_Tasks=0; int core,core2; bool feasibility = true; float Task_execution_time; //TODO:fek konam bayad or bashe na and while(list /* && list->task!=NULL*/ && executed_Tasks<number_of_Tasks) {/*list is not empty and total executed Tasks!=number of total Tasks*/ time += inc; printf("-----time: %d -----------\n",time); print_list(); update_ready_list(); print_ready(); update_cores(); //return 0; while (ready_list /*&& ready_list->task*/) { struct Task t = ready_list->task;//smallest ad printf("Task: %d", t.id); core = find_idle_core(); if (core != -1) {//if there is an idle core inc = 1; if (t.execution_count == 1) {//first time if (time + t.c > t.ad){ printf("deadline expired\n"); ready_list = rmv(ready_list,t); feasibility = false; } else { if (t.u < TETA) {//not critical - needs one core printf("(not critical)\n"); if (!execute(t, core)) {//the core is faulty - checkpointing printf("checkpointing\n"); update_tc(&t); } printf("start execution on core %d\n", core); t.s = time; ready_list = rmv(ready_list,t); executed_Tasks+=1; } else {//critical printf("(critical)\n"); ready_list = rmv(ready_list,t); execute(t, core); executed_Tasks+=1; printf("start execution on core %d\n", core); t.s = time; t.execution_count += 1; core2 = find_idle_core(); if (core2 != -1){//there exists another idle core printf("duplicate on core %d\n", core2); execute(t, core2); printf("start execution on core %d\n", core2); t.s = time; } else { printf("duplicate in readylist\n"); add_to_ready(ready_list, t); //executed_Tasks -=1; } } } } else if (t.execution_count > 1) {//second try (execution) printf("critical\n"); if (t.success){ printf("first try was successful\n"); ready_list = rmv(ready_list,t); } else { printf("(second try)\n"); if (time + t.c < t.ad) { printf("deadline expired"); execute(t, core); //executed_Tasks+=1; t.s = time; if (!t.success){feasibility = false;printf("both primary and backup copy of the critical Task are faulty\n");} ready_list = rmv(ready_list,t); } else feasibility = false; } } } else{//all cores are busy printf("--- time : %d -----------\n", time); printf("all cores are busy\n"); inc = min_execution_time(); time += inc; update_cores(); } } } while(find_busy_core()!=-1)//while there exists a busy core finish(); printf("feasibility: "); if(feasibility) printf("true"); else printf("false"); return 0; }
C
/*====================================================================== C <- MINHITSET(A,B) Minimum hitting set. (Minimum with respect to cardinality.) Inputs A : A list (l_1, ..., l_n), each l_i is a list of BETA-digits, given in ascending order. B : A BETA-Digit. Output C : A Word. If B is negative, then C is zero if no hitting set exists and is otherwise a list of integers which comprise a minimum (with respect to cardinality) hitting set. If B is non-negative, then C is zero if no hitting set with at most B elements exists, and is otherwise a list of integers which comprise a minimum hitting set. ======================================================================*/ #include "qepcad.h" #define MC_FAIL 0 Word MINHITSET(Word A, Word B) { Word L,As,C,Cp,p,Ap,T,s; Step1: /* Quick decisions. */ if (A == NIL) return (NIL); if ((B == 0) || (FIRST(A) == NIL)) return (MC_FAIL); Step2: /* Initialize loop. */ L = FIRST(A); As = RED(A); C = MC_FAIL; Step3: /* Loop over the elements of L, looking for a min. hit set of A. */ while ( (L != NIL) && (B != 0) ) { ADV(L,&p,&L); Step4: /* Eliminate from A all sets hit by p, call this Ap. */ Ap = NIL; T = As; while ( T != NIL) { ADV(T,&s,&T); if (! MEMBER(p,s)) { Ap = COMP(s,Ap); } } Ap = INV(Ap); Step5: /* Recurse: Look for a cover of Ap of at most B-1 columns. */ Cp = MINHITSET(Ap,B-1); if ( Cp != MC_FAIL ) { C = COMP(p,Cp); B = LENGTH(Cp); } } Return: /* Loop complete. Return. */ return (C); }
C
//Recibe un argumento, la ruta del fichero, Si no existe, el programa debe crearlo y escribir holaMundo //Si ya existe, el programa debe sobreescribir su contenido por "Hola Mundo" /*NOTA: MEJOR USAR RUTAS RELATIVAS QUE ABSOLUTAS PARA EJECUTARLO*/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char *argv[]) { if(argc == 1) { printf("ERROR: No se han introducido Parámetros\n"); exit -1; } //lo primero, abrimos el fichero. Como debe escribirse en el permiso de escritura y como si no esta debe crearlo, pues o de escritura o de crearlo segun corresponda int descriptorDelFichero = 0; descriptorDelFichero = open(argv[1], O_WRONLY | O_CREAT, 777); //le pasamos la ruta del archivo, los flag y los permisos //una vez abierto o creado segun proceda vamos a escribir en él char *buffer = "Hola Mundo\n"; write(descriptorDelFichero, buffer, 11); //contando el \n como 1 byte son 11 bytes la cadena close (descriptorDelFichero); //cerramos el archivo una vez terminamos return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { printf("Enter numbers (1 - 70) | CTRL + D to terminate:"); int next; if (scanf("%d", &next) != 1) { printf("\nInvalid input. Try again.\n"); exit(EXIT_FAILURE); } do { printf("%d |", next); for (int i = 0; i < next; i++) printf("*"); printf("\n"); } while (scanf("%d", &next) == 1); return 0; }
C
#include<stdio.h> int main() { double i, d, s=1, j=1; for(i=1; i<=7; i+=2) { d=(i/j); s += d; j = j*2; } printf("Value of series : %.2lf\n", s); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ruben <ruben@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/12/10 12:14:16 by mbahstou #+# #+# */ /* Updated: 2021/05/12 13:30:09 by ruben ### ########.fr */ /* */ /* ************************************************************************** */ #include "cube.h" #include <stdio.h> char *ft_remove(char *p, int len) { char *newstr; int i; i = 0; if(!(newstr = malloc((ft_strlen(p) - len) * sizeof(char)))) return (0); while (p[len]) newstr[i++] = p[len++ + 1]; free(p); return(newstr); } int ft_finder(char **p, char **line) { int i; i = 0; while ((*p)[i] && (*p)[i] != '\n') i++; if ((*p)[i] == '\n') { *line = ft_substr(*p, 0, i); *p = ft_remove(*p, i); return (1); } *line = ft_substr(*p, 0, i); *p = ft_remove(*p, i); **p = 0; return (0); } int get_next_line(int fd, char **line) { int lectura; char buff[BUFFER_SIZE + 1]; static char *p[4096]; int i; int j; i = 0; j = 0; if (fd < 0 || !line || !BUFFER_SIZE) return (-1); while ((lectura = read (fd, buff, BUFFER_SIZE)) > 0) { buff[lectura] = '\0'; if(!p[fd]) p[fd] = ft_strdup(buff); else p[fd] = ft_strjoin(p[fd], buff); } if (lectura < 0) return (-1); if (ft_strchr(p[fd], '\n') != 0) { return (ft_finder(&p[fd], line)); } else if (ft_strchr(p[fd], '\0') != 0) { return (ft_finder(&p[fd], line)); } return(-1); }
C
/* Program to find all possible paths to reach to bottom-right cell starting from the top-left Can move only right,down or diagonally lower Enter the no of rows: 2 Enter the no of columns: 2 Total paths: 3 j ___ i |1 1 |1 3 sum of all three sides, gives total path. */ #include<stdio.h> int main() { int a[100][100],i,j,r,c; printf("Enter the no of rows: "); scanf("%d",&r); printf("Enter the no of columns: "); scanf("%d",&c); a[0][0] = 1; for(i=0;i<r;i++) for(j=0;j<c;j++) { if(i==0 || j==0) a[i][j] = 1; else a[i][j] = a[i-1][j] + a[i-1][j-1] + a[i][j-1]; } printf("Total paths: %d ",a[r-1][c-1]); return 0; }
C
#include <stdio.h> int main() { float Matriz[2][2], Matriz2[2][2]; int i = 0, j = 0; for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { scanf("%f", &Matriz[i][j]); } } Matriz2[0][0] = (Matriz[0][0] * Matriz[0][0]) + (Matriz[0][1] * Matriz[1][0]); Matriz2[0][1] = (Matriz[0][0] * Matriz[0][1]) + (Matriz[0][1] * Matriz[1][1]); Matriz2[1][0] = (Matriz[1][0] * Matriz[0][0]) + (Matriz[1][1] * Matriz[0][1]); Matriz2[1][1] = (Matriz[1][0] * Matriz[0][1]) + (Matriz[1][1] * Matriz[1][1]); for (i = 0; i < 2; i++) { for (j = 0; j < 2; j++) { printf("%0.3f ", Matriz2[i][j]); } puts(""); } return (0); }
C
/* * Table des symboles.c * * Created by Janin on 12/10/10. * Copyright 2010 LaBRI. All rights reserved. * */ #include "Table_des_symboles.h" #include <stdlib.h> #include <stdio.h> /* The storage structure is implemented as a linked chain */ /* linked element def */ typedef struct elem { sid symbol_name; symb_value_type symbol_value; struct elem * next; } elem; /* linked chain initial element */ static elem** storage=NULL; //static elem** tables=NULL; static int compteur=0; void moreStorage() { compteur+=1; storage[compteur]=NULL; } void cleanStorage() { elem* tracker = storage[compteur]; elem* next = tracker->next; while (tracker) { free(tracker); tracker = next; next = tracker->next; } } void lessStorage() { compteur-=1; } /* get the symbol value of symb_id from the symbol table */ symb_value_type get_symbol_value(sid symb_id) { elem * tracker=storage[compteur]; /* look into the linked list for the symbol value */ while (tracker) { if (tracker -> symbol_name == symb_id) return tracker -> symbol_value; tracker = tracker -> next; } /* if not found does cause an error */ fprintf(stderr,"Error : symbol %s have no defined value\n",(char *) symb_id); exit(-1); }; /* set the value of symbol symb_id to value */ symb_value_type set_symbol_value(sid symb_id,symb_value_type value) { if (storage == NULL) storage = malloc(sizeof(elem*)) ; elem * tracker; /* (optionnal) check that sid is valid symbol name and exit error if not */ if (! sid_valid(symb_id)) { fprintf(stderr,"Error : symbol id %p is not have no valid sid\n",symb_id); exit(-1); } /* look for the presence of symb_id in storage */ tracker = storage[compteur]; while (tracker) { if (tracker -> symbol_name == symb_id) { tracker -> symbol_value = value; return tracker -> symbol_value; } tracker = tracker -> next; } /* otherwise insert it at head of storage with proper value */ tracker = malloc(sizeof(elem)); tracker -> symbol_name = symb_id; tracker -> symbol_value = value; tracker -> next = storage[compteur]; storage[compteur] = tracker; return storage[compteur] -> symbol_value; }
C
#include <stdio.h> void getLine (char * const s, const size_t max); int main (void) { char string[100]; getLine(string, 100); printf("%s\n", string); return 0; } void getLine (char * const s, const size_t max) { char *p = s; while ((*p = getchar()) != '\n' && p - s < max - 1) ++p; *p = '\0'; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* set_camera.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mpauw <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/30 15:43:19 by mpauw #+# #+# */ /* Updated: 2018/01/30 17:27:33 by mpauw ### ########.fr */ /* */ /* ************************************************************************** */ #include "rtv1.h" static void set_values_camera(t_source *cam, char *s, char *value) { if (ft_strncmp(s, "origin", 6) == 0) update_vector(&(cam->origin), value); else if (ft_strncmp(s, "rotation", 5) == 0) update_vector(&(cam->rotation), value); } void set_camera(t_scene **scene, int fd) { char *line; char *s; char *value; if ((*scene)->cam_set) return ; while (get_next_line(fd, &line) == 1) { if (*(line) == '}') break ; if (ft_isalpha(*line) || !(s = ft_brace_content(line, '{', '}'))) error(0); if (!(value = ft_brace_content(s, '{', '}'))) error(0); set_values_camera(&((*scene)->camera), s, value); free(s); free(value); free(line); } free(line); (*scene)->cam_set = 1; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "../rbtree.h" typedef struct StrUnit { rbtree_node_t node; uint32_t len; char *data; }str_unit_t; rbtree_t *rbtree; void str_unit_rbtree_insert_value(rbtree_node_t *root, rbtree_node_t *node, rbtree_node_t *sentinel) { rbtree_node_t *temp = root; str_unit_t *n, *t; rbtree_node_t **p; n = (str_unit_t *)node; for( ; ; ) { t = (str_unit_t *)temp; if(node->key != temp->key) { p = (node->key > temp->key) ? &temp->right : &temp->left; } else if(n->len != t->len) { p = (n->len > t->len) ? &temp->right : &temp->left; } else { p = (memcmp(n->data, t->data, n->len) > 0) ? &temp->right : &temp->left; } if(*p == sentinel) break; temp = *p; } *p = node; node->parent = temp; node->left = sentinel; node->right = sentinel; rbt_red(node); } str_unit_t *str_unit_rbtree_lookup(rbtree_t *tree, str_unit_t *val, uint32_t hash) { int32_t rc; str_unit_t *n; rbtree_node_t *node, *sentinel; node = tree->root; sentinel = tree->sentinel; while(node != sentinel) { n = (str_unit_t *)node; if(hash != node->key) { node = (hash > node->key) ? node->right : node->left; continue; } if(n->len != val->len) { node = (val->len > n->len) ? node->right : node->left; continue; } rc = memcmp(n->data, val->data, val->len); if(rc > 0) { node = node->left; continue; } if(rc < 0) { node = node->right; continue; } return n; } return NULL; } int main() { str_unit_t str[6], *pstr = NULL; rbtree = (rbtree_t *)malloc(RbtreeSize); rbtree_node_t sentinel; rbtree_init(rbtree, &sentinel, str_unit_rbtree_insert_value); str[0].data = "abcdef"; str[0].len = strlen("abcdefg") + 1; str[0].node.key = 3; rbtree_insert(rbtree, (rbtree_node_t *)&str[0]); str[1].data = "qwerty"; str[1].len = strlen("qwerty") + 1; str[1].node.key = 2; rbtree_insert(rbtree, (rbtree_node_t *)&str[1]); str[2].data = "zxcvb"; str[2].len = strlen("zxcvb") + 1; str[2].node.key = 9; rbtree_insert(rbtree, (rbtree_node_t *)&str[2]); str[3].data = "poiuy"; str[3].len = strlen("poiuy") + 1; str[3].node.key = 5; rbtree_insert(rbtree, (rbtree_node_t *)&str[3]); str[4].data = "lkjh"; str[4].len = strlen("lkjh") + 1; str[4].node.key = 1; rbtree_insert(rbtree, (rbtree_node_t *)&str[4]); pstr = (str_unit_t *)rbtree_min(rbtree->root, &sentinel); printf("min len: %u data: %s\n", pstr->len, pstr->data); pstr = str_unit_rbtree_lookup(rbtree, &str[3], 5); printf("data: %s key: %u\n", pstr->data, pstr->node.key); str[5].data = "lkjh"; str[5].len = strlen("lkjh") + 1; str[5].node.key= 6; pstr = str_unit_rbtree_lookup(rbtree, &str[5], 6); if(pstr) printf("data: %s key: %u\n", pstr->data, pstr->node.key); else printf("Not Found\n"); return 0; }
C
#include <vxWorks.h> #include <math.h> #include <float.h> #include <stdio.h> void math() { int i; double b; /* smallest integer greater than or equal to a specified value */ i= ceil(4.3); printf("the value of i using ceil is %d\n",i); /* It gives largest integer less than or equal to a specified value */ i= floor(4.3); printf("the value of i using floor is %d\n",i); i= fabs (4.9); printf("the value of i using fabs is %d\n",i); /* It gives modulus of 15 and 4 */ i= fmod (15,4); printf("The modulus value of 15,4 is %d\n",i); /* It gives result by multiply a number by an integral power of 2 ( 3 * 2^5 ) */ i= ldexp(3,5); printf("The exponent value of 3,5 is %d\n",i); /* It finds the power of the operand */ i= pow (3,5); printf("The power of 3 raised to 5 is %d\n",i); }
C
#include<stdio.h> #include<stdlib.h> int main() { int num; printf("DAYS OF THE WEEK!!\nSelect a number from 1-7\n"); scanf("%d",&num); switch(num) { case 1: printf("\nMONDAY"); break; case 2: printf("\nTUESDAY"); break; case 3: printf("\nWEDNESDAY"); break; case 4: printf("\nTHURSDAY"); break; case 5: printf("\nFRIDAY"); break; case 6: printf("\nSATURDAY"); break; case 7: printf("\nSUNDAY"); break; default: printf("ERROR!! NUMBER NOT BETWEEN 1 AND 7\n"); } return 0; }
C
/* Title : Program to check if number is even or odd Author : Shashi Kumar M Date : 1 October 2019 Description : WAP to check whether a number is even or odd using bitwise operators Input : A number Output : Print whether a number is even or odd. */ #include<stdio.h> int main() { //Declare and read input int num; unsigned mask; char option; do { //Read the number printf("\nEnter a number : "); scanf("%d", &num); //Mask to get 1 at last index mask = 1 << sizeof(int) * 8 - 1; //Print the result printf("The number is "); //If else to find positive or negative if ((num & mask) == mask) { //Ternary operator to find zero, odd or even. (num & -1) == 0 ? printf("Zero\n") : (num & 1) == 0 ? printf("-ve Even\n") : printf("-ve Odd\n"); } else { //Ternary operator to find zero, odd or even. (num & -1) == 0 ? printf("Zero\n") : (num & 1) == 0 ? printf("+ve Even\n") : printf("+ve Odd\n"); } //Prompt to continue printf("\nDo you want to continue ? [Yy || Nn] : "); getchar(); scanf("%c", &option); }while(option == 'Y' || option == 'y'); return 0; }
C
#include<stdio.h> void printbinary(int i){ while (i > 0){ if (i % 2 != 0) printf("1"); else printf("0"); i = i / 2; } } void printhexadecimal(float x) { printf("0x%08X, %f\n", *(int *)&x, x); } main(){ float x; float y; printf("Enter a float value: "); scanf("%f", &x); printbinary(5); printhexadecimal(5); }
C
/* ** EPITECH PROJECT, 2018 ** Project ** File description: ** join.c */ #include "client.h" void resp_join(ui_t *ui, char **resp) { char *nick = get_nickname(resp[0]); chan_t *chan_cpy = ui->session->chan; if (!nick) return; if (!strcmp(ui->session->nickname, nick)) ui->session->printChan( ui->session, resp[2], "You have joined this channel"); else ui->session->printfChan(ui->session, resp[2], "%s has joined this channel", nick); while (chan_cpy) { if (!strcmp(chan_cpy->name, resp[2])) { ui->session->cur_chan = chan_cpy; ui->w_logs->update(ui->w_logs); ui->w_chan->update(ui->w_chan); } chan_cpy = chan_cpy->next; } }
C
#include<stdio.h> int step; int a[1000]; int m,n; void dfs(int nx,int m){ if(nx != n && m == 0){ step++; } else if(nx == n && m != 0){ return; } else if(nx == n &&m == 0){ step++; } else{ if(m >= a[nx]){ dfs(nx+1,m-a[nx]); dfs(nx+1,m); } else{ dfs(nx+1,m); } } } int main(){ scanf("%d%d",&n,&m); for(int i = 0;i < n;i++){ scanf("%d",&a[i]); } dfs(0,m); printf("%d",step); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef union { int balcon; char apartament; char casa[31]; }detaliu; typedef struct { char adresa[101]; int suprafata; char locuinta[31]; int nr_camere; detaliu ceva; }locuinta; int main() { locuinta v[101]; int n, i, k, supr_max; scanf("%d", &n); for (i=0; i<n; i++) { scanf("%s %d %s %d", &v[i].adresa, &v[i].suprafata, &v[i].locuinta, &v[i].nr_camere); if (strcmp(v[i].locuinta, "casa")==0) scanf("%s", &v[i].ceva.casa); else if (strcmp(v[i].locuinta, "garsoniera")==0) scanf("%d", &v[i].ceva.balcon); else if (strcmp(v[i].locuinta, "apartament")==0) scanf("%c", &v[i].ceva.apartament); } supr_max=0; k=-1; for (i=0; i<n; i++) { if (strcmp(v[i].locuinta, "garsoniera")==0 && v[i].ceva.balcon==1 && v[i].suprafata > supr_max) { k=i; supr_max=v[i].suprafata; } } if (k>0) printf("%s", v[k].adresa); else printf("Nu exista"); return 0; }
C
#ifndef _header_basic_types_ #define _header_basic_types_ #include <stdint.h> typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int8_t s8; typedef int16_t s6; typedef int32_t s32; typedef int64_t s64; typedef float f32; typedef double f64; static_assert( sizeof(u8)==1, "u8 of wrong size"); static_assert(sizeof(u16)==2, "u16 of wrong size"); static_assert(sizeof(u32)==4, "u32 of wrong size"); static_assert(sizeof(u64)==8, "u64 of wrong size"); #endif
C
#include "listing.h" /*Ces fonction me servent uniquement a executer mes algorithme dans le main()*/ void viderBuffer(){ int c = 0; while (c != '\n' && c != EOF){ c = getchar(); } } void lire(char *chaine, int longueur){ char *positionEntree = NULL; if (fgets(chaine, longueur, stdin) != NULL){ positionEntree = strchr(chaine, '\n'); if (positionEntree != NULL){ *positionEntree = '\0'; } else{viderBuffer();} } else{viderBuffer();} } void choix(char character){ int a=0; printf("voulez vous passer a la question suivante ?(y/n):"); while(a==0){ scanf("%s", &character); if(character == 'y'){a=1;} else if(character == 'n'){exit(0);} else{printf("veuillez taper la lettre y pour yes ou n pour no:");} } viderBuffer(); } /*----------------------------------------------------------------------*/ /*J'écrirai a coté de quasiment toute les comparaison ou affectation ou autre, ce que sa signifie ou pourquoi j'aurai fait sa.*/ /*La déscription de chaque fonction est décrite briévement dans listing.h.*/ List new_list(void){return NULL;} /*----------------------------------------------------------------------*/ /*Compléxité : o(1) */ int is_empty_list(List list1){ //return 1 si NULL sinon return 0// if (list1 == NULL){return 1;} else{return 0;} } /*----------------------------------------------------------------------*/ /*Compléxité : o(n), "n" étant la taille maximum de la liste.*/ void print_list(List list1){ if(is_empty_list(list1)){ printf("[]"); } else{ while (!is_empty_list(list1)){ printf("[%c]", list1->letter); list1 = list1->next; //on passe a la liste suivante// } } } /*----------------------------------------------------------------------*/ /*Compléxité : o(5), je prend en compte les affectation et comparaison.*/ List push_front_list(List list1, char character){ Element *newElement; newElement = malloc(sizeof(Element)); if (is_empty_list(newElement)){ fprintf(stderr, "Allocation échouée\n"); exit(EXIT_FAILURE); } if(is_empty_list(list1)){ newElement->letter = character; newElement->next = NULL;} else{ newElement->letter = character; newElement->next = list1;} return newElement; } /*----------------------------------------------------------------------*/ /*Compléxité : o(n), n etant la taille de la liste chainéé*/ List push_back_list(List list1, char character){ Element *newElement; newElement = malloc(sizeof(Element)); if (is_empty_list(newElement)){ fprintf(stderr, "Allocation échouée\n"); exit(EXIT_FAILURE); } newElement->letter = character; newElement->next = NULL; if(is_empty_list(list1)){return newElement;} Element *tmp; tmp = list1;//on utilise une variable de type liste pour souvegarder la tete de liste// while(!is_empty_list(tmp->next)){tmp = tmp->next;} //on parcour toute la liste.// tmp->next = newElement; return list1; } /*----------------------------------------------------------------------*/ /*Compléxité : o(n), n etant la taille maximal de la liste*/ List push_word_list(List list1, char *chaine){ int i; for (i=0; chaine[i] != '\0'; i++){ list1 = push_back_list(list1, chaine[i]); //on insere les caractere a la fin de la pile.// } return list1; } /*----------------------------------------------------------------------*/ /*Compléxité : o(n), n etant la taille maximal de la liste*/ int cpt_same_letter(List list1, char character){ if (is_empty_list(list1)){ fprintf(stderr, "La liste est vide.\n"); return 0; } //on compare chaque caractere de la liste avec le caractere qu'on veut comparer// int cpt = 0; //on rajoute 1 au compteur a chaque fois que les deux caracteres son égales// while (!is_empty_list(list1)){ if (list1->letter == character){cpt++;} list1 = list1->next; } return cpt; } /*----------------------------------------------------------------------*/ /*Compléxité : o(n) */ void cmp_list(List list1, List list2) { if (is_empty_list(list1) || is_empty_list(list2)){ fprintf(stderr, "<<Comparaison impossible."); return; } int i = cpt_same_letter(list2, list1->letter); /*si on trouve aucun caractere en commun avec le premier caractere de la liste, on quitte l'algo.*/ if(i == 0){printf("La premiere liste n'ai pas contenu dans la deuxieme liste.\n");} else{ List tmp; tmp = list1; /* on utilise une liste temporaire pour ne pas perdre le pointeur de tete de liste*/ while (list2->letter != list1->letter){list2 = list2->next;} while((!is_empty_list(list2) && !is_empty_list(tmp)) && (list2->letter == tmp->letter)){ list2 = list2->next; tmp = tmp->next; } if (is_empty_list(tmp)){/*s la premiere liste est NULL alors on aura parcourue toute la liste, donc tout les caracteres son égaux*/ printf("La premiere liste est contenu dans la deuxieme liste.\n");return; } else if (!is_empty_list(tmp) && !is_empty_list(list2)){cmp_list(tmp, list2);} /*si la deuxieme liste est vide mais que la premiere non , alors la premiere liste n'ai pas incluse dans la deuxieme*/ else if(!is_empty_list(tmp) && is_empty_list(list2)){ printf("La premiere liste n'ai pas contenu dans la deuxieme liste.\n");return; } } } /*----------------------------------------------------------------------*/ /*Compléxité : o(n*n), (n*n) représente n au carré.*/ int lexic_cmp_list(List list1, List list2){/*on va faire des apelles recursives avec toute les conditions.*/ if (is_empty_list(list1) && is_empty_list(list2)){return 0;} else if (!is_empty_list(list1) && is_empty_list(list2)){return 0;} else if (!is_empty_list(list2) && is_empty_list(list1)){return 1;} else if (list2->letter > list1->letter){return 1;} else if (list2->letter < list1->letter){return 0;} else if (list2->letter == list1->letter){lexic_cmp_list(list1->next, list2->next);} } /*----------------------------------------------------------------------*/ /*la compléxité est : o(n*tailleMAX), n:taille du tableau, tailleMAX:taille de la liste*/ void print_table_list(List table[]){ int i; if(n == 0){ fprintf(stderr, "Le tableau de liste est vide.\n"); return; } for(i=0; i<n; i++){ /*on apelle en boucle la fonction print_list qui affiche une liste*/ printf("Case [%d] : ", i+1); print_list(table[i]); printf("\n"); } } /*----------------------------------------------------------------------*/ /*la compléxité de : o(n*n), (n*n) représente n au carré.*/ List sort_table_list(List table[]){ List tmp; int i,j; if(table[n] == NULL){ printf("Le tableau est vide.\n"); return 0; } for(i=0; i<n; i++){ for(j=i+1; j<n; j++){ if(lexic_cmp_list(table[i], table[j]) == 0){/*sa compare les caractere de la liste deux a deux, et les pérmute pour les metre en ordre croissant*/ tmp = table[i]; table[i] = table[j]; table[j] = tmp; } } } return table[n]; } /*----------------------------------------------------------------------*/ /*Compléxité : o(n);*/ int partition(List table[], int debut, int fin){ int cpt = debut; int j = debut; List pivot,tmp; pivot = table[fin]; /*on place toujour le pivot a la fin de la liste*/ while(cpt<fin){ /*cpt est le compteur qui parcours le tableau*/ if(table[cpt]->letter <= table[fin]->letter){/*si la case du compteur est plus petite que le pivot, on permute avec j et cpt*/ tmp = table[cpt]; table[cpt] = table[j]; table[j] = tmp; j++; /*on implémente j seulement quand la case du tableau est plus petite que le pivot*/ } cpt++; /*cpt parcours le tableau*/ } tmp = table[fin]; table[fin] = table[j];/*on inverse j et le pivot pour que toute les valeur apres table[j] sois superieur , et les valeur avons son inferieur*/ table[j] = tmp; return j; /*on return j qui est le nouveau pivot*/ } /*----------------------------------------------------------------------*/ /*compléxité : n*logn .*/ void quicksort(List table[], int debut, int fin){ List pivot; int j; int i; for(i=debut; i<n; i++){ /*je fait cette boucle pour metre au debut du tableau toute les liste qui son NULL*/ if(table[i] == NULL){ pivot = table[i]; table[i] = table[debut]; table[debut] = pivot; debut++; /*j'implémente debut pour ne plus toucher au premiere case qui son NULL*/ } } if(fin>debut){ /*ici on fait des apelles récurcives pour triés le tableau avec la méthode du pivot*/ pivot = table[fin]; j = partition(table, debut, fin); quicksort(table, debut, j-1); quicksort(table,j+1,fin); } } /*----------------------------------------------------------------------*/ /*compléxité : o(n).*/ void merge(List table[], int debut, int milieu, int fin){ Element *fusion[(fin-debut+1)]; fusion[(fin-debut+1)] = malloc((fin-debut+1)*sizeof(Element));/*on crée une variable de type liste pour faire une copie du tableau de base*/ int i = debut; int j = milieu+1; int k = 0; while((i <= milieu) && (j <= fin)){ /*la boule ne s'arrete pas avons que les deux coté des deux tableau son égaux et de taille superieur a 1.*/ if(table[i]->letter <= table[j]->letter){ /*on compare chaque tableau entre eu pour determiner le plus petit*/ fusion[k++] = table[i++]; /*puis on souvegarde les valeurs dans le tableau temporaire "fusion"*/ } else{ fusion[k++] = table[j++]; } } while(i <= milieu){ /* ce cas est plutot déstiné au tableau dont la taille n'ai pas une puissane de 2*/ fusion[k++] = table[i++];/*si il reste toujours des tableau non triée alors on les affecte directement dans le tableau fusion*/ } while(j <= fin){ fusion[k++] = table[j++]; } i = debut; k = 0; while(i<=fin){ /*on fait une simple boucle pour affecter les valeur du tableau triée dans notre encien tableau non triée*/ table[i++] = fusion[k++]; } free(fusion[(fin-debut+1)]); /*on libere la mémoire alloué préalablement.*/ } /*----------------------------------------------------------------------*/ /*Compléxité : nlogn .*/ void mergesort(List table[], int debut, int fin){ int milieu; int cpt; List tmp; for(cpt=debut; cpt<n; cpt++){ /*je fait cette boucle pour metre au debut du tableau toute les liste qui son NULL en fesant des permutation*/ if(table[cpt] == NULL){ tmp = table[cpt]; table[cpt] = table[debut]; table[debut] = tmp; debut++; /*j'implémente debut pour ne plus toucher au premiere case qui son NULL*/ } } if(fin>debut){ milieu = (debut+fin)/2; /*on divise le tableau en 2 a chaque apelle recursive, il s'arrete quand tout les tableau vallent 1.*/ mergesort(table, debut, milieu); mergesort(table, milieu+1, fin); merge(table, debut, milieu, fin); } } /*----------------------------------------------------------------------*/
C
#include<stdio.h> void main(void){ char nome[20]; printf("Qual e o seu nome? \n"); scanf("%s",&nome); printf("Olá %s! \n", nome); }
C
#include<stdio.h> int main() { int n; scanf("%d",&n); int ara[1000]; int i,j,k; for(i=0;i<n;i++){ scanf("%d",&ara[i]); } for(i=0;i<n;i++){ for(j=0 ; j<n ; j++){ for(k=0 ; k<n ; k++){ if(i!=j && ara[i]+ara[j]==ara[k]){ printf("%d %d %d\n",k+1,j+1,i+1); return 0; } } } } printf("-1"); return 0; }
C
#include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <syslog.h> #include <ini_parser.h> #define __CONFIG_C__ #include "config.h" const char * config_lookup_key_str(const CONF_KV_T* config, const INI_KEY_T key) { for(const CONF_KV_T* tc = config; INI_KEY_INVALID_KEY != tc->key; tc++) { if(key == tc->key) { return tc->value; } #ifdef DEBUG else { printf("KEY-VALUE pair (%s:%s) found while searching for KEY %s.\n", ini_keys_str[tc->key], tc->value, ini_keys_str[key]); } #endif } return NULL; } const long config_lookup_key_long(const CONF_KV_T* config, const INI_KEY_T key) { const char * value = config_lookup_key_str(config, key); char * finpos; long ret; if(NULL == value) { fprintf(stderr, "Key %s not found in configuration.\n", ini_keys_str[key]); return -1; } else { ret = strtol(value, &finpos, 10); if( 0 == ret ) fprintf(stderr, "%s is not a valid value for key %s.\n" , value, ini_keys_str[key]); return ret; } } /* returns list of configuration kv pairs terminated by an entry with key<-INVALID_KEY */ CONF_KV_T* read_config(const char * filepath) { CONF_KV_T* conf = malloc(sizeof(CONF_KV_T)*(INI_KEY_N_KEYS + 1)); if(NULL == conf) { syslog(LOG_ERR, "Failed to allocate memory for configuration array.\ Unrecoverable error, exiting from %s:%d", __FILE__, __LINE__); exit(EXIT_FAILURE); } FILE *f = fopen(filepath, "r"); if(!f) { syslog(LOG_WARNING, "Failed to open configuration file at %s. Using compile-time defaults specified in config.h", filepath); // FIXME add defaults in config.h } int type; CONF_KV_T *conf_tmp = conf; INI_KEY_T ini_key = INI_KEY_INVALID_KEY; do { char key[CONFIG_KEY_MAXLEN], value[CONFIG_VAL_MAXLEN]; type = parse_ini_file(f, key, sizeof(key), value, sizeof(value)); char * tmpk = key; for(;0 != *tmpk; tmpk++) *tmpk = toupper(*tmpk); switch(type){ case INI_SECTION: break; case INI_VALUE: ini_key = INI_KEY_INVALID_KEY; for(int i = 0; i < INI_KEY_N_KEYS; i++) { if(0 == strcmp(ini_keys_str[i],key)) { ini_key = (INI_KEY_T)i; conf_tmp->key = ini_key; conf_tmp->value = strdup(value); if(NULL == conf_tmp->value) { syslog(LOG_ERR, "Failed to allocate memory for configuration value %s:%d.\ Unrecoverable error, exiting...", __FILE__,__LINE__); exit(EXIT_FAILURE); } conf_tmp++; break; } } if(INI_KEY_INVALID_KEY==ini_key) { syslog(LOG_WARNING, "Unrecognised key %s with value %s in config file %s\n", key, value, filepath); } break; } } while (type); fclose(f); conf_tmp->key = INI_KEY_INVALID_KEY; conf_tmp->value = NULL; return conf; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_three.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fle-bach <fle-bach@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/09 04:48:00 by fle-bach #+# #+# */ /* Updated: 2014/03/12 16:01:18 by fle-bach ### ########.fr */ /* */ /* ************************************************************************** */ #include <p4.h> int ft_lines_columns(t_gboard *p4, int player, t_axe p, int cl) { int check; check = 0; if (cl == 0) { check = ft_check_three(p4->board[p.x][p.y], player, check); check = ft_check_three(p4->board[p.x][p.y + 1], player, check); check = ft_check_three(p4->board[p.x][p.y + 2], player, check); check = ft_check_three(p4->board[p.x][p.y + 3], player, check); } else { if (p.x > 2) { check = ft_check_three(p4->board[p.x][p.y], player, check); check = ft_check_three(p4->board[p.x - 1][p.y], player, check); check = ft_check_three(p4->board[p.x - 2][p.y], player, check); check = ft_check_three(p4->board[p.x - 3][p.y], player, check); } } return (check); } int ft_three(t_gboard *p4, int player, t_axe p) { int check; if (p.y < (p4->nb_columns - 3)) { check = ft_lines_columns(p4, player, p, 0); if (check == 2) return (ft_good_check_l_c(p.x, p.y, p4, 0)); } check = ft_lines_columns(p4, player, p, 1); if (check == 2) return (ft_good_check_l_c(p.x, p.y, p4, 1)); return (0); } int ft_double(t_gboard *p4, t_axe p, int check) { if (check == 0 && p4->board[p.x][p.y] == 0 && p4->board[p.x][p.y + 3] == 0) { if ((p.x + 1) == p4->nb_lines && (p.y - 1) == -1 && p4->board[p.x][p.y + 4] == 0) return (p.y + 4); else if ((p.x + 1) == p4->nb_lines && (p.y + 4) == p4->nb_columns && p4->board[p.x][p.y - 1] == 0) return (p.y + 1); else if ((p.x + 1) == p4->nb_lines && (p.y + 4) != p4->nb_columns && (p.y - 1) != -1 && p4->board[p.x][p.y - 1] == 0) return (p.y + 1); else if ((p.x + 1) == p4->nb_lines && (p.y + 4) != p4->nb_columns && (p.y - 1) != -1 && p4->board[p.x][p.y + 4] == 0) return (p.y + 4); else if ((p.x + 1) != p4->nb_lines && (p.y + 4) != p4->nb_columns && (p.y - 1) == -1 && p4->board[p.x + 1][p.y + 3] && p4->board[p.x + 1][p.y] && p4->board[p.x + 1][p.y + 4] && p4->board[p.x][p.y + 4] == 0) return (p.y + 4); else if ((p.x + 1) != p4->nb_lines && (p.y + 4) == p4->nb_columns && (p.y + 4) != p4->nb_columns && (p.y - 1) != -1 && p4->board[p.x + 1][p.y + 3] && p4->board[p.x + 1][p.y] && p4->board[p.x + 1][p.y - 1] && p4->board[p.x][p.y - 1] == 0) return (p.y + 1); else if ((p.x + 1) != p4->nb_lines && (p.y + 4) != p4->nb_columns && (p.y - 1) != -1 && p4->board[p.x + 1][p.y + 3] && p4->board[p.x + 1][p.y] && p4->board[p.x + 1][p.y + 4] && p4->board[p.x][p.y + 4] == 0) return (p.y + 4); else if ((p.x + 1) != p4->nb_lines && (p.y + 4) != p4->nb_columns && (p.y - 1) != -1 && p4->board[p.x + 1][p.y + 3] && p4->board[p.x + 1][p.y] && p4->board[p.x + 1][p.y - 1] && p4->board[p.x][p.y - 1] == 0) return (p.y + 1); } return (0); } int check_double_triple(t_gboard *p4, int player, int dt) { int check; t_axe p; p.x = -1; while (++p.x != p4->nb_lines) { p.y = -1; while (++p.y != p4->nb_columns) { if (dt == 0) { if ((check = ft_three(p4, player, p))) return (check); } else if (p.y < (p4->nb_columns - 3)) { check = ft_lines_columns(p4, player, p, 0); if ((check = ft_double(p4, p, check))) return (check); } } } return (0); } int check_three(t_gboard *p4, int player, int ok) { int check; check = check_double_triple(p4, player, 0); if (check == 0 && ok == 1) check = check_double_triple(p4, player, 1); return (check); }
C
// 312350192 Omer Eckstein #include <stdbool.h> typedef struct { unsigned char red; unsigned char green; unsigned char blue; } pixel; typedef struct { int red; int green; int blue; // int num; } pixel_sum; /* Compute min and max of two integers, respectively */ int min(int a, int b) { return (a < b ? a : b); } int max(int a, int b) { return (a > b ? a : b); } int calcIndex(int i, int j, int n) { return ((i)*(n)+(j)); } /* * initialize_pixel_sum - Initializes all fields of sum to 0 */ void initialize_pixel_sum(pixel_sum *sum) { sum->red = sum->green = sum->blue = 0; // sum->num = 0; return; } /* * assign_sum_to_pixel - Truncates pixel's new value to match the range [0,255] */ static void assign_sum_to_pixel(pixel *current_pixel, pixel_sum sum, int kernelScale) { // divide by kernel's weight sum.red = sum.red / kernelScale; sum.green = sum.green / kernelScale; sum.blue = sum.blue / kernelScale; // truncate each pixel's color values to match the range [0,255] current_pixel->red = (unsigned char) (min(max(sum.red, 0), 255)); current_pixel->green = (unsigned char) (min(max(sum.green, 0), 255)); current_pixel->blue = (unsigned char) (min(max(sum.blue, 0), 255)); return; } /* * sum_pixels_by_weight - Sums pixel values, scaled by given weight */ static void sum_pixels_by_weight(pixel_sum *sum, pixel p, int weight) { sum->red += ((int) p.red) * weight; sum->green += ((int) p.green) * weight; sum->blue += ((int) p.blue) * weight; // sum->num++; return; } /* * Applies kernel for pixel at (i,j) - DONE */ //DONE static pixel applyKernel(int dim, int i, int j, pixel *src, int kernelSize, int kernel[kernelSize][kernelSize], int kernelScale, bool filter) { int ii, jj; int currRow, currCol; pixel_sum sum; pixel current_pixel; int min_intensity = 766; // arbitrary value that is higher than maximum possible intensity, which is 255*3=765 int max_intensity = -1; // arbitrary value that is lower than minimum possible intensity, which is 0 int min_row, min_col, max_row, max_col; pixel loop_pixel; initialize_pixel_sum(&sum); ii = max(i-1, 0); int iiStop = min(i+1, dim-1); jj = max(j-1, 0); int jjStop = min(j+1, dim-1); for(ii ; ii <= iiStop ; ii++) { int calindex = calcIndex(ii, 0, dim); for(jj = max(j-1, 0); jj <= jjStop; jj++) { int kRow, kCol; // compute row index in kernel if (ii < i) { kRow = 0; } else if (ii > i) { kRow = 2; } else { kRow = 1; } // compute column index in kernel if (jj < j) { kCol = 0; } else if (jj > j) { kCol = 2; } else { kCol = 1; } // apply kernel on pixel at [ii,jj] sum_pixels_by_weight(&sum, src[calindex + jj], kernel[kRow][kCol]); } } ii = max(i-1, 0); iiStop = min(i+1, dim-1); jj = max(j-1, 0); jjStop = min(j+1, dim-1); if (filter) { // find min and max coordinates for(ii; ii <= iiStop; ii++) { int calindex = calcIndex(ii, 0, dim); for(jj = max(j-1, 0); jj <= jjStop; jj++) { // check if smaller than min or higher than max and update loop_pixel = src[calindex + jj]; if ((((int) loop_pixel.red) + ((int) loop_pixel.green) + ((int) loop_pixel.blue)) <= min_intensity) { min_intensity = (((int) loop_pixel.red) + ((int) loop_pixel.green) + ((int) loop_pixel.blue)); min_row = ii; min_col = jj; } if ((((int) loop_pixel.red) + ((int) loop_pixel.green) + ((int) loop_pixel.blue)) > max_intensity) { max_intensity = (((int) loop_pixel.red) + ((int) loop_pixel.green) + ((int) loop_pixel.blue)); max_row = ii; max_col = jj; } } } // filter out min and max pixel srcPix = src[calcIndex(min_row, min_col, dim)]; sum_pixels_by_weight(&sum, srcPix, -1); sum_pixels_by_weight(&sum, srcPix, -1); } // assign kernel's result to pixel at [i,j] assign_sum_to_pixel(&current_pixel, sum, kernelScale); return current_pixel; } /* * Apply the kernel over each pixel. * Ignore pixels where the kernel exceeds bounds. These are pixels with row index smaller than kernelSize/2 and/or * column index smaller than kernelSize/2 */ //DONE void smooth(int dim, pixel *src, pixel *dst, int kernelSize, int kernel[kernelSize][kernelSize], int kernelScale, bool filter) { int i, j; int halfkernalsize = kernelSize / 2; int stop = dim - halfkernalsize; for (i = halfkernalsize ; i < stop; i++) { int calcind = calcIndex(i, 0, dim); for (j = halfkernalsize ; j < stop; j++) { dst[calcind + j] = applyKernel(dim, i, j, src, kernelSize, kernel, kernelScale, filter); } } } //DONE void charsToPixels(Image *charsImg, pixel* pixels) { int row, col; for (row = 0 ; row < m ; row++) { int rown = row*n; int Threerown = rown + rown + rown; for (col = 0 ; col < n ; col++) { int ind = rown + col; int threeRownThreeCol = Threerown + col + col + col; pixels[ind].red = image->data[threeRownThreeCol]; pixels[ind].green = image->data[threeRownThreeCol + 1]; pixels[ind].blue = image->data[threeRownThreeCol + 2]; } } } //DONE void pixelsToChars(pixel* pixels, Image *charsImg) { int row, col; for (row = 0 ; row < m ; row++) { int rown = row*n; int Threerown = rown + rown + rown; for (col = 0 ; col < n ; col++) { int ind = rown + col; int threeRownThreeCol = Threerown + col + col + col; image->data[threeRownThreeCol] = pixels[ind].red; image->data[threeRownThreeCol + 1] = pixels[ind].green; image->data[threeRownThreeCol + 2] = pixels[ind].blue; } } } //DONE void copyPixels(pixel* src, pixel* dst) { int row, col; for (row = 0 ; row < m ; row++) { int rown = row*n; for (col = 0 ; col < n ; col++) { int ind = rown + col; dst[ind].red = src[ind].red; dst[ind].green = src[ind].green; dst[ind].blue = src[ind].blue; } } } void doConvolution(Image *image, int kernelSize, int kernel[kernelSize][kernelSize], int kernelScale, bool filter) { pixel* pixelsImg = malloc(m*n*sizeof(pixel)); pixel* backupOrg = malloc(m*n*sizeof(pixel)); charsToPixels(image, pixelsImg); copyPixels(pixelsImg, backupOrg); smooth(m, backupOrg, pixelsImg, kernelSize, kernel, kernelScale, filter); pixelsToChars(pixelsImg, image); free(pixelsImg); free(backupOrg); } void myfunction(Image *image, char* srcImgpName, char* blurRsltImgName, char* sharpRsltImgName, char* filteredBlurRsltImgName, char* filteredSharpRsltImgName, char flag) { /* * [1, 1, 1] * [1, 1, 1] * [1, 1, 1] */ int blurKernel[3][3] = {{1, 1, 1}, {1, 1, 1}, {1, 1, 1}}; /* * [-1, -1, -1] * [-1, 9, -1] * [-1, -1, -1] */ int sharpKernel[3][3] = {{-1,-1,-1},{-1,9,-1},{-1,-1,-1}}; if (flag == '1') { // blur image doConvolution(image, 3, blurKernel, 9, false); // write result image to file writeBMP(image, srcImgpName, blurRsltImgName); // sharpen the resulting image doConvolution(image, 3, sharpKernel, 1, false); // write result image to file writeBMP(image, srcImgpName, sharpRsltImgName); } else { // apply extermum filtered kernel to blur image doConvolution(image, 3, blurKernel, 7, true); // write result image to file writeBMP(image, srcImgpName, filteredBlurRsltImgName); // sharpen the resulting image doConvolution(image, 3, sharpKernel, 1, false); // write result image to file writeBMP(image, srcImgpName, filteredSharpRsltImgName); } }
C
/*P15.7 Program to understand the use of local static variable */ #include<stdio.h> void func(int n); int main(void) { int n,i ; printf("Enter a number : "); scanf("%d",&n); for(i=1; i<=10; i++) func(n); printf("\n"); return 0; } void func(int n) { static int step; /*Automatically initialized to 0*/ step=step+n; printf("%d\t",step); }
C
/** * Mutex that sleeps... and can be owned across sleeping... * * @copyright * This file is part of ToaruOS and is released under the terms * of the NCSA / University of Illinois License - see LICENSE.md * Copyright (C) 2021 K. Lange <klange@toaruos.org> */ #include <kernel/types.h> #include <kernel/printf.h> #include <kernel/time.h> #include <kernel/string.h> #include <kernel/spinlock.h> #include <kernel/assert.h> #include <kernel/process.h> #include <kernel/list.h> #include <kernel/mutex.h> extern int wakeup_queue_one(list_t * queue); sched_mutex_t * mutex_init(const char * name) { sched_mutex_t * out = malloc(sizeof(sched_mutex_t)); spin_init(out->inner_lock); out->status = 0; out->owner = NULL; out->waiters = list_create(name, out); return out; } int mutex_acquire(sched_mutex_t * mutex) { spin_lock(mutex->inner_lock); while (mutex->status) { sleep_on_unlocking(mutex->waiters, &mutex->inner_lock); spin_lock(mutex->inner_lock); } mutex->status = 1; mutex->owner = (process_t*)this_core->current_process; spin_unlock(mutex->inner_lock); return 0; } int mutex_release(sched_mutex_t * mutex) { assert(mutex->owner == this_core->current_process); spin_lock(mutex->inner_lock); mutex->owner = NULL; mutex->status = 0; wakeup_queue_one(mutex->waiters); spin_unlock(mutex->inner_lock); return 0; }
C
#include <string.h> #include <stdio.h> int replace_char(char *str, char old_char, char new_char); int main(void) { int result = 0; char str[] = "this is my test string"; result = replace_char(str, ' ', '_'); printf("\n%s\n%d replacments", str, result); return 0; } int replace_char(char *str, char old_char, char new_char) { int count = 0; int made_change_flag = 0; for(count = 0; count < (int)strlen(str); count ++) { if(str[count] == old_char) { str[count] = new_char; made_change_flag++; } } return made_change_flag; }
C
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__CWE135_61b.c Label Definition File: CWE122_Heap_Based_Buffer_Overflow__CWE135.label.xml Template File: sources-sinks-61b.tmpl.c */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: Void pointer to a wchar_t array * GoodSource: Void pointer to a char array * Sinks: * GoodSink: Allocate memory using wcslen() and copy data * BadSink : Allocate memory using strlen() and copy data * Flow Variant: 61 Data flow: data returned from one function to another in different source files * * */ #include "std_testcase.h" #include <wchar.h> #ifndef OMITBAD void * CWE122_Heap_Based_Buffer_Overflow__CWE135_61b_badSource(void * data) { { wchar_t * dataBadBuffer = (wchar_t *)malloc(50*sizeof(wchar_t)); wmemset(dataBadBuffer, L'A', 50-1); dataBadBuffer[50-1] = L'\0'; /* POTENTIAL FLAW: Set data to point to a wide string */ data = (void *)dataBadBuffer; } return data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B() uses the GoodSource with the BadSink */ void * CWE122_Heap_Based_Buffer_Overflow__CWE135_61b_goodG2BSource(void * data) { { char * dataGoodBuffer = (char *)malloc(50*sizeof(char)); memset(dataGoodBuffer, 'A', 50-1); dataGoodBuffer[50-1] = '\0'; /* FIX: Set data to point to a char string */ data = (void *)dataGoodBuffer; } return data; } /* goodB2G() uses the BadSource with the GoodSink */ void * CWE122_Heap_Based_Buffer_Overflow__CWE135_61b_goodB2GSource(void * data) { { wchar_t * dataBadBuffer = (wchar_t *)malloc(50*sizeof(wchar_t)); wmemset(dataBadBuffer, L'A', 50-1); dataBadBuffer[50-1] = L'\0'; /* POTENTIAL FLAW: Set data to point to a wide string */ data = (void *)dataBadBuffer; } return data; } #endif /* OMITGOOD */
C
#include <stdio.h> #include <stdlib.h> int *entregarDirMemArr(int arregloInt[5],int posicion){ // Recordar que los arreglos son punteros de por si. return arregloInt + posicion; } int main(){ int arregloInt[5]; int *direccionMemoriaPos = entregarDirMemArr(arregloInt,2); printf("Direccion del arreglo: %p\n",&arregloInt); printf("Direccion de la posicion buscada: %p",direccionMemoriaPos); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<ctype.h> FILE * fp; int main() { int input; int intin; int intin2; int outp; int op; printf("Enter first number: "); if (scanf("%d", &input)) { intin = atoi(input); } printf("Enter second number: "); if (scanf("%d", &input)) { intin2 = atoi(input); } printf("%d", intin, intin2); }
C
#include<stdio.h> int main() { //usinf for loop printf("using for loop\n"); for(int i=0;i<4;i++){ staticdemo(); } printf("\n"); printf("using while loop\n"); //using while loop int i=0; while(i<4){ staticdemo(); i++; } return 0; } void staticdemo(){ static int a=4; a=a+4; printf("%d ",a); }
C
#include<stdio.h> int main() { unsigned long long int max=0,p,a[20][20],i,j; for(i=0;i<20;i++) for(j=0;j<20;j++) scanf("%llu",&a[i][j]); //horizontal products for(i=0;i<20;i++) for(j=0;j<=16;j++) { p=1; p*=a[i][j]*a[i][j+1]*a[i][j+2]*a[i][j+3]; max=max>p?max:p; } //vertical products for(i=0;i<20;i++) for(j=0;j<=16;j++) { p=1; p*=a[j][i]*a[j+1][i]*a[j+2][i]*a[j+3][i]; max=max>p?max:p; } //left diagonal products for(i=0;i<=16;i++) for(j=0;j<=16;j++) { p=1; p*=a[i][j]*a[i+1][j+1]*a[i+2][j+2]*a[i+3][j+3]; max=max>p?max:p; } //right diagonal products for(i=0;i<=16;i++) for(j=3;j<20;j++) { p=1; p*=a[i][j]*a[i+1][j-1]*a[i+2][j-2]*a[i+3][j-3]; max=max>p?max:p; } printf("%llu\n",max); return 0; }
C
#include <stdio.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> volatile int int_c = 0; volatile int tstp_c = 0; void hler(int senial){ if (senial == SIGINT) int_c++; if (senial == SIGTSTP) tstp_c++; } int main(int argc, char* argv[]){ printf("Pid del proceso: %d.\n", getpid()); struct sigaction act; //SIGINT sigaction(SIGINT, NULL, &act); //Get handler act.sa_handler = hler; sigaction(SIGINT, &act, NULL); //Set sa_handler //SIGTSTP sigaction(SIGTSTP, NULL, &act); //Get handler act.sa_handler = hler; sigaction(SIGTSTP, &act, NULL); //Set sa_handler while (int_c + tstp_c < 10) pause(); printf("Numero de señales SIGINT recibidas: %i\n", int_c); printf("Numero de señales SIGTSTP recibidas: %i\n", tstp_c); return 0; }
C
// // Created by bartek on 3/18/20. // #include "nb_iot.h" #include "uart_comm.h" #include "string.h" #include "stdlib.h" #include "stm32f1xx_hal_dma_ex.h" #include "stm32f1xx_hal_uart.h" #include "helpers.h" // Initialize with 0 every elem static uint16_t concatenate_counter = 0; uart_struct pc_uart = { .name = "PC_UART", .concatenate_counter = 0}; uart_struct pms_uart = { .name = "PMS_UART", .concatenate_counter = 0}; uart_struct nb_iot_uart = { .name = "NB-IOT_UART", .concatenate_counter = 0 }; void start_dma_uart_rx(void) { HAL_UART_Receive_DMA(&PM_SENSOR_UART, (uint8_t *) pms_uart.raw_data_rx_buffer, UART_RECEIVE_MAX); HAL_UART_Receive_DMA(&PC_COMM_UART, (uint8_t *) pc_uart.raw_data_rx_buffer, UART_RECEIVE_MAX); HAL_UART_Receive_DMA(&NB_IOT_UART, (uint8_t *) nb_iot_uart.raw_data_rx_buffer, UART_RECEIVE_MAX); } HAL_StatusTypeDef uart_send_message(UART_HandleTypeDef *handle, const char *message, const char *receiver) { size_t length = 0; // while(__HAL_DMA_GET_COUNTER(handle->hdmatx) != 0) { } while(handle->gState != HAL_UART_STATE_READY) { } // Prevent from corrupting TX Messages if (handle == &PC_COMM_UART) { char message_to_pc[UART_TRANSMIT_MAX] = { 0 }; sprintf(message_to_pc, "[%s] %s", receiver, message); length = strlen(message_to_pc); HAL_UART_Transmit_DMA(handle, (uint8_t *) message_to_pc, (uint16_t) length); } else { length = strlen(message); HAL_UART_Transmit_DMA(handle, (uint8_t *) message, (uint16_t) length); } } // Interruptions void IDLE_DETECT_UART_IRQHandler(UART_HandleTypeDef * handle) { if(RESET != __HAL_UART_GET_FLAG(handle, UART_FLAG_IDLE)) // Check if IDLE IT { __HAL_UART_CLEAR_IDLEFLAG(handle); // Clear IDLE IT Flag if (handle == &PC_COMM_UART) { IDLE_UART_String_Callback(handle, &pc_uart); } else if (handle == &NB_IOT_UART) { IDLE_UART_String_Callback(handle, &nb_iot_uart); } else if (handle == &PM_SENSOR_UART) { IDLE_UART_Raw_Callback(handle, &pms_uart); } else { Error_Handler(); } } } uint8_t concatenate_message_buffer(uart_struct *uart_struct_handle, uint16_t counter) { memcpy(&uart_struct_handle->raw_data_rx[counter], uart_struct_handle->raw_data_rx_buffer, uart_struct_handle->data_length); } void IDLE_UART_Raw_Callback(UART_HandleTypeDef *handle, uart_struct *uart_struct_handle) { HAL_UART_DMAStop(handle); uart_struct_handle->data_length = UART_RECEIVE_MAX - __HAL_DMA_GET_COUNTER(handle->hdmarx); memset(uart_struct_handle->raw_data_rx, 0, UART_RECEIVE_MAX); // Clear whole buffer concatenate_message_buffer(uart_struct_handle, 0); memset(uart_struct_handle->raw_data_rx_buffer, 0, UART_RECEIVE_MAX); // Clear whole buffer uart_struct_handle->rx_flag = 1; HAL_UART_Receive_DMA(handle, (uint8_t *) uart_struct_handle->raw_data_rx_buffer, UART_RECEIVE_MAX); } /* Character '/n' terminates the string! In case when not spotted, concatenation is performed */ /* When RX Buffer is longer than UART_RECEIVE_MAX then send message on PC to handle this! */ void IDLE_UART_String_Callback(UART_HandleTypeDef *handle, uart_struct *uart_struct_handle) { HAL_UART_DMAStop(handle); uart_struct_handle->data_length = UART_RECEIVE_MAX - __HAL_DMA_GET_COUNTER(handle->hdmarx); if ((uart_struct_handle->data_length + uart_struct_handle->concatenate_counter) >= UART_RECEIVE_MAX) { /* If concatenated buffer is longer. Clear everything and notify user on PC Uart*/ sprintf(pc_uart.raw_data_tx_buffer, "RX Buffer exceeds UART_RECEIVE_MAX %d!. Not handling this one!\r\n", UART_RECEIVE_MAX); uart_send_message(&PC_COMM_UART, pc_uart.raw_data_tx_buffer, uart_struct_handle->name); memset(uart_struct_handle->raw_data_rx_buffer, 0, UART_RECEIVE_MAX); memset(uart_struct_handle->raw_data_rx, 0, UART_RECEIVE_MAX); uart_struct_handle->data_length = 0; uart_struct_handle->concatenate_counter = 0; uart_struct_handle->concatenate_counter = 0; HAL_UART_Receive_DMA(handle, (uint8_t *) uart_struct_handle->raw_data_rx_buffer, UART_RECEIVE_MAX); return; } // Clear RX Buffer at the beginning if (0 == uart_struct_handle->concatenate_counter) { memset(uart_struct_handle->raw_data_rx, 0, UART_RECEIVE_MAX); // Clear whole buffer } if (uart_struct_handle->raw_data_rx_buffer[(uart_struct_handle->data_length) - 1] == '\n') { concatenate_message_buffer(uart_struct_handle, uart_struct_handle->concatenate_counter); uart_struct_handle->concatenate_counter += uart_struct_handle->data_length; uart_struct_handle->data_length = uart_struct_handle->concatenate_counter; uart_struct_handle->rx_flag = 1; uart_struct_handle->concatenate_counter = 0; } else { concatenate_message_buffer(uart_struct_handle, uart_struct_handle->concatenate_counter); uart_struct_handle->concatenate_counter += uart_struct_handle->data_length; } memset(uart_struct_handle->raw_data_rx_buffer, 0, UART_RECEIVE_MAX); HAL_UART_Receive_DMA(handle, (uint8_t *) uart_struct_handle->raw_data_rx_buffer, UART_RECEIVE_MAX); } // Mes_consistency // Expected = 0 // Not expected = 1 uint8_t send_check_message(UART_HandleTypeDef *handle, const char *mes_send, const char *mes_check, uart_struct *uart_struct_handle, const uint8_t mes_consistency, const uint16_t timeout) { if(1 == uart_struct_handle->rx_flag) { uart_struct_handle->rx_flag = 0; } uart_send_message(handle, mes_send, NULL); uart_struct_handle->tim_counter = timeout; while(uart_struct_handle->rx_flag == 0) { if(uart_struct_handle->tim_counter == 0) { return 2; } } uart_struct_handle->tim_counter = 0; uart_struct_handle->rx_flag = 0; memset(uart_struct_handle->raw_data_tx_buffer, 0, UART_TRANSMIT_MAX); /* EXOR Mes_Consistency && ret */ if(0 != strcmp(remove_req_from_read( (char *)uart_struct_handle->raw_data_rx), mes_check) ) { return 0 ^ mes_consistency; } else { return 1 ^ mes_consistency; } }
C
#include <stdio.h> int _length(char s1) { int i, cont = 0; for (i = 0; s1[i] != '\0'; i++) if (str[i] != ' ') { alpha = 1; cont++; } cont += 1; return (cont) } #include "holberton.h" #include <stdio.h> #include <ctype.h> #include <stdlib.h> /** * strtow - function that splits into words * @str: string * Return: Returns null if str = NULL or is empty * Returns a pointer to an array of strings */ char **strtow(char *str) { int i, j, alpha,cont = 0, cont1 = 0; char **s1; if (str == NULL || str == "") return (NULL); for (i = 0; s[i] != '\0'; i++) if (str[i] != ' ') { alpha = 1; } if (str[i] == ' ' && alpha = 1) cont++; alpha = 0; } *s1 = malloc(sizeof(char) * cont); if(str == NULL || str == "") return (NULL); for (i = 0;str[i] != '\0'; i++) { if (str[i] != ' ') alpha = 1 cont1++; *s1 = malloc(sizeof(char) * cont1); if (str == NULL || str == "") return (NULL); for (j = 0; j >= 0; j++) { free(str[j]); } free(str);
C
#include <stdio.h> //int main (){ //char a = 'a'; //int b = 65; //char c[20] = "Hello world"; //type data //printf ("%-20s Hello2", c); //rata kanan hello 2 //printf("%20s Hello2", c); //rata kiri hello 2 //putchar ('z') //print cuma 1 karakter //puts(c); //printf("test"); //return 0; //} int main (){ int a = 5; int b = 5 ; char c [20]; printf("Masukan Angka : "); scanf("%d", &b); fflush (stdin) return 0; }
C
#define LIM 32 #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <fcntl.h> #include <time.h> #include <pmmintrin.h> float randfloat() { float r= (float)(rand()); float div =(float)(1-RAND_MAX); return r/div; } int main(){ float y[LIM],x[LIM],yc[LIM],a; int i,j; a=2.0; for (i=0;i<LIM;i++) { x[i]=-randfloat(); y[i]=-randfloat(); yc[i]=y[i]; } for (i=0;i<LIM;i++) {//printf("%f ",x[i]); printf("%f ",y[i]); } printf("\n"); //saxpy for (i=0;i<LIM;i++) y[i]=a*x[i]+y[i]; for (i=0;i<LIM;i++) {//printf("%f ",x[i]); printf("%f ",y[i]); } printf("\n"); for (i=0;i<LIM;i++) y[i]=yc[i]; //Poner aqui version de saxpy con SSE __m128 aVector = _mm_set1_ps(a); __m128 vectorX, vectorY; for (i=0;i<LIM;i+=4){ vectorX = _mm_loadu_ps(x+i); vectorY = _mm_loadu_ps(y+i); vectorX = _mm_mul_ps(vectorX,aVector); vectorY = _mm_add_ps(vectorX,vectorY); _mm_store_ps(y+i,vectorY); } /* con puntero: __m128 m1; __m128 ma = _mmset_ps1(a); __m128 pSrc1 = (__m128*) x; __m128 pSrc2 = (__m128*) y; for (i=0;i<LIM;i+=4){ m1 = _mm_mul_ps(*pSrc1, ma); *pSrc2 = _mm_add_ps(m1,*pSrc2); pSrc1++; pSrc2++; } */ for (i=0;i<LIM;i++) {//printf("%f ",x[i]); printf("%f ",y[i]); } printf("\n"); }
C
#include "calculator.h" static RNResult *calculatorResult; static RNResult *storedCalculatorInput; static RNResult *currentCalculatorInput; static char arithmeticOperator; static void performComputation(); static void allocResult(RNResult **result); static void freeResult(RNResult **result); static void reallocResult(RNResult **result); static void saveResult(RNResult *result, const char *romanValue); static int isValidOperator(const char operator); void recallCurrentInput(RNResult *resultBuffer) { if (currentCalculatorInput != NULL) { memcpy(resultBuffer, currentCalculatorInput, sizeof * resultBuffer); } } void recallStoredInput(RNResult *resultBuffer) { if (storedCalculatorInput != NULL) { memcpy(resultBuffer, storedCalculatorInput, sizeof * resultBuffer); } } void recallResult(RNResult *resultBuffer) { if (calculatorResult != NULL) { memcpy(resultBuffer, calculatorResult, sizeof * resultBuffer); } } const char recallOperator() { return arithmeticOperator; } void resetCalculator() { reallocResult(&currentCalculatorInput); reallocResult(&storedCalculatorInput); reallocResult(&calculatorResult); } void enterInput(const char *input) { reallocResult(&currentCalculatorInput); saveResult(currentCalculatorInput, input); } void enterOperator(const char operator) { reallocResult(&calculatorResult); reallocResult(&storedCalculatorInput); if (0 == strcmp(currentCalculatorInput->roman, "")) { setError(calculatorResult->error, ERROR_NO_INPUT_BEFORE_OPERATOR); } else { if (!isValidOperator(operator)) { setError(calculatorResult->error, ERROR_BAD_OPERATOR); } else { arithmeticOperator = operator; } saveResult(storedCalculatorInput, currentCalculatorInput->roman); reallocResult(&currentCalculatorInput); } } void compute() { reallocResult(&calculatorResult); if (0 == strcmp(storedCalculatorInput->roman, "")) { setError(calculatorResult->error, ERROR_NO_PREVIOUS_INPUT_BEFORE_COMPUTE); } else if (!isValidOperator(arithmeticOperator)) { setError(calculatorResult->error, ERROR_NO_OPERATOR); } else if (0 == strcmp(currentCalculatorInput->roman, "")) { setError(calculatorResult->error, ERROR_NO_INPUT_BEFORE_COMPUTE); } else { performComputation(); } arithmeticOperator = 0; reallocResult(&currentCalculatorInput); reallocResult(&storedCalculatorInput); } static void performComputation() { if ('+' == arithmeticOperator) { add(calculatorResult, storedCalculatorInput->roman, currentCalculatorInput->roman); } else if ('-' == arithmeticOperator) { subtract(calculatorResult, storedCalculatorInput->roman, currentCalculatorInput->roman); } } static void allocResult(RNResult **result) { if (*result == NULL) { *result = malloc(sizeof **result); initRNResult(*result); } } static void freeResult(RNResult **result) { if (*result != NULL) { freeRNResult(*result); free(*result); } *result = NULL; } static void reallocResult(RNResult **result) { freeResult(result); allocResult(result); } static void saveResult(RNResult *result, const char *romanValue) { strcpy(result->roman, romanValue); result->arabic = convertToInt(romanValue, result->error); } static int isValidOperator(const char operator) { return ('+' == operator || '-' == operator); } void add(RNResult *sumResult, const char *augend, const char *addend) { int arabicSum = 0; int augendValue = convertToInt(augend, sumResult->error); if (ERROR_NONE == sumResult->error->number) { int addendValue = convertToInt(addend, sumResult->error); if (ERROR_NONE == sumResult->error->number) { arabicSum = augendValue + addendValue; if (arabicSum > MAX_ROMAN_VALUE) { setError(sumResult->error, ERROR_GREATER_THAN_MAX); return; } convertToNumeral(sumResult, arabicSum); } } } void subtract(RNResult *diffResult, const char *minuend, const char *subtrahend) { int arabicDifference = 0; int minuendValue = convertToInt(minuend, diffResult->error); if (ERROR_NONE == diffResult->error->number) { int subtrahendValue = convertToInt(subtrahend, diffResult->error); if (ERROR_NONE == diffResult->error->number) { arabicDifference = minuendValue - subtrahendValue; if (arabicDifference < MIN_ROMAN_VALUE) { setError(diffResult->error, ERROR_LESS_THAN_MIN); return; } convertToNumeral(diffResult, arabicDifference); } } }
C
#include <stdio.h> #include <stdlib.h> //1 double add(double firstNumber, double secondNumber){ double sum; sum = firstNumber + secondNumber; return sum; } //2 double multiply(double firstNumber, double secondNumber){ double result; result = firstNumber * secondNumber; return result; } //3 double divide(double firstNumber, double secondNumber){ double result; result = firstNumber / secondNumber; return result; } //4 void minOfList(int list[],int size){ int min,i,location; min=list[0]; for(i=1;i<size;i++){ if(min>list[i]){ min=list[i]; location=i+1; } } printf("The Minimum number in the list is :%d and Represented in location %d\n",min,location); } //5 float calculateSin(float angle){ float toRadian=3.142 / 180.0; angle = angle * toRadian; //Converting the angle to radian float term = angle; //The radian angle is now our initial term float lastValue = term; int n = 1; int i=0; while(i<10){ //Calculate the sum of Taylor's Series Terms and add them to the initial term // Keep doing this until you get a desired precise output float denominator = 2 * n * (2 * n + 1); term = -term * angle * angle / denominator; lastValue = lastValue + term; n = n + 1; i++; } return lastValue; } //6 double calculateCosine(double x) { double t0, t1, R, sum; x = x * 0.01745;//to convert the degree value to radian t0 = 1; sum = t0; for(int i = 1; i < 100; i++) { R =- (x*x)/(2*i-1)/(2*i);//Find the ratio of the second term to the first term using already known relation t1 = R * t0;//Calculate the second term sum = sum + t1; //find the new sum t0 = t1; //Keep on summing the terms to get a more precise number after the floating point } return sum; } //7 float calculateTan(float angle){ float sin,cosine,result; sin = calculateSin(angle); cosine = calculateCosine(angle); result = sin / cosine; return result; } //8 int square_detection(float a, float b, float c, float d) { return(a == b && a == c && a == d); //if the return value is true then it is a square, otherwise it is not } //9 int rectangle_detection(float a, float b, float c, float d) { if(a == b && c == d) return 1; if(a == d && b == c) return 1; if(a == c && b == d) return 1; return 0; } //10 int triangle_detection(float a, float b, float c) { return(a + b > c && b + c > a && a + c > b); //if the return value is true then it is a triangle, otherwise it is not } int main() { int operationNumber,c; do{ printf("\nScientific Calculator:\n0- Exit\n1- Add Operation\n2- Multiply Operation\n3- Division Operation\n4- Minimum of List\n5- Sin of angle\n6- Cos of angle\n7- Tan of angle\n8- Square Detection\n9- Rectangle Detection\n10- Triangle Detection\n\n"); printf("Your choice: \n"); scanf("%d",&operationNumber); switch(operationNumber){ case 0: break; case 1: printf("Enter the first number: \n"); double h,y,sum; scanf("%lf",&h); printf("Enter the second number: \n"); scanf("%lf",&y); sum = add(h,y); printf("The result = %lf\n",sum); break; case 2: printf("Enter the first number: \n"); double s,r,number; scanf("%lf",&s); printf("Enter the second number: \n"); scanf("%lf",&r); number = multiply(s,r); printf("The result = %lf\n", number); break; case 3: printf("Enter the first number: \n"); double e,n,end; scanf("%lf",&e); printf("Enter the second number: \n"); scanf("%lf",&n); end = divide(e,n); printf("The result = %lf\n", end); break; case 4: printf("Enter the size of list "); int *list; int size; scanf("%d",&size); list = (int *) malloc(sizeof(int) * size); printf("Enter the elements of list:"); for(int i=0;i<size;i++){ scanf("%d",&list[i]); } minOfList(list,size); break; case 5: printf("Enter the angle in degree: \n"); float angle,result; scanf("%f",&angle); result = calculateSin(angle); printf("The sine = %f\n",result); break; case 6: printf("Enter the angle in degree: \n"); double x,value; scanf("%lf",&x); value = calculateCosine(x); printf("The sine = %f\n",value); break; case 7: printf("Enter the angle in degree: \n"); scanf("%f",&angle); result = calculateTan(angle); printf("The tan = %f\n",result); break; case 8: printf("Enter the four sides of the square: \n"); int answer; float a,b,c,d; scanf("%f",&a); scanf("%f",&b); scanf("%f",&c); scanf("%f",&d); answer = square_detection(a,b,c,d); if(answer){ printf("It is a Square"); } else printf("It is not a Square"); break; case 9: printf("Enter the four sides of the Rectangle: \n"); int t; float o,p,z,m; scanf("%f",&o); scanf("%f",&p); scanf("%f",&z); scanf("%f",&m); t = rectangle_detection(o,p,z,m); if(t){ printf("It is a Rectangle"); } else printf("It is not a Rectangle"); break; case 10: printf("Enter the three sides of the Triangle: \n"); int k; float first,second,third; scanf("%f",&first); scanf("%f",&second); scanf("%f",&third); k = triangle_detection(first,second,third); if(k){ printf("It is a Triangle"); } else printf("It is not a Triangle"); break; default: printf("Please enter a valid choice\n"); break; } if(operationNumber!= 0){ printf("0- Exit\n1- Another Operation\n"); scanf("%d",&operationNumber); while(operationNumber!= 1 && operationNumber!= 0){ printf("Please enter a valid choice\n"); scanf("%d",&operationNumber); } }} while(operationNumber != 0); return 0; }
C
/* Program to find distance between two given points */ /* Author:Sravanthi_yachareni */ #include<stdio.h> #include<math.h> void main() { float x1,y1,x2,y2,xd,yd,Distance; printf("Enter first point(x1,y1)"); scanf("%f%f",&x1,&y1); printf("Enter second point(x2,y2)"); scanf("%f%f",&x2,&y2); xd=x2-x1; yd=y2-y1; Distance=sqrt(xd*xd+yd*yd); printf("Distance is:%f",Distance); }
C
#include <stdio.h> #include <termios.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/select.h> /*-------------------------------------------------------*/ static struct termios initial_settings, new_settings; static int peek_character = -1; /*-------------------------------------------------------*/ void init_keyboard() { tcgetattr( 0, &initial_settings ); new_settings = initial_settings; new_settings.c_lflag &= ~ICANON; new_settings.c_lflag &= ~ECHO; new_settings.c_lflag &= ~ISIG; new_settings.c_cc[VMIN] = 1; new_settings.c_cc[VTIME] = 0; tcsetattr( 0, TCSANOW, &new_settings ); } void close_keyboard() { tcsetattr( 0, TCSANOW, &initial_settings ); } int kbhit() { char ch; int nread; if( peek_character != -1 ) return( 1 ); new_settings.c_cc[VMIN] = 0; tcsetattr( 0, TCSANOW, &new_settings ); nread = read( 0, &ch, 1 ); new_settings.c_cc[VMIN] = 1; tcsetattr( 0, TCSANOW, &new_settings ); if( nread == 1 ) { peek_character = ch; return( 1 ); } return( 0 ); } int readch() { char ch; init_keyboard(); if( peek_character != -1 ) { ch = peek_character; peek_character = -1; return( ch ); } read( 0, &ch, 1 ); close_keyboard(); return( ch ); } int main() { char c,ext; c=readch(); // <---- getch() if(c!=27) printf("Caracter: %c - ASCII: %d\n\n",c,c); else { ext=readch(); printf("Caracteres: %d - %d\n\n",c,ext); ext=readch(); printf("Caracteres: %d - %d\n\n",c,ext); } }
C
#include<stdio.h> #include<string.h> int main(void) { char str[100]; gets(str); int len,i; len=strlen(str); if(len%2!=0) {str[(len-1)/2]='*'; }else { str[len/2]='*'; str[(len/2)-1]='*'; } printf("%s",str); return 0; }
C
/*ip: 3 op: ***** *** * */ #include <stdio.h> #include <stdlib.h> int main() { int n,i,j; printf("Enter the number of rows:"); scanf("%d",&n); printf("The inverted triangle :\n"); for(i=0;i<n;i++) { for(j=0;j<2*n-1;j++) { if(i+j>=2*i && i+j<=2*n-2) printf("*"); else printf(" "); } printf("\n"); } }
C
#define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20 typedef int Status; typedef int ElemType; typedef struct { ElemType data[MAXSIZE]; int length; }SqList; Status ListInsert(SqList *L, int i, ElemType e)/*将元素插入线性表*/ { int k; if (L -> length == MAXSIZE) return ERROR; if (i < 1 || i > length + 1) return ERROR; if (i < L->Length) { for (k = L->Length - 1; k >= i - 1; --k) data[k + 1] = data[k]; } L->data[i - 1] == e; ++L->Length; return OK; }
C
#include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include "Lec1_st03983_A3_malloc.h" int main(int argc, char *argv[]) { my_init(); /* printf("%" PRIuPTR "\n", (uintptr_t)head); printf("%d\n", head->size); printf("%d\n", sizeof(node_t)); printf("%d\n", sizeof(node)); */ //printf("%d\n%d\n",sizeof(int), sizeof(node_t*)); void * ptr = my_malloc(1024); void * ptr1 = my_malloc(100); void * ptr2 = my_malloc(100); my_showfreelist(); my_free(ptr2); my_showfreelist(); my_realloc(ptr1, 100); my_showfreelist(); my_free(ptr1); //node * myptr = (node * ) ptr - 1; //printf("%d\n", myptr->size); //printf("%" PRIuPTR "\n", (uintptr_t)ptr); /* printf("%" PRIuPTR "\n", (uintptr_t)head); printf("%d\n", head->size); void * ptr1 = my_malloc(100); myptr = ptr1; printf("%d\n", myptr->size); printf("%" PRIuPTR "\n", (uintptr_t)ptr1); printf("%" PRIuPTR "\n", (uintptr_t)head); printf("%d\n", head->size); void * ptr2 = my_malloc(100); myptr = ptr2; printf("%d\n", myptr->size); printf("%" PRIuPTR "\n", (uintptr_t)ptr2); printf("%" PRIuPTR "\n", (uintptr_t)head); printf("%d\n", head->size); printf("Showing FREELIST \n"); my_showfreelist(); my_free(ptr1); printf("Showing FREELIST \n"); my_showfreelist(); my_free(ptr2); printf("Showing FREELIST \n"); my_showfreelist(); ptr2 = my_calloc(4, 18); printf("Showing FREELIST \n"); my_showfreelist(); myptr = ptr2; printf("%" PRIuPTR "\n", (uintptr_t)ptr2); printf("%" PRIuPTR "\n", (uintptr_t)head); ptr2 = my_realloc(ptr2, 500); printf("Showing FREELIST \n"); my_showfreelist(); */ }
C
#include<stdio.h> int main() { int dDivisors = 0; int counter = 0; int dN = 1; while(counter<=999) //the code ignores 2 numbers, so we have two number less to count! { dN+=2; for(int j = 1; j<=dN; j++) if (dN%j == 0) dDivisors++; if (dDivisors==2) counter++; dDivisors = 0; } printf("The 1001st prime is: %d", dN); return 0; } //end main
C
#include <stdio.h> #include <stdlib.h> #include "list.h" ////////////////////////////////////////////////////////////////////// // // OPERATION:RANGE - Determine the RANGE of info values from a // list of nodes. // int main() { ////////////////////////////////////////////////////////////////// // // Declare and initialize variables // List *myList = NULL; Node *result = NULL; int index = 0; char data[] = { 73, 86, 96, 47, 56, 99, 103, 92, 91, 47, 95, 84, 37, 73, 59, 61, 104, 42, 73, 97, 98, 79, 78, 16, 52, 39, 26, 13, 73, 79, 24, 78 }; ////////////////////////////////////////////////////////////////// // // Create the list, fill it with values // myList = mklist(); for (index = 0; index < 32;) myList = append(myList, myList->caboose, mknode(data[index++])); // // Initialize highest, lowest, and range values // int highest; int lowest; int range; // // Sort list in ascending order // myList = sortlist(myList, 0); // // Set the highest and lowest values of the list // highest = myList->caboose->contents; lowest = myList->engine->contents; // // calculate range // range = highest - lowest; // // Make result into node with range value. // result = mknode(range); ////////////////////////////////////////////////////////////////// // // Store computed value in info element of result Node. // if (result != NULL) fprintf(stdout, "Result of OPERATION is: %hhu\n", result->contents); ////////////////////////////////////////////////////////////////// // // Clean up // myList = rmlist(myList); return (0); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jawatter <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/21 21:52:24 by jawatter #+# #+# */ /* Updated: 2019/10/21 21:53:06 by jawatter ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" // builtin functions accessed through cmd[0] being compared to the name t_cmd_line g_dispatch_cmd[DSP] = { {"echo", &echo}, {"cd", &cd}, {"exit", &exit_func}, {"env", &put_env}, {"unsetenv", &unset_env}, {"setenv", &set_env}, }; // go through 2d array of path split char *get_bin(char **cmds, t_minishell *sp) { //find path env and split it at each ':', if the executable is not in the path, add a '/' and concatenate it to the end //funky implementation but neccessary to prevent segfaults when path env is not present sp->y = 0; if ((sp->new = find_env("PATH=")) != NULL) { sp->tmp = ft_strsplit(sp->new, ':'); free(sp->new); } else return (NULL); while (sp->tmp[sp->y]) { if (ft_start(cmds[0], sp->tmp[sp->y])) sp->path = ft_strdup(cmds[0]); else sp->path = make_path(sp->tmp[sp->y], cmds[0]); if (lstat(sp->path, &sp->buf) != -1) { free_2d(sp->tmp); return (sp->path); } else free(sp->path); sp->y++; } free_2d(sp->tmp); return (NULL); } //if the executable is not found in the path it has to be a directory or a exe like ./a.out void fin_cmd(t_minishell *sp, char **cmds) { char *path; struct stat buf; path = get_bin(cmds, sp); if (!(lstat(cmds[0], &buf) != -1) && path == NULL) { ft_putstr("minishell: command not found: "); ft_putstr(cmds[0]); ft_putchar('\n'); } else if (path) { lstat(cmds[0], &buf); exec_fork(sp, path, cmds); } else if (lstat(cmds[0], &buf) != -1) { if (S_ISDIR(buf.st_mode)) chdir(cmds[0]); else if (S_ISREG(buf.st_mode)) exec_fork(sp, cmds[0], cmds); } free(path); } // if the command is a builtin dispatch it to its function else check if its a executable, regular file or directory void exec_cmd(t_minishell *sp, char **cmds) { int x; int y; x = 0; y = 0; while (x < DSP) { if (ft_strcmp(cmds[0], g_dispatch_cmd[x].name) == 0) { g_dispatch_cmd[x].choosedist(cmds, sp); y = 1; } x++; } if (y == 0) fin_cmd(sp, cmds); } // split line read from stdin into arguments by the ';' then split it by spaces to handle expansions // iterate through your arguments which are split by spaces and handle for expansions if '~' or '$' is found // cd $PWD; becomes a 2_d array like so | cd | $PWD | iterate through this 2d array and check for expansions void parse_stdin(t_minishell *sp) { int x; int z; x = -1; sp->fhold = ft_strsplit(sp->value, ';'); free(sp->value); while (sp->fhold[++x]) { z = -1; sp->split = ft_strsplit(sp->fhold[x], ' '); while (sp->split[++z]) { if (ft_strrchr(sp->split[z], '$')) { sp->tmp1 = sp->split[z]; sp->split[z] = handle_exp(sp->split[z]); free(sp->tmp1); } else if (ft_strchr(sp->split[z], '~')) sp->split[z] = handle_tild(sp->split[z]); } if (sp->split[0]) exec_cmd(sp, sp->split); free_2d(sp->split); } free_2d(sp->fhold); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap_main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: amargy <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/27 16:03:16 by amargy #+# #+# */ /* Updated: 2020/02/27 19:18:01 by amargy ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void write_commands(t_ps *p) { p->tmp_c = p->c; while (p->tmp_c != NULL) { ft_printf("%s\n", p->tmp_c->com); p->tmp_c = p->tmp_c->next; } } void sort_chunks(t_ps *p) { if (check_sort(p->a, p->i_last) && p->top_a == 0) return ; if (p->b_ch == NULL) { create_main_chunk(p); b_chunks_operations(p); } else { p->first_iter = 1; a_chunks_operations(p); } sort_chunks(p); } void algo(t_ps *p) { if (p->i_last > 2) { sort_chunks(p); return ; } if (p->i_last == 2) sort_three_a(p); else if (p->i_last == 1) sort_two_in_top("a", p); } int main(int argc, char **argv) { t_ps *p; if (argc >= 2) { p = create_main_struct(); if (check_arg_terminator(argv) && check_arg(argv, p)) { algo(p); write_commands(p); free_stacks_and_com(p); } else { free_stacks_and_com(p); write(1, "Error\n", 6); } } return (0); }
C
// https://en.wikipedia.org/wiki/Consistent_Overhead_Byte_Stuffing #include "codec.h" #define StartBlock() (code_ptr = dst++, code = 1) #define FinishBlock() (*code_ptr = code) size_t stuffData(const uint8_t *ptr, size_t length, uint8_t *dst) { const uint8_t *start = dst, *end = ptr + length; uint8_t code, *code_ptr; /* Where to insert the leading count */ StartBlock(); while (ptr < end) { if (code != 0xFF) { uint8_t c = *ptr++; if (c != 0) { *dst++ = c; code++; continue; } } FinishBlock(); StartBlock(); } FinishBlock(); return dst - start; } size_t unstuffData(const uint8_t *ptr, size_t length, uint8_t *dst) { const uint8_t *start = dst, *end = ptr + length; uint8_t code = 0xFF, copy = 0; for (; ptr < end; copy--) { if (copy != 0) { *dst++ = *ptr++; } else { if (code != 0xFF) *dst++ = 0; copy = code = *ptr++; if (code == 0) break; /* Source length too long */ } } return dst - start; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <sys/socket.h> #include <sys/types.h> #include <sys/stat.h> #include <arpa/inet.h> #include <fcntl.h> #include <netdb.h> #include "cJSON.h" #include <ctype.h> #include <signal.h> #include <errno.h> #include <iconv.h> #define MAX 20480 #define INET_ADDRSTRLEN 16 #define DESTPORT 80 char local_city_id[9]; ssize_t readn(int fd, void *vptr, size_t n) { size_t nleft; ssize_t nread; char *ptr; ptr = vptr; nleft = n; while (nleft > 0) { if ((nread = read(fd, ptr, nleft)) < 0) { if (errno == EINTR) nread = 0; else return(-1); }else if (nread == 0) break; nleft -= nread; ptr += nread; } return (n - nleft); } char *http_request(char *str, char *URL, char *DestIP, int DestPort) { //printf("Try to request the json data from weather.com\n"); int headlen; // http request header char *head = (char *)malloc(MAX); strcat(head, "GET "); strcat(head, URL); strcat(head, str); strcat(head, " HTTP/1.1\r\n"); strcat(head, "Host: "); strcat(head, DestIP); strcat(head, "\r\nConnection: keep-alive\r\n"); strcat(head, "Accept: */*\r\n"); //strcat(head, "Referer: http://www.weather.com.cn/weather/101210101.shtm\r\n\r\n"); //http://m.weather.com.cn/data/101010100.html strcat(head, "Referer: http://m.weather.com.cn/data/101010100.html\r\n\r\n"); headlen = strlen(head); //create socket int sockfd; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { printf("http request: create socket error %s (errno: %d)\n", strerror(errno), errno); exit(1); } else { //printf("http request:create socket success\n"); } struct sockaddr_in dest_addr; dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(DestPort); dest_addr.sin_addr.s_addr = inet_addr(DestIP); char *ptr, **pptr, str_addr[32]; ptr = DestIP; struct hostent *hptr; if ((hptr = gethostbyname(DestIP)) == NULL) { printf("gethostbyname erro %s.\n", DestIP);} pptr = hptr -> h_addr_list; dest_addr.sin_addr.s_addr = inet_addr(inet_ntop(hptr->h_addrtype, *pptr, str_addr, sizeof(str_addr))); // connect int ret; ret = connect(sockfd, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); if (ret < 0) { printf("http request: connect error %s(errno: %d)\n", strerror(errno), errno); } else{//printf("http request: connect socket succes.\n"); } //send ret = write(sockfd, head, headlen); if (ret < 0) { printf("http request: write error %s(errno: %d)\n", strerror(errno), errno); exit(1); } else{ //printf("http request: write succes.\n"); } // read char *strResponse = (char *)malloc(MAX); memset(strResponse, 0, MAX); ssize_t n = readn(sockfd, strResponse, MAX); printf("read : %d\n", n); strResponse[MAX] = '\0'; close(sockfd); //printf("*******************%s\n", strResponse); return strResponse; } char *extract_news_json(char *src, int i_for) { //printf("extract weather json: try to extract weather json.\n"); int i; char *p = src; char *dst; for(i = 0; i < i_for; i++) { strsep(&p, "\n"); //printf("*********************%d %s\n",i, p); } dst = strsep(&p, ";"); //printf("&&&&&&&&&&&&&&&&&&%s\n", dst); //printf("extract weather json: extract weather json success.\n"); return dst; } char *parse_json(char *src) { //printf("parse json: try to parse json data.\n"); char *city, *cityid, *temp1, *temp2, *weather; char *result = (char *)malloc(MAX); cJSON *root, *format; root = cJSON_Parse(src); format = cJSON_GetObjectItem(root,"last_time") -> valuestring; //city = cJSON_GetObjectItem(format,"serverSeconds")->valuestring; printf("city:::::::::::%s", format); // strcat(city, ", "); //strcat(city, cityid); //strcat(city, ", "); //strcat(city, weather); //strcpy(result, city); //printf("parsejson success.\n"); return result; } void get_news() { char *re = (char *)malloc(MAX); memset(re, 0, MAX); char *out = (char *)malloc(MAX); memset(out, 0, MAX); re = http_request("rollnews_ch_out_interface.php","/interface/", "roll.news.sina.com.cn", 80); g2u(re, strlen(re), out, MAX); //printf("%s\n", out); char *new_json = extract_news_json(out, 19); printf("%s\n", new_json); free(re); free(out); } //int code_convert()和 int g2u()用于编码之间的转换,如 将gb2312转换为utf-8 int code_convert(char *from_char, char *to_char, char *inbuf, int inlen,char *outbuf, int outlen) { iconv_t cd; int rc; char **pin = &inbuf; char **pout = &outbuf; cd = iconv_open(to_char, from_char); if(cd == 0) return -1; memset(outbuf, 0, outlen); if(iconv(cd, pin, &inlen, pout, &outlen) == -1) return -1; iconv_close(cd); return 0; } int g2u(char *inbuf, size_t inlen, char *outbuf, size_t outlen) { return code_convert("gb18030", "utf-8", inbuf, inlen, outbuf, outlen); } int main() { get_news(); }
C
#include <REGX52.H> void delay(unsigned int t) //ʱ { unsigned char n = 0;; for(;t > 0;t-- ) for(n = 0;n <125;n++); } void main() { unsigned char i,j; unsigned int led; while(1) { delay(500); led = 0xfe; for(i = 0;i < 8;i++) { P1 = led; //ȿp1 delay(500); led = led<<1; //ƴ if(P1 == 0x00) { delay(500); led = 0x7f; //ٴ for(j = 0;j < 8;j++) { P1 = led; led = led>>1; delay(500); } } } } }
C
#include<stdio.h> main() { int x[]={1,2,3,4,5,6,7,8,9,0},y[10],m,*p,i,j,k=0; printf("\nEnter number of numbers"); scanf("%d",&m); printf("\nEnter the numbers"); for(i=0;i<m;i++) scanf("%d",&y[i]); p=y; for(i=0;i<10;i++) { if(k==m)break; else for(j=0;j<m;j++) if(*(p+j)==x[i])printf("%d ",x[i]); k++; } getch(); return 0; }
C
#include "holberton.h" /** * print_binary - check the code for Holberton School students. * @n: number * Return: Always 0. */ void print_binary(unsigned long int n) { int i, j = 0, result; unsigned long int k; if (n == 0) _putchar('0'); k = n; while (k != 0) { k = k >> 1; j++; } for (i = j - 1; i >= 0; i--) { result = n >> i; if (result & 1) _putchar('1'); else _putchar('0'); } }
C
#include<stdio.h> #include<conio.h> #include<stdlib.h> struct node { int info ; struct node *llink ; struct node *rlink ; }; typedef struct node *NODE ; NODE getnode() { NODE t ; t = (NODE) malloc(sizeof(struct node)); return t ; } NODE insertfront(NODE head , int item ) { NODE t , cur ; cur = head->rlink ; t = getnode(); t->info = item ; t->llink = head ; t->rlink = cur ; cur -> llink = t ; head ->rlink = t ; return head ; }
C
#include "../inc/pathfinder.h" static int *fourth_check(int *k_l_con, char **splite, char **arr) { int er = 0; int len = mx_strlen("error: invalid number of islands\n"); while (er < k_l_con[1]) { if (mx_strcmp(splite[k_l_con[0]], arr[er]) == 0) { k_l_con[1]--; k_l_con[0]++; break; } else if(mx_strcmp(splite[k_l_con[0]], arr[er]) != 0) { er++; } if (er == k_l_con[1]) { write(2, "error: invalid number of islands\n", len); mx_del_strarr(&splite); exit(0); } } return k_l_con; } static int *first(int *k_l_con) { k_l_con[0]++; k_l_con[2]++; return k_l_con; } static char **second(int *k_l_con, char **splite, char **arr) { int rem = 0; while (rem < k_l_con[1] ) { if(mx_strcmp(splite[k_l_con[0]], arr[rem]) == 0) { k_l_con[1]--; k_l_con[0]++; break; } else if(mx_strcmp(splite[k_l_con[0]], arr[rem]) != 0) { rem++; } if (rem == k_l_con[1]) { arr[k_l_con[1]] = mx_strnew(mx_strlen(splite[k_l_con[0]])); mx_strcpy(arr[k_l_con[1]],splite[k_l_con[0]]); k_l_con = first(k_l_con); } } return arr; } char **mx_fix_audit1(int *k_l_con, char **splite, char **arr, int kilkisto) { if (k_l_con[1] == 0) { arr[k_l_con[1]] = mx_strnew(mx_strlen(splite[k_l_con[0]])); mx_strcpy(arr[k_l_con[1]],splite[k_l_con[0]]); k_l_con = first(k_l_con); } else if (k_l_con[1] > 0 && k_l_con[1] < kilkisto) { arr = second(k_l_con, splite, arr); } else if (k_l_con[1] >= kilkisto) { k_l_con = fourth_check(k_l_con, splite, arr); } return arr; }
C
#include "requirments.h" int sumOfSquaresOfSides(int a,int b) { return (pow(a,2)+pow(b,2)); } int pythogreanTripletCondition(int a,int b,int c) { int lhs,rhs; lhs = rhs = 0; if(a > b && a > c) { lhs = sumOfSquaresOfSides(b,c); rhs = pow(a,2); #ifdef DEBUG { printf("The largest side is : %d\n",a ); printf("The compared values are : %d == %d \n",lhs,rhs); } #endif if(lhs == rhs) return true; else return false; } else if(b > c) { lhs = sumOfSquaresOfSides(a,c); rhs = pow(b,2); #ifdef DEBUG { printf("The largest side is : %d\n",b); printf("The compared values are : %d == %d \n",lhs,rhs); } #endif if(lhs == rhs) return true; else return false; } else if(c > a && c >b) { lhs = sumOfSquaresOfSides(a,b); rhs = pow(c,2); #ifdef DEBUG { printf("The largest side is : %d\n",c); printf("The compared values are : %d == %d \n",lhs,rhs); } #endif if(lhs == rhs) return true; else return false; } else { #ifdef DEBUG { printf("There is no largest side \n"); } #endif return false; } printf("End of pythogreanTripletCondition()\n"); // (a>b && a>c) ? return a:((b>c)?return b:return c) } void readSidesOfTriangle(triagle* atriangle) { int side1,side2,side3; printf("Enter the side of triangle\n"); scanf("%d %d %d",&side1,&side2,&side3); (*atriangle).side1 = side1; (*atriangle).side2 = side2; (*atriangle).side3 = side3; //QUESTION : how to saved data to structure variables using scanf // using 1. By reference // 2. By value } void isaPythagorean(triagle* atriangle) { int a = atriangle->side1; int b = atriangle->side2; int c = atriangle->side3; printf("Inside function isaPythagorean()\n"); #ifdef DEBUG { printf("The sides of triangle are : %d %d %d \n",a,b,c); printf("Evaluated for condition\n"); } #endif atriangle->isPythoagorean = pythogreanTripletCondition(a,b,c); printf("The value of t/f is : %d\n",atriangle->isPythoagorean); }
C
/* * open.c -- * Test of the open system call. This does timing tests or * error condition testing. */ #include <sprite.h> #include <stdio.h> #include <sys/types.h> #include <sys/time.h> #include <sys/file.h> #include <sys/stat.h> #include <option.h> Boolean timing = FALSE; Boolean errorTest = FALSE; Option optionArray[] = { {OPT_TRUE, "t", (char *) &timing, "Do timing test"}, {OPT_TRUE, "e", (char *) &errorTest, "Do error tests"}, }; #define NAME_SIZE 10 * 1024 char name[NAME_SIZE]; main(argc, argv) int argc; char **argv; { argc = Opt_Parse(argc, argv, optionArray, Opt_Number(optionArray), 0); if (timing) { DoTiming(argc, argv); } if (errorTest) { DoOpenErrors(argc, argv); } } /* * DoTiming -- * Time the cost of an open/close pair. */ DoTiming(argc, argv) int argc; char *argv[]; { int count, index, i; char name[200]; FILE *f; double cost; struct timeval before, after; struct timezone foo; if (argc < 2) { count = 100; } else { count = atoi(argv[1]); } if (argc == 3) { sprintf(name, "%s/.FooA", argv[2]); } else { strcpy(name, ".FooA"); } index = strlen(name) - 1; /* * Create 20 files in the given directory with names like ".FooA" * etc. */ for (i = 0; i < 20; i++) { name[index] = 'A' + i; f = fopen(name, "w"); if (f == NULL) { fprintf(stderr, "Couldn't create %s.\n", name); exit(1); } fclose(f); } /* * Time the opens and closes. */ gettimeofday(&before, &foo); for (i = 0; i < count; i++) { name[index] = 'A' + i%20; f = fopen(name, "r"); fclose(f); } gettimeofday(&after, &foo); cost = after.tv_sec - before.tv_sec; cost += (after.tv_usec - before.tv_usec)*.000001; cost /= count; cost *= 1000; printf("%d opens and closes at %.2f msec each.\n", count, cost); /* * Remove all the temporary files that were created. */ for (count = 0; count < 20; count++) { name[index] = 'A' + count; unlink(name); } } /* * DoOpenErrors -- * Attempt to generate all errors associated with open. */ DoOpenErrors(argc, argv) int argc; char *argv[]; { printf("Open Error Tests\n"); printf(" ERROR: indicates failure case did not work\n"); printf(" otherwise perror() is used to print system error\n\n"); /* * Test bad pathname argument. */ { int fd; struct stat statb; if ((fd = open(-1, 0, 0)) >= 0) { printf("ERROR: open(-1, 0, 0) succeeded!\n"); if (fstat(fd, &statb) < 0) { perror("but fstat failed"); } else { printf("-1 found file <%d,%d>\n", statb.st_dev, statb.st_ino); close(fd); } } else { perror("open(-1, 0, 0) (bad pathname)"); } if ((fd = open(15, 0, 0)) >= 0) { printf("ERROR: open(15, 0, 0) succeeded!\n"); if (fstat(fd, &statb) < 0) { perror("but fstat failed"); } else { printf("15 found file <%d,%d>\n", statb.st_dev, statb.st_ino); close(fd); } } else { perror("open(15, 0, 0) (bad pathname)"); } } /* * Test too long a pathname. */ { register char *cPtr; register int i; for (cPtr = name, i=0 ; i < NAME_SIZE ; ) { *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; *cPtr++ = 'a'; i++ ; } if (open(name, 0, 0) >= 0) { printf("ERROR: open(tooLongName, 0, 0) succeeded!\n"); } else { perror("open(tooLongName, 0, 0)"); } } /* * Do various permission checks. This checks against violations * of the following conditions: * Exclusive open * read permission * write permission * busy file * writing a directory */ { char *name = "./FooA"; int fd, fd2; /* * Test open-unlink-close */ if ((fd = open(name, O_CREAT, 0444)) < 0) { perror("Can't create ./FooA"); } else { if ((fd2 = open(name, O_RDONLY)) >= 0) { close(fd2); } else { perror("Can't open readable file"); } unlink(name); close(fd); } /* * Test permission checking. */ if ((fd = open(name, O_CREAT, 0)) < 0) { perror("Can't create ./FooA"); } else { if ((fd2 = open(name, O_CREAT|O_EXCL, 0)) >= 0) { printf("ERROR: exclusive open of existing file succeeded!\n"); if (chmod(name, 0) < 0) { perror("Can't chmod file"); } close(fd2); } else { perror("open exclusive"); } if (open(name, O_RDONLY) >= 0) { printf("ERROR: opened with no read permission!\n"); } else { perror("read when mode == 0"); } chmod(name, 0444); if (open(name, O_WRONLY) >= 0) { printf("ERROR: opened with no write permission!\n"); } else { perror("write when mode == read only"); } if (open("/sprite/cmds/csh", O_WRONLY) >= 0) { printf("ERROR: opened executing program (csh) for writing!\n"); } else { perror("open active file"); } if (open(".", O_WRONLY) >= 0) { printf("ERROR: opened directory for writing!\n"); } else { perror("write directory"); } if (unlink(name) < 0) { perror("Can't remove test file"); } /* * Test closing closed file. */ close(fd); if (close(fd) < 0) { perror("close of closed file"); } else { printf("ERROR: closed a closed file descriptor!\n"); } } } }
C
#include "amo_net.h" struct sockaddr_in si_other; int net_connect() { int sock; if ((sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) { perror("socket()"); exit(1); } memset((char *) &si_other, 0, sizeof(si_other)); si_other.sin_family = AF_INET; si_other.sin_port = htons(PORT); if (inet_aton("127.0.0.1", &si_other.sin_addr)==0) { fprintf(stderr, "inet_aton() failed\n"); exit(1); } return sock; } int net_listen() { struct sockaddr_in si_me; int sock, n; if ((sock=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP))==-1) { perror("socket()"); exit(1); } n = 1; setsockopt( sock, SOL_SOCKET, SO_REUSEADDR, (const char *) &n, sizeof( n ) ); memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; si_me.sin_port = htons(PORT); si_me.sin_addr.s_addr = htonl(INADDR_ANY); if (bind(sock, (const struct sockaddr *)&si_me, sizeof(si_me)) == -1) { perror("bind()"); exit(1); } return sock; } void net_close(int sock) { close(sock); } void net_send(int sock, unsigned char *buf, int buflen) { int slen = sizeof(si_other); if (sendto(sock, buf, buflen, 0, (const struct sockaddr *)&si_other, slen) == -1) { perror("sendto()"); exit(1); } } void net_read(int sock, unsigned char *buf, int buflen) { int slen = sizeof(si_other); if (recvfrom(sock, buf, buflen, 0, (struct sockaddr *)&si_other, &slen) == -1) { perror("recvfrom()"); exit(1); } }
C
unsigned power(unsigned x, unsigned y) { if (x == 0 && y == 0) return 1; if (x == 0) return 0; if (y == 0) return 1; if (y == 1) return x; unsigned pow = power(x, y/2); if (y % 2 == 0) return pow * pow; return x * pow * pow; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* char_handling_fts.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: darbib <darbib@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/18 12:26:05 by darbib #+# #+# */ /* Updated: 2021/02/18 12:26:37 by darbib ### ########.fr */ /* */ /* ************************************************************************** */ /* int main() { //-----tests check_new_op printf("---------------------\n"); t_fsm fsm5; int ret5; t_lexer lexer5; fsm5.state = NORMAL_STATE; fsm5.count = 0; fsm5.current_token.type = WORD_TOKEN; fsm5.size = 1024; bzero(fsm5.buf, fsm5.size); memcpy(fsm5.buf, "ab", 2); lexer5.tokens = malloc(sizeof(t_token) * LEXERSIZE); bzero(lexer5.tokens, sizeof(t_token) * LEXERSIZE); lexer5.count = 0; lexer5.size = LEXERSIZE; ret5 = check_new_op(&lexer5, &fsm5, '>'); printf("ret = %d\n", ret5); for (size_t i = 0; i < lexer5.size; i++) { printf("token : %s\n", lexer5.tokens[i].value); printf("token type: %u\n", lexer5.tokens[i].type); } printf("fsm buffer : %s\n", fsm5.buf); //-----tests for check_operator_completion printf("---------------------\n"); t_lexer lexer2; t_fsm fsm2; lexer2.tokens = malloc(sizeof(t_token) * LEXERSIZE); lexer2.count = 0; lexer2.size = LEXERSIZE; fsm2.state = NORMAL_STATE; fsm2.current_token.type = GREAT_TOKEN; fsm2.current_token.value = ">"; fsm2.size = 1024; bzero(fsm2.buf, fsm2.size); memcpy(fsm2.buf, ">", 1); fsm2.count = 1; printf("completion possible: %d\n", check_operator_completion(&lexer2, &fsm2, '>')); printf("token type : %d\n", fsm2.current_token.type); for (size_t i = 0; i < lexer2.size; i++) { printf("token : %s\n", lexer2.tokens[i].value); printf("token type: %u\n", lexer2.tokens[i].type); } //-----tests check_quoting_char printf("---------------------\n"); t_fsm fsm3; int ret; fsm3.count = 0; bzero(fsm3.buf, 1024); fsm3.state = NORMAL_STATE; ret = check_quoting_char(&fsm3, '\''); printf("machine state : %d\nret : %d\n", fsm3.state, ret); fsm3.state = NORMAL_STATE; ret = check_quoting_char(&fsm3, '\"'); printf("machine state : %d\nret : %d\n", fsm3.state, ret); fsm3.state = NORMAL_STATE; ret = check_quoting_char(&fsm3, '\\'); printf("machine state : %d\nret : %d\n", fsm3.state, ret); fsm3.state = NORMAL_STATE; ret = check_quoting_char(&fsm3, 'q'); printf("machine state : %d\nret : %d\n", fsm3.state, ret); //-----tests check_substitution_mark printf("---------------------\n"); t_fsm fsm4; int ret2; fsm4.state = NORMAL_STATE; fsm4.count = 0; bzero(fsm4.buf, 1024); ret2 = check_substitution_mark(&fsm4, '$'); printf("buffer : %s\nret : %d\n", fsm4.buf, ret2); bzero(fsm4.buf, 1024); fsm4.count = 0; ret2 = check_substitution_mark(&fsm4, 'a'); printf("buffer : %s\nret : %d\n", fsm4.buf, ret2); //-----tests check_blank printf("---------------------\n"); t_fsm fsm6; t_lexer lexer6; fsm6.state = NORMAL_STATE; fsm6.count = 0; fsm6.current_token.type = WORD_TOKEN; fsm6.size = 1024; bzero(fsm6.buf, fsm6.size); memcpy(fsm6.buf, "ab", 2); lexer6.tokens = malloc(sizeof(t_token) * LEXERSIZE); bzero(lexer6.tokens, sizeof(t_token) * LEXERSIZE); lexer6.count = 0; lexer6.size = LEXERSIZE; check_blank(&lexer6, &fsm6, '\t'); for (size_t i = 0; i < lexer6.size; i++) { printf("token : %s\n", lexer6.tokens[i].value); printf("token type: %u\n", lexer6.tokens[i].type); } printf("fsm buffer : %s\n", fsm6.buf); } */
C
#include <stdio.h> #include <string.h> #include <limits.h> #include <stdint.h> #include <sys/types.h> #include <sys/stat.h> #include "t_error.h" #include "pread.h" #include "log.h" #include "procmem.h" #include "process_info.h" static bool file_exists(char const * filename); extern intptr_t get_process_base_address(pid_t const pid) { char command[PATH_MAX] = {0}; int printed_characters = snprintf(command, PATH_MAX, "cat /proc/%d/maps | grep r.*`pgrep -n %d`", pid, pid); if (printed_characters < 0) { RAISE(T_EPRINTF, "snprintf failed"); return 0; } intptr_t const base_address = pread_word(command); if (error_occurred()) return 0; DEBUG("Process %d base address: %#lx", pid, base_address); return base_address; } extern intptr_t get_symbol_offset_in_binary(char const binary_path[const], char const symbol[const], bool const shared_object) { if (binary_path == NULL) { RAISE(T_ENULL_ARG, "binary_path"); return 0; } if (symbol == NULL) { RAISE(T_ENULL_ARG, "symbol"); return 0; } char command[PATH_MAX] = {0}; if (file_exists(binary_path) == false) { RAISE(T_EPATH_INVALID, "%s", binary_path); return 0; } int printed_characters = 0; if (shared_object) { printed_characters = snprintf(command, PATH_MAX, "nm -D %s | grep -w %s", binary_path, symbol); } else { printed_characters = snprintf(command, PATH_MAX, "nm %s | grep -w %s", binary_path, symbol); } if (printed_characters < 0) { RAISE(T_EPRINTF, "snprintf failed"); return 0; } intptr_t const offset = pread_word(command); if (error_occurred()) { RAISE(T_ESYMBOL_NOT_FOUND, "%s", symbol); return 0; } return offset; } extern intptr_t locate_libc_in(pid_t const pid) { char command[PATH_MAX] = {0}; int printed_characters = snprintf(command, PATH_MAX, "cat /proc/%d/maps | grep r.*%s", pid, LIBC_NAME); if (printed_characters < 0) { RAISE(T_EPRINTF, "snprintf failed"); return 0; } intptr_t const libc_address = pread_word(command); if (error_occurred()) return 0; return libc_address; } extern void get_libc_path(char const binary_path[const], char path[const]) { if (binary_path == NULL) { RAISE(T_ENULL_ARG, "binary_path"); return; } if (path == NULL) { RAISE(T_ENULL_ARG, "path"); return; } char command[PATH_MAX] = {0}; int printed_characters = snprintf(command, PATH_MAX, "ldd %s | grep -o -e \"/.*%s.* \"", binary_path, LIBC_NAME); if (printed_characters < 0) { RAISE(T_EPRINTF, "snprintf failed"); return; } pread_raw_line(command, path); if (error_occurred()) return; path[strlen(path) - 1] = '\0'; // remove empty character in the end } extern size_t get_function_code(pid_t const pid, intptr_t const start_address, uint8_t code_output[]) { if (code_output == NULL) { RAISE(T_ENULL_ARG, "code_output"); return 0; } uint8_t const retq_instruction = 0xC3; size_t i = 0; for (; i < MAX_CODE_LENGTH; i++) { uint8_t const byte = proc_read_byte(pid, start_address + (intptr_t) i); if (error_occurred()) return 0; code_output[i] = byte; if (byte == retq_instruction) { i++; break; } if ((i + 1) == MAX_CODE_LENGTH) { RAISE(T_EFUNC_TOO_BIG, "function at %#lx", start_address); return 0; } } DEBUG("Read %lu bytes from %d", i, pid); return i; } extern pid_t get_pid(char const process_name[const]) { if (process_name == NULL) { RAISE(T_ENULL_ARG, "process_name"); return -1; } char command[PATH_MAX] = {0}; int printed_characters = snprintf(command, PATH_MAX, "pgrep %s", process_name); if (printed_characters < 0) { RAISE(T_EPRINTF, "snprintf failed"); return -1; } pid_t pid = pread_int(command); if (error_occurred()) { RAISE(T_EPROC_NOT_RUNNING, "%s", process_name); return -1; } return pid; } static bool file_exists(char const * const filename){ struct stat file; int res = stat(filename, &file); if (res == -1) { return false; } return true; }
C
/* @ requires tab est un tableau avec deux dimensions, size est la taille d'une dimension @ assigns @ ensure afficher le tableau */ /* @ requires tab est un tableau avec deux dimensions, size est la taille d'une dimension @ assigns @ ensure afficher le tableau */ void affiche(int tab[100][100], int size){ int i,j,k; char c; for(i=0; i<size; i=i+1){ for(k=0; k<size; k=k+1){ printf(" ---"); } printf("\n"); printf("|"); for(j=0; j<size; j=j+1){ if(tab[i][j]=='+' || tab[i][j]=='x' || tab[i][j]=='*'){ c=tab[i][j]; printf(" %c |",c); } else printf(" %d |",tab[i][j]); } printf("\n"); } for(k=0; k<size; k=k+1){ printf(" ---"); } printf("\n"); return ; }
C
/** * @file AllMyVariables.h * @author Team Elizabeth * @date 5th october 2016 * @brief This defines all of our variables * / /*Required include files*/ #include <p18f4520.h> #include "MotorInputDefs.h" /*First argument is the value to be written to the output pins to determine direction*/ void SetDirection(unsigned char direction) { PORTD = direction; //Set the input direction } /*Configure the timer and period for the PWM, does not cover duty cycle*/ void ConfigPWM(void) { T2CON = 0x05; //enable timer PR2 = 0xff; //max out the period CCP1CON = 0x0c; //Set both CCP modules to PWM CCP2CON = 0x0c; } /*Set the speed, given a metric based on the controller*/ /*INPUT 1 is the 8bit value corresponding to a speed*/ /*INPUT 2 is a simple 0 or 1 bit deciding which motor is being changed*/ void SetSpeed(unsigned char speed, unsigned char motor) { //Check if correct selection if( (motor == LEFTMOTOR)||(motor == RIGHTMOTOR) ) { //Check which motor to set if ( motor == RIGHTMOTOR ) { CCPR1L = speed; //Duty cycle of PWM } else if ( motor == LEFTMOTOR ) { CCPR2L = speed; //Duty cycle of PWM CCPR1L = speed; //Duty cycle of PWM } } else { ; //Shouldn't do anything, would prefer a compiler error though } } //Input the raw data and motor selection. Will need to determine this via some code form void ConvertInput(unsigned char rawinput, unsigned char motorsel, unsigned char* realinput, unsigned char* wheelsel) { int tempdir; /*First step is to tell if the input is in our desired range*/ if(rawinput >= 128) { /*Subtract the value by 128 and just double it*/ rawinput = rawinput - 128; rawinput = rawinput*2; *realinput = rawinput; tempdir = ISFORWARD; } else if (rawinput < 127) { /*Take the raw input and minus 127 before doubling it*/ rawinput = (127 - rawinput); rawinput = rawinput*2; *realinput = rawinput; tempdir = ISBACKWARD; } /*Next step is to determine if the wheel is a left or a right*/ /*Change this condition later. LEFT WHEEL*/ if(motorsel == 0) { /*Then understand wheel rotation*/ if(tempdir == ISFORWARD) { *wheelsel = FORL; } else if (tempdir == ISBACKWARD) { *wheelsel = BACKL; } } /*RIGHT WHEEL*/ else if (motorsel == 1) { if(tempdir == ISFORWARD) { *wheelsel = FORR; } else if (tempdir == ISBACKWARD) { *wheelsel = BACKR; } } }
C
#include <stdio.h> #include <stdlib.h> int main() { int n; printf("Please enter a odd number.\n\n"); scanf("%d",&n); if(n%2==0){ printf("Please enter a valid odd number."); } else{ patternPrinter(n); } } void patternPrinter(int n){ for(int i = 1;i<(n+1)/2;i++){{ for(int j = 1;j<=n;j++){ int n1= ((n+1)/2)-i+1; int n2= ((n+1)/2); int n3= ((n+1)/2)+i-1; if(j==n1||j==n2||j==n3){ printf("*"); } else{ printf(" "); } } printf("\n\n"); } } for(int i=1;i<=n;i++){ printf("*"); } printf("\n\n"); for(int i=((n+1)/2)+1;i<=n;i++){ for(int j=1;j<=n;j++){ int n1= i-((n+1)/2)+1; int n2= ((n+1)/2); int n3= n-i+((n+1)/2); if(j==n1||j==n2||j==n3){ printf("*"); } else{ printf(" "); } } printf("\n\n"); } int rating; printf("Please provide any rating to my program!!!\n"); scanf("%d",&rating); }
C
#include <conio.h> #include <conio.h> void main() { int smallest, secondsmallest, i, n; int str[25]; printf("enter the array size"); scanf("%d", &n); for (i = 0; i < n; i++) { scanf("%d", &str[i]); } if (str[0] < str[1]) { smallest = str[0]; secondsmallest = str[1]; } else { smallest = str[1]; secondsmallest = str[0]; } for (i = 2; i < n; i++) { if (str[i] < smallest) { secondsmallest = smallest; smallest = str[i]; } else if (str[i] < secondsmallest) { secondsmallest = str[i]; } } printf(" \nSecond smallest element is %d", secondsmallest); getch(); }
C
#include "binary_trees.h" /** * binary_tree_rotate_right - rotate a root node right * @root: the current root node * Return: the pointer to the new root node */ btt *binary_tree_rotate_right(btt *root) { btt *r = root; btt *l; btt *mid; if (root == NULL || root->left == NULL) return (NULL); l = r->left; mid = r->left->right; l->right = r; l->parent = r->parent; r->left = mid; r->parent = l; if (mid != NULL) { mid->parent = r; } return (l); }