language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include "mochilaDoHeroi.h" float areaCirculo(float raioCirculo); void main(){ apresentacao(); printf("\nCalculadora de area de circulo"); float raioCirculo = lerFloat(); printf("\nA area do circulo e %f", areaCirculo(raioCirculo)); despedida(); } float areaCirculo(float raioCirculo){ /* Lucas Santiago - 11/04/19 Objetivo calcular area de circulo Entrada: raio do circulo Saida: area do circulo */ float pi = PI(); float resultado = pi * raioCirculo * raioCirculo; }
C
#include <stdio.h> #include<string.h> int main(void) { char flag[3]="0"; char pass[15]=""; int i=0; puts("CTFłBtOFLAG_ZŽ`Ŏ܂B"); while(i<3){ puts("pX[h͂Ă:"); scanf("%s",pass); if(strcmp(pass,"banana")==0){ strcpy(flag,"correct"); } if(strcmp(flag,"0")!=0){ puts("OC܂B"); puts("pX[hbananałB\nobt@I[o[t[̖łB\ntOFLAG_OVERFLOWłB"); system("pause"); break; }else{ puts("pX[h܂B"); if(i==1){ puts("qg:"); printf("ϐpass̃AhX:%p\n",pass); printf("ϐflag̃AhX:%p\n",flag); getchar(); } if(i==2){ puts("qg:"); puts("flag̃AhXpasšɂƂƂ́ApassflagɉeEEEH"); getchar(); getchar(); } } i++; } return 0; }
C
// nget.c #include "nget.h" void usage( char* argv0 ) { fprintf(stderr, "Usage: %s [-r|-l|-d|-c|-n] [-h HOST[:PORT]] RANK\n\ Options:\n\ -l lowest latency\n\ -r highest free RAM\n\ -d highest free disk\n\ -c highest free CPU\n\ -h HOST[:PORT] Access the daemon running on HOST[:PORT]\n\ -n Don't print a host; print the number of nodes.\n\ If this option is given, RANK is ignored\n\ RANK The rank the desired host must have (0 being the highest/best\n", argv0 ); exit(1); } int main( int argc, char** argv ) { int c; int opt = 0; uint64_t rank = 0; bool get_count = false; char* hostname = NULL; int portnum = -1; uint32_t props = 0; while((c = getopt(argc, argv, "h:lrdcn")) != -1) { switch( c ) { case 'h': { // is there a hostname given? hostname = strdup( optarg ); char* tmp = strchr(hostname, ':'); if( tmp != NULL ) { *tmp = 0; char* tmp2; portnum = strtol(tmp + 1, &tmp2, 10 ); if( tmp2 == tmp + 1 ) { free( hostname ); usage( argv[0] ); } } break; } case 'n': { if( !props ) get_count = true; else usage(argv[0]); break; } case 'r': if( !props ) props = HEARTBEAT_PROP_RAM; else usage(argv[0]); break; case 'l': if( !props ) props = HEARTBEAT_PROP_LATENCY; else usage(argv[0]); break; case 'c': if( !props ) props = HEARTBEAT_PROP_CPU; else usage(argv[0]); break; case 'd': { if( !props ) props = HEARTBEAT_PROP_DISK; else usage(argv[0]); break; } default: { usage( argv[0] ); } } } if( !get_count ) { // rank must be given if( optind >= argc ) { fprintf(stderr, "No rank given\n"); usage(argv[0]); } else { char* tmp; rank = (uint64_t)strtoll( argv[optind], &tmp, 10 ); if( tmp == argv[optind] ) { fprintf(stderr, "Could not parse rank\n"); usage(argv[0]); } } } else { if( props ) { fprintf(stderr, "Option %c is exclusive with -n\n", opt ); usage(argv[0]); } else { props = HEARTBEAT_PROP_COUNT; } } // no hostname given? then check the environment variables if( hostname == NULL ) { hostname = getenv( WISH_ORIGIN_ENV ); if( hostname == NULL ) { hostname = (char*)"localhost"; } else { char* portnum_str = getenv( WISH_PORTNUM_ENV ); if( portnum_str ) { char* tmp; long port_candidate = strtol(portnum_str, &tmp, 10 ); if( tmp != portnum_str ) { portnum = port_candidate; } } } } // read the config file struct wish_conf conf; int rc = wish_read_conf( WISH_DEFAULT_CONFIG, &conf ); if( rc != 0 ) { fprintf(stderr, "Config file %s could not be read\n", WISH_DEFAULT_CONFIG ); exit(1); } // override conf's portnum if( portnum > 0 ) { conf.portnum = portnum; } // connect to daemon struct wish_connection con; rc = wish_connect( NULL, &con, hostname, conf.portnum ); if( rc != 0 ) { // could not connect fprintf(stderr, "Could not connect to daemon on %s:%d\n", hostname, conf.portnum); exit(1); } struct wish_packet pkt; struct wish_nget_packet npkt; wish_init_nget_packet( NULL, &npkt, rank, props ); wish_pack_nget_packet( NULL, &pkt, &npkt ); rc = wish_write_packet( NULL, &con, &pkt ); wish_free_packet( &pkt ); if( rc != 0 ) { // could not write fprintf(stderr, "Could not write to daemon on %s:%d\n", hostname, conf.portnum ); exit(1); } // get back the hostname rc = wish_read_packet( NULL, &con, &pkt ); if( rc != 0 ) { // could not read fprintf(stderr, "Could not read from daemon on %s:%d\n", hostname, conf.portnum ); exit(1); } // this should be a string packet if( pkt.hdr.type != PACKET_TYPE_STRING ) { // nope fprintf(stderr, "Received invalid packet from daemon, type = %d\n", pkt.hdr.type ); exit(1); } struct wish_string_packet spkt; wish_unpack_string_packet( NULL, &pkt, &spkt ); printf("%s\n", spkt.str); wish_free_packet( &pkt ); wish_disconnect( NULL, &con ); exit(0); }
C
#include <stdio.h> #include <stdlib.h> // You will write a program that keeps track of exam results. // First, your program should ask the user how many classes took the exam. Let's say this number is N. // Then you need to ask how many students took the exam in the first class. Let's say this number is M. // You need to ask for the name of the class, the the exam results in percentage M times and store them. // The number of students might be different for each class. // You need to repeat this N times. // Make sure you have a separate function that reads the data and returns it. // Once you have the data write functions for the following questions: // Which class has the biggest difference between the worst and best exam and how much is the difference? // Which class has the best exam? // What is the average of all the exams? typedef struct { char name[12]; int cnt_students; float* res_exam; } class_t; void print_class_data(const class_t* class_data, int cnt_classes) { for (int i = 0; i < cnt_classes; ++i) { printf("%d. class:\n", i); printf(" name: %s\n", (class_data + i)->name); printf(" students: %d\n", (class_data + i)->cnt_students); printf(" exam results: \n "); for (int j = 0; j < (class_data + i)->cnt_students; ++j) { printf("%.2f", *((class_data + i)->res_exam + j)); if (j != (class_data + i)->cnt_students - 1) printf(", "); } printf("\n\n"); } } void print_biggest_diff(class_t* class_data, int cnt_classes) { int index_max_diff = 0; float max_diff = 0; for (int i = 0; i < cnt_classes; ++i) { float class_max = 0.0f; for (int j = 0; j < (class_data + i)->cnt_students; ++j) { if (*((class_data + i)->res_exam + j) > class_max) { class_max = *((class_data + i)->res_exam + j); } } float class_min = class_max; for (int j = 0; j < (class_data + i)->cnt_students; ++j) { if (*((class_data + i)->res_exam + j) < class_min) { class_min = *((class_data + i)->res_exam + j); } } float class_diff = class_max - class_min; if (class_diff > max_diff) { max_diff = class_diff; index_max_diff = i; } } printf("The class with the biggest difference in its grades is: %s\n", (class_data + index_max_diff)->name); printf("The biggest difference among the grades is: %.2f\n", max_diff); } void print_class_best_exam(class_t* class_data, int cnt_classes) { int index_class = 0; float best_grade = 0.0f; for (int i = 0; i < cnt_classes; ++i) { for (int j = 0; j < (class_data + i)->cnt_students; ++j) { if (*((class_data + i)->res_exam + j) > best_grade) { best_grade = *((class_data + i)->res_exam + j); index_class = i; } } } printf("The class that has the student with the best result is: %s\n", (class_data + index_class)->name); } float average(class_t* class_data, int cnt_classes) { float sum_grades = 0; int counter = 0; for (int i = 0; i < cnt_classes; ++i) { for (int j = 0; j < (class_data + i)->cnt_students; ++j) { sum_grades += *((class_data + i)->res_exam + j); counter++; } } if (!counter) return -1.0f; return sum_grades / (float)counter; } int main() { int cnt_classes; printf("How many classes took the exam?\n"); scanf("%d", &cnt_classes); class_t* class_data = (class_t*)malloc(cnt_classes * sizeof(class_t)); for (int i = 0; i < cnt_classes; ++i) { printf("What is the name of the %d. class?\n", i); scanf("%s", (class_data + i)->name); printf("How many students took the exam in the %d. class?\n", i); scanf("%d", &((class_data + i)->cnt_students)); (class_data + i)->res_exam = (float*)malloc((class_data + i)->cnt_students * sizeof(int)); for (int j = 0; j < (class_data + i)->cnt_students; ++j) { printf("What are the results of the %d. student?\n", j); scanf("%f", ((class_data + i)->res_exam) + j); } } print_class_data(class_data, cnt_classes); print_biggest_diff(class_data, cnt_classes); print_class_best_exam(class_data, cnt_classes); printf("Average results: %.2f\n", average(class_data, cnt_classes)); //Free dynamically allocated memory for (int i = 0; i < cnt_classes; ++i) { free((class_data + i)->res_exam); } free(class_data); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int is_prime(int number) { int i=3; float max=sqrt(number); for(;i<=max;i+=2) { if(number%i==0) return 0; } return 1; } int next_prime_candidate(int x) { int closest_tenth=x-(x%10); int zero[]={0,6,0,0,0,0,0,4,0,0}; int one[]= {0,2,0,4,0,0,0,2,0,4}; int two[]= {0,0,0,6,0,0,0,0,0,2}; int offset_to_use=closest_tenth%3; switch(offset_to_use) { case 0:return zero[x%10]+x; case 1:return one[x%10]+x; case 2:return two[x%10]+x; } } int range_of(int start, int end, int **result) { int i; int total=0; if(start%2==0 && is_prime(start)) { start++; total++; } start=next_prime_candidate(start); while(start<end) { start=next_prime_candidate(start); if(is_prime(start)) total++; } return total; } int main(int argc, char const *argv[]) { int start,end; sscanf(argv[1],"%d",&start); sscanf(argv[2],"%d",&end); printf("%d\n", range_of(start, end, NULL)); // if(is_prime(number)) // printf("%d is prime\n", number); // else // printf("%d is not prime\n", number); return 0; }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void) { int fd1, fd2, sz1,sz2; char *c1 = (char *) calloc (100, sizeof(char)); char *c2 = (char *) calloc (100, sizeof(char)); fd1 = open("content1.txt", O_RDWR | O_APPEND); fd2 = open("content2.txt", O_RDWR); if(fd1 < 0) { perror("Error in opening content1.txt"); exit(1); } if(fd2 < 0) { perror("Error in opening content2.txt"); exit(1); } sz1 = read(fd1, c1, 17); sz2 = read(fd2, c2, 15); printf("fd1 = %d, fd2 = %d \n", fd1, fd2); printf("Called read which returned %d \n", sz1); printf("Content read: %s \n", c2); write(STDOUT_FILENO, c1, sz1); write(STDOUT_FILENO, c2, sz2); close(fd1); close(fd2); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* checker.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dmelnyk <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/11 11:12:32 by dmelnyk #+# #+# */ /* Updated: 2018/03/24 17:57:59 by dmelnyk ### ########.fr */ /* */ /* ************************************************************************** */ #include "checker.h" static int check(t_stack stacks) { int i; int max; if (stacks.size_b == 0) { max = stacks.a[0]; i = 1; while (i < stacks.size_a) { if (max < stacks.a[i]) max = stacks.a[i]; else return (0); i++; } return (1); } return (0); } static void read_and_execute(t_stack *stacks, t_command **command_list) { char *command; while (get_next_line(0, &command) > 0) { add_command(command_list, command); ft_strdel(&command); } check_command(*command_list, stacks->flags); *command_list = (*command_list)->next; while (*command_list) { execute(stacks, (*command_list)->command); (*command_list) = (*command_list)->next; } if (check(*stacks)) ft_putstr("OK\n"); else ft_putstr("KO\n"); } int main(int ac, char **av) { t_stack stacks; int begin; t_command *command_list; t_command *head; if (ac == 1) exit(0); begin = get_flags(ac, av, &stacks); if (ac - begin == 0) usage(); check_input(av, begin, stacks.flags); stacks.b = (int*)malloc(sizeof(int) * ac - begin); stacks.a = get_stack(ac - begin, av, begin, stacks.flags); stacks.size_a = ac - begin; stacks.size_b = 0; check_dublicates(stacks); command_list = (t_command*)malloc(sizeof(t_command)); command_list->command = NULL; command_list->next = NULL; head = command_list; read_and_execute(&stacks, &command_list); command_list = head; return (0); }
C
#include "graphs.h" #define WHITE 0 #define GRAY 1 #define BLACK 2 int color[MAX]; void GraphgraphL (GraphL g, int V) { FILE *f = fopen("graph.dot", "w"); Edge p; fprintf (f, "digraph G {\n"); fprintf (f, "\tlabelloc=\"t\";\n"); fprintf (f, "\tlabel=\"Graph\";\n"); for (int u=0; u<V; ++u) { fprintf (f, "\t%d [label=\"%d\"];\n", u, u); for (p=g[u]; p; p=p->next) fprintf (f, "\t%d->%d [label=\"%d\"];\n", u, p->dest, p->weight); } fprintf (f, "}"); fclose (f); system ("dot -Kfdp -Tpng -Goverlap=false -Gsplines=true graph.dot > graph.png"); } void GraphgraphM (GraphM g, int V) { FILE *f = fopen("graph.dot", "w"); fprintf (f, "digraph G {\n"); fprintf (f, "\tlabelloc=\"t\";\n"); fprintf (f, "\tlabel=\"Graph\";\n"); for (int u=0; u<V; ++u) { fprintf (f, "\t%d [label=\"%d\"];\n", u, u); for (int v=0; v<V; ++v) if (g[u][v] != NE) fprintf (f, "\t%d->%d [label=\"%d\"];\n", u, v, g[u][v]); } fprintf (f, "}"); fclose (f); system ("dot -Kfdp -Tpng -Goverlap=false -Gsplines=true graph.dot > graph.png"); } void graphMtoL (GraphM gm, GraphL gl, int V) { for (int i=0; i<V; ++i) { gl[i] = NULL; for (int j=0; j<V; ++j) if (gm[i][j] != NE) { Edge aux = malloc (sizeof (struct edge)); aux->dest = j; aux->weight = gm[i][j]; aux->next = gl[i]; gl[i] = aux; } } } void graphLtoM (GraphL gl, GraphM gm, int V) { int i, j; Edge aux; for (i=0; i<V; ++i) { j = V-1; aux = gl[i]; while (aux != NULL) { if (aux->dest == j) { gm[i][j] = aux->weight; aux = aux->next; } j--; } } } void ShowGraphM (GraphM g, int V) { printf ("GraphM:\n"); for (int i=0; i<V; ++i) { for (int j=0; j<V; ++j) printf ("%d ", g[i][j]); printf ("\n"); } printf ("\n"); } void ShowGraphL (GraphL g, int V) { printf ("GraphL:\n"); Edge aux; for (int i=0; i<V; ++i) { printf ("V %d: ", i); for (aux=g[i]; aux && aux->next; aux=aux->next) printf ("| V %d , W %d | -> ", aux->dest, aux->weight); if (aux != NULL) printf ("| V %d , W %d |", aux->dest, aux->weight); printf ("\n"); } printf ("\n"); } void dfs_visit (GraphL g, int s) { Edge p; color[s] = GRAY; for (p=g[s]; p; p=p->next) if (color[p->dest] == WHITE) dfs_visit (g, p->dest); color[s] = BLACK; } void dfs (GraphL g, int V) { int u; printf ("Depth Traversal:\n"); for (u=0; u<V; ++u) color[u] = WHITE; for (u=0; u<V; ++u) if (color[u] == WHITE) dfs_visit (g, u); for (u=0; u<V; ++u) printf ("V: %d | C: %d\n", u, color[u]); printf ("\n"); } void bfs_visit (GraphL g, int s) { Edge p; int u, queue[MAX], first=0, last=0; color[s] = GRAY; queue[last++] = s; while (first < last) { u = queue[first++]; for (p=g[u]; p; p=p->next) if (color[p->dest] == WHITE) { color[p->dest] = GRAY; queue[last++] = p->dest; } color[u] = BLACK; } } void bfs (GraphL g, int V) { int u; printf ("Breadth Traversal:\n"); for (u=0; u<V; ++u) color[u] = WHITE; for (u=0; u<V; ++u) if (color[u] == WHITE) bfs_visit (g, u); for (u=0; u<V; ++u) printf ("V: %d | C: %d\n", u, color[u]); printf ("\n"); } int getEdgeFringe (int f[], int cost[], int size) { int r, index=0; for (int i=0; i<size; ++i) if (cost[f[i]] < cost[f[index]]) index = i; r = f[index]; f[index] = f[size-1]; return r; } int PrimMST (GraphL g, int V, int s, int mst[V]) { int r=0, u, cost[V], fringe[V], fringesize=0; Edge p; for (u=0; u<V; ++u) color[u] = WHITE; cost[s] = 0; color[s] = GRAY; fringe[fringesize++] = s; while (fringesize > 0) { u = getEdgeFringe (fringe, cost, fringesize); fringesize--; r += cost[u]; color[u] = BLACK; for (p=g[u]; p; p=p->next) if (color[p->dest]==WHITE || (color[p->dest]==GRAY && p->weight<cost[p->dest])) { mst[p->dest] = u; cost[p->dest] = p->weight; if (color[p->dest]==WHITE) fringe[fringesize++] = p->dest; } } return r; } int minimumDist (int color[], int dist[], int V) { int r = -1, dmin = INF; for (int i=0; i<V; ++i) if (color[i] == WHITE && dist[i]<=dmin) { dmin = dist[i]; r = i; } return r; } void singleDjikstra (GraphL g, int V, int u, int dist[V], int parent[V]) { Edge p; int v, visited, color[V]; // Inicializar todos os vértices como não visitados // e a sua distância mínima como infinita for (int i=0; i<V; ++i) { color[i] = WHITE; dist[i] = INF; parent[i] = -2; } // Distância nula para o vértica onde se começa dist[u] = 0; parent[u] = -1; visited = 0; while (visited < V) { v = minimumDist (color, dist, V); color[v] = BLACK; for (p=g[v]; p; p=p->next) if (dist[v] + p->weight < dist[p->dest]) { parent[p->dest] = v; dist[p->dest] = dist[v] + p->weight; } visited++; } } void Warshall (GraphM g, GraphM r, int V) { int i, j, k; for (i=0; i<V; ++i) for (j=0; j<V; ++j) r[i][j] = g[i][j]; for (k=0; k<V; ++k) for (i=0; i<V; ++i) for (j=0; j<V; ++j) if (r[i][k] && r[k][j]) r[i][j] = 1; } int min (int a, int b) { int r; if (a < b) r = a; else r = b; return r; } void dynDistances (GraphM g, GraphM r, int V) { int i, j, k; for (i=0; i<V; ++i) for (j=0; j<V; ++j) r[i][j] = g[i][j]; for (k=0; k<V; ++k) for (i=0; i<V; ++i) for (j=0; j<V; ++j) if (r[i][j] == 0) r[i][j] = r[i][k]+r[k][j]; else r[i][j] = min (r[i][j], r[i][k]+r[k][j]); }
C
/*#include <stdio.h> #include <stdlib.h> int main() { printf("HELLO GAMES \n THIS TIME , I CAME WITH A TIC TOE GAME\n"); int row, col; int arr[3][3]; for (row=0 ; row <3 ;row++) { for (col=0 ;col<3 ; col++) { arr[row][col]==0; } } print(arr); int x,y; { again: printf("enter the x cordinate :"); scanf("%d",&x); printf("enter the y cordinate :"); scanf("%d",&y); if (x>=0 && x<10 && y>=0 && y<10) arr[x][y]=2; //elements entered by user has value 2 else { printf("the coordinate are out of range\n"); goto again; } return 0; } int print(int arr[][3]) { printf("HELLO GAMERS \n THIS TIME , I CAME WITH A TIC TOE GAME\n"); int row,col; for (row=0 ; row <3 ;row++) { printf("%d",row); for (col=0 ;col<3 ; col++) { if (row==0) { printf(" %d |",col); } } printf("\n"); } return 0; } */ #include <stdio.h> #include <stdlib.h> int main() { int arr[3][3]; int a,b,x,y,d,e,user=10,pc=9; for(a=0 ; a<3 ; a++) { for (b=0 ;b<3 ; b++) arr[a][b]=0; //all elements of array has 0 value } } print(arr); for (e=0 ; e<9 ; e++) { loopagain: printf("USER 1\nenter the x cordinate :"); scanf("%d",&x); printf("enter the y cordinate :"); scanf("%d",&y); if (x>0 && x<4 && y>0 && y<4) { arr[x-1][y-1]=1; } else { printf("the coordinate are out of range\n"); goto loopagain; } print(arr); for(a=0 ; a<3 ; a++) { if (arr[a][0]==arr[a][1] && arr[a][0]==arr[a][2]) { if (arr[a][0]==1) { printf(" USER 1 WON THE BATTLE\n"); user=1; } else if (arr[a][0]==2) { printf(" USER 2 WON THE BATTLE\n"); pc=2; } } else if (arr[0][a]==arr[1][a] && arr[0][a]==arr[2][a]) { if (arr[0][a]==1) { printf(" USER 1 WON THE BATTLE\n"); user=1; } else if (arr[0][a]==2) { printf(" USER 2 WON THE BATTLE\n"); pc=2; } } else if (arr[0][0]==arr[1][1] && arr[0][0]==arr[2][2]) { if (arr[0][0]==1) { printf(" USER 1 WON THE BATTLE\n"); user=1; } else if (arr[0][0]==2) { printf(" USER 2 WON THE BATTLE\n"); pc=2; } } else if (arr[0][3]==arr[1][2] && arr[0][3]==arr[3][0]) { if (arr[3][0]==1) { printf(" USER 1 WON THE BATTLE\n"); user=1; } else if (arr[3][0]==2) { printf(" USER 2 WON THE BATTLE\n"); pc=2; } } } loopagain1: printf("USER 2\nenter the x cordinate :"); scanf("%d",&x); printf("enter the y cordinate :"); scanf("%d",&y); if (x>0 && x<4 && y>0 && y<4) { arr[x-1][y-1]=2; } else { printf("the coordinate are out of range\n"); goto loopagain1; } print(arr); /* int g,h; g=(rand()%3)+1; h=(rand()%3)+1; arr[g][h]=2; print(arr);*/ for(a=0 ; a<3 ; a++) { if (arr[a][0]==arr[a][1] && arr[a][0]==arr[a][2]) { if (arr[a][0]==1) { printf("you won the battle"); user=1; } else if (arr[a][0]==2) { printf("PC,WON THE GAME"); pc=2; } } else if (arr[0][a]==arr[1][a] && arr[0][a]==arr[2][a]) { if (arr[0][a]==1) { printf("you won the battle"); user=1; } else if (arr[0][a]==2) { printf("PC,WON THE GAME"); pc=2; } } else if (arr[0][0]==arr[1][1] && arr[0][0]==arr[2][2]) { if (arr[0][0]==1) { printf("you won the battle"); user=1; } else if (arr[0][0]==2) { printf("PC,WON THE GAME"); pc=2; } } else if (arr[0][3]==arr[1][2] && arr[0][3]==arr[3][0]) { if (arr[3][0]==1) { printf("you won the battle"); user=1; } else if (arr[3][0]==2) { printf("PC,WON THE GAME"); pc=2; } } } if (user==1) break; else if (pc==2) break; }printf("GAME OVER"); return 0;} int print(int arr[][3]) { int a,b; printf("\n\n\nHELLO GAMERS , WELCOME TO THE TIC TOE GAME\n"); for(a=0 ; a<4 ; a++) { printf("%d",a); for (b=1 ;b<4 ; b++) { if (a==0 && b>0) printf(" %d |",b); else if (arr[a-1][b-1]==0) printf(" |"); else if (arr[a-1][b-1]==1) printf(" * |"); else if (arr[a-1][b-1]==2) printf(" - |"); } printf("\n",a); } return 0; }
C
// circumference of a circle #include<stdio.h> #include<stdlib.h> int main(int argc, char const *argv[]) { float radius,c; scanf("%f",&radius); c=3.14*radius*radius; printf("%0.2f",c); return 0; }
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "httpClient.h" #define HTTP_RCVBUF_SIZE_MAX (3*1024*1024) #define HTTP_SERVER_IP "127.0.0.1" #define HTTP_SERVER_PORT 6666 #define HTTP_SERVER_PATH "/" #define POSTDATA "{\"username\":\"gailun\",\"password\":\"123123\",\"driver\":\"yes\"}" char gHttpRcvHeadBuffer[16*1024]={0}; char gHttpRcvBodyBuffer[HTTP_RCVBUF_SIZE_MAX]={0}; char gHttpSendBuffer[HTTP_RCVBUF_SIZE_MAX]={0}; int main() { int nRet = -1; long lTmp = -1; stHttpClientInfo stHttpClient; memcpy(stHttpClient.chClientIP,HTTP_SERVER_IP,strlen(HTTP_SERVER_IP)); memcpy(stHttpClient.chClientPath,HTTP_SERVER_PATH,strlen(HTTP_SERVER_PATH)); stHttpClient.nClientPort = HTTP_SERVER_PORT; stHttpClient.stHttpUserHead.nOperation = HTTP_POST_ONE_SHOT_PIC_MEM; stHttpClient.stHttpUserHead.ucFlag = HTTP_HEAD; stHttpClient.stHttpUserHead.nRcvBufLen = sizeof(gHttpRcvHeadBuffer); stHttpClient.stHttpUserHead.pRcvBuffer = gHttpRcvHeadBuffer; stHttpClient.stHttpUserHead.pSendBuffer = NULL; stHttpClient.stHttpUserHead.nRcvSize = 0; stHttpClient.stHttpUserBody.nOperation = HTTP_POST_ONE_SHOT_PIC_MEM; stHttpClient.stHttpUserBody.ucFlag = HTTP_BODY; stHttpClient.stHttpUserBody.nRcvBufLen = sizeof(gHttpRcvBodyBuffer); stHttpClient.stHttpUserBody.pRcvBuffer = gHttpRcvBodyBuffer; stHttpClient.stHttpUserBody.pSendBuffer = gHttpSendBuffer; stHttpClient.stHttpUserBody.nRcvSize = 0; stHttpClient.stHttpUserBody.nSedSize = strlen(POSTDATA); memcpy(stHttpClient.stHttpUserBody.pSendBuffer,POSTDATA,strlen(POSTDATA)); sprintf(stHttpClient.chUrl,"%s:%d/%s",stHttpClient.chClientIP,stHttpClient.nClientPort,stHttpClient.chClientPath); printf("->%s\n",stHttpClient.chUrl); /*ϴͼƬ*/ nRet = httpClient_httpPost(&stHttpClient,&lTmp); if(nRet < 0) { printf("[picUpload] ====> %s func http_Post failed,at (%d) lines\n",__FUNCTION__,__LINE__); return -1; } printf("\nRcv Head:\n%s\n",stHttpClient.stHttpUserHead.pRcvBuffer); printf("\nRcv Body:\n%s\n",stHttpClient.stHttpUserBody.pRcvBuffer); return 0; }
C
#include<stdio.h> int rotateArray(int arr[],int,int); void display(int arr[],int); void leftRotatebyOne(int arr[], int n); int main(){ int a,b,size; scanf("%d ",&a); int arr[5]; size=sizeof(arr)/sizeof(arr[0]); int c=0; while(c<size){ scanf("%d",&arr[c]); c+=1; } rotateArray(arr,size,a); } int rotateArray(int arr[],int size,int a){ int i; for(i=0;i<a;i++){ leftRotatebyOne(arr,size); display(arr,size); } return 0; } void leftRotatebyOne(int arr[], int n) { int temp = arr[n-1], i; for (i = n-1; i>0; i--) arr[i] = arr[i-1]; arr[0] = temp; } void display(int arr[],int size){ int i; for(i=0;i<size;i++){ printf("%d",arr[i]); } }
C
#include <stdio.h> int main() { float score; char grade; printf("score="); scanf("%f", &score); if (score>=90) grade = 'A'; else if (score>=80) grade = 'B'; else if (score>=70) grade = 'C'; else if (score>=60) grade = 'D'; else grade = 'F'; printf("%.2f %c", score, grade); return 0; }
C
// 範例:用來減少判斷的次數. #include <stdio.h> #define N 10 int add(int a, int b) { return a + b; } int sub(int a, int b) { return a - b; } int mul(int a, int b) { return a * b; } int div(int a, int b) { return a / b; } int main(void) { int (*oper)(int a, int b); char key; int a[N], b[N], c[N]; int i; for (i = 0; i < N; i++) { a[i] = i + 1; b[i] = i + 1; } printf("Press +,-,*,/ for add, sub, mul, div\n"); key = getchar(); switch (key) { case '+': oper = add; break; case '-': oper = sub; break; case '*': oper = mul; break; case '/': oper = div; break; } for (i = 0; i < N; i++) { c[i] = oper(a[i], b[i]); printf("%d ", c[i]); } printf("\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <dirent.h> // function prototypes void parse_line(char *command); char **tokenize(char *line, int *num_tokens); // static variables static char *line; static char *name; static int last_status; // main function int main(void) { name = (char*)malloc(256*sizeof(char)); strcpy(name, "mysh"); last_status = 0; line = (char*)malloc(256*sizeof(char)); // main loop used for interactive mode if(isatty(0)) { while(1) { printf("%s> ", name); if(!fgets(line, 256, stdin)){ exit(0); } parse_line(line); } } else { while(fgets(line, 256, stdin)) { parse_line(line); } } exit(0); } void parse_line(char *line) { int *num_tokens = (int*)malloc(sizeof(int)); *num_tokens = 0; char** tokens = tokenize(line, num_tokens); if(tokens[0][0] == '#') { return; } if(!strcmp(tokens[0], "name")) { if(*num_tokens == 1) { printf("%s\n", name); } else { name = tokens[1]; last_status = 0; } } if(!strcmp(tokens[0], "exit")) { int status = atoi(tokens[1]); exit(status); } if(!strcmp(tokens[0], "print")) { for(int i = 1; i < *num_tokens; i++) { printf((i == *num_tokens - 1) ? "%s" : "%s ", tokens[i]); } last_status = 0; } if(!strcmp(tokens[0], "echo")) { for(int i = 1; i < *num_tokens; i++) { printf("%s ", tokens[i]); } printf("\n"); last_status = 0; } if(!strcmp(tokens[0], "pid")) { pid_t pid = getpid(); printf("%d\n", pid); last_status = 0; } if(!strcmp(tokens[0], "ppid")) { pid_t ppid = getppid(); printf("%d\n", ppid); last_status = 0; } if(!strcmp(tokens[0], "help")) { printf("TODO\n"); last_status = 0; } if(!strcmp(tokens[0], "status")) { printf("%s\n", strerror(last_status)); last_status = 0; } if(!strcmp(tokens[0], "dirchange")) { char *dir_path; dir_path = (*num_tokens == 1) ? "/" : tokens[1]; if((last_status = chdir(dir_path)) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "dirwhere")) { char *cwd = (char*)malloc(256*sizeof(char)); if((getcwd(cwd, 256)) < 0) { last_status = errno; return; } else { last_status = 0; printf("%s\n", cwd); } } if(!strcmp(tokens[0], "dirmake")) { if((last_status = mkdir(tokens[1], 0700)) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "dirremove")) { if((last_status = rmdir(tokens[1])) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "dirlist")) { struct dirent *entry; DIR *dir = opendir((*num_tokens == 1) ? "." : tokens[1]); if(dir == NULL) { last_status = errno; return; } else { last_status = 0; } while((entry = readdir(dir)) != NULL) { printf("%s ", entry->d_name); } printf("\n"); last_status = 0; } // Make hard link to destination. if(!strcmp(tokens[0], "linkhard")) { if((last_status = link(tokens[1], tokens[2])) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "linksoft")) { if((last_status = symlink(tokens[1], tokens[2])) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "linkread")) { char *buff = malloc(256*sizeof(char*)); if(readlink(tokens[1], buff, 256) < 0) { last_status = errno; return; } else { last_status = 0; } printf("%s\n", buff); } if(!strcmp(tokens[0], "linklist")) { struct dirent *entry; DIR *dir = opendir("."); if(dir == NULL) { last_status = errno; return; } else { last_status = 0; } struct stat f; int ref_inode; stat(tokens[1], &f); ref_inode = f.st_ino; while((entry = readdir(dir)) != NULL) { lstat(entry->d_name, &f); if(f.st_ino == ref_inode) { printf("%s ", entry->d_name); } } printf("\n"); last_status = 0; } if(!strcmp(tokens[0], "unlink")) { if((last_status = unlink(tokens[1])) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "rename")) { if((last_status = rename(tokens[1], tokens[2])) < 0) { last_status = errno; } } if(!strcmp(tokens[0], "cpcat")) { } } char **tokenize(char *line, int *num_tokens) { char *buff = (char*)malloc(256*sizeof(char)); char **res = (char**)malloc(256*sizeof(char*)); int buff_index = 0; int res_index = 0; for(int i = 0; i < strlen(line) - 1; i++) { if(isspace(line[i])) { buff[buff_index] = '\0'; res[res_index] = malloc((strlen(buff) + 1)*sizeof(char*)); strcpy(res[res_index], buff); res_index++; buff_index = 0; (*num_tokens)++; while(line[i] == ' ') { i++; } i--; } else if(line[i] == '"') { i++; while(line[i] != '"') { buff[buff_index] = line[i]; buff_index++; i++; } } else { buff[buff_index] = line[i]; buff_index++; } } buff[buff_index] = '\0'; res[res_index] = malloc((strlen(buff) + 1)*sizeof(char*)); strcpy(res[res_index], buff); res_index++; (*num_tokens)++; return res; }
C
#include <stdio.h> #include <sys/types.h> #include <unistd.h> int main() { // forks to main process => subprocess1 fork(); // forks main process => subprocess2, subprocess1 => subprocess3 fork(); // main and subprocess1-3, executes below. printf("Called fork() system call\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { float loan, rate, day, sum; printf("Enter loan principal (-1 to end): "); scanf_s("%f", &loan); while (loan != -1) { printf("Enter interest rate: "); scanf_s("%f", &rate); printf("Enter term of the loan in days: "); scanf_s("%f", &day); sum = loan * rate / 365 * day; printf("The interest charge is $%.2f", sum); printf("\n\n"); printf("Enter loan principal (-1 to end): "); scanf_s("%f", &loan); } system("pause"); return 0; }
C
#include <omp.h> #include <stdio.h> int main(int argc, char const *argv[]){ int iam = 0, np = 1, i = 0; //MODIFICACIÓN HECHA //iam debe de ser privada porque si no el th_id se repetiría, np también #pragma omp parallel private(i, iam, np) { #if defined (_OPENMP) np = omp_get_num_threads(); iam = omp_get_thread_num(); #endif printf("Hello from thread %d out of %d\n", iam,np); #pragma omp for for(i = 0; i < (np*2) ; i++){ printf("Thread %d, contador %d \n", iam, i); } } return 0; } //las variables del pragma son privadas porque sólo dentro de ese hilo existirán esas variables //para que las variables no se confundan
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_get_unsign_ptr_bin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abodnar <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/17 12:00:50 by abodnar #+# #+# */ /* Updated: 2018/01/17 12:01:03 by abodnar ### ########.fr */ /* */ /* ************************************************************************** */ #include "libftprintf.h" char *ft_get_binary(va_list ap) { char *temp; temp = ft_itoa_base_unsign(va_arg(ap, uintmax_t), 2); return (temp); } char *ft_get_unsign(t_params *params, va_list ap) { char *temp; if (params->len >= 32) temp = ft_itoa_base_unsign(va_arg(ap, uintmax_t), 10); else if (params->len >= 16) temp = ft_itoa_base_unsign(va_arg(ap, size_t), 10); else if (params->len >= 8) temp = ft_itoa_base_unsign(va_arg(ap, unsigned long long int), 10); else if (params->len >= 4) temp = ft_itoa_base_unsign(va_arg(ap, unsigned long int), 10); else if (params->len >= 2) temp = ft_itoa_base_unsign((unsigned short)va_arg(ap, int), 10); else if (params->len >= 1) temp = ft_itoa_base_unsign((unsigned char)va_arg(ap, int), 10); else temp = ft_itoa_base_unsign(va_arg(ap, unsigned int), 10); return (temp); } char *ft_get_longunsign(t_params *params, va_list ap) { char *temp; if (params->len >= 32) temp = ft_itoa_base_unsign(va_arg(ap, uintmax_t), 10); else if (params->len >= 16) temp = ft_itoa_base_unsign(va_arg(ap, size_t), 10); else if (params->len >= 8) temp = ft_itoa_base_unsign(va_arg(ap, unsigned long long int), 10); else temp = ft_itoa_base_unsign(va_arg(ap, unsigned long int), 10); return (temp); } char *ft_get_ptr(t_params *params, va_list ap) { char *temp; char *fordel; temp = ft_itoa_base_unsign(va_arg(ap, unsigned long int), 16); ft_apply_precision(&temp, params); if (!ft_strcmp(temp, "0") && params->dot && params->prec == 0) *temp = '\0'; fordel = temp; temp = ft_strjoin("0x", temp); ft_strdel(&fordel); return (temp); } char *ft_get_char_str_perc(char **temp, char conv, va_list ap) { if (conv == 'c') { *temp = ft_strnew(1); **temp = va_arg(ap, int); if (**temp == 0) **temp = -100; } if (conv == 's') { *temp = ft_strdup(va_arg(ap, char*)); if (!*temp) *temp = ft_strdup("(null)"); } if (conv == '%') { *temp = ft_strnew(1); **temp = '%'; } return (*temp); }
C
#include "accounts.h" #define PIPE_READ 0 #define PIPE_WRITE 1 static pthread_mutex_t accountMutexes[MAX_BANK_ACCOUNTS]; static bank_account_t accounts[MAX_BANK_ACCOUNTS]; static bool usedAccounts[MAX_BANK_ACCOUNTS]; bank_account_t* getAccount(uint32_t account_id) { if(!usedAccounts[account_id]) return NULL; else return &accounts[account_id]; } void clearAccounts() { for (int i = 0; i < MAX_BANK_ACCOUNTS; i++) { usedAccounts[i] = false; pthread_mutex_init (&accountMutexes[i], NULL); } } void destroyAccounts() { for (int i = 0; i < MAX_BANK_ACCOUNTS; i++) { usedAccounts[i] = false; pthread_mutex_destroy(&accountMutexes[i]); } } void lockAccount(uint32_t id, int threadID) { logSyncMech(getSLogFD(), threadID, SYNC_OP_MUTEX_LOCK, SYNC_ROLE_ACCOUNT, id); pthread_mutex_lock(&accountMutexes[id]); } void unlockAccount(uint32_t id, int threadID) { pthread_mutex_unlock(&accountMutexes[id]); logSyncMech(getSLogFD(), threadID, SYNC_OP_MUTEX_UNLOCK, SYNC_ROLE_ACCOUNT, id); } void createAccount(uint32_t id, uint32_t balance, char* password, int threadNum) { char* salt = generateSalt(); char* hash = generateHash(password, salt); if (salt == NULL || hash == NULL) return; bank_account_t account; account.account_id = id; account.balance = balance; strcpy(account.salt, salt); strcpy(account.hash, hash); free(salt); free(hash); accounts[id] = account; usedAccounts[id] = true; logAccountCreation(getSLogFD(), threadNum, &account); } char* generateSalt() { char* salt = malloc(SALT_LEN + 1); for(int i = 0; i < SALT_LEN; i++) { sprintf(salt + i, "%x", rand() % 16); } return salt; } char* generateHash(char* password, char* salt) { char* hash = malloc(HASH_LEN + 1); char* concatd = malloc(1000); sprintf(concatd, "%s%s", password, salt); int fd1[2], fd2[2]; pipe(fd1); pipe(fd2); if(fork() == 0) { if (close(fd1[PIPE_READ]) == -1) { perror("Error closing coprocess FD1[READ]"); exit(1); } if (close(fd2[PIPE_WRITE]) == -1) { perror("Error closing coprocess FD2[WRITE]"); exit(1); } if (dup2(fd1[PIPE_WRITE], STDOUT_FILENO) == -1) { perror("Error invoking dup2 to STDOUT"); exit(1); } if (dup2(fd2[PIPE_READ], STDIN_FILENO) == -1) { perror("Error invoking dup2 to STDIN"); exit(1); } if (execlp("sha256sum", "sha256sum", NULL) == -1) { perror("Error invoking execlp"); exit(1); } exit(0); } else { if (close(fd2[PIPE_READ]) == -1) { perror("Error closing process FD2[READ]"); return NULL; } if (close(fd1[PIPE_WRITE]) == -1) { perror("Error closing process FD1[WRITE]"); return NULL; } if (write(fd2[PIPE_WRITE], concatd, strlen(concatd)) != strlen(concatd)) { printf("Error writing to FD2[WRITE]\n"); return NULL; } if (close(fd2[PIPE_WRITE]) == -1) { perror("Error closing process FD2[WRITE]"); return NULL; } if (read(fd1[PIPE_READ], hash, HASH_LEN) != HASH_LEN) { printf("Error reading from FD1[READ]\n"); return NULL; } if (close(fd1[PIPE_READ]) == -1) { perror("Error closing process FD1[READ]"); return NULL; } } hash[HASH_LEN] = '\0'; /* dup2(getSLogFD(), STDOUT_FILENO); printf("concatd: %s\n", concatd); printf("pass: %s\n", password); printf("hash: %s\n", hash); printf("salt: %s\n", salt); */ return hash; }
C
/* * 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 3 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, see <http://www.gnu.org/licenses/>. */ #pragma once #include <stdint.h> #include <stdbool.h> struct ringbuf_t { volatile char* const buf; const uint16_t max_size; volatile uint16_t head; volatile uint16_t tail; }; bool ringbuf_push(volatile struct ringbuf_t* buf, char value); bool ringbuf_peek(volatile struct ringbuf_t* buf, uint16_t idx, char* value); bool ringbuf_pop(volatile struct ringbuf_t* buf, char* value); void ringbuf_clear(volatile struct ringbuf_t* buf); uint16_t ringbuf_size(volatile struct ringbuf_t* b);
C
#include <stdio.h> #include "ft_printf.h" static int f_x_sharp(t_data *data, const char *ptr) { if (data->flags[SHARP] > 0 && *ptr == 'x') print_str("0x", data); else if (data->flags[SHARP] && *ptr == 'X') print_str("0X", data); return (0); } int pick_f_x_two(char *result, t_data *data, const char *ptr) { if (data->precision > 0) { f_width(data); f_x_sharp(data, ptr); f_precision(data); print_str(result, data); } else if (data->flags[ZERO]) { f_x_sharp(data, ptr); f_zero(data); print_str(result, data); } else if (data->width > 0) { f_width(data); f_x_sharp(data, ptr); print_str(result, data); } else { f_x_sharp(data, ptr); print_str(result, data); } return (0); } char *determine_xo_call(const char *ptr, va_list param) { char *result; if (*ptr == 'x') result = to_base(va_arg(param, int), BASE_H); else if (*ptr == 'X') result = to_base(va_arg(param, int), BASE_HC); else if (*ptr == 'o') result = to_base(va_arg(param, int), BASE_O); else return (NULL); return (result); } int pick_f_base(va_list param, t_data *data, const char *ptr) { //comportement indéfini precision et largeur = int max char *result; if (!(result = determine_xo_call(ptr, param))) return (-1); if ((data->len = ft_strlen(result)) == 1 && *result == '0') return (print_str("0", data)); data->len = (data->flags[SHARP] && (*ptr == 'x' || *ptr == 'X')) ? data->len + 2 : data->len; data->len = (data->flags[SHARP] && (*ptr == 'o' || *ptr == 'O')) ? ++data->len : data->len; data->precision = (data->precision > data->len) ? data->precision - (data->len) : 0; if (data->flags[MINUS]) { f_x_sharp(data, ptr); f_precision(data); print_str(result, data); f_width(data); } else if (data->precision > 0 && data->width > 0) { f_width(data); f_x_sharp(data, ptr); f_precision(data); print_str(result, data); } else (pick_f_x_two(result, data, ptr)); free(result); return (0); }
C
#include <stdint.h> #include <stm8s.h> // works ok! // Setup the system clock to run at 16MHz using the internal oscillator. void initialize_system_clock() { CLK_ICKR = 0; // Reset the Internal Clock Register. CLK_ICKR |= (1 << CLK_ICKR_HSIEN); // Enable the HSI. CLK_ECKR = 0; // Disable the external clock. while((CLK_ICKR & CLK_ICKR_HSIRDY) == 0 ); // Wait for the HSI to become ready CLK_CKDIVR = 0; // Ensure the clocks are running at full speed. CLK_PCKENR1 = 0xff; // Enable all peripheral clocks. CLK_PCKENR2 = 0xff; // Ditto. CLK_CCOR = 0; // Turn off CCO. CLK_HSITRIMR = 0; // Turn off any HSIU trimming. CLK_SWIMCCR = 0; // Set SWIM to run at clock / 2. CLK_SWR = 0xe1; // Use HSI as the clock source. CLK_SWCR = 0; // Reset the clock switch control register. CLK_SWCR |= (1 << CLK_SWCR_SWEN); // Enable switching. while((CLK_SWCR & CLK_SWCR_SWBSY) != 0 ); // Pause until the clock switch is complete. } uint16_t delay_counter; void timer_isr_handler() __interrupt(TIM4_ISR) { if (delay_counter) delay_counter--; TIM4_SR &= ~(1 << TIM4_SR_UIF); // clear interrupt flag } void tim4_setup(void) { TIM4_PSCR = 0b00000000; // Prescaler = 1 // 16MHz * 0.5-10^-6 = 80 // PSCR * ARR = 80 // PSCR: 2^0 = 1 // set auto reload register TIM4_ARR = 80; TIM4_IER |= (1 << TIM4_IER_UIE); // Enable Update Interrupt TIM4_CR1 |= (1 << TIM4_CR1_CEN); // Enable TIM2 } void delay_us(uint16_t us) { delay_counter = us/5; tim4_setup(); // 5us ~ 1 count while (delay_counter) {} } void delay_ms(signed int ms) { while(ms--) delay_us(1000); } #define LED_PIN 5 void main() { initialize_system_clock(); enable_interrupts(); PB_DDR |= (1 << LED_PIN); //PB_CR1 |= (1 << LED_PIN); // push-pull PB_CR1 &= ~(1 << LED_PIN); // open drain while (1) { PB_ODR ^= (1 << LED_PIN); // toggle output delay_ms(300); } }
C
/* * tiny_web - a mini simple web program. */ #include "csapp.h" void sigchld_handler(int sig) { while (waitpid(-1, 0, WNOHANG) > 0) ; return; } void doit(int fd); /* main - an C/S module. */ int main(int argc, char **argv) { struct sockaddr_in cliaddr; int listenfd, connfd, port; socklen_t clilen; pid_t childpid; if(argc != 2){ fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(1); } port = atoi(argv[1]); Signal(SIGCHLD, sigchld_handler); listenfd = Open_listenfd(port); while(1){ clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); if( (childpid = Fork()) == 0){ Close(listenfd); doit(connfd); Close(connfd); exit(0); } Close(connfd); } } /* doit - deal with the an http transcation. */ void serve_static(int fd, char *filename, int filesize); void serve_dynamic(int fd, char *filename, char *cgiargs); void clienterror(int fd, char *str, char *err_code, char *err_name, char *err_message); int prase_uri(char *uri, char *filename, char *cgiargs); void read_header(rio_t *rp); void doit(int fd) { int is_static; /* static content or dynamic content. */ char method[MAXLINE], uri[MAXLINE], version[MAXLINE], buf[MAXLINE]; char filename[MAXLINE], cgiargs[MAXLINE]; struct stat sbuf; rio_t rio; /* be used by the Rio_readinitb to attach this buff to the fd file. Or we called it a read buff. */ /*Read request line and headers */ Rio_readinitb(&rio, fd); Rio_readlineb(&rio, buf, MAXLINE); /* read a line from the rio_buff to the buff. */ sscanf(buf, "%s %s %s", method, uri, version); if(strcasecmp(method, "GET")){ clienterror(fd, method, "501", "Not Implemented", "Tiny does not implement this method"); return; } read_header(&rio); /* Prase URI from GET request */ is_static = prase_uri(uri, filename, cgiargs); /* when static return 1, dynamic content return 0. */ if(stat(filename, &sbuf) < 0){ clienterror(fd, filename, "404", "Not found", "Tiny couldn't find this file"); return; } if(is_static){ /* Serve static content */ if(!(S_ISREG(sbuf.st_mode)) || !(S_IRUSR & sbuf.st_mode)) /*S_ISDEG determine a file's type is regular file or not.*/ /* S_IRUSR determine the user does have the access right or not.*/ { clienterror(fd, filename, "403", "Forbidden", "Tiny couldn't read this file"); return; } serve_static(fd, filename, sbuf.st_size); } else { /*Serve dynamic content */ if(!(S_ISREG(sbuf.st_mode)) || !(S_IXUSR & sbuf.st_mode)) { clienterror(fd, filename, "403", "Forbidden", "Tiny couldn't run the CGI program"); return; } serve_dynamic(fd, filename, cgiargs); } } void clienterror(int fd, char *str, char *err_code, char *err_name, char *err_message) { char buff[MAXLINE]; sprintf(buff, "%s\n%s, %s, %s\n", str, err_code, err_name, err_message); Rio_writen(fd, buff, strlen(buff)); } /* read_header - read the header from the read buff pointered by the rp but ignore it. */ void read_header(rio_t *rp) { char buf[MAXLINE]; Rio_readlineb(rp, buf, MAXLINE); while(strcmp(buf, "\r\n")) { /* if the buf is "\r\n", return 0. */ Rio_readlineb(rp, buf, MAXLINE); printf("%s", buf); } return; } /* prase_uri - turn the URI to the filename and CGI program's argument. */ int prase_uri(char *uri, char *filename, char *cgiargs) { char *ptr; if(!strstr(uri, "cgi-bin")){ /* static content */ /* the strstr function find the cgi-bin 's location in the uri. */ strcpy(cgiargs, ""); /* empty the cgiargs */ strcpy(filename, "."); /* line 101-102 transfer the uri to the unix style file location. */ strcat(filename, uri); if(uri[strlen(uri) - 1] == '/') /* auto add the default file if not assigned. */ strcat(filename, "home.html"); return 1; } else{ /* dynamic content */ ptr = index(uri, '?'); /* find the '?' */ if(ptr){ /* if the prt not a empty string */ strcpy(cgiargs, ptr + 1); *ptr = '\0'; } else strcpy(cgiargs, ""); /* transfer the uri to the unix style file location. */ strcpy(filename, "."); strcat(filename, uri); return 0; } } /* * serve_static - serve for an request of static content. */ void get_filetype(char *filename, char *filetype); void serve_static(int fd, char *filename, int filesize) { int srcfd; char *srcp, filetype[MAXLINE], buf[MAXBUF]; /* Send response headers to client */ get_filetype(filename, filetype); sprintf(buf, "HTTP/1.0 200 OK\r\nServer: Tiny Web Server\r\nContent-length:%d\r\nContent-type:%s\r\n\r\n", filesize, filetype); Rio_writen(fd, buf,strlen(buf)); /* Send response body to client */ srcfd = Open(filename, O_RDONLY, 0); srcp = Mmap(0, filesize, PROT_READ, MAP_PRIVATE, srcfd, 0); Close(srcfd); Rio_writen(fd, srcp, filesize); Munmap(srcp, filesize); exit(0); } /* * get_filetype - derive file type from file name */ void get_filetype(char *filename, char *filetype) { if (strstr(filename, ".html")) strcpy(filetype, "text/html"); else if (strstr(filename, ".gif")) strcpy(filetype, "image/gif"); else if (strstr(filename, ".jpg")) strcpy(filetype, "image/jpg"); else strcpy(filetype, "text/plain"); } /* * serve_dynamic - serve for an request of dynamic content. */ void serve_dynamic(int fd, char *filename, char *cgiargs) { char buf[MAXLINE], *arg[] = { NULL }; /* Return first part of HTTP response */ sprintf(buf, "HTTP/1.0 200 OK\r\nServer: Tiny Web Server\r\n"); Rio_writen(fd, buf,strlen(buf)); /* Send response body to client */ if (Fork() == 0) { /* Real server would set all CGI vars here */ setenv("QUERY_STRING", cgiargs, 1); Dup2(fd, STDOUT_FILENO); Execve(filename, arg, environ); } Wait(NULL); }
C
#include <stdio.h> int nullTheEven(int value) { int mask = 0x55555555; int result = value & mask; return result; } int main() { int a; a = 31; printf("%i", nullTheEven(a)); return 0; }
C
/* psinv.c CCMATH mathematics library source code. * * Copyright (C) 2000 Daniel A. Atkinson All rights reserved. * This code may be redistributed under the terms of the GNU library * public license (LGPL). ( See the lgpl.license file for details.) * ------------------------------------------------------------------------ */ #include <math.h> #include "matutl.h" int psinv(double *v,int n) { double z,*p,*q,*r,*s,*t; int j,k; for(j=0,p=v; j<n ;++j,p+=n+1){ for(q=v+j*n; q<p ;++q) *p-= *q* *q; if(*p<=0.) return -1; *p=sqrt(*p); for(k=j+1,q=p+n; k<n ;++k,q+=n){ for(r=v+j*n,s=v+k*n,z=0.; r<p ;) z+= *r++ * *s++; *q-=z; *q/= *p; } } trnm(v,n); for(j=0,p=v; j<n ;++j,p+=n+1){ *p=1./ *p; for(q=v+j,t=v; q<p ;t+=n+1,q+=n){ for(s=q,r=t,z=0.; s<p ;s+=n) z-= *s * *r++; *q=z* *p; } } for(j=0,p=v; j<n ;++j,p+=n+1){ for(q=v+j,t=p-j; q<=p ;q+=n){ for(k=j,r=p,s=q,z=0.; k<n ;++k) z += *r++ * *s++; *t++ =(*q=z); } } return 0; }
C
// One-star problem // Problem 10038 Jolly Jumpers /* This program is written by Prof. Chua-Huang Huang Department of Information Engineering and Computer Science Feng Chia University Taichung, Taiwan Disclaimer: The programming problem is downloaded from UVa Online Judge (https://uva.onlinejudge.org/). The program solution is provided for helping students to prepare Collegiate Programming Examination (CPE). The author does not guarantee the program is completely correct to pass UVa Online Judge platform or CPE examination platform. This program is not intended for a student to copy only. He/She should practice the programming problem himself/herself. Only use the program solution as a reference. The author is not responsible if the program causes any damage of your computer or personal properties. No commercial use of this program is allowed without the author's written permission. */ #include <stdlib.h> #include <stdio.h> #include <math.h> int main(void) { int data[3000], difference[3000]; int length, temp; int i, j; while (scanf("%d", &length)==1) { // Input the length of the number sequence, if there is any. for (i=0; i<length; i++) scanf("%d", &data[i]); // Input the sequence elements. for (i=1; i<length; i++) difference[i] = abs(data[i-1] - data[i]); // Compute the difference of two neighboring sequence elements. // Sort the difference sequence, not including difference[0], in ascending order. for (i=length-1; i>1; i--) for (j=2; j<=i; j++) { if (difference[j-1]>difference[j]) { temp = difference[j-1]; difference[j-1] = difference[j]; difference[j] = temp; } } for (i=1; i<length; i++) if (difference[i]!=i) break; // Check if the sorted difference is 1, 2, 3, .... if (i==length) printf("Jolly\n"); // If the check passes through all difference elements, it is a jolly seqence, else printf("Not jolly\n"); // otherwise, it is not. } return 0; }
C
/********************************************************** Copyright (C) 2015 . File name: SVGAmode.H Author: Version 2.0 Date 2015/8/12 Description SVGAʾģʽͷļģʽ»ijʼͼͼȵʵ֡ 괦SVGAmode.hС Ϊ궨ԵʣϽļжΪRGBrgbı Ϊgraphics.hеĺдĸд дĻοϵΪ׼ LineCircleCirclefillΪϴ룬빤 Աļ޸뼰ʱ¸ʽ¼棨ÿ޸ĵг Function List 1.void SetSVGA256(void); SVGAʾģʽúΪ0x105 2.void SetSVGA64k(void); SVGAʾģʽúΪ0x117 3.unsigned int GetSVGA(void); ȡSVGAʾģʽbx 4.void Selectpage(register char page); жϹܵĻҳдԴʱѰַ 5.void Putpixel256(int x, int y, unsigned char color); 㺯ͼĻ0x105ģʽ 6.void Putpixel64k(int x, int y, unsigned int color); 㺯ͼĻ0x117ģʽ 7.int Putbmp256(int x, int y, const char * path); 8λѹbmpͼλʾ 8.int Putbmp64k(int x, int y, const char * path); 24λѹbmpͼλʾ 9.void Xorpixel(int x, int y, unsigned char color); λ򻭵㺯 10.void Horizline(int x, int y, int width, unsigned char color); ˮƽߺ 11.void Line(int x1, int y1, int x2, int y2, unsigned char color); һֱߺ 12.void Bar(int x1, int y1, int x2, int y2, unsigned char color); ο麯 13.void Circle(int xc, int yc, int radius, unsigned char color); ԲȦ 14.void Circlefill(int xc, int yc, int radius, unsigned char color); ʵԲ History Աļ޸뼰ʱ¸ʽ¼棨ÿ޸ĵг Example Date Author Version Modification 1. Date2015/8/14 Author Version2.0 Modificationļദش޸ģ汾Ϊ2.0ļΪSVGAmode.h 2. Date2015/8/14 Author Version2.0 ModificationʵֲֳַΪļSVGAmode.cļֻй 3. Date2015/8/14 Author Version2.0 Modificationк int Putbmp(int x, int y, const char * path) 4. Date2015/8/14 Author Version2.0 Modification½ṹ ͼɫɫṹCOLORS bmpλͼɫɫṹRGBQUAD bmpλͼϢͷṹBITMAPINFOHEADER飩 5. Date2015/9/2 Author Version2.1 Modificationļദ޸ģSVGAmode.cѰ汾Ϊ2.1 6. Date2015/9/2 Author Version2.1 ModificationӶ24λbmpͼɫṹCOLORS24 7. Date2015/9/3 Author Version2.1 Modificationֺ¸Ӧע޸ SetSVGAΪSetSVGA256 PutbmpΪPutbmp256 PutpixelΪPutpixel256 8. Date2015/9/3 Author Version2.1 Modificationº SetSVGA64k Putpixel64k Putbmp64k SVGAģʽ256ɫ64kɫѡ ߽24λbmpת16λͼͻ㺯ͼһɲã 9. Date2015/9/12 Author Version2.1 Modificationѹõͷļγhead.h 10. Date2015/11/5 Author Version2.1 Modificationɾȥ14ú;עͣļ **********************************************************/ #ifndef _SVGAmode_H_ #define _SVGAmode_H_ #define SCR_WIDTH 1024 /*SCREEN_WIDTHдĻ */ #define SCR_HEIGHT 768 /*SCREEN_HEIGHTдĻ߶ */ #include<dos.h> /*int86outportbͷļunion REGSĶļ*/ #include<stdio.h> /*ļͷļ*/ #include<time.h> /*timeͷļclock_tĶͷļ*/ #include<math.h> /*absfabssincosͷļ*/ #include<stdlib.h> /*randsrandexitͷļ*/ #include<graphics.h> /*Դͼͷļ*/ #include<conio.h> /*getchͷļ*/ #include<string.h> /*memmoveͷļ*/ #include<bios.h> /*bioskeyͷļ*/ /*ͼɫɫṹ*/ typedef struct { unsigned char R; /*ɫREDд*/ unsigned char G; /*ɫGREENд*/ unsigned char B; /*ɫBLUEд*/ } COLORS; /*24λbmpͼɫṹ*/ typedef struct { unsigned char B; /*ɫBLUEд*/ unsigned char G; /*ɫGREENд*/ unsigned char R; /*ɫREDд*/ } COLORS24; /*bmpλͼɫɫṹ*/ typedef struct tagRGBQUAD { unsigned char b; /*ɫREDд*/ unsigned char g; /*ɫGREENд*/ unsigned char r; /*ɫBLUEд*/ unsigned char reserved; /**/ } RGBQUAD; /*bmpλͼϢͷ˵λͼijߴϢ*/ typedef struct tagBITMAPINFOHEADER { unsigned long int biSize; /*ṹռֽ15-18ֽڣ*/ long int biWidth; /*λͼĿȣΪλ19-22ֽڣ*/ long int biHeight; /*λͼĸ߶ȣΪλ23-26ֽڣ*/ unsigned int biPlanes; /*Ŀ豸ļ𣬱Ϊ1(27-28ֽڣ*/ unsigned int biBitCount; /*ÿλ1˫ɫ4(16ɫ8(256ɫ16(߲ɫ)24ɫ֮һ29-30ֽڣ*/ unsigned long int biCompression; /*λͼѹͣ0ѹ1(BI_RLE8ѹͣ2(BI_RLE4ѹ֮ͣһ31-34ֽڣ*/ unsigned long int biSizeImage; /*λͼĴС(аΪ˲4ıӵĿֽ)ֽΪλ35-38ֽڣ*/ long int biXPelsPerMeter; /*λͼˮƽֱʣÿ39-42ֽڣ*/ long int biYPelsPerMeter; /*λͼֱֱʣÿ43-46ֽ)*/ unsigned long int biClrUsed; /*λͼʵʹõɫеɫ47-50ֽڣ*/ unsigned long int biClrImportant; /*λͼʾҪɫ51-54ֽڣ*/ } BITMAPINFOHEADER; /********************************************************** Function SetSVGA256 Description SVGAʾģʽúΪ0x105 Calls int86 delay printf exit Called By AutoSimulate HandOperate Input None Output Ϣ Return None Others None **********************************************************/ extern void SetSVGA256(void); /********************************************************** Function SetSVGA64k Description SVGAʾģʽúΪ0x117 Calls int86 delay printf exit Called By AutoSimulate HandOperate Input None Output Ϣ Return None Others None **********************************************************/ extern void SetSVGA64k(void); /********************************************************** Function GetSVGA Description ȡSVGAʾģʽbxժ¼õģʽ£ ģʽ ֱ ɫ ɫλ 0x101 640*480 256 - 0x103 800*600 256 - 0x104 1024*768 16 - 0x105 1024*768 256 - 0x110 640*480 32K 1:5:5:5 0x111 640*480 64K 5:6:5 0x112 640*480 16.8M 8:8:8 0x113 800*600 32K 1:5:5:5 0x114 800*600 64K 5:6:5 0x115 800*600 16.8M 8:8:8 0x116 1024*768 32K 1:5:5:5 0x117 1024*768 64K 5:6:5 0x118 1024*768 16.8M 8:8:8 Calls int86 delay printf exit Called By Unknown Input None Output ʼʧʱĻš Return unsigned int graph_regs.x.bx ʾģʽ Others None **********************************************************/ extern unsigned int GetSVGA(void); /********************************************************** Function Selectpage Description жϹܵĻҳдԴʱѰַ Calls int86 Called By Putpixel256 Putpixel64k Xorpixel Horizline Getpixel64k Input register char page Ҫҳ Output None Return None Others None **********************************************************/ extern void Selectpage(register char page); /********************************************************** Function Putpixel256 Description 㺯ͼĻ0x105ģʽ Calls Selectpage Called By Putbmp256 Line Circle Input int x غ꣬ӣ0ΪСֵĻοϵ int y ꣬ϵӣ0ΪСֵĻοϵ unsigned char color ɫ256 Output Ļϻָɫĵ Return None Others None **********************************************************/ extern void Putpixel256(int x, int y, unsigned char color); /********************************************************** Function Putpixel64k Description 㺯ͼĻ0x117ģʽ Calls Selectpage Called By Putbmp64k MousePutBk MouseDraw Input int x غ꣬ӣ0ΪСֵĻοϵ int y ꣬ϵӣ0ΪСֵĻοϵ unsigned int color ɫ64k Output Ļϻָɫĵ Return None Others None **********************************************************/ extern void Putpixel64k(int x, int y, unsigned int color); extern void XORPutpixel64k(int x, int y, unsigned int color); /********************************************************** Function Putbmp256 Description 8λѹbmpͼλʾ ֻ֧8λѹbmpͼΪ1024 bmp;֧֣ 0x105ģʽʹã Ϊ˼򻯣ûļͼ⹦ܼ⹦ܣ벻Ҫļ ˺ʺڲλ¶ȡͼƬ Ȼ˶ȡɫܣܼʵʹɫͼƬ ͳһҪʹWindowsĬɫӰͼƬʾ Calls Putpixel256 fseek fread fclose outportb malloc free Called By AutoSimulate HandOperate Input int x ͼƬϽǵĺ꣨Ļοϵ int y ͼƬϽǵ꣨Ļοϵ const char * path bmpͼƬ· Output ĻʾͼƬ Return 0 ʾɹ -1 ʾʧ Others None **********************************************************/ extern int Putbmp256(int x, int y, const char * path); /********************************************************** Function Putbmp64k Description 24λѹbmpͼλʾ ֻ֧24λѹbmpͼΪ1024 bmp;֧֣ 0x117ģʽʹã Ϊ˼򻯣ûļͼ⹦ܼ⹦ܣ벻Ҫļ Calls Putpixel64k fseek fread fclose outportb malloc free Called By AutoSimulate HandOperate Menu Input int x ͼƬϽǵĺ꣨Ļοϵ int y ͼƬϽǵ꣨Ļοϵ const char * path bmpͼƬ· Output ĻʾͼƬ Return 0 ʾɹ -1 ʾʧ Others None **********************************************************/ extern int Putbmp64k(int x, int y, const char * path); extern int Putbmp64k2(int x, int y, const char * path); extern int Putbmp64k3(int x, int y, const char * path); extern int XORPutbmp64k(int x, int y, const char * path); /********************************************************** Function Xorpixel Description λ򻭵㺯 Calls Selectpage Called By XorCarBmp Input int x غ꣬ӣ0ΪСֵĻοϵ int y ꣬ϵӣ0ΪСֵĻοϵ unsigned char color ɫ256 Output Ļϻ Return None Others None **********************************************************/ extern void Xorpixel(int x, int y, unsigned int color); /********************************************************** Function Horizline Description ˮƽߺ ԽճĻΧݣֻĻڲ ΪûзֹͱжϣĻʱӦֹش Calls Selectpage Called By Line Bar Circlefill Input int x ʼ꣬ӣ0ΪСֵĻοϵ int y ʼ꣬ϵӣ0ΪСֵĻοϵ int width ˮƽȣΪ죬Ϊ unsigned char color ɫ256 Output Ļϻˮƽ Return None Others None **********************************************************/ extern void Horizline(int x, int y, int width, unsigned int color); /********************************************************** Function Line Description һֱߺ ԽճĻΧݣֻĻڲ ΪûзֹͱжϣĻʱӦֹش Calls Putpixel256 abs Called By LightSW LightNE LightNW LightSE Input int x1 ʼ꣬ӣ0ΪСֵĻοϵ int y1 ʼ꣬ϵӣ0ΪСֵĻοϵ int x2 ֹ꣨Ļοϵ int y2 ֹ꣨Ļοϵ unsigned char color ɫ256 Output Ļϻֱ Return None Others None **********************************************************/ extern void Line(int x1, int y1, int x2, int y2, unsigned int color); /********************************************************** Function Bar Description ο麯 ԽճĻΧݣֻĻڲ ΪûзֹͱжϣĻIJʱӦֹش Calls Horizline Called By LightSW LightNE LightNW LightSE Input int x1 Խǵ1ĺ꣬ӣ0ΪСֵĻοϵ int y1 Խǵ1꣬ϵӣ0ΪСֵĻοϵ int x2 Խǵ2ĺ꣬ӣ0ΪСֵĻοϵ int y2 Խǵ2꣬ϵӣ0ΪСֵĻοϵ unsigned char color ɫ65536 Output Ļϻο Return None Others None **********************************************************/ extern void Bar(int x1, int y1, int x2, int y2, unsigned int color); /********************************************************** Function Circle Description ԲȦ ԽճĻΧݣֻĻڲ ΪûзֹͱжϣĻIJʱӦֹش Calls Putpixel256 Called By LightSW LightNE LightNW LightSE Input int xc x_centerдԲĺ꣨Ļοϵ int yc y_centerдԲ꣨Ļοϵ int radius 뾶Ϊ unsigned char color ɫ65536 Output ĻϻԲȦ Return None Others None **********************************************************/ extern void Circle(int xc, int yc, int radius, unsigned int color); /********************************************************** Function Circlefill Description ʵԲ ԽճĻΧݣֻĻڲ ΪûзֹͱжϣĻIJʱӦֹش Calls Horizline Called By LightColorR LightColorY LightColorG LightColor1 LightColor2 LightColor3 LightColor4 LightColorD1 LightColorD2 LightColorD3 TrafficLight Input int xc x_centerдԲĺ꣨Ļοϵ int yc y_centerдԲ꣨Ļοϵ int radius 뾶Ϊ unsigned char color ɫ256 Output ĻϻԲȦ Return None Others None **********************************************************/ extern void Circlefill(int xc, int yc, int radius, unsigned int color); int Imagesize(int xmin,int ymin,int xmax,int ymax); unsigned char Getpixel256(int x, int y); int Getpixel64k(int x, int y); void Get_image(int xmin,int ymin,int xmax,int ymax,unsigned char* bufer);//õÿһصɫ void Put_image(int xmin,int ymin,int xmax,int ymax,const unsigned char* bufer);//ص #endif
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> struct hash{ struct node **arr; int size; }; struct node{ char *ch; struct node *next; }; struct node* create_node(char *str){ struct node* new; new = (struct node*)malloc(sizeof(struct node)); new->next = NULL; new->ch = (char*)malloc(sizeof(char)*30); strcpy(new->ch,str); return new; } int power(int base,int exp){ int pro = 1; int temp = exp; while(temp>0){ pro = pro*base; temp--; } return pro; } int val(char ch){ int value = ch - 97; return power(2,value); } int spv(char* str){ int i=0; int sum=0; for(i=0;i<strlen(str);i++){ for(int z=i+1;z<strlen(str);z++){ if(str[i] == str[z]){ sum = sum - val(str[i]); break; } } sum = sum + val(str[i]); } return sum; } void insert(struct hash *T,char *str){ struct node *newnode = create_node(str); int sp_val = spv(str); char temp[50]; int key = sp_val % 255; if(T->arr[key] == NULL){ T->arr[key] = newnode; return; } else{ struct node *root = T->arr[key]; if(strcmp(newnode->ch,root->ch) < 0){ newnode->next = root; T->arr[key] = newnode; return; } while(root->next && strcmp(root->ch,newnode->ch) < 0){ root = root->next; } newnode->next = root->next; root->next = newnode; return; } } void print(struct hash *T){ int i; for(i=0;i<255;i++){ if(T->arr[i] == NULL){ continue; } else{ struct node* root = T->arr[i]; while(root){ printf("%s ",root->ch); root = root->next; } printf("\n"); } } } int main(){ struct hash *T; int n; T = (struct hash*)malloc(sizeof(struct hash)); T->size = 255; scanf("%d",&n); T->arr = (struct node**)malloc(sizeof(struct node*)*T->size); int i; char temp[40]; for(i=0;i<n;i++){ scanf("%s",temp); insert(T,temp); } print(T); }
C
#include <stdio.h> #include "functions.h" #include <stdlib.h> struct min_heap{ int index; int data; struct min_heap* left; struct min_heap* right; }; struct min_heap* min_heap_tree(struct min_heap* root, int arr[], int i, int n){ if(i < n){ struct min_heap* new_node = (struct min_heap*)malloc(sizeof(struct min_heap)); new_node->index = i; new_node->data = arr[i]; new_node->left = NULL; new_node->right = NULL; root = new_node; root->left = min_heap_tree(root->left, arr, 2 * i + 1, n); root->right = min_heap_tree(root->right, arr, 2 * i + 2, n); } return root; } void ordering_array(int arr[], int i, int n){ int j; int aux = arr[i]; j = 2 * i; while(j <= n){ if( (j < n) && (arr[j + 1] < arr[j]) ) j++; if (aux < arr[j]) break; else{ arr[j/2] = arr[j]; j = 2 * j; } } arr[j/2] = aux; return; } void create_min_heap_array(int arr[], int n){ int i; for(i = n/2; i >= 1; i--){ ordering_array(arr, i, n); } } void search_min_heap(struct min_heap *root, int searched_value, int *found){ if ( (root != NULL) && (root->data == searched_value) ){ (*found) = 1; return; }else{ if(root->left != NULL) search_min_heap(root->left, searched_value, found); if(root->right != NULL) search_min_heap(root->right, searched_value, found); } } int get_position_of_element(int arr[], int n, int searched_value){ int i; for(i=0; i<=n; i++) if(arr[i] == searched_value) return i; return 0; } void pop_element_array(int arr[], int *n, int i){ for(i=1; i<=(*n)-1; i++) arr[i] = arr[i + 1]; arr[(*n)] = 0; (*n)--; }
C
/* ** check_all_ship.c for in /home/januar_m/delivery/PSU/PSU_2016_navy ** ** Made by Martin Januario ** Login <martin.januario@epitech.eu> ** ** Started on Mon Feb 13 11:16:12 2017 ** Last update Mon Feb 13 11:32:05 2017 */ #include <stdio.h> #include "battleship.h" int check_all_ship(int **all_ship) { int idx; idx = 0; while (idx < 4) { if ((*all_ship)[idx] != 0) return (84); idx++; } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 50 #define LENGHT 25 typedef struct List { char code[LENGHT]; char AuthorName [SIZE]; char PaintingName [SIZE]; double Price; int year; struct List *next; }Painting; void menu (); void choiceManage (int choice); void addPainting(); void deletePainting(Painting **head); void PrintAllPaintings(Painting **head); void updatePainting(Painting **head); void Writing (Painting *listPainting, int choice); void Reading (int choice); Painting *list_switch( Painting *l1, Painting *l2 ); Painting *FreeAll(Painting **head); void addPainting (){ Painting *current, *head; int i = 0; char c; head = NULL; do{ if ((current = (Painting *) malloc (sizeof(Painting)))== NULL){ printf ("\nError allocating memory!!!"); exit (2); } printf ("\nEnter the data of the %d painting:\n", i + 1); printf ("\nEnter the code of the painting: "); fgets (current->code, LENGHT, stdin); current->code[strlen(current->code) - 1] = '\0'; fflush(stdin); printf ("\nEnter the author of the painting: "); fgets (current->AuthorName, SIZE, stdin); current->AuthorName[(strlen(current->AuthorName) - 1)] = '\0'; fflush(stdin); printf ("\nEnter the name of the painting: "); fgets (current->PaintingName, SIZE, stdin); current->PaintingName[strlen(current->PaintingName) - 1] = '\0'; fflush(stdin); printf ("\nEnter the painting's price: "); scanf ("%lf", &current->Price); fflush(stdin); printf ("\nEnter the painting's year: "); scanf("%d", &current->year); fflush(stdin); current->next = head; head = current; i++; printf ("\nDo you want to add another painting? (Y\\N): "); scanf("%c", &c); fflush(stdin); }while (c != 'n' && c != 'N'); current = head; Writing(current, 1); } void deletePainting(Painting **head){ Painting *localHead, *temp; char CodetoDelete[LENGHT], ch; int i = 0; localHead = *head; temp = *head; printf ("\nPictures you have in the gallery.\n\n"); printf ("------------------------------\n"); while(*head){ printf ("Code: %s\n", (*head)->code); printf ("Author: %s\n", (*head)->AuthorName); printf ("Painting: %s\n", (*head)->PaintingName); printf ("Price: %.2lf\n", (*head)->Price); printf ("Year: %d\n", (*head)->year); printf ("------------------------------"); printf ("\n"); *head = (*head)->next; } *head = temp; deleting: localHead = *head; temp = *head; *head = temp; printf ("\nEnter the code of the painting you want to delete: "); scanf ("%s", CodetoDelete); fflush(stdin); CodetoDelete[strlen(CodetoDelete)] = '\0'; i = 0; while (temp){ if (!strcmp(CodetoDelete, temp->code)){ if (i == 0){ *head = (*head)->next; localHead = *head; i++; break; }else { (*head)->next = temp->next; temp = temp->next; } }else { temp = temp->next; if(i != 0){ *head = (*head)->next; } } if (temp == NULL) printf ("\nThere's not a painting with such a code!\n"); i++; } *head = localHead; printf ("\nPictures after the Deleting.\n"); printf ("------------------------------\n"); while(*head){ printf ("Code: %s\n", (*head)->code); printf ("Author: %s\n", (*head)->AuthorName); printf ("Painting: %s\n", (*head)->PaintingName); printf ("Price: %.2lf\n", (*head)->Price); printf ("Year: %d\n", (*head)->year); printf ("------------------------------"); printf ("\n"); *head = (*head)->next; } *head = localHead; printf ("Do you want to delete another painting? (Y\\N): "); scanf ("%c", &ch); fflush(stdin); if ((ch == 'y') || (ch == 'Y')) goto deleting; if ((remove("Paintings.bin")) != 0){ printf ("Error deleting the old file."); exit(3); } Writing(*head, 2); } void updatePainting(Painting **head){ char PaintingtoUpdate[LENGHT], ch; Painting *temp; int userChoice; temp = *head; printf ("\nPictures you have in the gallery.\n\n"); printf ("------------------------------\n"); while(*head){ printf ("Code: %s\n", (*head)->code); printf ("Author: %s\n", (*head)->AuthorName); printf ("Painting: %s\n", (*head)->PaintingName); printf ("Price: %.2lf\n", (*head)->Price); printf ("Year: %d\n", (*head)->year); printf ("------------------------------"); printf ("\n"); *head = (*head)->next; } updating: *head = temp; printf ("\nEnter the code of the painting you want to update: "); fgets (PaintingtoUpdate, LENGHT, stdin); PaintingtoUpdate[strlen(PaintingtoUpdate) - 1] = '\0'; fflush(stdin); while (*head){ if (!strcmp(PaintingtoUpdate, (*head)->code)) { do { printf ("\nWhat do you want to change? \n\n\n"); printf ("1. Painting's code.\n"); printf ("2. Painting's author.\n"); printf ("3. Painting's name.\n"); printf ("4. Painting's Price.\n"); printf ("5. Painting's year.\n"); printf ("Your choice is: "); scanf("%d", &userChoice); fflush(stdin); switch (userChoice){ case 1: printf ("\nEnter the new code of the painting: "); fgets ((*head)->code, LENGHT, stdin); (*head)->code[strlen((*head)->code) - 1] = '\0'; fflush (stdin); printf ("\nDo you want to change something else? (Y\\N): "); scanf("%c", &ch); fflush(stdin); continue; case 2: printf ("\nEnter the new author of the painting: "); fgets ((*head)->AuthorName, SIZE, stdin); (*head)->AuthorName[(strlen((*head)->AuthorName) - 1)] = '\0'; fflush (stdin); printf ("\nDo you want to change something else? (Y\\N): "); scanf("%c", &ch); fflush(stdin); continue; case 3: printf ("\nEnter the new name of the painting: "); fgets ((*head)->PaintingName, SIZE, stdin); (*head)->PaintingName[(strlen((*head)->PaintingName) - 1)] = '\0'; fflush (stdin); printf ("\nDo you want to change something else? (Y\\N): "); scanf("%c", &ch); fflush(stdin); continue; case 4: printf ("\nEnter the new price of the painting: "); scanf ("%lf", &(*head)->Price); fflush (stdin); printf ("\nDo you want to change something else? (Y\\N): "); scanf("%c", &ch); fflush(stdin); continue; case 5: printf ("\nEnter the new year of the painting: "); scanf ("%d", &(*head)->year); fflush (stdin); printf ("\nDo you want to change something else? (Y\\N): "); scanf("%c", &ch); fflush(stdin); continue; } }while ((ch != 'n') && (ch != 'N')); break; }else { *head = (*head)->next; } } *head = temp; printf ("\nPictures after the update.\n"); printf ("------------------------------\n"); while(*head){ printf ("Code: %s\n", (*head)->code); printf ("Author: %s\n", (*head)->AuthorName); printf ("Painting: %s\n", (*head)->PaintingName); printf ("Price: %.2lf\n", (*head)->Price); printf ("Year: %d\n", (*head)->year); printf ("------------------------------"); printf ("\n"); *head = (*head)->next; } *head = temp; printf ("\nDo you want to update another painting? (Y\\N): "); scanf("%c", &ch); fflush(stdin); if ((ch == 'y') || (ch == 'Y')) goto updating; if (remove("Paintings.bin") != 0){ printf ("Error deleting the old file."); exit(4); } Writing(*head, 4); } void PrintAllPaintings(Painting **head){ Painting *p, *q, *top; int flag = 1; if( (top = (Painting *) malloc(sizeof(Painting))) == NULL) { printf ("Memory Allocation error.\n"); exit(23); } top->next = *head; if( *head != NULL && (*head)->next != NULL ) { while( flag ) { flag = 0; q = top; p = top->next; while( p->next != NULL ) { if( (strcmp(p->AuthorName, p->next->AuthorName)) > 0) { q->next = list_switch( p, p->next ); flag = 1; }else if( (strcmp(p->AuthorName, p->next->AuthorName)) == 0){ if (p->Price < p->next->Price){ q->next = list_switch( p, p->next ); flag = 1; } } q = p; if( p->next != NULL ) p = p->next; } } } p = top->next; *head = p; free(top); printf ("\nSorted list is:\n\n"); while(*head){ printf ("Code: %s\n", (*head)->code); printf ("Author: %s\n", (*head)->AuthorName); printf ("Painting: %s\n", (*head)->PaintingName); printf ("Price: %.2lf\n", (*head)->Price); printf ("Year: %d\n", (*head)->year); printf ("------------------------------"); printf ("\n"); *head = (*head)->next; } *head = p; p = FreeAll(&(*head)); free(p); } Painting *list_switch( Painting *l1, Painting *l2 ) { l1->next = l2->next; l2->next = l1; return l2; } void Writing (Painting *listPainting, int choice){ FILE *fp; Painting *temp; int i, j, k; temp = listPainting; if ((fp = fopen ("Paintings.bin", "ab")) == NULL){ printf ("\nError opening file for adding"); exit(5); } while (temp){ i = sizeof(temp->AuthorName); j = sizeof(temp->PaintingName); k = sizeof(temp->code); if ((fwrite (&k, sizeof(int), 1, fp)) != 1){ printf ("\nError writing in file!"); exit (6); } if ((fwrite (&temp->code, sizeof(char), k, fp)) != k){ printf ("\nError writing in file!"); exit (7); } if ((fwrite (&i, sizeof(int), 1, fp)) != 1){ printf ("\nError writing in file!"); exit (8); } if ((fwrite (&temp->AuthorName, sizeof(char), i, fp)) != i){ printf ("\nError writing in file!"); exit (9); } if ((fwrite (&j, sizeof(int), 1, fp)) != 1){ printf ("\nError writing in file!"); exit (10); } if ((fwrite (&temp->PaintingName, sizeof(char), j, fp)) != j){ printf ("\nError writing in file!"); exit (11); } if ((fwrite (&temp->Price, sizeof(double), 1, fp)) != 1){ printf ("\nError writing in file!"); exit (12); } if ((fwrite (&temp->year, sizeof(int), 1, fp)) != 1){ printf ("\nError writing in file!"); exit (13); } temp = temp->next; } fclose(fp); if (choice == 1) printf ("\nWriting successful.\n"); if (choice == 2) printf ("\nDeleting successful.\n"); if (choice == 4) printf ("\nUpdating successful.\n"); temp = FreeAll(&temp); free(temp); } void Reading(int choice){ FILE *fp; Painting *curr, *first; int i, j, k; first = NULL; if ((fp = fopen ("Paintings.bin", "rb")) == NULL){ printf ("\nError opening file for reading!\n"); system("Pause"); exit (14); } while (1){ if ((curr = (Painting *) malloc (sizeof(Painting))) == NULL){ printf ("\nError allocating memory!"); exit (15); } if ((fread (&k, sizeof(int), 1, fp)) != 1){ free(curr); break; } if ((fread (&curr->code, sizeof(char), k, fp)) != k){ printf ("\nError reading from file1!"); exit (16); } if ((fread (&i, sizeof(int), 1, fp)) != 1){ printf ("\nError reading from file2!"); exit (17); } if ((fread (&curr->AuthorName, sizeof(char), i, fp)) != i){ printf ("\nError reading from file2!"); exit (18); } if ((fread (&j, sizeof(int), 1, fp)) != 1){ printf ("\nError reading from file2!"); exit (3); } if ((fread (&curr->PaintingName, sizeof(char), j, fp)) != j){ printf ("\nError reading from file3!"); exit (19); } if ((fread (&curr->Price, sizeof(double), 1, fp)) != 1){ printf ("\nError reading from file4!"); exit (20); } if ((fread (&curr->year, sizeof(int), 1, fp)) != 1){ printf ("\nError reading from file5!"); exit (21); } curr->next = first; first = curr; } fclose (fp); curr = first; printf ("\nReading successful.\n"); if (choice == 2) deletePainting(&curr); if (choice == 3) PrintAllPaintings(&curr); if (choice == 4) updatePainting(&curr); } Painting *FreeAll (Painting **head){ Painting *temp, *p; for (temp = *head; temp != NULL;){ p = temp; temp = temp->next; free(p); } *head = NULL; return *head; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_int.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: larosale <larosale@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/06/08 11:40:15 by larosale #+# #+# */ /* Updated: 2020/06/19 14:34:04 by larosale ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdint.h> #include <stddef.h> #include "libftprintf.h" /* ** Handles width and flags in the specification, pointed to by "specs". ** Mofifies the "input" string accordingly and outputs the resulting string. ** Reallocates memory when needed for the resulting string. */ static char *handle_width_and_flags(t_specs *specs, int *sign, char *input) { char *output; char *temp; int excess; output = input; excess = specs->width - ft_strlen(input); (specs->flags_plus || specs->flags_space || *sign) ? excess-- : 0; if (excess > 0 && specs->flags_zero && !specs->flags_minus && !specs->precision_set) output = ft_strpad(input, '0', -1 * excess, 1); else if (excess > 0 && specs->flags_minus) output = ft_strpad(input, ' ', excess, 1); temp = output; *sign ? output = ft_strpad(temp, '-', -1, 1) : 0; (!*sign && specs->flags_plus) ? output = ft_strpad(temp, '+', -1, 1) : 0; (!*sign && !specs->flags_plus && specs->flags_space) ? output = ft_strpad(temp, ' ', -1, 1) : 0; if (output && (excess = specs->width - ft_strlen(output)) > 0) { temp = output; output = ft_strpad(temp, ' ', -1 * excess, 1); } return (output); } /* ** Handles conversion of integer "*arg" to the string, taking the specs ** into account and returns the resulting string. Handles precision and calls ** "handle_width_and_flags" function to handle width and flags. ** Allocates memory needed for the string. */ static char *handle_conversion(t_specs *specs, intmax_t *arg, int *sign) { char *output; char *temp; int excess; output = NULL; if (specs->precision_set && specs->precision == 0 && *arg == 0 && !(output = ft_strdup(""))) return (NULL); else if (!output && !(output = ft_itoa_base((uintmax_t)(*arg), 0, 10, 0))) return (NULL); if (output && (excess = specs->precision - ft_strlen(output)) > 0) { temp = output; output = ft_strpad(temp, '0', -1 * excess, 1); } if (output && (specs->width > ft_strlen(output) || specs->flags_plus || *sign == -1 || specs->flags_space)) { temp = output; output = handle_width_and_flags(specs, sign, temp); } return (output); } /* ** Converts int argument to unsigned value and passes for further processing ** to the "handle_conversion" function. ** Prints the conversion result and returns the count of printed characters. ** Allocates and frees memory needed to store the resulting string. */ static int generate_result(t_specs *specs, intmax_t *arg) { char *result; int count_printed; int sign; sign = 0; if (*arg < 0) { sign = -1; *arg = -*arg; } if (!(result = handle_conversion(specs, arg, &sign))) return (-1); count_printed = ft_strlen(result); ft_putstr_fd(result, 1); free(result); return (count_printed); } /* ** Prints the resulting string of the ft_printf %d and %i conversions. ** Takes pointer to variadic arguments' list "args" as an argument and ** assigns the value of "args", converted to the respective int, to ** the "arg" variable for further processing in the "generate_result" ** function. ** Returns the count of characters printed. */ int print_int(t_specs *specs, va_list args) { intmax_t arg; specs->width == -1 ? specs->width = va_arg(args, int) : 0; specs->width < 0 ? specs->flags_minus = 1 : 0; specs->width < 0 ? specs->width *= -1 : 0; specs->precision == -1 ? specs->precision = va_arg(args, int) : 0; specs->precision < 0 ? specs->precision_set = 0 : 0; if (specs->length) { specs->length == HH ? arg = (signed char)(va_arg(args, int)) : 0; specs->length == H ? arg = (short)(va_arg(args, int)) : 0; specs->length == L ? arg = va_arg(args, long) : 0; specs->length == LL ? arg = va_arg(args, long long) : 0; specs->length == Z ? arg = va_arg(args, ssize_t) : 0; specs->length == J ? arg = va_arg(args, intmax_t) : 0; specs->length == T ? arg = va_arg(args, ptrdiff_t) : 0; } else arg = va_arg(args, int); return (generate_result(specs, &arg)); }
C
#define _CRT_SECURE_NO_WARNINGS #include "stdafx.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <locale.h> #include <conio.h> #include <Windows.h> // Вспомогательные функции: int not_a_stop_symbol(char sym) { if ((sym == ' ') || (sym == '.') || (sym == ',') || (sym == '!') || (sym == '?') || (sym == 0) || (sym == ':') || (sym == '-') || (sym == '\0')) { return 0; } return 1; } int correct_input() { int param = 0; char inpStr[1024]; char bufStub = 0; while (1) { bufStub = 0; if ((!scanf("%1023[^\n]%c", inpStr, &bufStub)) || bufStub != '\n') { getchar(); } else if (3 < strlen(inpStr)) printf("Слишком длинный ввод\n"); else if (!sscanf(inpStr, "%d%c", &param, &bufStub) || bufStub != '\n') printf("Ошибка ввода (неправильный формат)\n"); else return param;; } } void to_low(char * value) { for (int i = 0; i < strlen(value); i++) { value[i] = tolower(value[i]); } } // Работа с бинарным деревом поиска typedef struct NODE { char word[20]; struct NODE *left; struct NODE *right; struct NODE *parent; }NODE; NODE* NewNode(char * value, NODE *parent) { NODE* tmp_Node = (NODE*)malloc(sizeof(NODE)); tmp_Node->left = tmp_Node->right = NULL; strcpy(tmp_Node->word, value); tmp_Node->parent = parent; return tmp_Node; } void insert(NODE **head, char * value) { to_low(value); NODE *tmp_Node = NULL; if (*head == NULL) { *head = NewNode(value, NULL); return; } tmp_Node = *head; while (tmp_Node) { int cmp_res = strcmp(value, tmp_Node->word); if (cmp_res > 0) { if (tmp_Node->right) { tmp_Node = tmp_Node->right; continue; } else { tmp_Node->right = NewNode(value, tmp_Node); return; } } else if (cmp_res < 0) { if (tmp_Node->left) { tmp_Node = tmp_Node->left; continue; } else { tmp_Node->left = NewNode(value, tmp_Node); return; } } else { printf("\nДанное слово уже в словаре\n"); break; } } } int search(NODE *root, char * value) { while (root) { if (strcmp(root->word, value) > 0) { root = root->left; continue; } else if (strcmp(root->word, value) < 0) { root = root->right; continue; } else { return 1; } } return 0; } void printTree(NODE *root, int level) { if (root) { printTree(root->left, level + 1); printf("%s\n", root->word); printTree(root->right, level + 1); } } // Работа с файлом--------------------------------------------------------- int menu_for_file_existence() { int local_status; printf("● Выберите действие:\n1.Попробовать снова\n0.Выйти\n>> "); while (1) { local_status = correct_input(); if (local_status == 1) { return 1; } else if (local_status == 0) { return 0; } else { printf("неправильный ввод, попробуйте снова:\n"); } } } FILE *check_for_existence_of_a_file() { FILE *TEST_FILE; int status = 1; char filename[256]; while (status != 0) { printf("Введите имя файла, содержащего текст:\n>> "); scanf("%[^\n]s", filename); if (TEST_FILE = fopen(filename, "r")) { return TEST_FILE; } else { printf("Файл не найден\nПроверьте корректность написания имени файла\n"); status = menu_for_file_existence(); } } return NULL; } void checking_from_file_action(NODE * head) { FILE *FILE; FILE = check_for_existence_of_a_file(); if (FILE) { printf("Слова, написанные с ошибками:\n"); int i = 0; char text[100000]; if (fgets(text, 100000, FILE) == NULL) { printf("длина текста не может превышать 100000 символов\n"); return; } while (text[i]) { char word[20] = ""; int j = 0; while (not_a_stop_symbol(text[i]) && i < strlen(text)) { word[j] = text[i]; j++; i++; } i++; if (strcmp(word, "")) { to_low(word); int search_result = search(head, word); if (search_result == 0) { printf("%s\n", word); } } } fclose(FILE); printf("проверка успешно заврешена!\n"); } else { printf("Ошибка обработки файла\n"); } } void save_dictionary(FILE * dic, NODE *root, int level) { if (root) { fprintf(dic, "%s\n", root->word); save_dictionary(dic, root->left, level + 1); save_dictionary(dic, root->right, level + 1); } } // ---------------------------------------------------------------------------------- int main() { setlocale(LC_ALL, "Russian"); SetConsoleCP(1251); SetConsoleOutputCP(1251); NODE *dic_head = NULL; //выгрузка из dic FILE * dic; dic = fopen("dic.txt", "r"); if (dic == NULL) { printf("Ошибка чтения словаря"); return 5; } char word[20]; while (EOF != fscanf(dic, "%s", word)) { insert(&dic_head, word); } fclose(dic); // начало основного цикла программы int new_word_flag = 0; // флаг добавления нового слова в словарь while (1) { printf("Выберите действие:\n1. Проверка текста на орфографию\n2. Открытие словаря\n3. Добавление нового слова\n0. Выход\n>> "); int action = correct_input(); if (action == 1) { checking_from_file_action(dic_head); system("pause"); continue; } // end of action 1 if (action == 2) { printf("Словарь:\n"); printTree(dic_head, 0); printf("\n"); system("pause"); continue; } if (action == 3) { printf("Введите новое слово для добавления:\n>> "); { char new_word[50]; scanf("%s", new_word); if (strlen(new_word) < 21) { new_word_flag = 1; insert(&dic_head, new_word); } else { printf("Поддерживаются только слова длиной до 20 символов\n"); } } system("pause"); continue; } if (action == 0) { if (new_word_flag == 1) { // если было добавлено новое слово, то обновим словарь printf("обновление словаря...\n"); dic = fopen("dic.txt", "w"); save_dictionary(dic, dic_head, 0); fclose(dic); } printf("Завершение программы...\n"); system("pause"); break; } printf("неправильный ввод, попробуйте снова\n"); } return 0; }
C
#include "ev_header.h" #include <string.h> #include <stdio.h> #include <stdlib.h> struct function_table funtable; extern char *EV_LOG; static char mylog[512]; static struct table_entry *get_entry(struct function_table *table, struct se_symbol symbol) { if (table->entry_count < 1) { strcpy(mylog, "Low entry count: "); sprintf(mylog + strlen(mylog), "%d", table->entry_count); return NULL; } char symname[7]; memset(symname, 0, 7); memcpy(symname, symbol.sym, symbol.sym_size); uint8_t keyBytesH[4]; memcpy(keyBytesH, symname, 4); uint8_t keyBytesL[4]; memcpy(keyBytesL, symname + 4, 3); keyBytesL[3] = symbol.sym_size; uint32_t hKey = *(uint32_t *)keyBytesH; uint32_t lKey = *(uint32_t *)keyBytesL; uint32_t key = hKey + lKey; struct table_entry *node = table->entries; while (node != NULL) { if (node->key == key) return node; else if (node->key > key) node = node->left; else node = node->right; } if (node == NULL) { strcpy(mylog, "Failed to find entry for key: "); sprintf(mylog + strlen(mylog), "%lu.", key); } return node; } static int create_entry(struct function_table *table, struct table_entry **reference_entry) { int entryIndex = table->entry_count++; if (table->entry_count > table->entry_size) { int oldSize = table->entry_size; table->entry_size *= 2; struct table_entry *newEntries = calloc(sizeof(struct table_entry), (table->entry_size)); struct table_entry *oldEntries = table->entries; memcpy(newEntries, oldEntries, sizeof(struct table_entry) * (oldSize)); for (int i = 0; i < oldSize; i++) { if (newEntries[i].left != NULL) { newEntries[i].left = (newEntries[i].left - oldEntries) + newEntries; } if (newEntries[i].right != NULL) { newEntries[i].right = (newEntries[i].right - oldEntries) + newEntries; } } *reference_entry = (*reference_entry) - oldEntries + newEntries; free(table->entries); table->entries = newEntries; } return entryIndex; } static struct table_entry *put_entry(struct function_table *table, struct se_symbol symbol, se_function function) { char symname[7]; memset(symname, 0, 7); memcpy(symname, symbol.sym, symbol.sym_size); uint8_t keyBytesH[4]; memcpy(keyBytesH, symname, 4); uint8_t keyBytesL[4]; memcpy(keyBytesL, symname + 4, 3); keyBytesL[3] = symbol.sym_size; uint32_t hKey = *(uint32_t *)keyBytesH; uint32_t lKey = *(uint32_t *)keyBytesL; uint32_t key = hKey + lKey; if (table->entry_count < 1) { table->entries[0] = (struct table_entry){.key = key}; table->entry_count++; } sprintf(mylog + strlen(mylog), "(hash for %s:%lu)", symname, key); struct table_entry *destNode = table->entries; while (destNode->function != NULL) { if (destNode->key == key) { destNode->function = NULL; EV_LOG = "Replaced at least one function while starting up\r\n"; } else if (destNode->key > key) { if (destNode->left == NULL) { int entryIndex = create_entry(table, &destNode); destNode->left = table->entries + entryIndex; destNode->left->key = key; } destNode = destNode->left; } else { if (destNode->right == NULL) { int entryIndex = create_entry(table, &destNode); destNode->right = table->entries + entryIndex; destNode->right->key = key; } destNode = destNode->right; } } destNode->function = function; return destNode; } struct se_node *list_index_ptr(struct se_list *list, int index) { while (index-- > 0) { list = &list->next->list_val; } return list->element; } struct se_node *matrix_index_ptr(struct se_matrix matrix, int row, int column) { if (column >= matrix.columns) { EV_LOG = "Column index out of range."; return NULL; } if (row >= matrix.rows) { EV_LOG = "Row index out of range."; return NULL; } return list_index_ptr(&matrix.list->list_val, row * matrix.columns + column); } int get_list_size(struct se_list *list) { int list_size = 0; while (list != NULL) { list_size++; list = &list->next->list_val; } return list_size; } struct se_node matget(struct se_list *list) { struct se_node element = eval_object(list->element); if (element.tag != MATRIX) { sprintf(mylog, "Tried to matrix-index a non-matrix object!"); log_object(&element, mylog); EV_LOG = mylog; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } int row = list->next->list_val.element->int_val; int column = list->next->list_val.next->list_val.element->int_val; return *(matrix_index_ptr(element.matrix_val, row, column)); } struct se_node asmat(struct se_list *list) { struct se_node *source_list = list->element; int rows = list->next->list_val.element->int_val; int columns = list->next->list_val.next->list_val.element->int_val; int lsize = get_list_size(&source_list->list_val); if (rows * columns != lsize) { sprintf(mylog, "Tried to make a matrix from a non-conforming list: (%d*%d) != %d\r\n", rows, columns, lsize); EV_LOG = mylog; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } return (struct se_node){.tag = MATRIX, .matrix_val = {.rows = rows, .columns = columns, .list = source_list}}; } struct se_node listget(struct se_list *list) { struct se_node element = eval_object(list->next->list_val.element); if (element.tag != NUMBER) { EV_LOG = "List index must be a number."; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } int list_index = element.int_val; struct se_node list_element = eval_object(list->element); if (list_element.tag != NUMBER) { EV_LOG = "Tried to access a nonlist object."; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } return *(list_index_ptr(&list_element.list_val, list_index)); } struct se_node listsize(struct se_list *list) { struct se_node element = eval_object(list->element); if (element.tag != LIST) { EV_LOG = "Tried to get size of a nonlist object"; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } return (struct se_node){.tag = NUMBER, .int_val = get_list_size(&element.list_val)}; } struct se_node adds(struct se_list *list) { int r = eval_object(list->element).int_val; list = &list->next->list_val; while (list != NULL) { r += eval_object(list->element).int_val; list = &list->next->list_val; } return (struct se_node){.tag = NUMBER, .int_val = r}; } struct se_node subs(struct se_list *list) { int r = eval_object(list->element).int_val; list = &list->next->list_val; while (list != NULL) { r -= eval_object(list->element).int_val; list = &list->next->list_val; } return (struct se_node){.tag = NUMBER, .int_val = r}; } struct se_node muls(struct se_list *list) { int r = eval_object(list->element).int_val; list = &list->next->list_val; while (list != NULL) { r *= eval_object(list->element).int_val; list = &list->next->list_val; } return (struct se_node){.tag = NUMBER, .int_val = r}; } struct se_node divs(struct se_list *list) { int r = eval_object(list->element).int_val; list = &list->next->list_val; while (list != NULL) { r /= eval_object(list->element).int_val; list = &list->next->list_val; } return (struct se_node){.tag = NUMBER, .int_val = r}; } struct se_node matmul(struct se_list *list) { struct se_node mat1 = eval_object(list->element); if (mat1.tag != MATRIX) { EV_LOG = "Matrix multiplication must be between two matrix objects!"; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } struct se_node mat2 = eval_object(list->next->list_val.element); if (mat2.tag != MATRIX) { EV_LOG = "Matrix multiplication must be between two matrix objects!"; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } if (mat1.matrix_val.columns != mat2.matrix_val.rows) { sprintf(mylog, "Matrix multiplication must be between two matrix objects of shapes" "(M,N) and (N,P). Got (%d,%d) and (%d,%d)", mat1.matrix_val.rows, mat1.matrix_val.columns, mat2.matrix_val.rows, mat2.matrix_val.columns); EV_LOG = mylog; return (struct se_node){.tag = LIST, .list_val = {.element = NULL, .next = NULL}}; } int newmatR = mat1.matrix_val.rows; int newmatC = mat2.matrix_val.columns; int *values = calloc(sizeof(int), newmatR * newmatC); for (int r = 0; r < newmatR; r++) { for (int c = 0; c < newmatC; c++) { for (int j = 0; j < mat1.matrix_val.columns; j++) { int value = eval_object(matrix_index_ptr(mat1.matrix_val, r, j)).int_val; value *= eval_object(matrix_index_ptr(mat2.matrix_val, j,c)).int_val; values[r * newmatC + c] += value; } } } struct se_node *list_node = calloc(sizeof(struct se_node),1); list_node->tag = LIST; for(int i = 0; i < newmatR * newmatC; i++) { struct se_node *number_node = calloc(sizeof(struct se_node),1); number_node->tag = NUMBER; number_node->int_val = values[i]; add_to_list(list_node, number_node); } struct se_node matrix_node; matrix_node.tag = MATRIX; matrix_node.matrix_val.columns = newmatC; matrix_node.matrix_val.rows = newmatR; matrix_node.matrix_val.list = list_node; return matrix_node; } void init_map() { funtable = (struct function_table){.entries = calloc(sizeof(struct table_entry), 4), .entry_count = 0, .entry_size = 4}; strcpy(mylog, "adding add..."); put_entry(&funtable, (struct se_symbol){.sym = "ADD\0\0\0\0", .sym_size = 3}, adds); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding sub..."); put_entry(&funtable, (struct se_symbol){.sym = "SUB\0\0\0\0", .sym_size = 3}, subs); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding div..."); put_entry(&funtable, (struct se_symbol){.sym = "DIV\0\0\0\0", .sym_size = 3}, divs); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding mul..."); put_entry(&funtable, (struct se_symbol){.sym = "MUL\0\0\0\0", .sym_size = 3}, muls); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding lslen..."); put_entry(&funtable, (struct se_symbol){.sym = "LSLEN\0\0", .sym_size = 5}, listsize); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding lsget..."); put_entry(&funtable, (struct se_symbol){.sym = "LSGET\0\0", .sym_size = 5}, listget); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding asmat..."); put_entry(&funtable, (struct se_symbol){.sym = "ASMAT\0\0", .sym_size = 5}, asmat); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding matget..."); put_entry(&funtable, (struct se_symbol){.sym = "MATGET\0", .sym_size = 6}, matget); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "adding matmul..."); put_entry(&funtable, (struct se_symbol){.sym = "MATMUL\0", .sym_size = 6}, matmul); sprintf(mylog + strlen(mylog), "fcount:%d", funtable.entry_count); strcat(mylog, "DONE!\r\n"); EV_LOG = mylog; } void delete_object(struct se_node *rootw) { if (rootw->tag == LIST) { struct se_node *el = rootw->list_val.element; struct se_node *nx = rootw->list_val.next; free(rootw); if (el != NULL) delete_object(el); if (nx != NULL) delete_object(nx); } else if (rootw->tag == MATRIX) { struct se_node *list = rootw->matrix_val.list; free(rootw); if (list != NULL) delete_object(list); } else { free(rootw); } } void log_object(struct se_node *rootw, char *logBuffer) { switch (rootw->tag) { case NUMBER: sprintf(logBuffer + strlen(logBuffer), "%d", rootw->int_val); break; case SYMBOL: { char symname[7]; memset(symname, 0, 7); memcpy(symname, rootw->sym_val.sym, rootw->sym_val.sym_size); symname[rootw->sym_val.sym_size] = 0; sprintf(logBuffer + strlen(logBuffer), "'%s", symname); break; } case MATRIX: { struct se_matrix matrix = rootw->matrix_val; sprintf(logBuffer + strlen(logBuffer), "\r\n["); for (int r = 0; r < matrix.rows; r++) { for (int c = 0; c < matrix.columns; c++) { log_object(matrix_index_ptr(matrix, r, c), logBuffer); sprintf(logBuffer + strlen(logBuffer), " "); } if (r != matrix.rows - 1) sprintf(logBuffer + strlen(logBuffer), "\r\n "); } sprintf(logBuffer + strlen(logBuffer), "]"); break; } case LIST: { struct se_list *listNode = &rootw->list_val; sprintf(logBuffer + strlen(logBuffer), "("); log_object(listNode->element, logBuffer); while (listNode->next != NULL) { sprintf(logBuffer + strlen(logBuffer), " "); log_object(listNode->next->list_val.element, logBuffer); listNode = &listNode->next->list_val; } sprintf(logBuffer + strlen(logBuffer), ")"); break; } } } struct se_node eval_object(struct se_node *node) { switch (node->tag) { case LIST: { struct se_node *function = node->list_val.element; struct se_node result; if (function->tag != SYMBOL) { result = *node; } else { struct table_entry *func = get_entry(&funtable, function->sym_val); if (func != NULL) { result = func->function(&node->list_val.next->list_val); } else { strcat(mylog, "Failed to find function "); strcat(mylog, function->sym_val.sym); result = *node; } } return result; } default: return *node; } }
C
#include <stdio.h> int main() { printf("Hello World"); float x = 5; float z = 6 + 5; int n = 0; for (int i = 0;i < 10; i++) { cout << "Hello World"; << endl; } while (n != 0) { cout << 'a' << endl; } char c = 'a'; double output = p; std::cout << "This is a simple test \n" << std::endl; char c; printf("Enter a character: "); // Reads character input from the user scanf("%c", &c); // %d displays the integer value of a character // %c displays the actual character printf("ASCII value of %c = %d", c, c); return 0; }
C
#include "LDE.h" LDE *criaNo(int value) { LDE *novo = (LDE *)malloc(sizeof(LDE)); if (novo) { novo->prox = NULL; novo->prev = NULL; novo->value = value; } else { printf("Erro de alocacao de memoria.\n"); exit(1); } return novo; } LDE *novaLista() { LDE *l = (LDE *)calloc(1, sizeof(LDE)); if (!l) { printf("Erro de alocacao de memoria.\n"); exit(1); } return l; } void insereInicio(LDE *l, int value) { LDE *novo = criaNo(value); if (l->prox) { novo->prox = l->prox; l->prox->prev = novo; } else l->prev = novo; l->prox = novo; } int listaVazia(LDE *l) { return (l->prox) ? 0 : 1; } int ultimoElemento(LDE *l) { return (l->prox) ? l->prox->value : -1; } void removeFim(LDE *l) { if (!listaVazia(l)) { LDE *n = l->prev; l->prev = n->prev; if (l->prev) l->prev->prox = NULL; else l->prox = NULL; free(n); } } void imprime(LDE *l) { LDE *n = l->prox; while (n) { printf("%d ", n->value); n = n->prox; } printf("\n"); } void liberaLista(LDE *l) { while (l) { LDE *n = l; l = l->prox; free(n); } }
C
#include <stdio.h> #include <string.h> int main() { char a[20]; int i; int count=0; for(i=1;i<=5;i++) { scanf("%s",a); if(strstr(a,"FBI")!=NULL) printf("%d\n",i); else count++; if(count==5) printf("HE GOT AWAY!\n"); } return 0; }
C
#include <stdio.h> #include <math.h> #define NVERT 5 #define NPERM 24//number of permutations of vertices. Excluding cyclical permutations, (NVERT-1)! #define NPART 16 //The problem asks for a 16-digit string ==> 10 appears only once, so it must be in external node //It can be shown that both the sums of internal and external nodes must be multiples of NVERT --> limited number of partitions of 1-10 between internal and external nodes (2^(NVERT-1)) //It can also be shown that the constant sum of the lines C = (2*NVERT+1) + Sum(internal)/NVERT = 2*(2*NVERT+1) - Sum(external)/NVERT int genperm(int vpool[NVERT], int vertperm[NPERM][NVERT], int ind, int permnum){ int i,j,flag; if(ind==0){ for(i=0;i<NPERM;i++) vertperm[i][0] = vpool[0];//keep first element fixed to avoid cyclical perms return genperm(vpool,vertperm,1,0); } if(ind==NVERT) return permnum + 1; for(i=1;i<NVERT;i++){ flag=0; for(j=1;j<ind;j++) if(vertperm[permnum][j] == vpool[i]){ flag=1; break; } if(flag) continue; for(j=permnum;j<NPERM;j++) vertperm[j][ind] = vpool[i]; permnum = genperm(vpool,vertperm,ind + 1, permnum); if(permnum == NPERM) break; } return permnum; } void genpool(int pool[NPART][2*NVERT]){ int i, j, k, l, temp; for(i=0;i<2*NVERT;i++) for(j=0;j<NPART;j++) pool[j][i] = i+1;//no exchange for(i=0; i<NVERT-1; i++){//1 exchange temp = pool[i+1][i]; pool[i+1][i] = pool[i+1][i+5]; pool[i+1][i+5] = temp; } j=NVERT; for(i=0;i<NVERT-2;i++){//2 exchanges for(k=i+1;k<NVERT-1;k++){ temp = pool[j][i]; pool[j][i] = pool[j][i+5]; pool[j][i+5] = temp; temp = pool[j][k]; pool[j][k] = pool[j][k+5]; pool[j][k+5] = temp; j++; } } for(i=0;i<NVERT-3;i++){//3 exchanges for(k=i+1;k<NVERT-2;k++){ for(l=k+1;l<NVERT-1;l++){ temp = pool[j][i]; pool[j][i] = pool[j][i+5]; pool[j][i+5] = temp; temp = pool[j][k]; pool[j][k] = pool[j][k+5]; pool[j][k+5] = temp; temp = pool[j][l]; pool[j][l] = pool[j][l+5]; pool[j][l+5] = temp; j++; } } } for(i=0;i<NVERT-1;i++){//4 exchanges temp = pool[j][i]; pool[j][i] = pool[j][i+5]; pool[j][i+5] = temp; } return; } int main(){ int vertperm[NPERM][NVERT] = {0}, ext[NVERT], pool[NPART][2*NVERT], epool[NVERT], sols[10][2*NVERT] = {0}, tempsol[2*NVERT]; int i, j, k, partind, solind = 0; int sum; long solnums[10], maxnum = 0, poww; genpool(pool); for(partind=0;partind<NPART;partind++){ genperm(pool[partind], vertperm, 0, 0); sum = 0; for(i=0;i<NVERT;i++) sum += pool[partind][i]; sum /= 5; sum += 2 * NVERT + 1; for(i=0;i<NPERM;i++){ for(j=0;j<NVERT;j++){ ext[j] = 0; epool[j] = pool[partind][j+5]; } for(j=0;j<NVERT;j++){ for(k=0;k<NVERT;k++){ if(epool[k] && epool[k] + vertperm[i][j] + vertperm[i][(j+1) % 5] == sum){ ext[j] = epool[k]; epool[k] = 0; break; } } if(!ext[j]) break; } if(ext[NVERT-1]){ for(j=0;j<NVERT;j++){ sols[solind][j] = vertperm[i][j]; sols[solind][j+5] = ext[j]; } solind++; } } } // for(i=0;i<solind;i++){ // // printf("%2d) vert: ",i+1); // for(j=0;j<NVERT;j++) // printf("%d ", sols[i][j]); // printf(" ext: "); // for(j=0;j<NVERT;j++) // printf("%d ", sols[i][j+5]); // printf("\n"); // // } // printf("%d\n",solind); for(i=0;i<solind;i++){//reorder solutions starting from smallest external node k = 0; for(j=1;j<NVERT;j++) if(sols[i][j+NVERT] < sols[i][k+NVERT]) k = j; for(j=0;j<NVERT;j++){ tempsol[j] = sols[i][(j+k) % NVERT]; tempsol[j+5] = sols[i][(j+k) % NVERT + 5]; } for(j=0;j<2*NVERT;j++) sols[i][j] = tempsol[j]; } // for(i=0;i<solind;i++){ // // printf("%2d) vert: ",i+1); // for(j=0;j<NVERT;j++) // printf("%d ", sols[i][j]); // printf(" ext: "); // for(j=0;j<NVERT;j++) // printf("%d ", sols[i][j+5]); // printf("\n"); // // } for(i=0;i<solind;i++){//generate numbers corresponding to string of digits requested by the problem and find max poww = pow(10,15); solnums[i] = 0; for(j=0;j<NVERT;j++){ if(sols[i][j+NVERT] == 10) poww /=10; solnums[i] += sols[i][j+NVERT] * poww; poww /= 10; solnums[i] += sols[i][j] * poww; poww /= 10; solnums[i] += sols[i][(j+1) % NVERT] * poww; poww /= 10; } if (solnums[i] > maxnum) maxnum = solnums[i]; } // for(i=0;i<solind;i++) // printf("%ld\n",solnums[i]); printf("%ld\n",maxnum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define BLOCKSIZE 8 static void loop_opt() { int i = 0; int limit = 33; /* could be anything */ int blocklimit; /* The limit may not be divisible by BLOCKSIZE, * go as near as we can first, then tidy up. */ blocklimit = (limit / BLOCKSIZE) * BLOCKSIZE; /* unroll the loop in blocks of 8 */ while( i < blocklimit ) { printf("process(%d)\n", i); printf("process(%d)\n", i+1); printf("process(%d)\n", i+2); printf("process(%d)\n", i+3); printf("process(%d)\n", i+4); printf("process(%d)\n", i+5); printf("process(%d)\n", i+6); printf("process(%d)\n", i+7); /* update the counter */ i += 8; } /* * There may be some left to do. * This could be done as a simple for() loop, * but a switch is faster (and more interesting) */ if( i < limit ) { /* Jump into the case at the place that will allow * us to finish off the appropriate number of items. */ switch( limit - i ) { case 7 : printf("process(%d)\n", i); i++; case 6 : printf("process(%d)\n", i); i++; case 5 : printf("process(%d)\n", i); i++; case 4 : printf("process(%d)\n", i); i++; case 3 : printf("process(%d)\n", i); i++; case 2 : printf("process(%d)\n", i); i++; case 1 : printf("process(%d)\n", i); } } } static void loop_opt_for() { int max = 100; for(int i = max; i--;) { printf("i: %d\n", i); } } int main(int argc, char **argv) { loop_opt(); loop_opt_for(); system("pause"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_vertex.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: olaktion <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/06/25 14:03:58 by olaktion #+# #+# */ /* Updated: 2019/06/25 14:04:00 by olaktion ### ########.fr */ /* */ /* ************************************************************************** */ #include "player_stable.h" void parse_vertex(t_system *sys, t_list *list) { size_t s_ar; t_list *e; size_t vertex_num; size_t c; c = -1; s_ar = 0; vertex_num = 0; e = find_elem(list, "vertex"); vertex_num = content_len(e, "vertex"); sys->vertex = allocate_vertex(vertex_num); while (e && ++c < vertex_num) { if (validate_vertex((char *)e->content)) { sys->vertex[c].y = parse_ver_y((char *)e->content); sys->vertex[c].x_arr = parse_ver_x((char *)e->content, &s_ar); sys->vertex[c].x_arr_size = s_ar; sys->sum_vert_pair += s_ar; e = e->next; } else print_error("Error, bad vertex validation1."); } sys->sum_vert = vertex_num; } t_list *find_elem(t_list *list, char *elem) { while (list && !ft_strstr((char *)list->content, elem)) list = list->next; return (list); } size_t content_len(t_list *list, char *content) { size_t len; len = 0; while (list && ft_strstr((char *)list->content, content)) { len++; list = list->next; } return (len); } t_vertex *allocate_vertex(size_t size) { t_vertex *vert_arr; if (!(vert_arr = (t_vertex *)ft_memalloc(sizeof(t_vertex) * (size)))) print_error("Error, bad memory region"); return (vert_arr); } t_xy *pars_ver_par(char *data, t_system *sys, size_t *len) { t_xy *vertex_array; char **tmp; vertex_array = NULL; if (data) { tmp = ft_strsplit(data, ' '); if (two_len(tmp) >= 3 && !int_error(tmp)) { *len = two_len(tmp); vertex_array = parse_vertex_pair(sys, tmp, *len); } else print_error("Error, sector validation, bad vertex param"); two_del(&tmp); } return (vertex_array); }
C
#include <assert.h> #include "../common/alloca.h" int main() { char *b1 = alloca(13); int i; int lastoffs = 0; for(i = 0; i < 5; ++i) { char *bfs = alloca(24); int offset = b1 - bfs; memset(bfs, 0, 24); assert(offset > lastoffs); lastoffs = offset; } return 0; }
C
#include "./Include/mpu.h" #include <stdlib.h> #include <math.h> void _mpu_reset(pMPU* p) { uint8_t buf[] = { 0xFF, 0xAA, 0x52 }; HAL_UART_Transmit(p->huart, buf, sizeof(buf) / sizeof(buf[0]), 10); } void _mpu_acc(pMPU* p, float* x, float* y, float* z) { uint8_t buf[MPU_BUFSIZ]; uint8_t ptr = 0; HAL_UART_Receive(p->huart, buf, MPU_BUFSIZ, 20); while (buf[ptr] != 0x55 && buf[ptr + 1] != 0x51) { if (ptr < MPU_BUFSIZ - 2) ptr += 1; else break; } *x = *y = *z = 0.0F; if (ptr <= MPU_PAKSIZ) { if (buf[ptr] != 0x55 && buf[ptr + 1] != 0x51) return; uint8_t chksum = 0; for (uint8_t i = 0; i < MPU_PAKSIZ - 1; i++) chksum += buf[ptr + i]; if (chksum != buf[ptr + MPU_PAKSIZ - 1]) return; short tmp; tmp = (short) (buf[ptr + 3] << 8 | buf[ptr + 2]); *x = tmp / 32768.0F * p->gravity; tmp = (short) (buf[ptr + 5] << 8 | buf[ptr + 4]); *y = tmp / 32768.0F * p->gravity; tmp = (short) (buf[ptr + 7] << 8 | buf[ptr + 6]); *z = tmp / 32768.0F * p->gravity; tmp = (short) (buf[ptr + 9] << 8 | buf[ptr + 8]); p->temper = tmp / 340.0F + 36.25F; } } float _mpu_accsum(pMPU* p) { float x, y, z; _mpu_acc(p, &x, &y, &z); return sqrt(x * x + y * y + z * z); } MPUnit* MPUInit(UART_HandleTypeDef* huart, float G) { pMPU* p = malloc(sizeof(pMPU)); p->huart = huart; p->gravity = G; MPUnit* c = malloc(sizeof(MPUnit)); c->p = p; c->reset = &_mpu_reset; c->acc = &_mpu_acc; c->accsum = &_mpu_accsum; return c; }
C
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> int main(void) { int count = 0; pid_t pid; pid = fork(); if(pid < 0) { printf("error in fork!"); exit(1); } else if(pid == 0) { printf("I am the child process,the count is %d,my process ID is %d\n",count,getpid()); } else { printf("I am the parent,the count is %d,my process ID is %d\n",++count,getpid()); } return 0; }
C
#include<stdio.h> #include<stdlib.h> int a[10][10],vis[10],ex[10],n,j; void topo_dfs(int v) { vis[v]=1; for(int i=1;i<=n;i++) { if(a[v][i]==1&&vis[i]==0) topo_dfs(i); } ex[j++]=v; } int main() { int m,u,v; printf("enter no of vertices \n"); scanf("%d",&n); for(int i=1;i<=n;i++) { for(int j=1;j<=n;j++) a[i][j]=0; } printf("enter no of edges \n"); scanf("%d",&m); for(int i=1;i<=m;i++) { printf("enter an edge between 2 vertices\n"); scanf("%d%d",&u,&v); a[u][v]=1; } for(int i=1;i<=n;i++) vis[i]=0; for(int i=1;i<=n;i++) { if(vis[i]==0) topo_dfs(i); } printf("topological order by dfs method : \n"); for(int i=n-1;i>=0;i--) printf("%d --> ",ex[i]); }
C
// Demetrios Doumas 3/9/17 // Part 3 --Part2 // Copy the content of source.txt into destination1.txt and destination2.txt // Replace all 1s with As in source.txt into destination1.txt // Replace all 2s with Bs in source.txt into destination2.txt #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<string.h> #include<errno.h> #include<stdlib.h> int main(int argc, char* argv[]) { /////////////////////////////////////////////////////// File Descripters for Source, Destination1, and Destination2 files int size; // store size of source file int fd; // file descripter to source file int fd1; // file descripter to destination1 file int fd2;// file descripter to destination2 file fd=open("source.txt",O_RDONLY, S_IRWXU); fd1=open("destination1.txt",O_WRONLY,S_IRWXU); fd2=open("destination2.txt",O_WRONLY,S_IRWXU); //////////////////////////////////////////////////////////// Check if you are able to open these files if(fd == -1) //error opening file { printf("sorry, I couldn't open source file\n"); perror("open"); } else { printf("Source File is able to Open \n"); } if(fd1 == -1) //error opening file { printf("sorry, I couldn't open destination1 file\n"); perror("open"); } else { printf("Destination1 File is able to Open\n"); } if(fd2 == -1) //error opening file { printf("sorry, I couldn't open destination2 file\n"); perror("open"); } else { printf("Destination2 File is able to Open \n"); } /////////////////////////////////////// Get size of source.txt file ///////////////////////////////////////////////////////////////////////// FILE *fp =fopen("source.txt", "r"); // open the source file fseek(fp ,0,SEEK_END); //finds the end of the source file size = ftell(fp); // gives the file size of the source file rewind(fp); // Reposition the file handler fp to the beginng of the file fclose(fp); // closes the handler fp ////////////////////////////////////////////////////////////////////////// // Create two buffers to read the source content char buffer[100]; int num_of_loops = size/100; /////////////// //////////////////////////////////////////////////////////////////////////////////// // Hold read and write system call values int rt, rt2, ws, ws2; for (int i=0 ; i < num_of_loops ; i++) // read 100 Chars each iteration { rt = read(fd, buffer, 100); for (int j=0 ; j < 100 ; j++) { if (buffer[j] == '1') buffer[j]='A'; } ws = write (fd1,buffer,100); } int remainder = size%100; //Reading less than 100 characters at the end of the file char BUF[remainder]; read(fd, BUF, remainder); for (int u=0 ; u < remainder ; u++) { if (BUF[u] == '1') BUF[u]='A'; //Convert 1 to A if (u == remainder-1) // If reached the end start to write to the destination file. { write (fd1,BUF,remainder); // The less than 100 chars that were manipluated } } /////////////////////////////////////////////////////////////////////////////////////////////////// lseek(fd,0,SEEK_SET); /// Reset the file descripter fd to the begininng of the source file char bufferTwo[50]; int num_of_loops2= size/50; int remainder2 = size%50; for (int i=0 ; i < num_of_loops2 ; i++) // read 50 Chars each iteration { rt2 = read(fd, bufferTwo, 50); for (int j=0 ; j < 50 ; j++) { if (bufferTwo[j] == '2') bufferTwo[j]='B'; } ws2 = write (fd2,bufferTwo,50); } //Reading less than 50 characters at the end of the file char BUFF[remainder2]; read(fd, BUFF, remainder2); for (int u=0 ; u < remainder2 ; u++) { if (BUFF[u] == '2') BUFF[u]='B'; //Convert 2 to B if (u == remainder2-1) // If reached the end start to write to the destination file. { write (fd2,BUFF,remainder2); // The less than 50 chars that were manipluated } } /////////////////////////////////////////////////////////////////// /////////// close files close(fd); close(fd1); close(fd2); return 0; }
C
#include "sam.h" #include <stdio.h> #include "utils/print.h" #include "utils/delay.h" #define CONF_SERCOM_2_USART_BAUD_RATE 9600 #define CONF_SERCOM_0_USART_BAUD_RATE_REGISTER_VAL \ (65536 - ((65536 * 16.0f * (CONF_SERCOM_2_USART_BAUD_RATE)) / 120000000)) void initClocks(void); void initUSART(void); void initGPIO(void); int32_t SERCOM0_read(char *const buf, const uint32_t length); int32_t SERCOM0_write(const char *const buf, const uint32_t length); int32_t SERCOM0_IsDataAvailable(void); enum gpio_port { GPIO_PORTA, GPIO_PORTB, GPIO_PORTC, GPIO_PORTD, GPIO_PORTE }; int main(void) { char * buffer = "hello"; initClocks(); initUSART(); initGPIO(); print_init(); SERCOM0_write(buffer,5); //should be able to print now printf("this works\n"); /* Replace with your application code */ while (1) { //printf("this works\n"); } } void initGPIO(void) { // set UART RX input PORT->Group[GPIO_PORTA].WRCONFIG.reg = PORT_WRCONFIG_PMUX(MUX_PA09C_SERCOM0_PAD1) | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_PMUXEN | PORT_WRCONFIG_WRPINCFG | ((1 << 9) & 0xffff); // set UART TX output PORT->Group[GPIO_PORTA].WRCONFIG.reg = PORT_WRCONFIG_PMUX(MUX_PA08C_SERCOM0_PAD0) | PORT_WRCONFIG_WRPMUX | PORT_WRCONFIG_PMUXEN | PORT_WRCONFIG_WRPINCFG | ((1 << 8) & 0xffff); } void initUSART(void) { //unmask SERCOM0 in MCLK to enable clock to user interface MCLK->APBAMASK.bit.SERCOM0_ = 1; //connect GCLK3 with SERCOM0_SLOW running at 32khz //connect GLCK0 with SERCOM0_CORE running at 120MHz GCLK->PCHCTRL[SERCOM0_GCLK_ID_CORE].reg = GCLK_PCHCTRL_GEN_GCLK0 | GCLK_PCHCTRL_CHEN; GCLK->PCHCTRL[SERCOM0_GCLK_ID_SLOW].reg = GCLK_PCHCTRL_GEN_GCLK3 | GCLK_PCHCTRL_CHEN; //do a software reset of the module (write-synchronized) SERCOM0->USART.CTRLA.reg = SERCOM_USART_CTRLA_SWRST; while(SERCOM0->USART.SYNCBUSY.bit.SWRST); //configure USART mode and bit order SERCOM0->USART.CTRLA.reg = SERCOM_USART_CTRLA_MODE(1) | SERCOM_USART_CTRLA_RXPO(1) | SERCOM_USART_CTRLA_TXPO(0) | SERCOM_USART_CTRLA_DORD; //set character size to 8 SERCOM0->USART.CTRLB.bit.CHSIZE = 0; //setup baud rate SERCOM0->USART.BAUD.reg = CONF_SERCOM_0_USART_BAUD_RATE_REGISTER_VAL; //enable transmitter and receiver SERCOM0->USART.CTRLB.reg = SERCOM_USART_CTRLB_TXEN | SERCOM_USART_CTRLB_RXEN; while(SERCOM0->USART.SYNCBUSY.bit.CTRLB); //enable USART SERCOM0->USART.CTRLA.reg |= SERCOM_USART_CTRLA_ENABLE; while(SERCOM0->USART.SYNCBUSY.bit.ENABLE); } int32_t SERCOM0_write(const char *const buf, const uint32_t length) { uint32_t offset = 0; while(!(SERCOM0->USART.INTFLAG.bit.DRE)); do { SERCOM0->USART.DATA.reg = buf[offset]; while(!(SERCOM0->USART.INTFLAG.bit.DRE)); } while (++offset < length); while(!(SERCOM0->USART.INTFLAG.bit.TXC)); return (int32_t)offset; } int32_t SERCOM0_read(char *const buf, const uint32_t length) { uint32_t offset = 0; do { while(!(SERCOM0->USART.INTFLAG.bit.RXC)); buf[offset] = SERCOM0->USART.DATA.reg; } while (++offset < length); return (int32_t)offset; } int32_t SERCOM0_IsDataAvailable(void) { return (SERCOM0->USART.INTFLAG.reg & SERCOM_USART_INTFLAG_RXC) ? 1 : 0; } void initClocks(void) { /*-------CLOCK CONFIGURATION----------------------------------------------/ GCLK0 source: DPLL0 (120 MHz) GCLK0 sink: MCLK (CPU) GCLK2 source: DFLL48M (48 MHZ) GCLK2 sink: Peripheral core GCLK3 source: XOSC32k (32.768kHz) GCLK3 sink: Peripheral slow XOSC32k source: Clock input on PA01 & PA02 XOSC32k sink: DPLL0 XOSC32k sink: GCLK3 DPLL0 source: XOSC32k (32.768kHz) DPLL0 sink: GCLK0 (120MHz) DFLL48M source: GCLK3 DFLL48M sink: GCLK2 Steps to set up clocks in order: 1) Setup XOSC32k 2) Setup GCLK3 for 32kHz 3) Setup DPLL0 for 120MHz 4) Setup GCLK0 for 120MHz 5) Setup DFLL48M for 48MHz 6) Setup GCLK2 for 48MHz 7) Setup Core and slow clocks for Peripherals 8) Setup MCLK, including CLK_CPU and CLK_APBx, CLK_AHBx. */ //Set wait states NVMCTRL->CTRLA.bit.RWS = 5; //5ws for 120MHz //Gclk reset GCLK->CTRLA.bit.SWRST; //OSCILLATOR CONTROL //STEP 1) Setup XOSC32K OSC32KCTRL->XOSC32K.bit.CGM = 01; OSC32KCTRL->XOSC32K.bit.XTALEN = 1; OSC32KCTRL->XOSC32K.bit.EN32K = 1; OSC32KCTRL->XOSC32K.bit.ONDEMAND = 1; OSC32KCTRL->XOSC32K.bit.RUNSTDBY = 1; OSC32KCTRL->XOSC32K.bit.STARTUP = 0; OSC32KCTRL->XOSC32K.bit.ENABLE = 1; OSC32KCTRL->CFDCTRL.bit.CFDPRESC = 0; OSC32KCTRL->CFDCTRL.bit.SWBACK = 0; OSC32KCTRL->CFDCTRL.bit.CFDEN = 0; OSC32KCTRL->EVCTRL.bit.CFDEO = 0; // make sure osc32kcrtl is ready while (!OSC32KCTRL->INTFLAG.bit.XOSC32KRDY); //GCLK3 Control //Step 2) Setup GCLK3 for 32kHz GCLK->GENCTRL[3].reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_XOSC32K; //DPLL0 SETUP //Step 3) Setup DPLL0 for 120 MHz OSCCTRL->Dpll[0].DPLLCTRLB.bit.DIV = 1; OSCCTRL->Dpll[0].DPLLCTRLB.bit.DCOEN = 0; OSCCTRL->Dpll[0].DPLLCTRLB.bit.LBYPASS = 1; OSCCTRL->Dpll[0].DPLLCTRLB.bit.LTIME = 0; OSCCTRL->Dpll[0].DPLLCTRLB.bit.REFCLK = 1; //Sets input to XOSC32k OSCCTRL->Dpll[0].DPLLCTRLB.bit.WUF = 1; OSCCTRL->Dpll[0].DPLLRATIO.reg = (3<<16) + 0xe4d; OSCCTRL->Dpll[0].DPLLCTRLA.bit.ONDEMAND = 0; OSCCTRL->Dpll[0].DPLLCTRLA.bit.RUNSTDBY = 1; OSCCTRL->Dpll[0].DPLLCTRLA.bit.ENABLE = 1; //Per errata 2.13.1 while(!(OSCCTRL->Dpll[0].DPLLSTATUS.bit.CLKRDY == 1)) ; //GCLK0 Control //3) Setup DPLL0 for 120MHz GCLK->GENCTRL[0].reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_DPLL0; //Setup DFLL48M //5) Setup DFLL48M for 48MHz OSCCTRL->DFLLCTRLB.bit.MODE = 1; OSCCTRL->DFLLCTRLB.bit.WAITLOCK = 1; OSCCTRL->DFLLCTRLA.bit.ENABLE = 1; OSCCTRL->DFLLCTRLA.bit.ONDEMAND = 0; OSCCTRL->DFLLCTRLA.bit.RUNSTDBY = 1; //GCLK2 Control //Setup GCLK2 for 48MHz GCLK->GENCTRL[2].reg = GCLK_GENCTRL_GENEN | GCLK_GENCTRL_SRC_DFLL; GCLK->GENCTRL[0].reg = (0 << 16) | (0x21 << 8) | 7; // dpll0 = 7, enabled and standby = 0x21, divide by 1 while (GCLK->SYNCBUSY.bit.GENCTRL0) ; GCLK->GENCTRL[1].reg = (100 << 16) | (0x21 << 8) | 7; // dpll0 = 7, enabled and standby = 0x21, divide by 100 while (GCLK->SYNCBUSY.bit.GENCTRL1) ; MCLK->CPUDIV.reg = MCLK_CPUDIV_DIV_DIV1; }
C
#include<stdio.h> #include<string.h> main() { char string[10],i,*fp=fopen("file","r"); while(fscanf(fp,"%s",string)!=EOF && printf(" ")) for(i=strlen(string);i>=0;printf("%c",string[i--])); }
C
#include <stdio.h> #include <math.h> /*Operação soma*/ float soma(float x, float y) { return (x+y) ; } /*Operação subtração*/ float sub(float x, float y) { return (x-y) ; } /*Operação multiplicação*/ float multi(float x, float y) { return (x*y) ; } /*Operação divisão*/ float div(float x, float y) { return (x/y) ; } /*Operação potenciação*/ float pot(float x, float y) { return (pow(x, y)) ; } /*Seleção de opção*/ float opcao(int a, float x, float y) { switch (a) { case 1: return soma(x, y) ; case 2: return sub(x, y) ; case 3: return multi(x, y) ; case 4: return div(x, y) ; case 5: return pot(x, y) ; default: printf("Operação inválida") ; return -1 ; } } /*Função principal*/ int main() { int a; float x, y ; scanf("%d %f %f", &a, &x, &y) ; printf("%.2f\n", opcao(a, x, y)) ; return 0 ; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_space_wall.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hhoyl <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/03 19:06:41 by hhoyl #+# #+# */ /* Updated: 2021/04/03 19:06:44 by hhoyl ### ########.fr */ /* */ /* ************************************************************************** */ #include "../cub3d.h" /* **проверяем пустоту в стенах */ static int fo_norm(t_all *kuba, int i, int j) { if (kuba->map[i][j + 1] == ' ' || kuba->map[i][j + 1] == '\0' || kuba->map[i][j - 1] == ' ' || kuba->map[i][j - 1] == '\0' || kuba->map[i + 1][j] == ' ' || kuba->map[i + 1][j] == '\0' || kuba->map[i - 1][j] == ' ' || kuba->map[i - 1][j] == '\0' || kuba->map[i - 1][j - 1] == ' ' || kuba->map[i - 1][j - 1] == '\0' || kuba->map[i - 1][j + 1] == ' ' || kuba->map[i - 1][j + 1] == '\0' || kuba->map[i + 1][j + 1] == ' ' || kuba->map[i + 1][j + 1] == '\0' || kuba->map[i + 1][j - 1] == ' ' || kuba->map[i + 1][j - 1] == '\0') return (1); return (0); } /* **проверяем пустоту в стенах */ void check_space_in_wall(int size, t_all *kuba) { int i; int j; i = -1; while (++i != size) { j = 0; while (kuba->map[i][j] != '\0') { if ((i == 0 && kuba->map[i][j] == '0') || (i == size - 1 && kuba->map[i][j] == '0')) error("Error\nzero in last or first line check_zero", kuba); else if (kuba->map[i][j] == '0') { if (fo_norm(kuba, i, j)) error("Error\nCheck space in wall check_zero", kuba); } ++j; } } }
C
#include<stdio.h> int main() { int inta = 97; int intb = 98; printf("%d\n", intb-inta); int intc = 3; printf("%f\n", (float)intc); char chara = 'a'; char charb = 'b'; printf("%d\n", charb-chara); char charc = 3; printf("%f\n", (float)charc); }
C
/* ** Filename : db_manipulation.c ** ** Made by : Vincent GU�NIN ESGI - 3AL-1 ** ** Description : Contains the database manipulation functions */ /*================ INCLUDES ================*/ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include "../header/db_manipulation.h" #include "../header/general.h" #include "../header/table_manipulation.h" #include "../header/file_manager.h" #include "../header/directory_functions.h" #include "../header/string_array_functions.h" #include "../header/sql/query.h" //#include "../yaml/parser.c" #if _WIN32 #define CLEAR "cls" #define PAUSE "pause" #else #define CLEAR "clear" #define PAUSE "echo \"Please enter a character to continue ...\" && read _" #endif /*================ FUNCTIONS ================*/ /* Goal : Manage the database's manipulations Input : dbName (char*), name of the database we manipulate Output : void */ void databaseManipulationManager(char *dbName) { short menu; do{ menu = databaseManipulationManagerMenu(dbName); system(CLEAR); switch( menu ) { case 0: //Quitter le programme return; case 1: //Cr�er une table createTable(dbName); break; case 2: //Ouvrir une table openTableManager(dbName); break; case 3: //Lister toutes les tables displayTablesListManager(dbName); break; case 4: //Supprimer une base de donn�es dropDatabaseManager(dbName); return; case 5: createAttribut(dbName); break; case 6: handleSqlQueries(dbName); break; default: break; } system(CLEAR); }while( menu != 0 ); } /* Goal : display the menu for the database manipulation Input : dbName (char*), name of the database Output : short, choice of the user in the menu */ short databaseManipulationManagerMenu(char *dbName) { short length = 7; short choice; char *array[] = {"Quitter le programme", "Creer une table", "Ouvrir une table", "Lister toutes les tables", "Supprimer une base de donnees", "Definir des attributs", "Executer des requetes SQL"}; do{ system(CLEAR); displayMenu(dbName, length, array); printf("\nVotre choix : "); scanf("%hd", &choice); if( choice < 0 || choice > length ) { printf("Valeur non valide, Reessayer\n"); system(PAUSE); } }while( choice < 0 || choice > length ); return choice; } /* Goal : Remove all tables' files Input : dirName (char*), path of the database to destroy Output : short, state of the process : - 0, success - 1, error while opening the directory - 2, error while memory allocation - 3, error while deleting the file */ short deleteTableFiles(char *dirName) { char fileName[255]; char **tablesName = malloc(0); short tablesNameLength = 0; short funcState; short counter; funcState = getFilesInDirectory(&tablesNameLength, &tablesName, dirName); if( funcState != 0 ) { return funcState; } for( counter = 0; counter < tablesNameLength; counter++ ) { strcpy(fileName, dirName); strcat(fileName, tablesName[counter]); funcState = deleteFile(fileName); //Supprime le fichier table if( funcState != 0 ) { return 3; } } //Free tablesName freeStrArray(tablesNameLength, tablesName); return 0; } /* Goal : Drop a database Input : dbName (char*), name of the database to destroy Output : short, state of the function - 0, success - 1, error while opening the directory - 2, error while memory allocation - 3, error while deleting the table's file - 4, error while deleting the db's directory - 5, error while deleting the db's file - 6, error while concatening the strings */ short dropDatabase(char *dbName) { short dirLength = 100; char dirPath[15] = "resources\\"; char dirName[dirLength]; char fileName[255]; short funcState; short str1Length = 3; char *str1[] = {dirPath, dbName, "\\"}; short str2Length = 3; char *str2[] = {dirPath, dbName, ".yml"}; char **tableList; short tableListLength; short counter; if( concatenateSeveralStr(dirLength, dirName, str1Length, str1) != 0 ) { return 6; } /* if( dirExist(dirPath, dbName) == 1 ) { //Si le r�pertoire au nom de la base existe funcState = deleteTableFiles(dirName); //Supprime les fichiers table if( funcState != 0 ) { return funcState; } funcState = (short)rmdir(dirName); //Supprime le r�pertoire if( funcState != 0 ) { return 4; } } if( concatenateSeveralStr(255, fileName, str2Length, str2) != 0 ) { return 6; } funcState = (short)remove(fileName); //Supprime le fichier db if( funcState != 0 ) { return 5; } return 0; */ if( dirExist(dirPath, dbName) == 1 ) { //Si le répertoire au nom de la base existe //Récupère la liste des tables getTablesListManager(dirName, &tableListLength, &tableList); //Supprime toutes les tables for( counter = 0; counter < tableListLength; counter++ ) { if( dropTable(dbName, tableList[counter]) != 0 ) { return 3; } } //Supprime le répertoire de la base funcState = (short)rmdir(dirName); //Supprime le répertoire if( funcState != 0 ) { return 4; } } //Supprime le fichier de la base if( concatenateSeveralStr(255, fileName, str2Length, str2) != 0 ) { return 6; } funcState = (short)remove(fileName); //Supprime le fichier db if( funcState != 0 ) { return 5; } return 0; } /* Goal : Manage the db suppression Input : dbName (char*), name of the database to suppress Output : short, state of the process - 0, success - other, error */ short dropDatabaseManager(char *dbName) { short funcState; funcState = dropDatabase(dbName); if( funcState == 0 ) { printf("La base de donnees %s a ete supprimee avec succes.\n", dbName); }else{ printf("Erreur lors de la suppression de la base de donnees %s.\n", dbName); } system(PAUSE); system(CLEAR); return funcState; } /* * Goal : Init the created table file with the root node * Input : path (char*), path of the created file * Output : void */ void createTableFileInit(char* path) { Node *root = YAMLGetMapNode("structure"); YAMLSaveNode(root, path); YAMLFreeNode(root); } /* Goal : Create a table in database folder Input : db (char*), name of the db we manipulate tableName(char*), name of the table Output : int */ int createTableFile(char *db, char *tableName){ char tableFileName[255]; short strLength = 6; char *str[] = {"resources\\", db, "\\", tableName, "\\", "metadata.yml"}; concatenateSeveralStr(255, tableFileName, strLength, str); switch( createFile(tableFileName) ) { //cr�ation de la table dans le fichier de base de donn�es case 0: printf("Cette table existe deja.\n"); return 0; case 1: printf("Erreur lors de la creation de la table.\nL'emplacement ne doit pas etre accessible\n"); return 1; case 2: //Init le premier noeud printf("La table a ete creee avec succes.\n"); return 2; default: return 0; } } /* * Goal : Save the table into the yaml db file * Input : - dbName (char*), name of the database * - tableName (char*), name of the table * Output : void */ void addTableToDbFile(char* dbName, char* tableName) { Node *dbNode, *newTable, *name, *empty; char dbFilePath[255]; char *str[] = {"resources\\", dbName, ".yml"}; concatenateSeveralStr(255, dbFilePath, 3, str); //dbNode = YAMLParseFile(str); dbNode = YAMLGetChildAtIndex( YAMLParseFile(dbFilePath), 0 ); if(dbNode == NULL) { dbNode = YAMLGetSequenceNode(strdup("Tables")); } newTable = YAMLGetSequenceValueNode(); name = YAMLGetValueNode(strdup("name"), strdup(tableName)); empty = YAMLGetValueNode(strdup("empty"), strdup("yes")); YAMLAddChild(newTable, name); YAMLAddChild(newTable, empty); YAMLAddChild(dbNode, newTable); YAMLSaveNode(dbNode, dbFilePath); //YAMLFreeNode(newTable); YAMLFreeNode(dbNode); addColumns(dbName, tableName); } /* * Goal : Get the name of the table to create * Input : tableName (char*), name of the table * Output : void */ void askTableName(char* tableName) { ssize_t length = 0; size_t bufferSize = 100; do { flush(); printf("Saisir le nom de la table a creer : "); length = getline(&tableName, &bufferSize, stdin); tableName = trim(tableName); if( length <= 1 ) { //Y a-t'il d'autres conditions d'erreur ? printf("Le nom entre n'est pas valide.\n"); system(PAUSE); system(CLEAR); } } while (length <= 1); } /* Goal : Create a table Input : db (char*), name of the database we manipulate Output : void */ void createTable(char *db) { char tableName[100]; char tablePath[255]; char tableDirPath[255]; //Saisir le nom de la table askTableName(tableName); //Crée le chemin du répertoire table char *strDb[] = {"resources\\", db, "\\", tableName}; concatenateSeveralStr(255, tableDirPath, 4, strDb); //Créer le fichier de la table createDir(tableDirPath); if( createTableFile(db, tableName) == 2 ) { //Si la table a été créée avec succès //Créer le chemin du fichier char *strTable[] = {tableDirPath, "\\metadata.yml"}; concatenateSeveralStr(255, tablePath, 2, strTable); //Ajouter le nom dans le fichier db addTableToDbFile(db, tableName); } system(PAUSE); } /* Goal : Get the names of all tables created Input : - dirName (char*), path of the db directory - tableNamesLength (short*), length of tableNames (char***) - tableNames (char***), array to fill. Output : char, state of the treatment : - 0, success - 1, error while opening the directory - 2, error while memory allocation Require : - tableNames (char***) needs to be free. - tableNames (char***) needs to be initialized - malloc(0) works */ char getTablesList(char *dirName, short *tableNamesLength, char ***tableNames) { char funcState; funcState = getDirInDirectory(tableNamesLength, tableNames, dirName); if( funcState != 0 ) { return funcState; } return 0; } /* Goal : Get the names of all tables Input : - dirName (char*), path of the database's directory - resultArrayLength (short*), length of resultArray. - resultArray (char***), at the end of the function, this array contains the name of every database. Output : void Require : - resultArray char*** needs to be free. */ void getTablesListManager(char *dirName, short *resultArrayLength, char ***resultArray) { char **array; short arrayLength = 0; char funcState; array = malloc(0); //Initializing the pointer funcState = getTablesList(dirName, &arrayLength, &array); if( funcState == 1 ) { //Erreur lors de l'ouverture du r�pertoire printf("Impossible d'ouvrir le repertoire contenant les tables.\n"); return; } if( funcState == 2 ) { //Erreur lors de l'allocation m�moire printf("Une erreur s'est produite. Il est possible que la RAM de votre ordinateur soit insuffisante pour le traitement demande.\n"); return; } *resultArray = array; *resultArrayLength = arrayLength; } /* Goal : Display the tables' list Input : dirName (char*), path of the database's directory Output : void */ void displayTablesList(char *dirName) { char **list; short length; short counter; getTablesListManager(dirName, &length, &list); printf("Liste des tables creees :\n"); for( counter = 0; counter < length; counter++ ) { printf("\t%s\n", list[counter]); } } /* Goal : Manage the tables' list display Input : dbName (char*), name of the database Output : void */ void displayTablesListManager(char *dbName) { char dirName[255]; short strLength = 3; char *str[] = {"resources\\", dbName, "\\"}; concatenateSeveralStr(255, dirName, strLength, str); displayTablesList(dirName); system(PAUSE); system(CLEAR); } /* Goal : Manage the table opening Input : void Output : void */ void openTableManager(char *dbName) { //A tester en revenant char **list; short length; short choice; char table[70]; char dirName[255]; short strLength = 3; char *str[] = {"resources\\", dbName, "\\"}; concatenateSeveralStr(255, dirName, strLength, str); getTablesListManager(dirName, &length, &list); //R�cup�rer la liste des noms choice = openTableAskNumber(length, list); if( choice == 0 ) { system(CLEAR); return; } system(CLEAR); strcpy(table, list[choice - 1]); tableManipulationManager(dbName, table); } /* Goal : Ask the table to open Input : - length (short), length of array - array (char**), list of the tables' name Output : number of the table */ short openTableAskNumber(short length, char **array) { short counter; short choice; do{ printf("Liste des tables :\n"); printf("\t0. Retourner au menu precedent\n"); for( counter = 0; counter < length; counter++ ) { printf("\t%hd. %s\n", counter + 1, array[counter]); } printf("Entrer le numero de la table a ouvrir : "); scanf("%hd", &choice); if( choice < 0 || choice > length ) { printf("Valeur non valide, Reessayer\n"); system(PAUSE); system(CLEAR); } }while( choice < 0 || choice > length ); return choice; } /* * Goal : Add a table to a database * Input : void * Output : void * */ void testAddTable() { Node *newTable; Node *name, *status; Node *table = YAMLParseFile("resources\\test_Vincent.yml"); char tableName[50]; table = YAMLGetChildAtIndex(table, 0); if( YAMLIsUndefined(table) ) { //Si le noeud parent a pour type undefined (ne contient aucun enfant) YAMLFreeNode(table); table = YAMLGetSequenceNode("tables"); //On récupère une nouvelle séquence } printf("Entrer le nom de la table a creer : "); fflush(stdin); getInput(50, tableName); newTable = YAMLGetSequenceValueNode(); name = YAMLGetValueNode("name", tableName); status = YAMLGetValueNode("status", "empty"); YAMLAddChild(newTable, name); YAMLAddChild(newTable, status); YAMLAddChild(table, newTable); YAMLSaveNode(table, "resources\\test_Vincent.yml"); //YAMLFreeNode(name); //YAMLFreeNode(status); YAMLFreeNode(newTable); YAMLFreeNode(table); } /* * Goal : Create a Database and the associated file * Input : void * Output : void */ void testCreateDb() { Node *table = YAMLGetSequenceNode("tables"); YAMLSaveNode(table, "resources\\test_Vincent.yml"); YAMLFreeNode(table); } /* * Goal : Add attributs to columns line. * Input : str (char *) * Output : void * */ void createAttribut(char* dbName){ char *array[] = {"resources", "\\", dbName}; char **list; short length = 3; char path[255]; short choice; char table[100]; concatenateSeveralStr(255, path, length, array); getTablesListManager(path, &length, &list); //R�cup�rer la liste des noms choice = openTableAskNumber(length, list); if( choice == 0 ){ system(CLEAR); return; } strcpy(table, list[choice - 1]); definedAttributs(dbName, table); } /* * Goal : defined attribut to column. * Input : str (char *) * table (char *) * Output : void * */ void definedAttributs(char *dbName, char *table){ char *array[] = {"menu precedent", "clef primaire", "Valeur par defaut", "Auto increment"}; short length = 4; int choice; do{ displayMenu(table, length, array); printf("Votre choix: "); scanf("%d", &choice); system(CLEAR); }while(choice < 0 && choice >= length); switch(choice){ case 0: return; case 1: addCaracteristics(dbName, table, choice); break; case 2: addCaracteristics(dbName, table, choice); break; case 3: addCaracteristics(dbName, table, choice); break; default: return; } } /* * Goal : defined the primary key. * Input : dbName (char *) * table (char *) * Output : void * */ void addCaracteristics(char *dbName, char *table, int type){ char *array[] = {"resources", "/", dbName, "/", table, "/", "metadata.yml"}; char path[255]; char val[255]; short length = 7; int choice; Node *result; concatenateSeveralStr(255, path, length, array); Node *column = YAMLParseFile(path); result = YAMLGetChildByKey(column, "Structure"); choice = displayColumns(result); if( type == 1 ){ setCaracteristics(result, choice, "yes", path, type); }else if( type == 2 ){ do{ printf("Ecrire la valeur par defaut: "); getInput(255, val); }while(strcmp(val, "no") == 0); setCaracteristics(result, choice, val, path, type); }else if( type == 3 ){ setCaracteristics(result, choice, "yes", path, type); } system(PAUSE); system(CLEAR); } /* * Goal : display columns from yaml file. * Input : colums (Node *) * Output : choice of column * */ int displayColumns(Node *columns){ int i; int choice; char *value; Node *column; for( i = 0; i < YAMLGetSize(columns); i++ ){ column = YAMLGetChildAtIndex(columns, i); value = YAMLGetKey(column); printf("%d - %s\n", i, value); } do{ flush(); printf("Saisir le numéro de la colonne: "); scanf("%d", &choice); }while(choice >= YAMLGetSize(columns) || choice < 0); return choice; } /* * Goal : set values for columns caracteristics. * Input : result (Node *) * choice (int) * text (*char) * path (*char) * type (int) * Output : void * */ void setCaracteristics(Node *result, int choice, char *text, char *path, int type){ Node *column; Node *child; column = YAMLGetChildAtIndex(result, choice); child = YAMLGetChildAtIndex(column, type); YAMLSetValue(child, text); YAMLSaveNode(result, path); } /** * Handle SQL queries */ void handleSqlQueries(char *dbName) { if (dbName) { QueryResult *res; char *dbPath = concat(2, "./resources/", dbName); size_t QUERY_MAX_SIZE = 2048; char *buffer; long characters; buffer = (char *) malloc(QUERY_MAX_SIZE * sizeof(char)); if(buffer == NULL) { return; } system(CLEAR); flush(); while (1) { printf("Entrez une requete SQL (rien pour sortir) :\n"); characters = getline(&buffer, &QUERY_MAX_SIZE, stdin); if (characters == 1) { // for \n break; } res = SQLExecuteQuery(buffer, dbPath); SQLPrintQueryResult(res); SQLFreeQueryResult(res); } free(buffer); free(dbPath); system(CLEAR); } }
C
/* Listing B.6 (read-file.c) Read a File into a Buffer */ /* Read the contents of FILENAME into a newly allocated buffer. The size of the buffer is stored in *LENGTH. Returns the buffer, which the caller must free. If FILENAME doesn't correspond to a regular file. returns NULL. */ #include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <malloc.h> char *read_file(const char* filename, size_t* length) { int fd; struct stat file_info; char* buffer; /* Open the file. */ fd = open(filename, O_RDONLY); /* Get information about the file. */ fstat(fd, &file_info); *length = file_info.st_size; /* Make sure the file is an ordinary file. */ if (!S_ISREG(file_info.st_mode)) { /* It's not, so give up. */ close(fd); return NULL; } /* Allocate a buffer large enough to hold the file's contents. */ buffer = (char *)malloc(*length + 1); /* Read the file into the buffer. */ read(fd, buffer, *length); buffer[*length] = '\0'; /* Finish up. */ close(fd); return buffer; } int main (int argc, char *argv[]) { char *buf; size_t len; buf = read_file(argv[1], &len); printf("File length: %d\nFile content:\n%s--", len, buf); printf("\n--%d", buf[len]); free(buf); return 0; }
C
#include<stdio.h> struct singly { int info; struct singly *link; }; void main() { struct singly n1,n2,n3,n4; n1.info=20; n2.info=30; n3.info=50; n4.info=90; n1.link=&n2; n2.link=&n3; n3.link=&n4; n4.link=NULL; struct singly *start=&n1; struct singly *PTR; PTR=start; while(PTR!=NULL) { printf("%d->",PTR->info); PTR=PTR->link; } }
C
//AdjacencyMultilist邻接多重表 //邻接多重表是无向图的优化存储结构,方便对边进行操作 //顶点表 //datafirstedge //firstedge指向顶点data的序号(下标)与ivex的值相同的边 //边表 //ivexilinkjvexjlink //ivex和jvex表示某条边的两个顶点序号(顶点表的下标) //ilink表示指向包含ivex的另一条边, //ilink指向的边的jvex一定要和它本身的ivex的值相同,如果没有就为NULL //jlink表示指向包含jvex的另一条边, //jlink指向的边的jvex一定要和它本身的jvex的值相同,如果没有就为NULL //邻接多重表与邻接表的差别,仅仅是在于同一条边在邻接表中用两个结点表示, //而在邻接多重表中只有一个结点,这样对边的操作就方便多了, //若要删除某图的一个边,只需要改变链接的指向或改成^即可。
C
#include <stdio.h> #include <stdlib.h> #include <math.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ //quanganh-me1-02-20200031 int main(int argc, char *argv[]) { int a,b,i,check; check=0; scanf("%d", &a); if(a<=1){ check=1; goto A; } b=sqrt(a); for(i=2; i<=b; i++){ if(a%i==0){ check=1; break; } } A: if(check==0) printf("La so nguyen to"); else printf("Khong phai so nguyen to"); }
C
#include <stdio.h> int main () { int a; scanf("%d", &a); printf("%s", (a % 2 == 0) ? "짝수" : "홀수"); // 선생님께선 입출력과연산자 테스트 중 제 질문에 삼항도 조건문이라고 하셧읍니다. }
C
#include <stdio.h> #define row 5 #define col 5 void place(int rows, int column, char color); int balloon[row][col]; int placeRow=row-1; void initialize(){ for(int i=0; i<row; i++) for(int j=0; j<col; j++) balloon[i][j]='-'; } void printBalloon(){ printf("\n"); for(int i=0; i<row; i++){ for(int j=0; j<col; j++) printf("%c ", balloon[i][j]); printf("\n"); } } int freeAbovePos(int r, int c){ int pos; if(r<0) return r; if(balloon[r][c]!='-'){ pos=freeAbovePos(r-1, c); }else{ return r; } return pos; } int findPos(int rows, int cols, char color){ int i=0; for(i=0; i<col; i++){ if(balloon[rows][i]!='-'){ continue; }else{ return i; } } place(rows-1, cols, color); placeRow--; } void place(int rows, int column, char color){ //printf("\n%d %d %c", placeRow, column, color); /*if(freeAbovePos(placeRow, column)>=0) ballon[freeAbovePos(placeRow, column)][column]=color; else printf("Can't Fill!\n"); */ if(balloon[rows][column]!='-'){ balloon[rows][findPos(rows, column, color)]=color; } else{ balloon[rows][column]=color; } } int main(void) { int colNo, choice; char color; initialize(); printBalloon(); do{ /*ballon[4][2]='R'; ballon[3][2]='R'; ballon[2][2]='R';*/ printf("\nEnter Column No: "); scanf("%d", &colNo); printf("\nEnter Color: "); scanf("\n%c", &color); place(placeRow, colNo-1, color); printBalloon(); printf("Do you wish to continue? 1/0 : "); scanf("%d", &choice); }while(choice); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <malloc.h> int main(int nargs, char ** args) { FILE * fin; FILE * fout; long i,ii; long j,jj; long idx; float f; float *slice; long iPlusOne; long sliceSize; long sliceSizePlusOne; long nextSliceSize; long nextSliceSizePlusOne; if (nargs!=5) return 1; sscanf(args[1],"%i",&i); sscanf(args[2],"%i",&j); slice= (float *)malloc(sizeof(float)*i*j*2); if (slice==NULL) return 1; fin=fopen(args[3],"rb"); fout=fopen(args[4],"wb"); if (fin==NULL || fout==NULL) return 1; iPlusOne= i+1; sliceSize= i*j; sliceSizePlusOne= sliceSize+1; nextSliceSize= sliceSize+i; nextSliceSizePlusOne= nextSliceSize+1;; while (fread(slice,sizeof(float),i*j*2,fin)==i*j*2) { for (idx=jj=0; jj<j; jj+=2, idx+=i) for (ii=0; ii<i; ii+=2, idx+=2) { f=(slice[idx]+slice[idx+1]+ slice[idx+i]+slice[idx+iPlusOne]+ slice[idx+sliceSize]+slice[idx+sliceSizePlusOne]+ slice[idx+nextSliceSize]+slice[idx+nextSliceSizePlusOne] )/8.0; fwrite(&f,sizeof(float),1,fout); } } fclose(fin); fclose(fout); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int *newArray(int size) { int *array; // A pointer! not an array declaration array = (int*) calloc(size, sizeof(int)); // Get 'size' items large enough to hold one int each return array; } void populate_array(int *array, int size) { // your code here using pointer arithmetic // populate the array such that array[i] = i, i < size for (int k = 0; k < size; k++) { *(array+k) = k; } } void print_array(int *array, int size) { // your code here using pointer arithmetic // print each element of the array for (int k = 0; k < size; k++) { printf("%d", *(array+k)); } printf("\n"); } void free_array(int *array, int size) { // Option a) // for (int i = 0; i < size; i++) { // free(*(array+i)); // } // Option b) // for (int i=0; i<size; i++) { // free(array+i); // } // Option c) free(array); } int *new2DArray(int sizeX, int sizeY) { int *array; // Still just a pointer! array = (int*) calloc(sizeX * sizeY, sizeof(int)); // cast the void pointer to an int pointer because Paco said so return array; } /* Fill in the 2d array USING POINTER ARITHMETIC so that the [i][j]th entry is equal to (3*i) + (7*j) */ void populate_2d_array(int *array, int sizeX, int sizeY) { // your code goes here for (int i = 0; i < sizeX; i++) { for (int j = 0; j < sizeY; j++) { *(array + i + (j * sizeX)) = 3*i + 7*j; } } } void print_2d_array(int *array, int sizeX, int sizeY); void part1() { int size; int *my_array; // get size printf("Please enter the size of the array\n"); scanf("%d",&size); getchar(); //create new array my_array = newArray(size); // null check if (my_array == NULL) { printf("Out of memory allocating array!\n"); exit(1); } populate_array(my_array, size); print_array(my_array, size); free_array(my_array, size); } void part2() { int sizeX, sizeY; int *my_2d_array; // get x printf("Please enter the X size of the array\n"); scanf("%d",&sizeX); getchar(); // get y printf("Please enter the Y size of the array\n"); scanf("%d",&sizeY); getchar(); // new 2d array my_2d_array = new2DArray(sizeX, sizeY); if (my_2d_array == NULL) { printf("out of mem"); exit(1); } populate_2d_array(my_2d_array, sizeX, sizeY); print_2d_array(my_2d_array, sizeX, sizeY); } int main() { char input[30]; printf("Enter function to run.\n"); scanf("%s", input); if (strcmp(input, "part1") == 0) { part1(); } else if (strcmp(input, "part2") == 0) { part2(); } else { printf("Unrecognized function name.\n"); } return 0; } void print_2d_array(int *array, int sizeX, int sizeY) { for (int i = 0; i < sizeX; i++) { for (int j = 0; j < sizeY; j++) { printf("%d ", *(array + i + (j * sizeX))); } printf("\n"); } }
C
// // order_search.c // demo // // Created by vision chen on 2021/3/28. // #include "order_search.h" void order_search(int* a,int len, int m) { int i; for (i = 0 ; i < len; i++) { if (a[i] == m) { printf("下标为:%d\n",i); break; } } if (i == len) { printf("sorry\n"); } }
C
/* 实现 ps aux | grep xxx 子进程:ps aux,子进程结束后, */ #include <unistd.h> #include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <wait.h> int main() { int pipefd[2]; int ret = pipe(pipefd); if (ret == -1) { perror("pipe"); exit(0); } pid_t pid = fork(); if (pid > 0) { //父进程 //关闭写端 close(pipefd[1]); //从管道读 char buf[1024] = {0}; int len = -1; while ((len = read(pipefd[0], buf, sizeof(buf) - 1)) > 0) { //过滤数据输出 printf("%s", buf); memset(buf, 0, 1024); } wait(NULL); } else if (pid == 0) { //子进程 //关闭读端 close(pipefd[0]); //文件描述符重定向 dup2(pipefd[1], STDOUT_FILENO); //ps aux execlp("ps", "ps", "aux", NULL); perror("execlp"); exit(0); } else { perror("fork"); exit(0); } return 0; }
C
#include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #include <signal.h> #include <sys/wait.h> #define TEMP_BUF_LEN 1024 #define BUFFER_MAX 1024 // Program functions // int main(int argc, char* argv[]); void signal_handler(int signum); void receiver(int sock); void sender(int sock, char* name); int connect_to_host(char* host, char* sender); // MAIN FUNCTIONS // int main(int argc, char* argv[]){ struct sigaction sigact; memset(&sigact, 0, sizeof(sigact)); sigact.sa_handler = signal_handler; sigaction(SIGINT, &sigact, NULL); int sock = connect_to_host(argv[1], argv[2]); receiver(sock); sender(sock,argv[3]); return 0; } // MODIFIED SIGNAL HANDLER FOR FORKED CHILD // void signal_handler(int signum){ int status; if(signum == SIGINT){ } } // RECEIVER FUNCTION // void receiver(int sock){ pid = fork(); if(pid < 0){ fprintf(stderr, "Fork failed!\n"); exit(EXIT_FAILURE); } if(pid == 0){ close(STDIN_FILENO); unsigned char* recv_buffer; while(1){ recv(sock, buffer, 1024); recv_comm_until(sock, &recv_buffer, "\n"); free(recv_buffer); recv_buffer = 0; } } return; } // SENDER FUNCTION // void sender(int sock, char* name){ char send_buffer[BUFFER_MAX]; char name_buffer[BUFFER_MAX]; sprintf(name_buffer, "[%s]: ", name); while(1){ fgets(send_buffer, BUFFER_MAX, stdin); // using strlen() to send the length is only useful if you are using // human readable ASCII characters send_comm(sock, name_buffer, strlen(name_buffer)); send_comm(sock, send_buffer, strlen(send_buffer)); // lots of assumptions here... memset(send_buffer, 0, BUFFER_MAX); } close(sock); return; } /* * The god function for connecting to any port via TCP * Created by Mark O'Neil (CS 360 instructor) */ int connect_to_host(char* host, char* service){ int sock; int ret; struct addrinfo hints; struct addrinfo* addr_ptr; struct addrinfo* addr_list; // Structs initialized on the stack are not initialized to all zeros...so we // need to do that manually here memset(&hints, 0, sizeof(hints)); hints.ai_socktype = SOCK_STREAM; // typically TCP (change to SOCK_DEGRAM for VDN) hints.ai_family = AF_UNSPEC; // IP4 or IP6, we don't care ret = getaddrinfo(host, service, &hints, &addr_list); // returning multiple things in c can be done by passing pointer pointers if(ret != 0){ fprintf(stderr, "Failed in getaddrinfo: %s\n",gai_strerror(ret)); exit(EXIT_FAILURE); } // Loop through all the answers we received from getaddrinfo() for(addr_ptr = addr_list; addr_ptr != NULL; addr_ptr){ sock = socket(addr_ptr->ai_family, addr_ptr->ai_sockettype, addr_ptr->ai_protocol); if(sock == -1){ // perror() or strerror() - when encountering an error from a system call // we can call these to get all the details // (need to include errno.h) perror("socket"); continue; } if(connect(sock, addr_ptr->ai_addr, addr_ptr->ai_addrlen) == -1){ perror("connect"); close(sock); continue; } break; } if(addr_ptr == NULL){ fprintf(stderr, "Failed to find a suitable address for connection\n"); exit(EXIT_FAILURE); } freeaddrinfo(addr_list); return sock; }
C
#include<stdio.h> int main() { int array[10],i; { for(i=0;;i++) { scanf("%d",&array[i]); if(array[i]==61) { printf("Brasilia\n"); } else if(array[i]==71) { printf("Salvador\n"); } else if(array[i]==11) { printf("Sao Paulo\n"); } else if(array[i]==21) { printf("Rio de Janerio\n"); } else if(array[i]==32) { printf("Juiz de Fora\n"); } else if(array[i]==19) { printf("Campinos\n"); } else if(array[i]==27) { printf("Vitoria\n"); } else if(array[i]==31) { printf("Belo Horizonta\n"); } else if(array[i]!= 31 || 27 || 19 || 32 || 21 || 71) { printf("DDD nao cadastrado\n"); } else break; } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> typedef struct lista_encadeada{ int conteudo; struct lista_encadeada *pc; } celula; void imp(celula *lista){ celula *aux; for(aux = lista->pc; aux!=NULL; aux = aux->pc){ printf("%d->", aux->conteudo); } printf("NULL\n"); } void ins(int x, celula *lista){ celula *nova; nova = malloc(sizeof(celula)); nova->conteudo = x; nova->pc = lista->pc; lista->pc = nova; } void *media(celula *lista){ celula *aux; for(aux = lista->pc; aux!=NULL; aux = aux->pc){ printf("%p ->", aux); } printf("NULL\n"); } int main(void){ setlocale(LC_ALL, "Portuguese"); celula *lista; celula cabeca; celula *invertida; lista = &cabeca; cabeca.pc = NULL; ins(1, lista); ins(2, lista); ins(3, lista); ins(4, lista); imp(lista); media(lista); imp(lista); system("pause"); }
C
#include <stdio.h> #include <stdlib.h> typedef struct PNode* PtrToPNode; typedef PtrToPNode Polynomial; struct PNode { int cof; int exp; struct PNode* Next; }; Polynomial ReadPoly(); Polynomial Add(Polynomial P1,Polynomial P2); Polynomial Mul(Polynomial P1,Polynomial P2); void Print(Polynomial P); int main(){ Polynomial P1,P2,P_Add,P_Mul; P1 = ReadPoly(); P2 = ReadPoly(); P_Add = Add(P1,P2); P_Mul = Mul(P1,P2); Print(P_Mul); printf("\n"); Print(P_Add); // Polynomial P_test; // P_test = ReadPoly(); // Print(P_test); return 0; } Polynomial ReadPoly() { int number,cof,exp; Polynomial P = (Polynomial)malloc(sizeof(struct PNode)); P->Next = NULL; Polynomial Q = P; Polynomial R; scanf("%d",&number); for(int i = 0;i<number;i++){ scanf("%d",&cof); scanf("%d",&exp); R = (Polynomial)malloc(sizeof(struct PNode)); R->cof = cof; R->exp = exp; R->Next = NULL; Q->Next = R; Q = Q->Next; } return P; } Polynomial Add(Polynomial P1,Polynomial P2) { Polynomial R1,R2; R1 = P1; R2 = P2; Polynomial P = (Polynomial)malloc(sizeof(struct PNode)); Polynomial Q,Tmp; P->Next = NULL; Q = P; while(R1->Next && R2->Next){ Tmp = (Polynomial)malloc(sizeof(struct PNode)); Tmp->Next = NULL; if(R1->Next->exp == R2->Next->exp){ Tmp->exp = R1->Next->exp; Tmp->cof = R1->Next->cof + R2->Next->cof; R1 = R1->Next; R2 = R2->Next; } else if(R1->Next->exp > R2->Next->exp){ Tmp->exp = R1->Next->exp; Tmp->cof = R1->Next->cof; R1 = R1->Next; } else{ Tmp->exp = R2->Next->exp; Tmp->cof = R2->Next->cof; R2 = R2->Next; } if(Tmp->cof){ Q->Next = Tmp; Q = Q->Next; } } while(R1->Next){ Tmp = (Polynomial)malloc(sizeof(struct PNode)); Tmp->Next = NULL; Tmp->exp = R1->Next->exp; Tmp->cof = R1->Next->cof; R1 = R1->Next; Q->Next = Tmp; Q = Q->Next; } while(R2->Next){ Tmp = (Polynomial)malloc(sizeof(struct PNode)); Tmp->Next = NULL; Tmp->exp = R2->Next->exp; Tmp->cof = R2->Next->cof; R2 = R2->Next; Q->Next = Tmp; Q = Q->Next; } return P; } Polynomial Mul(Polynomial P1,Polynomial P2) { int c,e; Polynomial P,Q,Tmp,R1,R2; P = (Polynomial)malloc(sizeof(struct PNode)); P->Next = NULL; Q = P; R1 = P1; R2 = P2; if(!R2 || !R1){ return P; } while(R2->Next){ Tmp = (Polynomial)malloc(sizeof(struct PNode)); Tmp->exp = R1->Next->exp + R2->Next->exp; Tmp->cof = R1->Next->cof * R2->Next->cof; Tmp->Next = NULL; Q->Next = Tmp; Q = Q->Next; R2 = R2->Next; } R1 = R1->Next; while(R1->Next){ Q = P; R2 = P2; while(R2->Next){ c = R1->Next->cof * R2->Next->cof; e = R1->Next->exp + R2->Next->exp; while(Q->Next && Q->Next->exp > e){ Q = Q->Next; } if(Q->Next && Q->Next->exp == e){ if(Q->Next->cof + c){ Q->Next->cof += c; } else{ Tmp = Q->Next; Q->Next = Tmp->Next; free(Tmp); } } else{ Tmp = (Polynomial)malloc(sizeof(struct PNode)); Tmp->cof = c; Tmp->exp = e; Tmp->Next = Q->Next; Q->Next = Tmp; Q = Q->Next; } R2 = R2->Next; } R1 = R1->Next; } return P; } void Print(Polynomial P) { if(P->Next==NULL){ printf("%d %d",0,0); } while(P->Next){ P = P->Next; if(P->Next) printf("%d %d ",P->cof,P->exp); else printf("%d %d",P->cof,P->exp); } }
C
#include<stdio.h> int main(void) { char ch='0'; int asc=ch; printf("ascii_value:\t %d\n", asc); }
C
#include "codage.H" int DecodeI2( unsigned char *Source) { int EntierC; EntierC = Q1((short)MOINS( Source[1] ), 7); EntierC += Q0((short)MOINS( Source[0] ), 7); return EntierC; } void To_2_oct(short l, unsigned char *tb) { tb[1] = (unsigned char)PLUS(P1(l, 7)); tb[0] = (unsigned char)PLUS(P0(l, 7)); } int Write_Msg_Feed(FILE* file, char *Msg, short Lg, char TypCmpr, int flush) { char chaine[3]; if(!file) return 0; To_2_oct(Lg+1, (unsigned char *)chaine); if (fprintf(file, "%-2.2s%c", chaine, TypCmpr) < 3) { return 0; } if((short)fwrite(Msg,1,Lg,file) < Lg) { return 0; } if(flush) fflush(file); return 1; }
C
#include <stdlib.h> #include <stdio.h> #include <stdint.h> unsigned int absolute(int x) { if(x < 0) x = x * (-1); return x; } unsigned int absolute_asm(int x); int main(int argc, char **argv) { unsigned int x = absolute_asm(-10); unsigned int y = absolute_asm(20); printf("x: %d, y: %d \n", x, y); return 0; }
C
#include <string.h> extern const char *ramdisk_path_array; extern const char *ramdisk_file_data_array; extern size_t ramdisk_file_size_array; extern const unsigned int ramdisk_num; const char *ramdisk_lookup(const char *path, size_t *nbytes) { int i; for (i = 0; i < ramdisk_num; i++) { if (strcmp(path, (&ramdisk_path_array)[i]) == 0) { *nbytes = (&ramdisk_file_size_array)[i]; return (&ramdisk_file_data_array)[i]; } } return NULL; } const char *ramdisk_lookup_as_string(const char *path) { int i; for (i = 0; i < ramdisk_num; i++) { if (strcmp(path, (&ramdisk_path_array)[i]) == 0) { return (&ramdisk_file_data_array)[i]; } } return NULL; }
C
/* * Various functions using read and stdio for handling reads and buffers * Written by: James Ross */ #include "input.h" /* * Uses the read() system call to read from the given file descriptor. * Result of the read is placed in the provided buffer. * nbyte is the size of the buffer. * * Reads nbyte-1 and places a '\0' value at end of the buffer * * Returns -1 on error, errno is set by the read system call */ ssize_t read_input(int fd, char *buff, int nbyte) { ssize_t bytes_read; --nbyte; bytes_read = read(fd, buff, nbyte); if (bytes_read < nbyte) buff[bytes_read] = '\0'; else buff[nbyte] = '\0'; return bytes_read; } /* * TODO: * Parses a given buffer to a given delimater and returns the string. * The place in the buffer will be saved and can be reset given the * proper flag. * * RESET_PBUFF to reset the buffer placement * KEEP_PBUFF to maintain the place in the given buffer * * If the buffer ends before a given delemiter the fd will be read again until * the delimiter is found or EOF has occured. * * The resulting string will always end in a null value, * read_input() function above is used to re-read the file descriptor. * */ int parse_buff(int fd, char *buff, int reset_flag, char delim) { static int bfpl = 0; char *res; if (reset_flag == RESET_BFPL) bfpl = 0; } /* clears the input buffer using variable char ch; and getchar ().*/ void clear_stdin() { char CH; while((CH = getchar()) != '\n' && CH != EOF); } /* end CLEAR_STDIN */ char* fgets_input(size_t nbyte, FILE *fp) { size_t len; char *input; char *res; assert(fp); input = calloc(nbyte, sizeof(char)); if (!input) return NULL; res = fgets(input, nbyte, fp); if (!res) { /* fgets returned nothing read */ free(input); return NULL; } /* replace newline with '\0', clearing STDIN if required */ len = strlen(input) - 1; if(input[len] == '\n') input[len] = '\0'; else clear_stdin(); /* allocate res to smallest ammount required for string */ len = strlen(input) + 1; res = calloc(len, sizeof(char)); if (!res) { free(input); return NULL; } /* copy contents of input into result */ strncpy(res, input, len); free(input); return res; } /* end lineInput */
C
#include <stdlib.h> #include <stdio.h> #include <limits.h> int maxTriProd(int *arr, int size) { int max = 0, prod; for (int i = 0; i < size; i++) for (int j = 0; j < size; j++) for (int k = 0; k < size; k++) { // controlliamo gli indici e non gli elementi // contenuti in quell'indice !(arr[i]) // perchè se l'array in input contiene più occorrenze // dello stesso elemento, dobbiamo considerarle if (i != j && j != k && i != k) { prod = arr[i] * arr[j] * arr[k]; if (prod > max) max = prod; } } return max; } int *sommePrefisse(int *arr, int size) { int *sp = malloc(sizeof(int) * size); sp[0] = arr[0]; for (int i = 1; i < size; i++) sp[i] = sp[i-1] + arr[i]; return sp; } void printArray(int *arr, int size) { for (int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } int main() { int size = 4; int arr[] = {1, -1, 9, 21}; // printf("%d\n", maxTriProd(arr, size)); printArray(sommePrefisse(arr, size), size); }
C
#include <linux/module.h> #include <linux/kernel.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> /* This is the structure we shall use to register our function */ static struct nf_hook_ops nfho; /* This is the hook function itself */ unsigned int hook_func(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) { /* This is where you can inspect the packet contained in the structure pointed by skb, and decide whether to accept or drop it. You can even modify the packet */ // In this example, we simply drop all packets return NF_DROP; /* Drop ALL packets */ } /* Initialization routine */ int init_module() { /* Fill in our hook structure */ nfho.hook = hook_func; /* Handler function */ nfho.hooknum = NF_INET_PRE_ROUTING; /* First hook for IPv4 */ nfho.pf = PF_INET; nfho.priority = NF_IP_PRI_FIRST; /* Make our function first */ nf_register_hook(&nfho); return 0; } /* Cleanup routine */ void cleanup_module() { nf_unregister_hook(&nfho); }
C
/* * main.c * * Created on: 10 Nov 2019 * Author: oriel */ #include "stdio.h" #include "math.h" #include "myMath.h" int main(){ double x; printf("Please insert a real number:\n"); scanf("%lf",&x); float ansi = sub(add(Exp((int)x),Pow(x,3)),2.0); float ansii = add(mul(x,3),mul(Pow(x,2),2)); float ansiii = sub(div(mul(Pow(x,3),4),5),mul(x,2)); printf("The value of f(x) = e^x + x^3 -2 at the point x = %0.4lf is %0.4f\n", x, ansi); printf("The value of f(x) = 3x + 2x^2 at the point x = %0.4lf is %0.4f\n", x, ansii); printf("The value of f(x) = (4x^3)/5 -2x at the point x = %0.4lf is %0.4f\n", x, ansiii); return 0; }
C
#include <LPC214X.H> #include "font.h" unsigned char c; unsigned char z=0; void ctrloff() { IOSET1=0x00000000; //rs=rw=en=cs1=cs2=0; } //DELAY FUNCTION void delay(unsigned int j) { int k; for(k=0;k<=j;k++) { long i; for(i=0;i<90000;i++); } } void displayon() { ctrloff(); IOSET0=0x0000003F; IOSET1=0x001C0000; delay(5); IOSET0=0x0000003F; IOSET1=0x000C0000; } void displayoff() { ctrloff(); IOSET0=0x0000003E; IOSET1=0x001C0000; delay(5); IOSET0=0x0000003E; IOSET1=0x000C0000; } void setcolumn(unsigned char y) { if(y<64) { ctrloff(); c=y; IOSET0=0x00000040 |(y&63); //0x40 represents Column 0 IOSET1=0x00140000; delay(5); IOSET0=0x00000040 |(y&63); IOSET1=0x00040000; } else { ctrloff(); c=y; IOSET0=0x00000040|((y-64)&63); //0x40 represents Column 0 IOSET1=0x00180000; delay(5); IOSET0=0x00000040|((y-64)&63); IOSET1=0X00080000; } } void setpage(unsigned char x) { ctrloff(); IOSET0=0x000000B8|x; //0xb8 represents Page 0 IOSET0=0x001C0000; delay(5); IOSET0=0x000000B8|x; //0xb8 represents Page 0 IOSET1=0x000C0000; } //Function to Scroll Strings void setstartline(unsigned char z) { ctrloff(); IOSET0=0x000000C0|z; //0xc0 represents Line 0 IOSET1=0x001C0000; delay(5); IOSET0=0x000000C0|z; //0xc0 represents Line 0 IOSET1=0x000C0000; } void lcddata(unsigned char *value,unsigned int limit) { unsigned int i; for(i=0;i<limit;i++) { if(c<64) { IOSET0=value[i]; IOSET1=0x00150000; delay(5); IOSET0=value[i]; IOSET1=0x00050000; c++; } else { setcolumn(c); IOSET0=value[i]; IOSET1=0x00160000; delay(5); IOSET0=value[i]; IOSET1=0x00060000; c++; } if(c>127) return; } } void lcdputs(unsigned char y,unsigned char x,unsigned char *str) { unsigned char i; unsigned int a; setcolumn(y); setpage(x); for(i=0;str[i]!=0;i++) { a=(*(str+i)-32); a*=5; lcddata(&font5x7[a],5); } } void clrlcd() { unsigned char i,j; for (i=0;i < 8;i++) { setpage(i); setcolumn(0); for (j= 0 ;j < 128; j++) lcddata(&z,1); } } unsigned char ar0[]="*************** "; unsigned char ar1[]="MINOR PROJECT"; unsigned char ar2[]="ELECTRONICS AND COMMUNICATION "; unsigned char ar3[]="************** "; int main() { IODIR1=0xffffffff; IOCLR1=0xffffffff; IODIR0=0xffffffff; IOCLR0=0xffffffff; { unsigned char i; clrlcd(); displayon(); setcolumn(0); setpage(0); lcdputs(0,1,ar0); lcdputs(0,2,ar1); lcdputs(0,3,ar2); lcdputs(0,4,ar3); delay(65); delay(65); for(i=0;i<5;i++) { displayoff(); delay(65); displayon(); delay(65); delay(65); } i=0; while(1) { setstartline(i++); //Function to Scroll Strings delay(40); } } }
C
#include <event2/listener.h> #include <event2/bufferevent.h> #include <arpa/inet.h> #include <unistd.h> #include <pthread.h> #include <signal.h> #include <stdbool.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <ctype.h> #if 0 gcc -o server.out libevent_server.c -levent #endif static char *SERVER_ADDR = "127.0.0.1"; static char *SERVER_BIND = "0.0.0.0"; static int SERVER_PORT = 9395; void error_cb(struct bufferevent *bufev, short events, void *arg) { if(events & BEV_EVENT_EOF) { printf("connection closed...\n"); } if(events & BEV_EVENT_ERROR) { printf("event error...\n"); } if (events & BEV_EVENT_CONNECTED) { printf("connected to client...\n"); return ; } bufferevent_free(bufev); } void read_cb(struct bufferevent *bufev, void *arg) { char buf[BUFSIZ] = "01234567890"; long read_len = bufferevent_read(bufev, buf, sizeof(buf)); buf[read_len] = '\0'; printf("read from client: \e[32m%s\e[0m", buf); for(int i = 0; i < read_len; ++i) { buf[i] = toupper(buf[i]); } bufferevent_write(bufev, buf, read_len); } void listener_cb(struct evconnlistener *listener, evutil_socket_t fd, struct sockaddr *sock, int socklen, void *arg) { struct event_base *base = (struct event_base *)arg; struct bufferevent *bufev = bufferevent_socket_new(base, fd, BEV_OPT_CLOSE_ON_FREE); bufferevent_setcb(bufev, read_cb, NULL, error_cb, NULL); bufferevent_enable(bufev, EV_READ | EV_PERSIST); } int main(int argc, char *argv[]) { struct sockaddr_in server_in; server_in.sin_family = AF_INET; server_in.sin_addr.s_addr = inet_addr(SERVER_BIND); server_in.sin_port = htons(SERVER_PORT); struct event_base *base = event_base_new(); struct evconnlistener *listener = evconnlistener_new_bind(base, listener_cb, base, LEV_OPT_REUSEABLE | LEV_OPT_CLOSE_ON_FREE, 10, (struct sockaddr *)&server_in, sizeof(server_in)); event_base_dispatch(base); evconnlistener_free(listener); event_base_free(base); return 0; }
C
/* * spi_tx.c * * Created on: 25 Nis 2020 * Author: ERCAN */ #include <string.h> #include "stm32f103xx.h" #include "spi_driver.h" /* * PA6 --> SPI1_MISO * PA7 --> SPI1_MOSI * PA5 -> SPI1_SCLK * PA4 --> SPI1_NSS */ void SPI1_GPIOInits(void) { GPIO_Handle_t SPIPins; SPIPins.pGPIOx = GPIOA; SPIPins.GPIO_PinConfig.GPIO_OutputMode = GPIO_MODE_ALT_PP; SPIPins.GPIO_PinConfig.GPIO_PinMode= GPIO_MODE_OUTPUT_SPEED_50M; SPIPins.GPIO_PinConfig.GPIO_InputMode = GPIO_INPUT_PUPD; SPIPins.GPIO_PinConfig.GPIO_PinNumber = GPIO_PIN_NO_5; //SCLK GPIO_Init(&SPIPins); SPIPins.GPIO_PinConfig.GPIO_PinNumber = GPIO_PIN_NO_7; //MOSI GPIO_Init(&SPIPins); //SPIPins.GPIO_PinConfig.GPIO_PinNumber = GPIO_PIN_NO_6; //MISO //GPIO_Init(&SPIPins); //SPIPins.GPIO_PinConfig.GPIO_PinNumber = GPIO_PIN_NO_4; //NSS //GPIO_Init(&SPIPins); } void SPI1_Inits(void){ SPI_Handle_t SPI1handle; SPI1handle.pSPIx = SPI1; SPI1handle.SPIConfig.SPI_BusConfig = SPI_BUS_CONFIG_FD; SPI1handle.SPIConfig.SPI_DeviceMode = SPI_DEVICE_MODE_MASTER; SPI1handle.SPIConfig.SPI_SClkSpeed = SPI_SCLK_SPEED_DIV2; SPI1handle.SPIConfig.SPI_DFF = SPI_DFF_8BITS; SPI1handle.SPIConfig.SPI_CPHA = SPI_CPHA_HIGH; SPI1handle.SPIConfig.SPI_CPOL = SPI_CPOL_HIGH; SPI1handle.SPIConfig.SPI_SSM = SPI_SSM_EN; SPI_Init(&SPI1handle); } int main() { char data[] = "Embedded System"; SPI1_GPIOInits(); SPI1_Inits(); //this makes NSS signal internally high and avoids MODF error SPI_SSIConfig(SPI1, ENABLE); //enable the SPI1 peripheral SPI_PeripheralControl(SPI1, ENABLE); //send data SPI_SendData(SPI1, (uint8_t*)data, strlen(data)); //SPI (or I2S) is busy in communication or Tx buffer is not empty while(SPI_GetFlagStatus(SPI1,SPI_FLAG_BUSY)); //disable the SPI1 peripheral SPI_PeripheralControl(SPI1, DISABLE); while(1); return 0; }
C
#include "sparse_interface.h" #include "iter_solve_sparse.h" #include <math.h> #include "solvers.h" #define ABS(value) ( (value) >=0 ? (value) : -(value) ) #define EPS 1e-14 static int iter = ITER_NUM; static double tolerance = ITER_TOL; static void print_vector_gsl(gsl_vector* A) { int i; for(i = 0; i < A->size; i++) { printf("\t%.4f\n",gsl_vector_get(A,i)); } } static void print_matrix_gsl(gsl_matrix* A) { int i,j; for(i = 0; i < A->size1; i++) { for(j = 0; j < A->size2; j++) { printf("\t%.4f\t",gsl_matrix_get(A,i,j)); } printf("\n"); } } void safe_gsl_vector_alloc(gsl_vector** v, const size_t n) { *v = gsl_vector_alloc(n); if(*v != NULL) return; else{ fprintf(stderr, "Failed to allocate memory on gsl_vector_alloc\n. Exiting now\n"); exit (0); } } void safe_gsl_vector_calloc(gsl_vector** v, const size_t n) { *v = gsl_vector_calloc(n); if(*v != NULL) return; else{ fprintf(stderr, "Failed to allocate memory on gsl_vector_alloc\n. Exiting now\n"); exit (0); } } gsl_vector* sparse_solve_cg(sparse_matrix* A , gsl_vector* b , gsl_vector* x0){ int iteration = 0 ; gsl_vector *r, *b1, *z, *p, *q, *M; gsl_vector *temp_v; sparse_vector *q_vec,*p_vec; double rho,rho1; double beta; double alpha; safe_gsl_vector_alloc(&r,b->size); safe_gsl_vector_alloc(&b1,b->size); safe_gsl_vector_alloc(&z,b->size); safe_gsl_vector_alloc(&p,b->size); safe_gsl_vector_alloc(&q,b->size); q_vec = (sparse_vector *)safe_malloc(sizeof(double)*q->size); p_vec = (sparse_vector *)safe_malloc(sizeof(double)*p->size); safe_gsl_vector_calloc(&temp_v,p->size); M = lh_get_inv_diag_sparse(A); if( !M ){ perror("Problem occured while allocating memory\n"); return NULL; } gsl_vector_memcpy(b1,b); /* r = b - Ax */ lh_matrix_vector_mul_and_sum_sparse( x0,A,b1,NON_TRANSP,-1.0,1.0); gsl_vector_memcpy(r , b1); gsl_vector_free(b1); while ( iteration < iter && ((lh_norm(r) / lh_norm(b)) > 1e-3 ) ){ if(!(iteration % 100)) printf("Iteration: %d Tolerance: %f\n",iteration,tolerance); iteration++; lh_diag_mul(z,r,M); // Solve Mz = r rho = lh_dot_product( r , z); if( iteration == 1 ){ gsl_vector_memcpy(p,z); // p = z } else{ beta = rho / rho1; //gsl_vector* temp_v = gsl_vector_calloc(p->size); /* p = z + beta*p */ lh_scalar_vector_mul(p, beta,p); // p = beta* p gsl_vector_add( p , z); // p = z + p } rho1 = rho; /* q = Ap */ //lh_matrix_vector_mul_sparse( p,A,q,NON_TRANSP); //gsl_vector_sub(q,q); //cs_gaxpy(A,gsl_vector_ptr(p,0),gsl_vector_ptr(q,0)); gsl_vector_sub(q, q); lh_gslVector_to_pointerVector(q,q_vec); lh_gslVector_to_pointerVector(p,p_vec); cs_gaxpy(A, p_vec, q_vec); lh_pointerVector_to_gslVector(q_vec, q); alpha = rho / lh_dot_product( p , q); /* x = x + alpha * p */ lh_scalar_vector_mul(temp_v , alpha , p); // temp_v = alha * p gsl_vector_add( x0 , temp_v); // x = x + temp_v /* r = r - alpha * q */ lh_scalar_vector_mul( temp_v , alpha , q); // temp_v = alpha* p gsl_vector_sub(r,temp_v); // r = r - temp_v } printf("Solution approximated in %d recursions",iteration); /* clean up */ gsl_vector_free(r); gsl_vector_free(z); gsl_vector_free(p); gsl_vector_free(M); gsl_vector_free(q); gsl_vector_free(temp_v); free(q_vec); free(p_vec); /* result is written in x0 */ //printf("going to print x0\n"); //print_vector_gsl(x0); return x0; } gsl_vector* sparse_solve_bicg(sparse_matrix* A , gsl_vector* b , gsl_vector* x0){ int iteration=0; double normb; double alpha,beta,rho,rho1,omega; sparse_vector *q_vec, *q_t_vec; sparse_vector *p_vec, *p_t_vec; sparse_matrix* A_T; // A transposed gsl_vector *r,*r_t; gsl_vector *M; // M_t is M itself. gsl_vector *p,*p_t; gsl_vector *z,*z_t; gsl_vector *q,*q_t; gsl_vector *temp; safe_gsl_vector_calloc(&r,b->size); safe_gsl_vector_calloc(&r_t,b->size); //M = gsl_vector_calloc(b->size); M = lh_get_inv_diag_sparse(A); // init m if( !M){ gsl_vector_free(r); gsl_vector_free(r_t); return NULL; } safe_gsl_vector_calloc(&p,b->size); safe_gsl_vector_calloc(&p_t,b->size); p_vec = (sparse_vector *)safe_malloc(b->size * sizeof(sparse_vector)); p_t_vec = (sparse_vector *)safe_malloc(b->size * sizeof(sparse_vector)); safe_gsl_vector_calloc(&z,b->size); safe_gsl_vector_calloc(&z_t,b->size); safe_gsl_vector_calloc(&q,b->size); safe_gsl_vector_calloc(&q_t,b->size); q_vec = (sparse_vector *)safe_malloc(b->size * sizeof(sparse_vector)); q_t_vec = (sparse_vector *)safe_malloc(b->size * sizeof(sparse_vector)); safe_gsl_vector_calloc(&temp,b->size); //A_T = cs_spalloc(A->m, A->n, A->nzmax, 1, 1); A_T = cs_transpose(A, 1); if( !A_T ){ fprintf(stderr,"Error in bicg whilie trying to transpose the matrix.\n"); return NULL; } gsl_vector_memcpy(temp,b); /* temp = b - Ax; */ lh_matrix_vector_mul_and_sum_sparse( x0,A,temp,NON_TRANSP,-1.0,1.0); // r = temp & r_t = r gsl_vector_memcpy(r, temp); gsl_vector_memcpy(r_t, r); normb = lh_norm(b); if(normb < EPS) normb =1; while( iteration < 5*iter && ( (lh_norm(r) / normb) > tolerance )){ iteration++; lh_diag_mul(z,r,M); // Solve M * z = r lh_diag_mul(z_t,r_t,M); // Solve M * z_t = r_t rho = lh_dot_product( r_t , z); if(ABS(rho) < EPS){ printf("Algorith failed\n"); exit(0); } if(iteration == 1){ gsl_vector_memcpy(p , z); // p = z gsl_vector_memcpy(p_t , z_t); // p_t = z_t } else{ beta = rho/rho1; lh_scalar_vector_mul(p, beta, p); // p = beta* p gsl_vector_add( p , z); // p = z + p lh_scalar_vector_mul(p_t, beta, p_t); // p_t = beta * p_t gsl_vector_add(p_t, z_t); // p_t = z_t + p_t } rho1 = rho; /* q = Ap */ gsl_vector_sub(q, q); lh_gslVector_to_pointerVector(q,q_vec); lh_gslVector_to_pointerVector(p,p_vec); cs_gaxpy(A, p_vec, q_vec); lh_pointerVector_to_gslVector(q_vec, q); /* q_t = A_T*p_t */ gsl_vector_sub(q_t, q_t); lh_gslVector_to_pointerVector(q_t,q_t_vec); lh_gslVector_to_pointerVector(p_t,p_t_vec); cs_gaxpy(A_T, p_t_vec, q_t_vec); lh_pointerVector_to_gslVector(q_t_vec, q_t); omega = lh_dot_product(p_t, q); if( ABS(omega) < EPS ){ printf("Algorith failed\n"); exit(0); } alpha = rho/omega; /* x = x + alpha*q; */ lh_scalar_vector_mul(temp , alpha , p); // temp = alha * p gsl_vector_add( x0 , temp); // x = x + temp /* r = r -alpha*q; r_t = r_t - alpha*q_t; */ lh_scalar_vector_mul( temp , alpha , q); // temp = alpha* q gsl_vector_sub(r,temp); // r = r - temp lh_scalar_vector_mul( temp , alpha , q_t); // temp = alpha* q_t gsl_vector_sub(r_t,temp); // r_t = r_t - temp_v } // free allocated memory space gsl_vector_free(r); gsl_vector_free(r_t); gsl_vector_free(M); gsl_vector_free(p); gsl_vector_free(p_t); gsl_vector_free(z); gsl_vector_free(z_t); gsl_vector_free(q); gsl_vector_free(q_t); gsl_vector_free(temp); free(q_vec); free(q_t_vec); free(p_vec); free(p_t_vec); cs_free(A_T); //printf("going to print x0\n"); //print_vector_gsl(x0); return x0; }
C
#include "sigprobe.h" #include "task.h" #include <unistd.h> #include <stdio.h> #include <signal.h> #include <setjmp.h> /* * flag to show if signal is recieved */ volatile static sig_atomic_t haveSig; /* * using it to jump back */ static jmp_buf env_prev; volatile static sig_atomic_t sig_ret; /* * FUNCTION HELPER * void resetHaveSig() * void setHaveSig() * * set haveSig to false or true */ void resetHaveSig() { haveSig=0; } void setHaveSig() { haveSig=1; } /* * FUNCTION SIG_HANDLER * void sigsegv_handler(int) */ void sigsegv_handler(int sig) { setHaveSig(); longjmp(env_prev,sig_ret); } void init_handler() { resetHaveSig(); signal(SIGSEGV,sigsegv_handler); signal(SIGBUS,sigsegv_handler); } /* * FUNCTION HELPER * void probe_address(void *) * * probe the address and cause the sigsegv */ void probe_address(void *addr) { if(haveSig) return; //fprintf(stderr,"probing address %lx\n\n",(uint64_t)addr); char *p = (char *)addr,q; if(setjmp(env_prev)==0) q=*p; } static const int STRIPE = (1<<PAGE_BITS); uint64_t probe(uint64_t hint, struct task_t * task,const char * name) { init_handler(); sig_ret=1; int ret = 0; uint64_t start=0,end=0,curr=hint; for(;haveSig==0;curr-=STRIPE)probe_address((void*)curr); start=(curr+2*STRIPE); init_handler(); curr=hint; for(;haveSig==0;curr+=STRIPE)probe_address((void*)curr); end=(curr-STRIPE); if(start>=end) return PROBE_FAILED; ret=end; fill_task(PID_UNUSED,start,end,0,0,"UNDEV","N/A",name,task); return ret; }
C
#include <stdio.h> #include "range.h" void check_int(int i, int target) { if (i == target) printf("==> success\n"); else printf("==> failure\n"); } void check_str(const char* s, const char* target) { if (strcmp(s, target) == 0) printf("==> success\n"); else printf("==> failure\n"); } int main() { { char tmpFileName[L_tmpnam + 1]; tmpnam(tmpFileName); FILE* fp = fopen(tmpFileName, "w"); fputs("1231\n", fp); fputs("1\n", fp); fputs("441\n", fp); check_int(0, fclose(fp)); check_int(1230, range(tmpFileName)); } { char tmpFileName[L_tmpnam + 1]; tmpnam(tmpFileName); FILE* fp = fopen(tmpFileName, "w"); check_int(0, fclose(fp)); check_int(1, range(tmpFileName)); } { char tmpFileName[L_tmpnam + 1]; tmpnam(tmpFileName); FILE* fp = fopen(tmpFileName, "w"); fputs("1231\n", fp); fputs("\n", fp); fputs("22\n", fp); check_int(0, fclose(fp)); check_int(-1, range(tmpFileName)); } }
C
/** * C语言永远只传值给函数 * * @Author: Wang An * @Date: 4/27/2020 8:55 PM */ #include <stdio.h> void swap(int a, int b); int main() { int a, b; printf("Please input two numbers:\n"); scanf("%d %d", &a, &b); printf("a = %d, b = %d\n", a, b); swap(a, b); printf("a = %d, b = %d\n", a, b); return 0; } void swap(int a, int b) { int t = a; a = b; b = t; }
C
--------------------------------------------------------------------------- David Vogel CS362 Assignment 3 Due Feb 3, 2016 Filename: coverage1.c I've appended the output from gcov for my 4 card tests below. I have removed all functions that were not covered at all. Here is the summary: Lines executed:23.05% of 590 Branches executed:26.14% of 417 Taken at least once:17.27% of 417 Calls executed:16.67% of 90 Since my tests only checked a small number of conditions and features, there is no reason to think that there would be anywhere near full coverage. Of interest, the following functions were all called and received 100% block coverage: "function compare called 120 returned 100% blocks executed 83%" "function initializeGame called 4 returned 100% blocks executed 88%" "function shuffle called 8 returned 100% blocks executed 93%" "function whoseTurn called 4 returned 100% blocks executed 100%" "function drawCard called 28 returned 100% blocks executed 36%" "function cardEffect called 4 returned 100% blocks executed 11%" "function discardCard called 3 returned 100% blocks executed 75%" "function updateCoins called 5 returned 100% blocks executed 80%" This indicates that none of the errors that were checked for in the functions were ever triggered and the functions exited successfully each time they were called. It is good to have these statistics so you know where top focus your efforts when testing. --------------------------------------------------------------------------- File 'dominion.c' Lines executed:23.05% of 590 Branches executed:26.14% of 417 Taken at least once:17.27% of 417 Calls executed:16.67% of 90 dominion.c:creating 'dominion.c.gcov' -: 0:Source:dominion.c -: 0:Graph:dominion.gcno -: 0:Data:dominion.gcda -: 0:Runs:4 -: 0:Programs:4 -: 1:#include "dominion.h" -: 2:#include "dominion_helpers.h" -: 3:#include "rngs.h" -: 4:#include <stdio.h> -: 5:#include <math.h> -: 6:#include <stdlib.h> -: 7: function compare called 120 returned 100% blocks executed 83% 120: 8:int compare(const void *a, const void *b) { 120: 9: if (*(int *) a > *(int *) b) branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 10: return 1; 120: 11: if (*(int *) a < *(int *) b) branch 0 taken 27% (fallthrough) branch 1 taken 73% 32: 12: return -1; 88: 13: return 0; -: 14:} --------------------------------------------------------------------------- function initializeGame called 4 returned 100% blocks executed 88% 4: 37:int initializeGame(int numPlayers, int kingdomCards[10], int randomSeed, struct gameState *state) { -: 38: int i, j, it; -: 39: //set up random number generator 4: 40: SelectStream(1); call 0 returned 100% 4: 41: PutSeed((long) randomSeed); call 0 returned 100% -: 42: //check number of players 4: 43: if (numPlayers > MAX_PLAYERS || numPlayers < 2) branch 0 taken 100% (fallthrough) branch 1 taken 0% branch 2 taken 0% (fallthrough) branch 3 taken 100% #####: 44: return -1; -: 45: //set number of players 4: 46: state->numPlayers = numPlayers; -: 47: //check selected kingdom cards are different 44: 48: for (i = 0; i < 10; i++) { branch 0 taken 91% branch 1 taken 9% (fallthrough) 440: 49: for (j = 0; j < 10; j++) { branch 0 taken 91% branch 1 taken 9% (fallthrough) 400: 50: if (j != i && kingdomCards[j] == kingdomCards[i]) branch 0 taken 90% (fallthrough) branch 1 taken 10% branch 2 taken 0% (fallthrough) branch 3 taken 100% #####: 51: return -1; -: 52: } -: 53: } -: 54: //initialize supply -: 55: //set number of Curse cards 4: 56: if (numPlayers == 2) branch 0 taken 100% (fallthrough) branch 1 taken 0% 4: 57: state->supplyCount[curse] = 10; #####: 58: else if (numPlayers == 3) branch 0 never executed branch 1 never executed #####: 59: state->supplyCount[curse] = 20; -: 60: else #####: 61: state->supplyCount[curse] = 30; -: 62: //set number of Victory cards 4: 63: if (numPlayers == 2) { branch 0 taken 100% (fallthrough) branch 1 taken 0% 4: 64: state->supplyCount[estate] = 8; 4: 65: state->supplyCount[duchy] = 8; 4: 66: state->supplyCount[province] = 8; -: 67: } -: 68: else { #####: 69: state->supplyCount[estate] = 12; #####: 70: state->supplyCount[duchy] = 12; #####: 71: state->supplyCount[province] = 12; -: 72: } -: 73: //set number of Treasure cards 4: 74: state->supplyCount[copper] = 60 - (7 * numPlayers); 4: 75: state->supplyCount[silver] = 40; 4: 76: state->supplyCount[gold] = 30; -: 77: //set number of Kingdom cards 84: 78: for (i = adventurer; i <= treasure_map; i++) { //loop all cards branch 0 taken 95% branch 1 taken 5% (fallthrough) 660: 79: for (j = 0; j < 10; j++) { //loop chosen cards branch 0 taken 94% branch 1 taken 6% (fallthrough) 620: 80: if (kingdomCards[j] == i) { //check if card is a 'Victory' Kingdom card branch 0 taken 6% (fallthrough) branch 1 taken 94% 42: 81: if (kingdomCards[j] == great_hall || kingdomCards[j] == gardens) { branch 0 taken 95% (fallthrough) branch 1 taken 5% branch 2 taken 0% (fallthrough) branch 3 taken 100% 2: 82: if (numPlayers == 2) branch 0 taken 100% (fallthrough) branch 1 taken 0% 2: 83: state->supplyCount[i] = 8; -: 84: else #####: 85: state->supplyCount[i] = 12; -: 86: } -: 87: else 38: 88: state->supplyCount[i] = 10; 40: 89: break; -: 90: } -: 91: else //card is not in the set choosen for the game 580: 92: state->supplyCount[i] = -1; -: 93: } -: 94: } -: 95: //supply intilization complete -: 96: //set player decks 12: 97: for (i = 0; i < numPlayers; i++) { branch 0 taken 67% branch 1 taken 33% (fallthrough) 8: 98: state->deckCount[i] = 0; 32: 99: for (j = 0; j < 3; j++) { branch 0 taken 75% branch 1 taken 25% (fallthrough) 24: 100: state->deck[i][j] = estate; 24: 101: state->deckCount[i]++; -: 102: } 64: 103: for (j = 3; j < 10; j++) { branch 0 taken 88% branch 1 taken 13% (fallthrough) 56: 104: state->deck[i][j] = copper; 56: 105: state->deckCount[i]++; -: 106: } -: 107: } -: 108: //shuffle player decks 12: 109: for (i = 0; i < numPlayers; i++) { branch 0 taken 67% branch 1 taken 33% (fallthrough) 8: 110: if (shuffle(i, state) < 0) call 0 returned 100% branch 1 taken 0% (fallthrough) branch 2 taken 100% #####: 111: return -1; -: 112: } 12: 113: for (i = 0; i < numPlayers; i++) { branch 0 taken 67% branch 1 taken 33% (fallthrough) 8: 114: state->handCount[i] = 0; 8: 115: state->discardCount[i] = 0; -: 116: } -: 117: //set embargo tokens to 0 for all supply piles 112: 118: for (i = 0; i <= treasure_map; i++) branch 0 taken 96% branch 1 taken 4% (fallthrough) 108: 119: state->embargoTokens[i] = 0; -: 120: //initialize first player's turn 4: 121: state->outpostPlayed = 0; 4: 122: state->phase = 0; 4: 123: state->numActions = 1; 4: 124: state->numBuys = 1; 4: 125: state->playedCardCount = 0; 4: 126: state->whoseTurn = 0; 4: 127: state->handCount[state->whoseTurn] = 0; -: 128: //Moved draw cards to here, only drawing at the start of a turn 24: 129: for (it = 0; it < 5; it++) branch 0 taken 83% branch 1 taken 17% (fallthrough) 20: 130: drawCard(state->whoseTurn, state); call 0 returned 100% 4: 131: updateCoins(state->whoseTurn, state, 0); call 0 returned 100% 4: 132: return 0; -: 133:} -: 134: --------------------------------------------------------------------------- function shuffle called 8 returned 100% blocks executed 93% 8: 135:int shuffle(int player, struct gameState *state) { 8: 136: int newDeck[MAX_DECK], newDeckPos = 0, card, i; 8: 137: if (state->deckCount[player] < 1) branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 138: return -1; 8: 139: qsort((void *) (state->deck[player]), state->deckCount[player], sizeof(int), compare); call 0 returned 100% -: 140: /* SORT CARDS IN DECK TO ENSURE DETERMINISM! */ 96: 141: while (state->deckCount[player] > 0) { branch 0 taken 91% branch 1 taken 9% (fallthrough) 80: 142: card = floor(Random() * state->deckCount[player]); call 0 returned 100% 80: 143: newDeck[newDeckPos] = state->deck[player][card]; 80: 144: newDeckPos++; 271: 145: for (i = card; i < state->deckCount[player] - 1; i++) branch 0 taken 70% branch 1 taken 30% (fallthrough) 191: 146: state->deck[player][i] = state->deck[player][i + 1]; 80: 147: state->deckCount[player]--; -: 148: } 88: 149: for (i = 0; i < newDeckPos; i++) { branch 0 taken 91% branch 1 taken 9% (fallthrough) 80: 150: state->deck[player][i] = newDeck[i]; 80: 151: state->deckCount[player]++; -: 152: } 8: 153: return 0; -: 154:} -: 155: --------------------------------------------------------------------------- function whoseTurn called 4 returned 100% blocks executed 100% 4: 244:int whoseTurn(struct gameState *state) { 4: 245: return state->whoseTurn; -: 246:} -: 247: --------------------------------------------------------------------------- function drawCard called 28 returned 100% blocks executed 36% 28: 385:int drawCard(int player, struct gameState *state) { -: 386: int count, deckCounter, i; 28: 387: if (state->deckCount[player] <= 0) {//Deck is empty branch 0 taken 0% (fallthrough) branch 1 taken 100% -: 388: //Step 1 Shuffle the discard pile back into a deck -: 389: //Move discard to deck #####: 390: for (i = 0; i < state->discardCount[player]; i++) { branch 0 never executed branch 1 never executed #####: 391: state->deck[player][i] = state->discard[player][i]; #####: 392: state->discard[player][i] = -1; -: 393: } #####: 394: state->deckCount[player] = state->discardCount[player]; #####: 395: state->discardCount[player] = 0;//Reset discard -: 396: //Shufffle the deck #####: 397: shuffle(player, state);//Shuffle the deck up and make it so that we can draw call 0 never executed #####: 398: if (DEBUG) //Debug statements -: 399: printf("Deck count now: %d\n", state->deckCount[player]); #####: 400: state->discardCount[player] = 0; -: 401: //Step 2 Draw Card #####: 402: count = state->handCount[player];//Get current player's hand count #####: 403: if (DEBUG) //Debug statements -: 404: printf("Current hand count: %d\n", count); #####: 405: deckCounter = state->deckCount[player];//Create a holder for the deck count #####: 406: if (deckCounter == 0) branch 0 never executed branch 1 never executed #####: 407: return -1; #####: 408: state->hand[player][count] = state->deck[player][deckCounter - 1];//Add card to hand #####: 409: state->deckCount[player]--; #####: 410: state->handCount[player]++;//Increment hand count -: 411: } -: 412: else { 28: 413: int count = state->handCount[player];//Get current hand count for player -: 414: int deckCounter; 28: 415: if (DEBUG) //Debug statements -: 416: printf("Current hand count: %d\n", count); 28: 417: deckCounter = state->deckCount[player];//Create holder for the deck count 28: 418: state->hand[player][count] = state->deck[player][deckCounter - 1];//Add card to the hand 28: 419: state->deckCount[player]--; 28: 420: state->handCount[player]++;//Increment hand count -: 421: } 28: 422: return 0; -: 423:} -: 424: --------------------------------------------------------------------------- function cardEffect called 4 returned 100% blocks executed 11% 4: 485:int cardEffect(int card, int choice1, int choice2, int choice3, struct gameState *state, int handPos, int *bonus) { -: 486: int i, j, k, x, index; 4: 487: int currentPlayer = whoseTurn(state); call 0 returned 100% 4: 488: int nextPlayer = currentPlayer + 1; 4: 489: int tributeRevealedCards[2] = {-1, -1}; -: 490: int temphand[MAX_HAND];// moved above the if statement 4: 491: int drawntreasure = 0; -: 492: int cardDrawn; 4: 493: int z = 0;// this is the counter for the temp hand 4: 494: if (nextPlayer > (state->numPlayers - 1)) branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 495: nextPlayer = 0; -: 496: //uses switch to select card and perform actions 4: 497: switch (card) { branch 0 taken 25% branch 1 taken 0% branch 2 taken 0% branch 3 taken 0% branch 4 taken 0% branch 5 taken 0% branch 6 taken 25% branch 7 taken 25% branch 8 taken 0% branch 9 taken 25% branch 10 taken 0% branch 11 taken 0% branch 12 taken 0% branch 13 taken 0% branch 14 taken 0% branch 15 taken 0% branch 16 taken 0% branch 17 taken 0% branch 18 taken 0% branch 19 taken 0% branch 20 taken 0% -: 498: case adventurer: 5: 499: while (drawntreasure < 2) { branch 0 taken 75% branch 1 taken 25% (fallthrough) 3: 500: if (state->deckCount[currentPlayer] < 1) //if the deck is empty we need to shuffle discard and add to deck branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 501: shuffle(currentPlayer, state); call 0 never executed 3: 502: drawCard(currentPlayer, state); call 0 returned 100% -: 503: //top card of hand is most recently drawn card. 3: 504: cardDrawn = state->hand[currentPlayer][state->handCount[currentPlayer] - 1]; 5: 505: if (cardDrawn == copper || cardDrawn == silver || cardDrawn == gold) branch 0 taken 33% (fallthrough) branch 1 taken 67% branch 2 taken 100% (fallthrough) branch 3 taken 0% branch 4 taken 0% (fallthrough) branch 5 taken 100% 2: 506: drawntreasure++; -: 507: else { 1: 508: temphand[z] = cardDrawn; 1: 509: state->handCount[currentPlayer]--; //this should just remove the top card (the most recently drawn one). 1: 510: z++; -: 511: } -: 512: } 3: 513: while (z - 1 >= 0) { branch 0 taken 50% branch 1 taken 50% (fallthrough) -: 514: // discard all cards in play that have been drawn 1: 515: state->discard[currentPlayer][state->discardCount[currentPlayer]++] = temphand[z - 1]; 1: 516: z = z - 1; -: 517: } 1: 518: return 0; -: 519: -: 520: case council_room: #####: 521: for (i = 0; i < 4; i++) //+4 Cards branch 0 never executed branch 1 never executed #####: 522: drawCard(currentPlayer, state); call 0 never executed #####: 523: state->numBuys++; //+1 Buy -: 524: //Each other player draws a card #####: 525: for (i = 0; i < state->numPlayers; i++) { branch 0 never executed branch 1 never executed #####: 526: if (i != currentPlayer) branch 0 never executed branch 1 never executed #####: 527: drawCard(i, state); call 0 never executed -: 528: } -: 529: //put played card in played card pile #####: 530: discardCard(handPos, currentPlayer, state, 0); call 0 never executed #####: 531: return 0; -: 532: -: 533: case feast: //gain card with cost up to 5 -: 534: //Backup hand #####: 535: for (i = 0; i <= state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 536: temphand[i] = state->hand[currentPlayer][i];//Backup card #####: 537: state->hand[currentPlayer][i] = -1;//Set to nothing -: 538: } -: 539: //Update Coins for Buy #####: 540: updateCoins(currentPlayer, state, 5); call 0 never executed #####: 541: x = 1;//Condition to loop on #####: 542: while (x == 1) {//Buy one card branch 0 never executed branch 1 never executed #####: 543: if (supplyCount(choice1, state) <= 0) { call 0 never executed branch 1 never executed branch 2 never executed #####: 544: if (DEBUG) -: 545: printf("None of that card left, sorry!\n"); #####: 546: if (DEBUG) -: 547: printf("Cards Left: %d\n", supplyCount(choice1, state)); -: 548: } #####: 549: else if (state->coins < getCost(choice1)) { call 0 never executed branch 1 never executed branch 2 never executed #####: 550: printf("That card is too expensive!\n"); call 0 never executed #####: 551: if (DEBUG) -: 552: printf("Coins: %d < %d\n", state->coins, getCost(choice1)); -: 553: } -: 554: else { #####: 555: if (DEBUG) -: 556: printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + -: 557: state->discardCount[currentPlayer]); #####: 558: gainCard(choice1, state, 0, currentPlayer);//Gain the card call 0 never executed #####: 559: x = 0;//No more buying cards #####: 560: if (DEBUG) -: 561: printf("Deck Count: %d\n", state->handCount[currentPlayer] + state->deckCount[currentPlayer] + -: 562: state->discardCount[currentPlayer]); -: 563: } -: 564: } -: 565: //Reset Hand #####: 566: for (i = 0; i <= state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 567: state->hand[currentPlayer][i] = temphand[i]; #####: 568: temphand[i] = -1; -: 569: } #####: 570: return 0; -: 571: -: 572: case gardens: #####: 573: return -1; -: 574: -: 575: case mine: #####: 576: j = state->hand[currentPlayer][choice1]; //store card we will trash #####: 577: if (state->hand[currentPlayer][choice1] < copper || state->hand[currentPlayer][choice1] > gold) branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed #####: 578: return -1; #####: 579: if (choice2 > treasure_map || choice2 < curse) branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed #####: 580: return -1; #####: 581: if ((getCost(state->hand[currentPlayer][choice1]) + 3) > getCost(choice2)) call 0 never executed call 1 never executed branch 2 never executed branch 3 never executed #####: 582: return -1; #####: 583: gainCard(choice2, state, 2, currentPlayer); call 0 never executed #####: 584: discardCard(handPos, currentPlayer, state, 0); //discard card from hand call 0 never executed -: 585: //discard trashed card #####: 586: for (i = 0; i < state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 587: if (state->hand[currentPlayer][i] == j) { branch 0 never executed branch 1 never executed #####: 588: discardCard(i, currentPlayer, state, 0); call 0 never executed #####: 589: break; -: 590: } -: 591: } #####: 592: return 0; -: 593: -: 594: case remodel: #####: 595: j = state->hand[currentPlayer][choice1]; //store card we will trash #####: 596: if ((getCost(state->hand[currentPlayer][choice1]) + 2) > getCost(choice2)) call 0 never executed call 1 never executed branch 2 never executed branch 3 never executed #####: 597: return -1; #####: 598: gainCard(choice2, state, 0, currentPlayer); call 0 never executed #####: 599: discardCard(handPos, currentPlayer, state, 0); //discard card from hand call 0 never executed -: 600: //discard trashed card #####: 601: for (i = 0; i < state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 602: if (state->hand[currentPlayer][i] == j) { branch 0 never executed branch 1 never executed #####: 603: discardCard(i, currentPlayer, state, 0); call 0 never executed #####: 604: break; -: 605: } -: 606: } #####: 607: return 0; -: 608: -: 609: case smithy: //+3 Cards 4: 610: for (i = 0; i < 3; i++) branch 0 taken 75% branch 1 taken 25% (fallthrough) 3: 611: drawCard(currentPlayer, state); call 0 returned 100% 1: 612: discardCard(handPos, currentPlayer, state, 0); //discard card from hand call 0 returned 100% 1: 613: return 0; -: 614: -: 615: case village: //+1 Card 1: 616: drawCard(currentPlayer, state); call 0 returned 100% 1: 617: state->numActions = state->numActions + 2; //+2 Actions 1: 618: discardCard(handPos, currentPlayer, state, 0); //discard played card from hand call 0 returned 100% 1: 619: return 0; -: 620: -: 621: case baron: #####: 622: state->numBuys++;//Increase buys by 1 #####: 623: if (choice1 > 0) {//Boolean true or going to discard an estate branch 0 never executed branch 1 never executed #####: 624: int p = 0;//Iterator for hand #####: 625: int card_not_discarded = 1;//Flag for discard set #####: 626: while (card_not_discarded) { branch 0 never executed branch 1 never executed #####: 627: if (state->hand[currentPlayer][p] == estate) {//Found an estate card branch 0 never executed branch 1 never executed #####: 628: state->coins += 4;//Add 4 coins to the amount of coins #####: 629: state->discard[currentPlayer][state->discardCount[currentPlayer]] = state->hand[currentPlayer][p]; #####: 630: state->discardCount[currentPlayer]++; #####: 631: for (; p < state->handCount[currentPlayer]; p++) branch 0 never executed branch 1 never executed #####: 632: state->hand[currentPlayer][p] = state->hand[currentPlayer][p + 1]; #####: 633: state->hand[currentPlayer][state->handCount[currentPlayer]] = -1; #####: 634: state->handCount[currentPlayer]--; #####: 635: card_not_discarded = 0;//Exit the loop -: 636: } #####: 637: else if (p > state->handCount[currentPlayer]) { branch 0 never executed branch 1 never executed #####: 638: if (DEBUG) { -: 639: printf("No estate cards in your hand, invalid choice\n"); -: 640: printf("Must gain an estate if there are any\n"); -: 641: } #####: 642: if (supplyCount(estate, state) > 0) { call 0 never executed branch 1 never executed branch 2 never executed #####: 643: gainCard(estate, state, 0, currentPlayer); call 0 never executed #####: 644: state->supplyCount[estate]--;//Decrement estates #####: 645: if (supplyCount(estate, state) == 0) call 0 never executed branch 1 never executed branch 2 never executed #####: 646: isGameOver(state); call 0 never executed -: 647: } #####: 648: card_not_discarded = 0;//Exit the loop -: 649: } -: 650: else #####: 651: p++;//Next card -: 652: } -: 653: } -: 654: else { #####: 655: if (supplyCount(estate, state) > 0) { call 0 never executed branch 1 never executed branch 2 never executed #####: 656: gainCard(estate, state, 0, currentPlayer);//Gain an estate call 0 never executed #####: 657: state->supplyCount[estate]--;//Decrement Estates #####: 658: if (supplyCount(estate, state) == 0) call 0 never executed branch 1 never executed branch 2 never executed #####: 659: isGameOver(state); call 0 never executed -: 660: } -: 661: } #####: 662: return 0; -: 663: -: 664: case great_hall: //+1 Card 1: 665: drawCard(currentPlayer, state); call 0 returned 100% 1: 666: state->numActions++; //+1 Actions 1: 667: discardCard(handPos, currentPlayer, state, 0); //discard card from hand call 0 returned 100% 1: 668: return 0; -: 669: -: 670: case minion: //+1 action #####: 671: state->numActions++; #####: 672: discardCard(handPos, currentPlayer, state, 0); //discard card from hand call 0 never executed #####: 673: if (choice1) //+2 coins branch 0 never executed branch 1 never executed #####: 674: state->coins = state->coins + 2; #####: 675: else if (choice2) { //discard hand, redraw 4, other players with 5+ cards discard hand and draw 4 branch 0 never executed branch 1 never executed #####: 676: while (numHandCards(state) > 0) //discard hand call 0 never executed branch 1 never executed branch 2 never executed #####: 677: discardCard(handPos, currentPlayer, state, 0); call 0 never executed #####: 678: for (i = 0; i < 4; i++) //draw 4 branch 0 never executed branch 1 never executed #####: 679: drawCard(currentPlayer, state); call 0 never executed -: 680: //other players discard hand and redraw if hand size > 4 #####: 681: for (i = 0; i < state->numPlayers; i++) { branch 0 never executed branch 1 never executed #####: 682: if (i != currentPlayer) { branch 0 never executed branch 1 never executed #####: 683: if (state->handCount[i] > 4) { branch 0 never executed branch 1 never executed #####: 684: while (state->handCount[i] > 0) //discard hand branch 0 never executed branch 1 never executed #####: 685: discardCard(handPos, i, state, 0); call 0 never executed #####: 686: for (j = 0; j < 4; j++) //draw 4 branch 0 never executed branch 1 never executed #####: 687: drawCard(i, state); call 0 never executed -: 688: } -: 689: } -: 690: } -: 691: } #####: 692: return 0; -: 693: -: 694: case steward: #####: 695: if (choice1 == 1) { //+2 cards branch 0 never executed branch 1 never executed #####: 696: drawCard(currentPlayer, state); call 0 never executed #####: 697: drawCard(currentPlayer, state); call 0 never executed -: 698: } #####: 699: else if (choice1 == 2) //+2 coins branch 0 never executed branch 1 never executed #####: 700: state->coins = state->coins + 2; -: 701: else { //trash 2 cards in hand #####: 702: discardCard(choice2, currentPlayer, state, 1); call 0 never executed #####: 703: discardCard(choice3, currentPlayer, state, 1); call 0 never executed -: 704: } #####: 705: discardCard(handPos, currentPlayer, state, 0); //discard card from hand call 0 never executed #####: 706: return 0; -: 707: -: 708: case tribute: #####: 709: if ((state->discardCount[nextPlayer] + state->deckCount[nextPlayer]) <= 1) { branch 0 never executed branch 1 never executed #####: 710: if (state->deckCount[nextPlayer] > 0) { branch 0 never executed branch 1 never executed #####: 711: tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer] - 1]; #####: 712: state->deckCount[nextPlayer]--; -: 713: } #####: 714: else if (state->discardCount[nextPlayer] > 0) { branch 0 never executed branch 1 never executed #####: 715: tributeRevealedCards[0] = state->discard[nextPlayer][state->discardCount[nextPlayer] - 1]; #####: 716: state->discardCount[nextPlayer]--; -: 717: } -: 718: else //No Card to Reveal #####: 719: if (DEBUG) -: 720: printf("No cards to reveal\n"); -: 721: } -: 722: else { #####: 723: if (state->deckCount[nextPlayer] == 0) { branch 0 never executed branch 1 never executed #####: 724: for (i = 0; i < state->discardCount[nextPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 725: state->deck[nextPlayer][i] = state->discard[nextPlayer][i];//Move to deck #####: 726: state->deckCount[nextPlayer]++; #####: 727: state->discard[nextPlayer][i] = -1; #####: 728: state->discardCount[nextPlayer]--; -: 729: } #####: 730: shuffle(nextPlayer, state);//Shuffle the deck call 0 never executed -: 731: } #####: 732: tributeRevealedCards[0] = state->deck[nextPlayer][state->deckCount[nextPlayer] - 1]; #####: 733: state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1; #####: 734: state->deckCount[nextPlayer]--; #####: 735: tributeRevealedCards[1] = state->deck[nextPlayer][state->deckCount[nextPlayer] - 1]; #####: 736: state->deck[nextPlayer][state->deckCount[nextPlayer]--] = -1; #####: 737: state->deckCount[nextPlayer]--; -: 738: } #####: 739: if (tributeRevealedCards[0] == tributeRevealedCards[1]) {//If we have a duplicate card, just drop one branch 0 never executed branch 1 never executed #####: 740: state->playedCards[state->playedCardCount] = tributeRevealedCards[1]; #####: 741: state->playedCardCount++; #####: 742: tributeRevealedCards[1] = -1; -: 743: } #####: 744: for (i = 0; i <= 2; i++) { branch 0 never executed branch 1 never executed #####: 745: if (tributeRevealedCards[i] == copper || tributeRevealedCards[i] == silver branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed branch 4 never executed branch 5 never executed #####: 746: || tributeRevealedCards[i] == gold) {//Treasure cards #####: 747: state->coins += 2; -: 748: } #####: 749: else if (tributeRevealedCards[i] == estate || tributeRevealedCards[i] == duchy branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed branch 4 never executed branch 5 never executed branch 6 never executed branch 7 never executed branch 8 never executed branch 9 never executed #####: 750: || tributeRevealedCards[i] == province || tributeRevealedCards[i] == gardens #####: 751: || tributeRevealedCards[i] == great_hall) {//Victory Card Found #####: 752: drawCard(currentPlayer, state); call 0 never executed #####: 753: drawCard(currentPlayer, state); call 0 never executed -: 754: } -: 755: else //Action Card #####: 756: state->numActions = state->numActions + 2; -: 757: } #####: 758: return 0; -: 759: -: 760: case ambassador: #####: 761: j = 0; //used to check if player has enough cards to discard #####: 762: if (choice2 > 2 || choice2 < 0) branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed #####: 763: return -1; #####: 764: if (choice1 == handPos) branch 0 never executed branch 1 never executed #####: 765: return -1; #####: 766: for (i = 0; i < state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 767: if (i != handPos && i == state->hand[currentPlayer][choice1] && i != choice1) branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed branch 4 never executed branch 5 never executed #####: 768: j++; -: 769: } #####: 770: if (j < choice2) branch 0 never executed branch 1 never executed #####: 771: return -1; #####: 772: if (DEBUG) -: 773: printf("Player %d reveals card number: %d\n", currentPlayer, state->hand[currentPlayer][choice1]); -: 774: //increase supply count for choosen card by amount being discarded #####: 775: state->supplyCount[state->hand[currentPlayer][choice1]] += choice2; -: 776: //each other player gains a copy of revealed card #####: 777: for (i = 0; i < state->numPlayers; i++) { branch 0 never executed branch 1 never executed #####: 778: if (i != currentPlayer) branch 0 never executed branch 1 never executed #####: 779: gainCard(state->hand[currentPlayer][choice1], state, 0, i); call 0 never executed -: 780: } #####: 781: discardCard(handPos, currentPlayer, state, 0); //discard played card from hand call 0 never executed -: 782: //trash copies of cards returned to supply #####: 783: for (j = 0; j < choice2; j++) { branch 0 never executed branch 1 never executed #####: 784: for (i = 0; i < state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 785: if (state->hand[currentPlayer][i] == state->hand[currentPlayer][choice1]) { branch 0 never executed branch 1 never executed #####: 786: discardCard(i, currentPlayer, state, 1); call 0 never executed #####: 787: break; -: 788: } -: 789: } -: 790: } #####: 791: return 0; -: 792: -: 793: case cutpurse: #####: 794: updateCoins(currentPlayer, state, 2); call 0 never executed #####: 795: for (i = 0; i < state->numPlayers; i++) { branch 0 never executed branch 1 never executed #####: 796: if (i != currentPlayer) { branch 0 never executed branch 1 never executed #####: 797: for (j = 0; j < state->handCount[i]; j++) { branch 0 never executed branch 1 never executed #####: 798: if (state->hand[i][j] == copper) { branch 0 never executed branch 1 never executed #####: 799: discardCard(j, i, state, 0); call 0 never executed #####: 800: break; -: 801: } #####: 802: if (j == state->handCount[i]) { branch 0 never executed branch 1 never executed #####: 803: for (k = 0; k < state->handCount[i]; k++) { branch 0 never executed branch 1 never executed #####: 804: if (DEBUG) -: 805: printf("Player %d reveals card number %d\n", i, state->hand[i][k]); -: 806: } #####: 807: break; -: 808: } -: 809: } -: 810: } -: 811: } #####: 812: discardCard(handPos, currentPlayer, state, 0); //discard played card from hand call 0 never executed #####: 813: return 0; -: 814: -: 815: case embargo: #####: 816: state->coins = state->coins + 2; //+2 Coins -: 817: //see if selected pile is in play #####: 818: if (state->supplyCount[choice1] == -1) branch 0 never executed branch 1 never executed #####: 819: return -1; -: 820: //add embargo token to selected supply pile #####: 821: state->embargoTokens[choice1]++; -: 822: //trash card #####: 823: discardCard(handPos, currentPlayer, state, 1); call 0 never executed #####: 824: return 0; -: 825: -: 826: case outpost: #####: 827: state->outpostPlayed++; //set outpost flag #####: 828: discardCard(handPos, currentPlayer, state, 0); //discard card call 0 never executed #####: 829: return 0; -: 830: -: 831: case salvager: //+1 buy #####: 832: state->numBuys++; #####: 833: if (choice1) { //gain coins equal to trashed card branch 0 never executed branch 1 never executed #####: 834: state->coins = state->coins + getCost(handCard(choice1, state)); call 0 never executed call 1 never executed #####: 835: discardCard(choice1, currentPlayer, state, 1); //trash card call 0 never executed -: 836: } #####: 837: discardCard(handPos, currentPlayer, state, 0); //discard card call 0 never executed #####: 838: return 0; -: 839: -: 840: case sea_hag: #####: 841: for (i = 0; i < state->numPlayers; i++) { branch 0 never executed branch 1 never executed #####: 842: if (i != currentPlayer) { branch 0 never executed branch 1 never executed #####: 843: state->discard[i][state->discardCount[i]] = state->deck[i][state->deckCount[i]--]; #####: 844: state->deckCount[i]--; #####: 845: state->discardCount[i]++; #####: 846: state->deck[i][state->deckCount[i]--] = curse;//Top card now a curse -: 847: } -: 848: } #####: 849: return 0; -: 850: -: 851: case treasure_map: #####: 852: index = -1; //search hand for another treasure_map #####: 853: for (i = 0; i < state->handCount[currentPlayer]; i++) { branch 0 never executed branch 1 never executed #####: 854: if (state->hand[currentPlayer][i] == treasure_map && i != handPos) { branch 0 never executed branch 1 never executed branch 2 never executed branch 3 never executed #####: 855: index = i; #####: 856: break; -: 857: } -: 858: } #####: 859: if (index > -1) { branch 0 never executed branch 1 never executed -: 860: //trash both treasure cards #####: 861: discardCard(handPos, currentPlayer, state, 1); call 0 never executed #####: 862: discardCard(index, currentPlayer, state, 1); call 0 never executed #####: 863: for (i = 0; i < 4; i++) //gain 4 Gold cards branch 0 never executed branch 1 never executed #####: 864: gainCard(gold, state, 1, currentPlayer); call 0 never executed #####: 865: return 1; //return success -: 866: } -: 867: //no second treasure_map found in hand #####: 868: return -1; -: 869: } #####: 870: return -1; -: 871:} -: 872: --------------------------------------------------------------------------- function discardCard called 3 returned 100% blocks executed 75% 3: 873:int discardCard(int handPos, int currentPlayer, struct gameState *state, int trashFlag) { -: 874: //if card is not trashed, added to Played pile 3: 875: if (trashFlag < 1) { //add card to played pile branch 0 taken 100% (fallthrough) branch 1 taken 0% 3: 876: state->playedCards[state->playedCardCount] = state->hand[currentPlayer][handPos]; 3: 877: state->playedCardCount++; -: 878: } 3: 879: state->hand[currentPlayer][handPos] = -1; //set played card to -1 -: 880: //remove card from player's hand 3: 881: if (handPos == (state->handCount[currentPlayer] - 1)) //last card in hand array is played branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 882: state->handCount[currentPlayer]--; //reduce number of cards in hand 3: 883: else if (state->handCount[currentPlayer] == 1) //only one card in hand branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 884: state->handCount[currentPlayer]--; //reduce number of cards in hand -: 885: else { //replace discarded card with last card in hand 3: 886: state->hand[currentPlayer][handPos] = state->hand[currentPlayer][(state->handCount[currentPlayer] - 1)]; -: 887: //set last card to -1 3: 888: state->hand[currentPlayer][state->handCount[currentPlayer] - 1] = -1; -: 889: //reduce number of cards in hand 3: 890: state->handCount[currentPlayer]--; -: 891: } 3: 892: return 0; -: 893:} -: 894: --------------------------------------------------------------------------- function updateCoins called 5 returned 100% blocks executed 80% 5: 920:int updateCoins(int player, struct gameState *state, int bonus) { -: 921: int i; 5: 922: state->coins = 0; //reset coin count -: 923: //add coins for each Treasure card in player's hand 32: 924: for (i = 0; i < state->handCount[player]; i++) { branch 0 taken 84% branch 1 taken 16% (fallthrough) 27: 925: if (state->hand[player][i] == copper) branch 0 taken 81% (fallthrough) branch 1 taken 19% 22: 926: state->coins += 1; 5: 927: else if (state->hand[player][i] == silver) branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 928: state->coins += 2; 5: 929: else if (state->hand[player][i] == gold) branch 0 taken 0% (fallthrough) branch 1 taken 100% #####: 930: state->coins += 3; -: 931: } 5: 932: state->coins += bonus; //add bonus 5: 933: return 0; -: 934:} -: 935://end of dominion.c
C
/** * gdalio.h * Authors: Yizhao Gao <ygao29@illinois.edu> * Date: {05/25/2018} */ #ifndef GDALIOH #define GDALIOH /** * NAME: gdalIORegister * DESCRIPTION: Register drivers * PARAMETERS: void */ void gdalIORegister(); /** * NAME: getCellCenterLatLon * DESCRIPTION: Get the latitude and longtitude of pixel centers given a grid * PARAMETERS: * int outputEPSG: EPSG code of output spatial reference system * double xMin: west boundary of output area * double yMin: south boundary of output area * double xMax: east boundary of output area * double yMax: north boundary of output area * double cellSize: output raste cell size * double ** px: longitude of output pixel centers * double ** py: latitude of ouput pixel centers * Output: * double ** px: longitude of output pixel centers, memory will be allocated in this function * double ** py: latitude of ouput pixel centers, memory will be allocated in this function * Return: * int: the total number of pixels */ int getCellCenterLatLon(int outputEPSG, double xMin, double yMin, double xMax, double yMax, double cellSize, double ** px, double ** py); /** * NAME: writeGeoTiff * DESCRIPTION: Write the output grid as a GeoTiff * PARAMETERS: * char * fileName: output GeoTiff file name * double * grid: the grid of the output radianc values * int outputEPSG: EPSG code of output spatial reference system * double xMin: west boundary of output area * double yMin: south boundary of output area * double xMax: east boundary of output area * double yMax: north boundary of output area * double cellSize: output raste cell size */ void writeGeoTiff(char * fileName, double * grid, int outputEPSG, double xMin, double yMin, double xMax, double yMax, double cellSize); /** * NAME: getMaxRadiusOfUserdefine * DESCRIPTION: Get the maximum distance (in meters) for user-defined-grid to be used in "nearestNeighbor" when using summary interpolate * PARAMETERS: * int epsgCode: EPSG code of the spatial reference system * double cellSize: Raste cell size * Return: * double: the maximum distance (in meters) to be used in "nearestNeighbor" */ double getMaxRadiusOfUserdefine(int epsgCode, double cellSize); #endif
C
#include <stdio.h> #include <unistd.h> #include <malloc.h> #include <pthread.h> #include <time.h> #include <stdlib.h> #include "common.h" #include "main.h" #include <iobb.h> // Library to access GPIO of Beaglebone // macros and variables long int start, stop, count; // Variables to store values //clock_t before, end, difference; // To store Time of UltraSonic Sensor clock_t before_pulse, end_pulse,difference, distance; // To store Time to calculate distance int cflag = 1; // Flag to stabilize count int sensor1_last_state = 0, sensor2_last_state = 0; // static functions static void *distance_sensor_thread(void* thread) { //int last_known_state = 0; main_thread_msg msg; printf("[%s][%d] inside distance sensor thread\r\n",__FILE__, __LINE__); while(1) { /******SENSOR TO SENSE ARIVAL OF TRAIN*******/ pin_high(8, 7); // Trigger Ultrasonic Sensor usleep(10); pin_low(8, 7); while(is_low(8, 8)) // Waiting for Echo Pulse to starts { before_pulse = clock(); //Current Clock Time } while(is_high(8, 8)) // Waiting and reading time of Echo pulse { end_pulse = clock(); } difference = end_pulse - before_pulse; // reading absolute time of Echo Pulse by distance distance = (difference/2)/30; // calculating approximate value in centimeters // If distance is between 80-90cms....approximate distance of train from sensor if ( distance >= 3 && distance <= 7) { if (sensor1_last_state != 1) { msg.data = distance; msg.msg_id = main_thread_sensor_activity_train_arrived; main_thread_push_to_queue(msg); sensor1_last_state = 1; printf("[%s][%d]train arriving......\r\n", __FILE__, __LINE__); printf("[%s][%d]Distance= %ld \r\n", __FILE__, __LINE__, distance); printf("\r\n"); } } else { if (sensor1_last_state != 0) { printf("[%s][%d]Change last known state for sensor 1\r\n", __FILE__, __LINE__); sensor1_last_state = 0; } } pin_low(8, 7); // setting trigger low for next senses /******SENSOR TO SENSE DEPARTURE OF TRAIN*******/ pin_high(8,9); // Trigger Ultrasonic Sensor usleep(10); pin_low(8, 9); while(is_low(8, 10)) // Waiting for Echo Pulse to starts { before_pulse = clock(); //load current Clock Time } while(is_high(8, 10)) // waiting and reading time of Echo pulse { end_pulse = clock(); } difference = end_pulse - before_pulse;// reading absolute time of Echo Pulse by distance distance = (difference/2)/30; // calculating approximate value in centimeters // If distance is between 80-90cms....approximate distance of train from sensor if (distance >= 3 && distance <= 7) { if (sensor2_last_state != 1) { msg.data = distance; msg.msg_id = main_thread_sensor_activity_train_depart; main_thread_push_to_queue(msg); sensor2_last_state = 1; printf("[%s][%d]train Departing......\r\n", __FILE__, __LINE__); printf("[%s][%d]Distance= %ld\r\n", __FILE__, __LINE__, distance); printf("\r\n"); } } else { if (sensor2_last_state != 0) { printf("[%s][%d]Change last known state for sensor 2\r\n", __FILE__, __LINE__); sensor2_last_state = 0; } } pin_low(8,9); // setting trigger low for next senses iolib_delay_ms(500); // delay to settle trigger and Echo } return 0; } // External functions results distance_sensor_thread_init(void) { results rc = ERROR; pthread_t dist_sensor_thread_t; printf("[%s][%d] creating dist sensor thread \r\n", __FILE__, __LINE__); // create thread rc = pthread_create(&dist_sensor_thread_t, NULL, distance_sensor_thread, NULL); if (rc != 0) { perror("error creating distance sensor thread"); return THREAD_ERROR; } else { printf("[%s][%d] success creating thread\r\n",__FILE__, __LINE__); } return 1; }
C
#ifndef SKIPLIST_H #define SKIPLIST_H #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif /*************************************************************************** * M A C R O S ***************************************************************************/ #define SKIPLIST_MAXLEVEL 16 #define SKIPLIST_NUM_NODES(l) (l->numNodes) #define SKIPLIST_NODE_FIRST(l) (l->header->forward[0]) #define SKIPLIST_NODE_NEXT(n) (n->forward[0]) #define SKIPLIST_NODE_VALUE(n) (n ? n->value : NULL) /*************************************************************************** * T Y P E D E F I N I T I O N S ***************************************************************************/ typedef int (*SkipListCmp_t) (void *key1, void *key2); typedef void (*SkipListFree_t) (void *value); typedef void * (*SkipListUserAlloc_t)(void *key, void *data, void **newKey, void **newData); typedef struct SkipListNode_s { void *key; void *value; unsigned char level; unsigned char reserved[3]; struct SkipListNode_s *forward[1]; /* var size array of forward pointers */ } SkipListNode_t; typedef struct SkipList_s { int numNodes; int maxLevels; int level; /* Maximum level of the list (1 more than the number of levels in the list) */ SkipListCmp_t cmpFn; SkipListFree_t freeFn; void **bh; SkipListNode_t *header; /* pointer to header */ } SkipList_t; /*************************************************************************** * F U N C T I O N P R O T O T Y P E S ***************************************************************************/ /*************************************************************************** * Function : SkipListAlloc() * Description : Allocates a new skip list. * Input : Pointer to the compare function which is used to compare * the keys and a pointer to the free function which is used * to free the element stored in each skip list node. * Output : None. * Returns : Pointer to the newly allocated skip list. * ***************************************************************************/ SkipList_t *SkipListAlloc( SkipListCmp_t, SkipListFree_t ); /*************************************************************************** * Function : SkipListFree() * Description : Frees the given skip list. * Input : Pointer to the skip list to be freed. * Output : None. * Returns : None. ****************************************************************************/ void SkipListFree( SkipList_t * ); /*************************************************************************** * Function : SkipListInstert() * Description : Inserts the given element in the skip list at * the right place based on the specified key. * Input : The list in which the element is to be inserted, key, * element to be inserted and a flag which indicates * whether to replace the existing element, if any. * Output : None. * Returns : 0 -- success, -1 -- failure * ***************************************************************************/ int SkipListInsert( SkipList_t *, void *, void *, int ); /*************************************************************************** * Function : SkipListDelete() * Description : Deletes the matching element from the list. * Input : Pointer to the list and the key whose corresponding * entry is to be deleted from the list. * Output : None. * Returns : 0 -- success, -1 -- failure ****************************************************************************/ int SkipListDelete( SkipList_t *, void * ); /*************************************************************************** * Function : SkipListGetNode() * Description : Finds the matching node for the given key. * Input : Pointer to the list and the key whose matching * element is to be found. * Output : None. * Returns : Pointer to the matching node. ****************************************************************************/ SkipListNode_t *SkipListGetNode( SkipList_t *, void * ); /*************************************************************************** * Function : SkipListGetNodeOrNext() * Description : Gets the node or if not present, the next node * in the list based on the key. * Input : Pointer to the list and the key . * Output : None. * Returns : Pointer to the node or if not found, the next node. * ***************************************************************************/ SkipListNode_t *SkipListGetNodeOrNext( SkipList_t *, void * ); /*************************************************************************** * Function : SkipListGetCount() * Description : Gets the total number of elements in the list. * Input : Pointer to the list. * Output : None. * Returns : Number of elements in the skip list. ****************************************************************************/ int SkipListGetCount( SkipList_t * ); /*************************************************************************** * Function : SkipListGetFirst() * Description : Gets the first node in the list. * Input : Pointer to the list. * Output : None. * Returns : Pointer to the first node in the list. ****************************************************************************/ SkipListNode_t *SkipListGetFirst( SkipList_t * ); /*************************************************************************** * Function : SkipListGetNext() * Description : Gets the next node in the list based on the key. * Input : Pointer to the list and the key whose lexicographically * next node is to be found. * Output : None. * Returns : Pointer to the next node in the list. ****************************************************************************/ SkipListNode_t *SkipListGetNext( SkipList_t *, void * ); /*************************************************************************** * Function : SkipListFindOrInsert() * Description : Searches for the specified data item * If found returns it, otherwise allocates one using * user specified function, sets key and data and then * returns it. * If no user specified function exists, the given key * and data are inserted. * * * Input : The list in which the element is to be inserted, key, * element to be inserted, a allocation function if new key and * data are to be allocated, a return value for a flag to indicate * if allocation was called. * Output : sets found if it found an element. * Returns : Node ptr on success, NULL on failiure * ***************************************************************************/ SkipListNode_t * SkipListFindOrInsert( SkipList_t *list, void *key, void *value , SkipListUserAlloc_t allocFn, int *found ); /*************************************************************************** * Function : SkipListClear() * Description : Frees all data items on the skiplist. * Input : Pointer to the skip list to be cleared. * Output : None. * Returns : None. ****************************************************************************/ void SkipListClear( SkipList_t *list ); /*************************************************************************** * Function : SkipListDeleteNode() * Description : Deletes the matching node from the list. * Input : Pointer to the list and the key whose corresponding * NODE is to be deleted from the list. * The FREE FUNCTION is NOT called. * This is useful in cases where the structure needs to be preserved * without having to provide a dummy free function * Output : None. * Returns : 0 -- success, -1 -- failure ****************************************************************************/ int SkipListDeleteNode( SkipList_t *list, void *key ); /*************************************************************************** * Function : SkipListNClear() * Description : Frees n data items on the skiplist. * Input : Pointer to the skip list to be cleared. * Output : None. * Returns : None. ****************************************************************************/ void SkipListNClear( SkipList_t *list , int n) ; #ifdef __cplusplus } #endif #endif /* SKIPLIST_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* solve_instruments.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kkostrub <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/06/02 18:30:13 by kkostrub #+# #+# */ /* Updated: 2018/06/02 18:31:50 by kkostrub ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" char *delete_sqr(char **square) { free(*square); *square = NULL; return (*square); } void rewrite_tmp_x_y(t_lst **node, int x, int y) { int i; i = 0; while (i < 4) { (*node)->tmp_x[i] = (*node)->x[i] + x; (*node)->tmp_y[i] = (*node)->y[i] + y; i++; } } int try_to_write_tetr(char *square, t_lst *node) { int i; int pos; int d_polya; int pole_end; d_polya = calc_pole(square) + 1; i = 3; while (i >= 0) { pole_end = (d_polya * (node->tmp_x[i] + 1)) - 1; pos = node->tmp_x[i] * d_polya + node->tmp_y[i]; if (pos >= (int)ft_strlen(square) - 1) return (-1); else if (square[pos] == '\n') return (2); else if (pos == pole_end) return (1); else if (square[pos] != '.') return (1); i--; } return (0); } t_lst *delete_listfrom_tail(t_lst **node) { t_lst *current; t_lst *tail; current = *node; if (!current) return (NULL); if (current->next != NULL) while (current->next) current = current->next; while (current->prev) { tail = current; current = current->prev; tail->prev = NULL; current->next = NULL; free(tail); tail = NULL; } free(current); current = NULL; return (NULL); }
C
#include <stdio.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> int main(int argc, char *argv[]){ int val; printf("argc is %d\n", argc); printf("argv[1] is %s\n", argv[1]); val = fcntl(atoi(argv[1]), F_GETFL, 0); printf("val is %d\n", val); if (atoi(argv[1]) == 5){ int n = write(5, "iiiiii", 7); printf("n is %d", n); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <math.h> #include <assert.h> #include <string.h> #include <time.h> struct list { int id; struct list * next; }; void print_way (int * table, int n) { for (int i = 0; i < n; i++) { for (int j = 1; j < n; j++) { for (int k = 1; k < n; k++) { printf("%2d ", table[i*n*n + n*j + k]); } printf("\n"); } printf("\n\n"); } } void print_list (struct list * head) { struct list * p = head; while (p != NULL) { printf("%d ", p->id); p = p->next; } } void free_list (struct list * head) { while (head != NULL) { struct list * p = head; head = head->next; free(p); } } struct list * left_way (struct list * p, int k) { struct list * q = (struct list *)calloc(1, sizeof(struct list)); q->id = k; q->next = p; return q; } struct list * right_way (struct list * p, int k) { struct list * q = (struct list *)calloc(1, sizeof(struct list)); q->id = k; p->next = q; return q; } struct list * search_right (int n, int j, int * table, int k, struct list * right); struct list * search_left (int n, int i, int * table, int k, struct list * left) { int p = k--; while (k > 0) { if (table[k*n*n + i*n + p] == table[(k - 1)*n*n + i*n + p]) { k--; } else { break; } } if (k == 0) { return left; } left = left_way(left, k); struct list * right = left; search_right(n, p, table, k, right); return search_left(n, i, table, k, left); } struct list * search_right (int n, int j, int * table, int k, struct list * right) { int p = k--; while (k > 0) { if (table[k*n*n + p*n + j] == table[(k - 1)*n*n + p*n + j]) { k--; } else { break; } } if (k == 0) { return right; } right = right_way(right, k); struct list * left = right; search_left(n, p, table, k, left); return search_right(n, j, table, k, right); } int show_way (int * table, int n, int i, int j) { struct list * head = (struct list *)calloc(1, sizeof(struct list)); struct list * left = head; struct list * right = head; int k = n - 1; while (k > 0) { if (table[k*n*n + i*n + j] == table[(k-1)*n*n + i*n + j]) { k--; } else { break; } } if (k == 0) { if (table[i*n + j] == 0) { free_list(head); return -1; } else { head->id = i; right_way(head, j); } } else { head->id = k; left = search_left(n, i, table, k, left); right = search_right(n, j, table, k, right); head = left_way(left, i); right = right_way(right, j); } print_list(head); free_list(head); return 0; } void Floyd_Worcheall (int n, int k, int * table, int * prev_table) { for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { if (prev_table[n*i + k] == 0 || prev_table[n*k + j] == 0) { table[n*i + j] = prev_table[n*i + j]; continue; } int length = prev_table[n*i + k] + prev_table[n*k + j]; if (length < prev_table[n*i + j]) { table[n*i + j] = length; } else { if (prev_table[n*i + j] == 0 && length != 0) { table[n*i + j] = length; } else { table[n*i + j] = prev_table[n*i + j]; } } } } } void search_way (int * table, int n) { for (int k = 1; k < n; k++) { Floyd_Worcheall(n, k, table + k*n*n, table + (k-1)*n*n); } for (int i = 1; i < n; i++) { for (int j = 1; j < n; j++) { printf("%d -> %d: ", i, j); if (show_way(table, n, i, j) == -1) { printf("This way not exist"); } else { printf(" Length = %d", table[(n-1)*n*n + i*n + j]); } printf("\n"); } } } int read (FILE * data) { int n = 0; fscanf(data, "%d", &n); int * table = (int *)calloc(n*n*n, sizeof(int)); while (1) { int num1 = 0; int num2 = 0; int length = 0; int rc = 0; rc = fscanf(data, "%d %d %d", &num1, &num2, &length); if (rc == -1) { break; } if (rc != 3) { printf("Invalid input data\n"); return 1; } table[num1*n + num2] = length; } search_way(table, n); free(table); return 0; } int main (int argc, char * argv[]) { FILE * data; if (argc > 1) { data = fopen(argv[1], "r"); if (data == NULL) { printf("File open error\n"); return 1; } } else { printf("Not arguments\n"); return 1; } if (read(data) == 1) { fclose(data); return -1; } fclose(data); return 0; }
C
struct A_2_1 { int a; int b; int *p; }; int foo_2_1() { struct A_2_1 a; a.b = a.a; return 0; } // Memory int bar_2_1() { struct A_2_1 a; *a.p = 1; return 0; }
C
#include "boolector.h" #include "minand.h" #include "utils/btorutil.h" #include <stdio.h> #include <stdlib.h> int main (int argc, char **argv) { int num_bits; Btor *btor; BoolectorNode *formula, *zero_num_bits_m_1, *tmp, *a, *b, *c, *d, *m; BoolectorNode *result, *one, *x_and_y; BoolectorNode *premisse, *a_ulte_x, *x_ulte_b, *c_ulte_y, *y_ulte_d; BoolectorNode *x, *y, *concl; BoolectorSort sort_one, sort_nbits1, sort_nbits; if (argc != 2) { printf ("Usage: ./minand <num-bits>\n"); return 1; } num_bits = atoi (argv[1]); if (num_bits <= 1) { printf ("Number of bits must be greater than one\n"); return 1; } if (!btor_util_is_power_of_2 (num_bits)) { printf ("Number of bits must be a power of two\n"); return 1; } btor = boolector_new (); boolector_set_opt (btor, BTOR_OPT_REWRITE_LEVEL, 0); sort_one = boolector_bitvec_sort (btor, 1); sort_nbits1 = boolector_bitvec_sort (btor, num_bits - 1); sort_nbits = boolector_bitvec_sort (btor, num_bits); one = boolector_one (btor, sort_one); zero_num_bits_m_1 = boolector_zero (btor, sort_nbits1); m = boolector_concat (btor, one, zero_num_bits_m_1); a = boolector_var (btor, sort_nbits, "a"); b = boolector_var (btor, sort_nbits, "b"); c = boolector_var (btor, sort_nbits, "c"); d = boolector_var (btor, sort_nbits, "d"); x = boolector_var (btor, sort_nbits, "x"); y = boolector_var (btor, sort_nbits, "y"); x_and_y = boolector_and (btor, x, y); a_ulte_x = boolector_ulte (btor, a, x); x_ulte_b = boolector_ulte (btor, x, b); c_ulte_y = boolector_ulte (btor, c, y); y_ulte_d = boolector_ulte (btor, y, d); premisse = boolector_and (btor, a_ulte_x, x_ulte_b); tmp = boolector_and (btor, premisse, c_ulte_y); boolector_release (btor, premisse); premisse = tmp; tmp = boolector_and (btor, premisse, y_ulte_d); boolector_release (btor, premisse); premisse = tmp; result = btor_minand (btor, a, b, c, d, m, num_bits); /* conclusion: result is indeed the minimum of x & y */ concl = boolector_ulte (btor, result, x_and_y); formula = boolector_implies (btor, premisse, concl); /* we negate the formula and show that it is UNSAT */ tmp = boolector_not (btor, formula); boolector_release (btor, formula); formula = tmp; boolector_dump_btor_node (btor, stdout, formula); /* clean up */ boolector_release (btor, result); boolector_release (btor, premisse); boolector_release (btor, concl); boolector_release (btor, formula); boolector_release (btor, a_ulte_x); boolector_release (btor, x_ulte_b); boolector_release (btor, c_ulte_y); boolector_release (btor, y_ulte_d); boolector_release (btor, x_and_y); boolector_release (btor, a); boolector_release (btor, b); boolector_release (btor, c); boolector_release (btor, d); boolector_release (btor, m); boolector_release (btor, x); boolector_release (btor, y); boolector_release (btor, zero_num_bits_m_1); boolector_release (btor, one); boolector_release_sort (btor, sort_one); boolector_release_sort (btor, sort_nbits1); boolector_release_sort (btor, sort_nbits); boolector_delete (btor); return 0; }
C
/* gentree version 1.2; Brendan McKay Aug 2017 */ /* This program is a wrapper for the program FreeTrees.c written * by Gang Li & Frank Ruskey. See below for their original * comments. */ #define USAGE \ "gentreeg [-D#] [-Z#:#] [-ulps] [-q] n [res/mod] [file]" #define HELPTEXT \ " Generate (unrooted) trees.\n\ \n\ n : the number of vertices\n\ res/mod : only generate subset res out of subsets 0..mod-1\n\ \n\ -D# : an upper bound for the maximum degree\n\ -Z#:# : bounds for the diameter\n\ \n\ -s : use sparse6 output (default)\n\ -p : write a parent array\n\ -l : write a level array \n\ -u : do not output any graphs, just generate and count them\n\ \n\ -q : suppress auxiliary output\n\ \n\ See program text for much more information.\n" /* Comments on original program by original authors */ /*==============================================================*/ /* program: freetree.c */ /* purpose: generating all free trees */ /* input : n -- number of nodes */ /* m -- max degree */ /* lb,ub -- lower and upper bound on diameter */ /* res/mod -- splitting into parts */ /* output : listing of free trees in relex order */ /* date : September 1995, updated Sept 2000 */ /* programmers: Gang Li & Frank Ruskey */ /* algorithm: From the paper: G. Li and F. Ruskey, "The */ /* Advantages of Forward Thinking in Generating Rooted and */ /* Free Trees", 10th Annual ACM-SIAM Symposium on Discrete */ /* Algorithms (SODA), (1999) S939-940. See the web page at */ /* http://www.theory.csc.UVic.CA/~fruskey/ */ /* Publications/RootedFreeTree.html */ /* more info: See */ /* http://www.theory.csc.UVic.CA/~cos/inf/FreeTrees.html */ /*==============================================================*/ #define MAXN 128 /* max size of the tree. Check MAXOUTLEN if more than 1000 */ #include "gtools.h" /***************************************************************** OUTPROC feature. By defining the C preprocessor variable OUTPROC at compile time (for Unix the syntax is -DOUTPROC=procname on the cc command), gentreeg can be made to call void OUTPROC(FILE *f, int *par, int n) instead of the usual output routines. par[1..n] is the parent array of the tree. The edges in 1..n labelling are {j,par[j]} for j=2..n. WARNING: The vertices are 1..n, not 0..n-1, and also par[] uses elements 1..n, not 0..n-1. Your procedure can be in a separate file so long as it is linked with gentreeg. PRUNE feature. By defining the C preprocessor variable PRUNE at compile time, gentreeg can be made to call int PRUNE(int *par, int n) for each tree. The meaning of par[] is above and n is the number of vertices. If a non-zero value is returned, the tree is rejected: it is not included in the count, and output routines including OUTPROC are not called. SUMMARY If the C preprocessor variable SUMMARY is defined at compile time, the procedure/macro SUMMARY(nauty_counter nout, double cpu) is called just before the program exits. The purpose is to allow reporting of statistics collected by PRUNE or OUTPROC. The values nout and cpu are the output count and cpu time as reported on the >Z line. Output should be written to stderr. CALLING FROM A PROGRAM It is possible to call gentreeg from another program instead of using it as a stand-alone program. The main requirement is to change the name of the main program to be other than "main". This is done by defining the preprocessor variable GENTREEG_MAIN. You might also like to define OUTPROC to be the name of a procedure to receive the graphs. To call the program you need to define an argument list argv[] consistent with the usual one; don't forget that argv[0] is the command name and not the first argument. The value of argc is the number of strings in argv[]; that is, one more than the number of arguments. */ static int par[MAXN+1], /* parent position of i */ maxchild, /* max number of children */ chi[MAXN+1], /* number of children of a node */ nextp[MAXN+1], /* next good pos to add nodes */ rChi[MAXN+1], /* the right most child of node i */ ub; /* upper bound on something */ static nauty_counter nout; /* number of trees */ static FILE *outfile; static int splitlevel,splitcount,mod,res; /* -s res/mod */ static int nv; /* number of vertices */ static int mindiam; static int maxdeg; static int maxdiam; /* MAXOUTLEN must be at least the longest output line length */ #define MAXOUTLEN (10 + 4*MAXN) static char outstring[MAXOUTLEN]; void (*outproc)(FILE *f, int vpar[], int n); #ifdef OUTPROC extern void OUTPROC(FILE *f, int vpar[], int n); #endif #ifdef PRUNE extern int PRUNE(int vpar[], int n); #endif void WritePar(FILE *f, int vpar[], int n) /* Write parent array */ { int i,j; char *pout,*p,one[8]; size_t len; pout = outstring; for (i=1;i<=nv;++i) { j = vpar[i]; if (j == 0) *(pout++) = '0'; else { for (p = one; j > 0; j /= 10) *(p++) = '0' + j%10; while (--p >= one) *(pout++) = *p; } if (i < nv) *(pout++) = ' '; else *(pout++) = '\n'; } len = pout - outstring; if (fwrite(outstring,sizeof(char),len,f) != len) gt_abort(">E gentreeg: fwrite() failed\n"); } static void WriteLev(FILE *f, int vpar[], int n) /* Write levels array */ { int i,j; char *pout,*p,one[8]; size_t len; int lev[MAXN+1]; lev[1]=0; for ( i=2; i<=nv; ++i ) lev[i] = lev[vpar[i]]+1; pout = outstring; for (i=1;i<=nv;++i) { j = lev[i]; if (j == 0) *(pout++) = '0'; else { for (p = one; j > 0; j /= 10) *(p++) = '0' + j%10; while (--p >= one) *(pout++) = *p; } if (i < nv) *(pout++) = ' '; else *(pout++) = '\n'; } len = pout - outstring; if (fwrite(outstring,sizeof(char),len,f) != len) gt_abort(">E gentreeg: fwrite() failed\n"); } static void DontWrite(FILE *f, int vpar[], int n) /* Null print routine */ { } static void WriteS6(FILE *f, int vpar[], int n) /* Write in sparse6 format */ { char *pout; int nb,i,j,lastj,x,k,r,rr,topbit; size_t len; pout = outstring; *pout++ = ':'; encodegraphsize(n,&pout); for (i = n-1, nb = 0; i != 0 ; i >>= 1, ++nb) {} topbit = 1 << (nb-1); k = 6; x = 0; lastj = 0; for (j = 1; j < n; ++j) { i = vpar[j+1] - 1; if (j == lastj) { x <<= 1; if (--k == 0) { *pout++ = 63 + x; k = 6; x = 0; } } else { x = (x << 1) | 1; if (--k == 0) { *pout++ = 63 + x; k = 6; x = 0; } if (j > lastj+1) { for (r = 0, rr = j; r < nb; ++r, rr <<= 1) { if (rr & topbit) x = (x << 1) | 1; else x <<= 1; if (--k == 0) { *pout++ = 63 + x; k = 6; x = 0; } } x <<= 1; if (--k == 0) { *pout++ = 63 + x; k = 6; x = 0; } } lastj = j; } for (r = 0, rr = i; r < nb; ++r, rr <<= 1) { if (rr & topbit) x = (x << 1) | 1; else x <<= 1; if (--k == 0) { *pout++ = 63 + x; k = 6; x = 0; } } } if (k != 6) *pout++ = 63 + ((x << k) | ((1 << k) - 1)); *pout++ = '\n'; len = pout - outstring; if (fwrite(outstring,sizeof(char),len,f) != len) gt_abort(">E gentreeg: fwrite() failed\n"); } static void WriteIt(int level) { int i; if (level < splitlevel && res != 0) return; #ifdef PRUNE if (PRUNE(par,nv)) return; #endif ++nout; (*outproc)(outfile,par,nv); } static boolean good( int p, int h, int t ) { if (p==2 && mindiam<=2 && t==0) return TRUE; if (t == 1) { if (2*h>=mindiam+1 && 2*h <= maxdiam+1) { if ((p-1)*2 >= nv) return TRUE; else if (p - h-1 == 1) { if (par[p]> 2) return TRUE; } else if ((p - h-1 >=2) && ((par[h+2]>2) || (par[h+3]>2))) return TRUE; } } else if (nv-p >= h && 2*h>=mindiam) { if (maxdiam==nv-1 && nv%2==0) return 2*h<=maxdiam+1; else return 2*h <= maxdiam; } return FALSE; } /* good */ static void Gen( int level, int p, int s, int cL, int h, int l, int n, int f, int g ) /* The main generation procedure. */ { int hh,flag,entry,temp; if (level == splitlevel) { if (splitcount-- != 0) return; splitcount = mod - 1; } if (p > n) if (f == 0) { if (good(p-1,h,0)) Gen(level+1, p, 2, p-2,h,n,nv,1,0); if (good(p-1,h,1)) Gen(level+1, p, 2, p-3,h,n,nv,1,1); } else { WriteIt(level);} else { if (cL == 0) { if ( p< ub+2 ) par[p] = p-1; else { Gen(level+1, p, p-1, 1, h, l, n, f, g ); return; } } else if (par[p-cL] < s) par[p]=par[p-cL]; else { par[p] = cL + par[p-cL]; if (g==1) { if (((l-1)*2 < n) && (p-cL<=l) && ( ((p-cL+1<l) && (par[p-cL+1]==2) && (p-cL+2<=l) && (par[p-cL+2]==2)) /*case 1*/ || ((p-cL+1==l) && (par[p-cL+1]==2)) /*case 2*/ || (p-cL+1>l))) { /*case 3*/ s= par[p]; cL= p-s; par[p] = par[par[p]]; } else if (par[p-cL]==2) par[p]=1; } } if (s!=0 || p<=ub+1) { chi[par[p]] = chi[par[p]] + 1; temp = rChi[par[p]]; rChi[par[p]] = p; if (chi[par[p]] <= ((par[p]==1)?maxchild:maxchild-1)) { if (chi[par[p]] < (par[p]==1?maxchild:maxchild-1)) nextp[p] = par[p]; else nextp[p] = nextp[par[p]]; Gen(level+1, p+1, s, cL,h,l,n,f,g ); } chi[par[p]] = chi[par[p]] - 1; rChi[par[p]] = temp; } if (s==0 && 2*(p-2)<mindiam) return; nextp[p] = nextp[par[p]]; entry = nextp[p]; flag= 0; hh=1; while ((((f==0) && (entry>=2)) || ((f==1) && (entry>=1))) && (flag==0)) { if (s==0) h = p-2; if (p<=l+h-g) hh = 0; if ((f==0) || (hh==1)) { /*s = par[p]; par[p] = par[s];*/ par[p] = entry; chi[entry] = chi[entry] + 1; temp = rChi[par[p]]; rChi[par[p]] = p; if (chi[entry] >= (entry==1?maxchild:maxchild-1)) nextp[p] = nextp[entry]; if (f == 0) Gen(level+1,p+1,temp,p-temp,h,0,nv-h+1,f,g); else if (hh == 1) Gen(level+1,p+1,temp,p-temp,h,l,n,f,g); chi[entry] = chi[entry] - 1; rChi[par[p]] = temp; entry = nextp[entry]; nextp[p] = entry; } else flag= 1; } if (f == 0) { if (good(p-1,h,0)) Gen(level+1,p,2,p-2,h,p-1,nv,1,0); if (good(p-1,h,1)) Gen(level+1,p,2,p-3,h,p-1,nv,1,1); } } } /* Gen */ /**************************************************************************/ /**************************************************************************/ #ifdef GENTREEG_MAIN int GENTREEG_MAIN(int argc, char *argv[]) #else int main(int argc, char *argv[]) #endif { char *arg; boolean badargs,uswitch,sswitch,pswitch,lswitch,Zswitch; boolean qswitch,Dswitch,gotmr,gotf; long Z1,Z2; char *outfilename,sw; int i,j,argnum; int splitlevinc; double t1,t2; char msg[201]; HELP; PUTVERSION; badargs = FALSE; uswitch = sswitch = pswitch = lswitch = Zswitch = FALSE; qswitch = Dswitch = gotmr = gotf = FALSE; outfilename = NULL; splitlevinc = 0; argnum = 0; for (j = 1; !badargs && j < argc; ++j) { arg = argv[j]; if (arg[0] == '-' && arg[1] != '\0') { ++arg; while (*arg != '\0') { sw = *arg++; SWBOOLEAN('u',uswitch) else SWBOOLEAN('s',sswitch) else SWBOOLEAN('p',pswitch) else SWBOOLEAN('l',lswitch) else SWRANGE('Z',":-",Zswitch,Z1,Z2,"gentreeg -Z") else SWBOOLEAN('q',qswitch) else SWINT('D',Dswitch,maxdeg,"gentreeg -D") #ifdef PLUGIN_SWITCHES PLUGIN_SWITCHES #endif else badargs = TRUE; } } else if (arg[0] == '-' && arg[1] == '\0') gotf = TRUE; else { if (argnum == 0) { if (sscanf(arg,"%d",&nv) != 1) badargs = TRUE; ++argnum; } else if (gotf) badargs = TRUE; else { if (!gotmr) { if (sscanf(arg,"%d/%d",&res,&mod) == 2) { gotmr = TRUE; continue; } } if (!gotf) { outfilename = arg; gotf = TRUE; continue; } } } } if (argnum == 0) badargs = TRUE; else if (nv < 1 || nv > MAXN) { fprintf(stderr,">E gentreeg: n must be in the range 1..%d\n",MAXN); exit(1); } if (!gotmr) { mod = 1; res = 0; } if (!Dswitch || maxdeg >= nv) maxdeg = nv - 1; if (!Zswitch || Z2 >= nv) Z2 = nv - 1; if (!Zswitch || Z1 <= 1) Z1 = (nv == 1 ? 0 : nv == 2 ? 1 : 2); mindiam = Z1; maxdiam = Z2; if (!badargs && (maxdiam < mindiam || maxdiam < (nv == 1 ? 0 : nv == 2 ? 1 : 2))) gt_abort(">E gentreeg: impossible diameter bounds\n"); if (!badargs && maxdeg < (nv == 1 ? 0 : nv == 2 ? 1 : 2)) gt_abort(">E gentreeg: impossible degree bound\n"); if (!badargs && (res < 0 || res >= mod)) gt_abort(">E gentreeg: must have 0 <= res < mod\n"); if (badargs) { fprintf(stderr,">E Usage: %s\n",USAGE); GETHELP; exit(1); } if ((lswitch!=0) + (pswitch!=0) + (sswitch!=0) + (uswitch!=0) > 1) gt_abort(">E gentreeg: -uslp are incompatible\n"); #ifdef OUTPROC outproc = OUTPROC; #else if (uswitch) outproc = DontWrite; else if (lswitch) outproc = WriteLev; else if (pswitch) outproc = WritePar; else outproc = WriteS6; #endif #ifdef PLUGIN_INIT PLUGIN_INIT #endif if (qswitch) outfile = stdout; else if (!gotf || outfilename == NULL) { outfilename = "stdout"; outfile = stdout; } else if ((outfile = fopen(outfilename,"w")) == NULL) { fprintf(stderr, ">E gentree: can't open %s for writing\n",outfilename); gt_abort(NULL); } if (!qswitch) { msg[0] = '\0'; if (strlen(argv[0]) > 75) fprintf(stderr,">A %s",argv[0]); else CATMSG1(">A %s",argv[0]); CATMSG2(" Z=%d:%d",mindiam,maxdiam); CATMSG2(" D=%d n=%d",maxdeg,nv); if (mod > 1) CATMSG2(" class=%d/%d",res,mod); CATMSG0("\n"); fputs(msg,stderr); fflush(stderr); } t1 = CPUTIME; nout = 0; if (nv == 1) { if (res == 0) { ++nout; par[1] = 0; WriteIt(0); } } else if (nv == 2) { if (res == 0) { ++nout; par[1] = 0; par[2] = 1; WriteIt(0); } } else { if (mod > 1 && nv > 3) { splitlevel = nv/2; splitcount = res; } else { splitlevel = -1; mod = 1; } if ( maxdeg > 0 ) maxchild = maxdeg; else maxchild = -1; ub = (maxdiam+1)/2; for(i=1;i<=nv;i++) chi[i]=0; par[1] = 0; par[2] = 1; nextp[1]=0; nextp[2]=1;chi[1]=1; Gen( 0, 3, 0, 0, ub, 0, nv-ub+1, 0, 0 ); } t2 = CPUTIME; #ifdef SUMMARY SUMMARY(nout,t2-t1); #endif if (!qswitch) { fprintf(stderr,">Z " COUNTER_FMT " trees generated in %3.2f sec\n",nout,t2-t1); } #ifdef GENTREEG_MAIN return 0; #else exit(0); #endif }
C
int power(int x, int y) { int result; result = 1; if(y == 0) { return 1; } else if(x<0 || y<0) { return -1; } else if(y > 0 && x>0) { result = x*power(x,(y-1)); if(result < x) { return -1; } else return result; } else return -1; }
C
#include <stdio.h> int n; int k; int A[100000]; // 槍の長さは0,1,2,3...と // 整数で制限されているものとする // 長さxの槍がk本作れる場合は0を返す.作れない場合は1を返す. // これはxに対し単調増加となる. // 長さ0の槍は必ずk本作れるとする. int p(int x) { int k_avail = 0; //長さxの槍は何本作れるか int i; // 0除算を防止し,長さ0の槍は何本でも作れると考え,0を出力する. if (x == 0) return 0; for (i = 0; i < n; i++) { // A[i]/x の切り捨て(i番目の木から作成できる槍の数)を足し合わせる k_avail += A[i] / x; } return k_avail < k; } int main() { int i, lb, ub; scanf("%d%d", &n, &k); for (i = 0; i < n; i++) { scanf("%d", &A[i]); } // いかなる入力でも必ずp(0)=0になり、p(1)は1となる可能性があるため // lbの初期値は0とする. lb = 0; // 木の長さ(A[i])として入力できる値の最大値よりxが大きくなることはないから, // 木の長さとして入力できる最大の数である10^9をxの最大値と考える. // つまりp(10^9)=0となりうる. // p(10^9+1)は、木の長さとして入力できる値の最大値より作る槍の長さが大きくなってしまうため、必ず1となる. ub = 1E+9 + 1; while (ub - lb > 1) { int mid = (lb + ub) / 2; if (p(mid)) { ub = mid; } else { lb = mid; } } //出力すべきなのはp(x)=0となる(=k本の槍が作れる)xの最大値 printf("%d\n", lb); return 0; }
C
#include "watchdog.h" /*-------------------ӲŹ-------------------------*/ /* * IWDG ijʱʱ * Tout = prv/40 * rlv (s) * prv[4,8,16,32,64,128,256] * prv:ԤƵֵȡֵ£ * @arg IWDG_Prescaler_4: IWDG prescaler set to 4 * @arg IWDG_Prescaler_8: IWDG prescaler set to 8 * @arg IWDG_Prescaler_16: IWDG prescaler set to 16 * @arg IWDG_Prescaler_32: IWDG prescaler set to 32 * @arg IWDG_Prescaler_64: IWDG prescaler set to 64 * @arg IWDG_Prescaler_128: IWDG prescaler set to 128 * @arg IWDG_Prescaler_256: IWDG prescaler set to 256 * * rlv:ԤƵֵȡֵΧΪ0-0XFFF * þ * IWDG_Config(IWDG_Prescaler_64 ,625); // IWDG 1s ʱ */ void IWDG_Config(uint8_t prv ,uint16_t rlv) { // ʹ ԤƵĴPRװؼĴRLRд IWDG_WriteAccessCmd( IWDG_WriteAccess_Enable ); // ԤƵֵ IWDG_SetPrescaler( prv ); // װؼĴֵ IWDG_SetReload( rlv ); // װؼĴֵŵ IWDG_ReloadCounter(); // ʹ IWDG IWDG_Enable(); } // ι void IWDG_Feed(void) { // װؼĴֵŵУιֹIWDGλ // ֵ0ʱϵͳλ IWDG_ReloadCounter(); } /* Ź */ //ԼдĿŹʱ飬1msһΣ uint16_t WatchDog[5] = {1000,1000,1000,1000,1000}; /* *@briefͨöʱ4NVIC *@param *@retval */ static void WDG_TIM_NVIC_Config(void) { NVIC_InitTypeDef NVIC_InitStructure; // жԴ NVIC_InitStructure.NVIC_IRQChannel = WDG_TIM_IRQ ; // ȼΪ 0 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 1; // ռȼΪ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); } /* *ܣͨöʱ2ĵģʽ *Frequency-һζʱжϵƵ *أ *@notice:APB1ʱΪ36MǣʱʱͨCLKapb1*2=72Mõ */ void WDG_TIM_Init(uint16_t Frequency) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; // ʱʱ,ڲʱCK_INT=36M WDG_TIM_APBxClock_FUN(WDG_TIM_CLK, ENABLE); // ԶװؼĴֵۼTIM_Period+1Ƶʺһ»ж TIM_TimeBaseStructure.TIM_Period= Frequency - 1; // ʱԤƵ TIM_TimeBaseStructure.TIM_Prescaler= WDG_TIM_Prescaler; // ʱӷƵ ûõù TIM_TimeBaseStructure.TIM_ClockDivision=TIM_CKD_DIV1; // ģʽΪϼ TIM_TimeBaseStructure.TIM_CounterMode=TIM_CounterMode_Up; // ظֵûõù TIM_TimeBaseStructure.TIM_RepetitionCounter=0; // ʼʱ TIM_TimeBaseInit(WDG_TIM, &TIM_TimeBaseStructure); //NVIC WDG_TIM_NVIC_Config(); // ж TIM_ITConfig(WDG_TIM,TIM_IT_Update,ENABLE); // ʹܼ TIM_Cmd(WDG_TIM, ENABLE); //Źʱʼ } /** * @brief This function handles TIM2 interrupt request. * @param None * @retval None */ void WDG_TIM_IRQHandler (void) { if ( TIM_GetITStatus( WDG_TIM, TIM_IT_Update) != RESET ) { WatchDog[PULSE_WATCHDOG]--; if(!WatchDog[PULSE_WATCHDOG]) { WatchDog[PULSE_WATCHDOG] = PULSE_WDT_TIMEOUT; #ifndef BareDebug VelOfCar = 0; AngOfCar = 0; Vel_Set = 0; Ang_Set = 0; ModeReg = 0; FaultReg |= PULSE_BIT;//ϼĴӦΪΪ #endif } TIM_ClearITPendingBit(WDG_TIM , TIM_FLAG_Update); } }
C
#include "heclibDate.h" #include "standardIntervals.h" void minsToDateTime(int minsSince1900, char *dateString, char *timeString, size_t sizeofDateString, size_t sizeofTimeString) { // Takes minutes since 01Jan1900 and converts it to a date and time character string // int julian; int minsSinceMidnight; julian = minsSince1900 / MINS_IN_1_DAY; minsSinceMidnight = minsSince1900 - (julian * MINS_IN_1_DAY); julianToDate(julian, 4, dateString, sizeofDateString); minutesToHourMin(minsSinceMidnight, timeString, sizeofTimeString); }
C
/* Building.h DEFINISI ABSTRAKSI GAME */ #ifndef _BUILDING_H #define _BUILDING_H #include "Point/Point.h" #include "bool/bool.h" typedef struct { Point Koordinat; char Type; int Troops; int Level; int A; // Nilai penambahan pasukan pada bangunan tiap awal giliran int M; // Jumlah maksimum pasukan yang bisa terdapat pada bangunan bool Pb; // Status pertahanan bangunan int U; // Pasukan awal yang harus dikalahkan untuk menjadikan bangunan milik pemain bool AfterAttack; //Bernilai True jika bangunan sdh digunakan utk menyerang, False jika belum bool AfterMove; //Bernilai True jika bangunan sdh digunakan utk memindahkan pasukan, False jika belum } Building; /* Selektor */ #define Koordinat(B) (B).Koordinat #define Type(B) (B).Type #define Troops(B) (B).Troops #define Level(B) (B).Level #define A(B) (B).A #define M(B) (B).M #define Pb(B) (B).Pb #define U(B) (B).U #define AfterAttack(B) (B).AfterAttack #define AfterMove(B) (B).AfterMove void InitializationBuilding (Building *B); /* I.S. Parameter-parameter pada Building belum terisi F.S. Parameter-parameter pada building terisi, sesuai jenis Building */ void AddPasukanNextTurn (Building *B); /* I.S. Jumlah pasukan pada building sembarang F.S. Jumlah pasukan pada building bertambah sebesar A, sesuai jenis building */ void LevelAdd (Building *B); /* I.S. Level bangunan kurang dari 4 F.S. - Level bangunan bertambah apabila jumlah pasukan pada bangunan >= M/2 - Jika level bangunan bertambah, jumlah pasukan pada bangunan berkurang sebanyak M/2 - Nilai A, M, dan Pb berubah sesuai Type Bangunan dan Level */ void SetLvBuildingToLv1 (Building* B); /* I.S. B terdefinisi F.S. B menjadi level 1 dengan segala komponen di dalamnya diubah */ void PrintBuilding(Building B); /* Menampilkan info bangunan B */ Building CopyBuilding(Building Bin); /* Mengembalikan salinan dari Bin */ #endif
C
/** * Return an array of arrays of size *returnSize. * The sizes of the arrays are returned as *returnColumnSizes array. * Note: Both returned array and *columnSizes array must be malloced, assume caller calls free(). */ void _color(int** g, int r, int c, int x, int y, int oc, int nc) { if (x < 0 || x >= r || y < 0 || y >= c) return; if (g[x][y] == nc || g[x][y] != oc) return; g[x][y] = nc; _color(g, r, c, x - 1, y, oc, nc); _color(g, r, c, x + 1, y, oc, nc); _color(g, r, c, x, y - 1, oc, nc); _color(g, r, c, x, y + 1, oc, nc); } int** colorBorder(int** grid, int gridSize, int* gridColSize, int r0, int c0, int color, int* returnSize, int** returnColumnSizes) { *returnSize = gridSize; *returnColumnSizes = gridColSize; if (!gridSize || !gridColSize || !gridColSize[0]) return grid; int oc = grid[r0][c0]; int nc = color; _color(grid, gridSize, gridColSize[0], r0, c0, oc, -nc); for (int i = 1; i < gridSize - 1; i ++) for (int j = 1; j < gridColSize[0] - 1; j ++) { if (grid[i][j] != - nc) continue; // careful here !!!!! if ((grid[i - 1][j] == - nc || grid[i - 1][j] == - oc) && (grid[i + 1][j] == - nc || grid[i + 1][j] == - oc) && (grid[i][j - 1] == - nc || grid[i][j - 1] == - oc) && (grid[i][j + 1] == - nc || grid[i][j + 1] == - oc)) grid[i][j] = - oc; } for (int i = 0; i < gridSize; i ++) for (int j = 0; j < gridColSize[0]; j ++) { if (grid[i][j] == -oc) grid[i][j] = oc; else if (grid[i][j] == -nc) grid[i][j] = nc; } return grid; }
C
#include<stdio.h> void print(int num); main() { int input; scanf("%d", &input); print(input); } void print(num) { int i, j,k=65,l=1; char ch=k; for (i=0;i<num;i++) { for(j=0;j<num-i;j++) { printf(" "); } for(j=0;j<l+i;j++) { if(i==0) { printf("%c", ch); break; } else { if(j==0) { printf("%c", ch); } else if(j<=i) { k++; ch = k; printf("%c", ch); } else if(j>i) { k--; ch = k; printf("%c", ch); } } } puts(""); l++; ; } }
C
/* Image.h: header file for basic image manipulations */ /* Do not modify it */ #ifndef IMAGE_H #define IMAGE_H typedef struct { unsigned int W; /* image width */ unsigned int H;/* image height */ unsigned char *R; /* pointer to the memory storing all the R intensity values */ unsigned char *G; /* pointer to the memory storing all the G intensity values */ unsigned char *B; /* pointer to the memory storing all the B intensity values */ } IMAGE; /* Get the R intensity of pixel (x, y) in image */ unsigned char GetPixelR(const IMAGE *image, unsigned int x, unsigned int y); /* Get the G intensity of pixel (x, y) in image */ unsigned char GetPixelG(const IMAGE *image, unsigned int x, unsigned int y); /* Get the B intensity of pixel (x, y) in image */ unsigned char GetPixelB(const IMAGE *image, unsigned int x, unsigned int y); /* Set the R intensity of pixel (x, y) in image to r */ void SetPixelR(IMAGE *image, unsigned int x, unsigned int y, unsigned char r); /* Set the G intensity of pixel (x, y) in image to g */ void SetPixelG(IMAGE *image, unsigned int x, unsigned int y, unsigned char g); /* Set the B intensity of pixel (x, y) in image to b */ void SetPixelB(IMAGE *image, unsigned int x, unsigned int y, unsigned char b); /* Allocate dynamic memory for the image structure and its R/G/B values */ /* Return the pointer to the image, or NULL in case of error */ IMAGE *CreateImage(unsigned int Width, unsigned int Height); /* Free the memory for the R/G/B values and IMAGE structure */ void DeleteImage(IMAGE *image); /* Return the image's width in pixels */ unsigned int ImageWidth(const IMAGE *image); /* Return the image's height in pixels */ unsigned int ImageHeight(const IMAGE *image); #endif
C
/** * Implementation of various scheduling algorithms. * * Shortest-Job-First scheduling */ #include <stdlib.h> #include <stdio.h> #include <stddef.h> #include "task.h" #include "list.h" #include "cpu.h" struct node *head = NULL; Task *pickNextTask(); // add a new task to the list of tasks void add(char *name, int priority, int burst) { // first create the new task Task *newTask = (Task *) malloc(sizeof(Task)); newTask->name = name; newTask->priority = priority; newTask->burst = burst; // insert the new task into the list of tasks insert(&head, newTask); } /** * Run the priority scheduler */ void schedule() { Task *current; while (head != NULL) { current = pickNextTask(); run(current,current->burst); delete(&head, current); } } /** * Returns the next task selected to run. */ Task *pickNextTask() { struct node *temp; Task *hp = head->task; temp = head->next; while (temp != NULL) { if (temp->task->burst < hp->burst) hp = temp->task; temp = temp->next; } return hp; }