language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* rt_get.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: evilsbol <evilsbol@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/03/21 13:52:12 by evilsbol #+# #+# */ /* Updated: 2014/03/21 13:54:22 by evilsbol ### ########.fr */ /* */ /* ************************************************************************** */ #include "rt.h" void rt_get_cam(int fd, t_dt *dt) { char *line; float pos[3]; float dir[3]; line = NULL; rt_init_float(pos, 3); rt_init_float(dir, 3); while (get_next_line(fd, &line) > 0 && ft_count(line, '}') == 0) { if (ft_strstr(line, "pos:")) rt_get_float(line, pos, 3); if (ft_strstr(line, "dir:")) rt_get_float(line, dir, 3); else continue; } rt_set_cam(pos, dir, dt); int i = -1; while (++i < 3) printf("cam: pos[%d]: %f|dir[%d]: %f\n", i, dt->cam_pos[i], i, dt->dir[i]); } void rt_get_sph(int fd, t_obj *obj) { char *line; float pos[3]; int col[3]; float rad[1]; line = NULL; rt_init_float(pos, 3); rt_init_int(col, 3); while (get_next_line(fd, &line) > 0 && ft_count(line, '}') == 0) { if (ft_strstr(line, "pos")) rt_get_float(line, pos, 3); if (ft_strstr(line, "radius")) rt_get_float(line, rad, 1); if (ft_strstr(line, "color:")) rt_get_int(line, col, 3); } rt_set_sph(pos, rad, col, obj); int i = -1; while (++i < 3) printf("sphere: pos[%d]: %f|col[%d]: %d\n", i, obj->sph[i].c[i], i, obj->sph[i].col[i]); } // what is pos_v? void rt_get_cyl(int fd, t_obj *obj) { char *line; float posv[2][3]; int col[3]; float rad[1]; line = NULL; rt_init_float(posv[0], 3); rt_init_float(posv[1], 3); rt_init_int(col, 3); while (get_next_line(fd, &line) > 0 && ft_count(line, '}') == 0) { if (ft_strstr(line, "pos:")) //rt_get_float(line, pos, 3); if (ft_strstr(line, "radius")) rt_get_float(line, rad, 1); if (ft_strstr(line, "color")) rt_get_int(line, col, 3); } rt_set_cyl(posv, rad, col, obj); int i = -1; while (++i < 3) printf("cyl: pos[%d]: %f|col[%d]: %d\n", i, obj->cy[i].c[i], i, obj->cy[i].col[i]); } void rt_get_pln(int fd, t_obj *obj) { char *line; float pos[3]; int col[3]; float dist[1]; line = NULL; while (get_next_line(fd, &line) > 0 && ft_count(line, '}') == 0) { if (ft_strstr(line, "pos")) rt_get_float(line, pos, 3); if (ft_strstr(line, "dist")) rt_get_float(line, dist, 1); if (ft_strstr(line, "color")) rt_get_int(line, col, 3); } rt_set_pln(pos, dist, col, obj); int i = -1; while (++i < 3) printf("plane: dist[%d]: %f|col[%d]: %d\n", i, obj->pl[i].d, i, obj->pl[obj->nb_o[2]].col[i]); } void rt_get_spt(int fd, t_obj *obj) { char *line; float pos[3]; int col[3]; line = NULL; rt_init_float(pos, 3); rt_init_int(col, 3); while (get_next_line(fd, &line) > 0 && ft_count(line, '}') == 0) { if (ft_strstr(line, "pos:")) rt_get_float(line, pos, 3); if (ft_strstr(line, "color")) rt_get_int(line, col, 3); } rt_set_spt(pos, col, obj); int i = -1; while (++i < 3) printf("spt: pos[%d]: %f|col[%d]: %f\n", i, obj->li[i].c[i], i, obj->li[i].col[i]); }
C
// // Created by cubazis on 25.05.18. // #include <string.h> #include <ctype.h> #include "task.h" /** The stub function * just to demonstrate how to work with ck_assert * please look for test case for stub function in test_task.c */ int stub(void) { return 42; } /** The array_changer function * just to demonstrate how to work with returning of array from function * * 1) C language doesn't have strings * 2) array in a C language is just a segment of memory * 3) C lang doesn't have ability to pass array as parameter in a function * 4) we suppose that you don't know about memory allocation through pointers * * so, we provide you simple demo function which change 'c' char in input array * input parameter: constant array of chars * output: pointer to memory segment in which resulting array starts * * extra stuff: we provide you three define macros in task.h. * you can use them in your solutions * if you don't want to use them please, don't delete them - somebody may use it * * please look for test case for array_changer function in test_task.c */ char* array_changer(const char c[]) { char j = 0; int size = 0; STRING_LEN(size, c); char* b = ALLOCATE(size); for (;j < size;) { if(c[j] == 'c') b[j] = 'b'; else b[j] = c[j]; j++; } return b; } /** YOUR SOLUTIONS */ char *detab (const char input[]){ char *res = (char*) malloc(sizeof(char) * strlen(input)); unsigned int pos = 0; for (int i = 0; i < strlen(input); i++) { if (input[i] != '\t') { res[pos] = input[i]; pos++; } else { for (int j = 0; j < 4; j++){ res[pos] = ' '; pos++; } } } res[pos] = '\0'; return res; } char *entab (const char input[]){ char *res = (char*) malloc(sizeof(input)); unsigned int pos = 0; int i = 0; while (i < strlen(input)) { if (input[i] != ' ') { res[pos] = input[i]; pos++; } else { int space_counter = 0; for (int j = i; j < i + 4 && i + 4 < strlen(input); j ++){ if (input[j] == ' ') space_counter++; } if (space_counter == 4) { res[pos] = '\t'; i += 3; pos ++; } else { res[pos] = ' '; pos ++; } } i++; } res[pos] = '\0'; return res; } char* enter (int n, const char input[]) { char *res = (char*) malloc(sizeof(char) * (strlen(input) + strlen(input) / n)); unsigned int counter = 0; unsigned int pos = 0; for (int i = 0; i < strlen(input); i++) { counter++; res[pos] = input[i]; pos++; if (counter == n) { res[pos] = '\n'; pos++; counter=0; } } res[pos] = '\0'; return res; } char *flush(const char input[]) { char *result = malloc(sizeof(input)); char isComment = 'n'; int resultLastIndex = 0; for (int i = 0; i < strlen(input); i++) { switch (isComment) { case 'n': if (input[i] != '/') { result[resultLastIndex] = input[i]; resultLastIndex++; continue; } else { if (i + 1 < strlen(input)) { switch (input[i + 1]) { case '*': isComment = 'l'; i++; break; case '/': isComment = 's'; i++; break; default: result[resultLastIndex] = input[i]; resultLastIndex++; } } } break; case 'l': if (input[i] == '*' && i + 1 < strlen(input) && input[i + 1] == '/') { isComment = 'n'; i++; } break; case 's': if (input[i] == '\n') { isComment = 'n'; } break; } } result[resultLastIndex]='\0'; return result; } int htoi(const char hex[]) { int integer = 0; //result long long int stp16 = 1; //power of 16 int nonZeroDigitIndex = 0; //index of first non zero digit //Searching for nonzero digit to save time if (hex[0] == '0' && (hex[1] == 'x' || hex[1] == 'X')) { nonZeroDigitIndex = 2; } while (hex[nonZeroDigitIndex] == '0' && nonZeroDigitIndex < strlen(hex)) { nonZeroDigitIndex++; } //For every letter we use appropriate integer for (long int i = strlen(hex) - 1; i >= nonZeroDigitIndex; i--) { char cur = hex[i]; if ((cur >= 65) && (cur <= 90)) cur = (char) (cur + 32); switch (cur) { case 'f': integer += 15 * stp16; break; case 'e': integer += 14 * stp16; break; case 'd': integer += 13 * stp16; break; case 'c': integer += 12 * stp16; break; case 'b': integer += 11 * stp16; break; case 'a': integer += 10 * stp16; break; default: integer += (int) cur * stp16; break; } //Accumulation of power of 16 stp16 *= 16; } return integer; } char *squeeze(const char s1[], const char s2[]) { char* result = malloc(sizeof(s1)); //allocating memory for result string char isContains; //is current letter contains in s2 ('f' for false and 't' for true) long int lastS1Index = 0; //saving last index of result string for (long int i = 0; i < strlen(s1); i++) { isContains = 'f'; //comparison of letters from s1 and s2 for (long int j = 0; j < strlen(s2) && isContains=='f'; j++) { if(s1[i]==s2[j]) { isContains ='t'; } } //copying letter if s2 don't contain it if(isContains=='f') { result[lastS1Index] = s1[i]; lastS1Index++; } } result[lastS1Index]='\0'; return result; } int any(const char s1[], const char s2[]) { char doesContain = 'f';//indicator for immediate exit if s1 contain any character from s2 for (int i = 0; i < strlen(s1) && doesContain == 'f'; i++) { for (long int j = 0; j < strlen(s2) && doesContain == 'f'; j++) { //comparison if (s1[i] == s2[j]) { doesContain = 't'; } } if (doesContain == 't') { return i; } } return -1; } unsigned setbits(unsigned x, int p, int n, unsigned y){ unsigned x1 = x; int to_move = p + 1 - n; x1 = x1 & (~(~0 << to_move)); x = (x >> to_move) & ((~0 << n)); x = x | y & (~(~0 << n)); x = x << to_move | x1; return x; } int binsearch(int x, int v[], int n) { int low, high, mid; low = 0; high = n - 1; while (low < high) { mid = (low + high) / 2; if (x <= v[mid]) high = mid; else low = mid + 1; } if (v[low] == x) { return low; } else { return -1; } } char* escape(const char from[]) { char* result = malloc(sizeof(from)*2); //doubled size if string contains only tabulator or new line characters long int lastIndex = 0; for(int i = 0; i < strlen(from);i++) { switch(from[i]) { case 0x0A: //new line character result[lastIndex] = '\\'; result[lastIndex+1] = 'n'; lastIndex+=2; break; case 0x09: //tabulator character result[lastIndex] = '\\'; result[lastIndex+1] = 't'; lastIndex+=2; break; default: //other characters result[lastIndex] = from[i]; lastIndex++; } } result[lastIndex] = '\0'; return result; } char* expand(const char s1[]){ int i, j; char t; char * s2 = malloc(sizeof(char)); for (i = 0, j = 0; s1[i] != '\0'; i++) { if ( s1[i] == '-' ) { if ( (isdigit(s1[i-1]) && isdigit(s1[i+1]) && (s1[i-1]<s1[i+1])) || (islower(s1[i-1]) && islower(s1[i+1]) && (s1[i-1]<s1[i+1])) || (isupper(s1[i-1]) && isupper(s1[i+1]) && (s1[i-1]<s1[i+1])) ) for (t = (char)(s1[i-1]+1); t < s1[i+1]; t++){ s2 = realloc(s2, sizeof(char) * (i + t)); s2[j++] = t; } else s2[j++] = s1[i]; } else s2[j++] = s1[i]; } s2[j] = '\0'; return s2; } char* itoa(int n) { int i, sign; sign = n; char * s = malloc(sizeof(char)); i = 0; do { s = realloc(s, (i + 1) * sizeof(char)); s[i++] = abs(n % 10) + '0'; } while ( n /= 10 ); if (sign < 0) s[i++] = '-'; s[i] = '\0'; int c, ind, j ; for (ind = 0, j = strlen(s)-1; ind < j; ind ++, j--) { c = s [ind] ; s[ind] = s[j] ; s[j] = c; } return s; } char* itob(int n, int b) { int i, sign; char digits[] = "0123456789ABCDEF"; char * s = malloc(sizeof(char)); sign = n; i = 0; do { s = realloc(s, (i + 1) * sizeof(char)); s[i++] = digits[n % b]; } while ( n /= b ); /* исключить ее */ if (sign < 0) s[i++] = '-'; s[i] = '\0'; int c, ind, j ; for (ind = 0, j = strlen(s)-1; ind < j; ind ++, j--) { c = s [ind] ; s[ind] = s[j] ; s[j] = c; } return s; } int strrindex(const char s[], const char t[]){ int index = -1; for (int i = 0; i < strlen(s); i++) { if (s[i] == t[0] && strlen(s) - i >= strlen(t) && index == -1) { unsigned count = 0; for (int j = 0; j < strlen(t); j++) { if (s[i+j] == t[j]) count++; } if (count == strlen(t)) index = i; } } return index; } double atofe(const char s[]){ char* str = malloc(sizeof(s)); int index = 0; for (int i =0; i < strlen(s) && s[i] != 'e'; i++){ index = i; str[i] = s[i]; } double d; sscanf(s, "%lf", &d); return d; } /** GET FROM task.h */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "lib/mongoose.h" #include "lib/jerry-api.h" #include "lib/jerry-port.h" struct mg_mgr mgr; struct mg_connection *c; struct mt_response_object { const char *content; int length; unsigned int status_code; } mt_resp; static void ev_handler(struct mg_connection *c, int ev, void *p) { if (ev == MG_EV_HTTP_REQUEST) { struct http_message *hm = (struct http_message *) p; mg_send_head(c, mt_resp.status_code, mt_resp.length, "Content-Type: 'text/plain'"); mg_printf(c, "%.*s", mt_resp.length, mt_resp.content); } } static jerry_value_t handle (const jerry_value_t func_value, // function object const jerry_value_t this_value, // this arg const jerry_value_t *args_p, // function args const jerry_value_t args_cnt) { // nargs if (args_cnt < 3) { fprintf(stderr, "Insufficient number of arguments to handle()"); exit(-1); } mt_resp.content = args_p[0]; mt_resp.length = (int) strlen((const char *) args_p[0]); mt_resp.status_code = args_p[2]; c = mg_bind(&mgr, atoi(args_p[1]), ev_handler); mg_set_protocol_http_websocket(c); return jerry_create_string((const jerry_char_t *) args_p[0]); } void create_modules(void) { jerry_value_t object = jerry_create_object(); jerry_value_t prop_name = jerry_create_string((const jerry_char_t *) "handle"); jerry_value_t func_obj = jerry_create_external_function(handle); jerry_set_property(object, prop_name, func_obj); jerry_release_value(prop_name); jerry_release_value(func_obj); jerry_value_t global_object = jerry_get_global_object(); prop_name = jerry_create_string((const jerry_char_t *) "http"); jerry_set_property(global_object, prop_name, object); jerry_release_value(prop_name); jerry_release_value(object); jerry_release_value(global_object); } int main(void) { jerry_init(JERRY_INIT_EMPTY); mg_mgr_init(&mgr, NULL); const jerry_char_t script[] = "var str = http.handle('Hello world', '8000', '200'); print(str);"; size_t script_size = strlen((const char*) script); create_modules(); jerry_value_t eval_ret = jerry_eval(script, script_size, false); jerry_release_value(eval_ret); for (;;) { mg_mgr_poll(&mgr, 1000); } mg_mgr_free(&mgr); jerry_cleanup(); return 0; }
C
#include<stdio.h> #include<string.h> //strlen #include<sys/socket.h> #include<arpa/inet.h> //inet_addr #include<unistd.h> //write #include<stdlib.h> #include <sys/time.h> #include <sys/types.h> #include <sys/ioctl.h> #include "ext.h" #include "reader.h" #include "garbledcircuit.h" #include <time.h> #include <iostream> #include <fstream> #define ITR 333333333 int com_key; void Encrypt(char* message, int start, int s,int op); void show_usage(); void EncapsulateProgram(Circuit C, char buffer[],int *size); void decryptGProgram(char buffer[],int size,GCircuit *GC,key *ginput,key *fixedkey); void printkey(key kk); int main(int argc , char *argv[]) { struct sockaddr_in middle; int iterations;int sock; clock_t begin_time; if (argc!=4 && argc!=5){ show_usage(); exit(0); } if (argc==4) iterations = ITR; else iterations = atoi(argv[4]); // read circuit and pass it to the enclave printf("Read the circuit from file %s ....\n",argv[3]); Circuit C = readBRISCircuit(argv[3]); //passCircuit(eid,&C,sizeof(Circuit)); printf("Input size:%d\n",C.inpSize); printf("Output size:%d\n",C.outSize); printf("Wires :%d\n",C.numWires); printf("Gates:%d\n",C.numGates); printf("GGate size %d\n",sizeof(GGate)); char client_message[2+C.inpSize]; char enclave_message[C.inpSize+1]; char output_message[C.outSize+1]; sock = socket(AF_INET , SOCK_STREAM , 0); if (sock == -1) { printf("Could not create socket"); } puts("Socket created. Trying to connect to server"); middle.sin_addr.s_addr = inet_addr(argv[1]); //127.0.0.1 middle.sin_family = AF_INET; middle.sin_port = htons( atoi(argv[2]) ); //8887 //Connect to Enclave Parent com_key=10000; while (connect(sock , (struct sockaddr *)&middle , sizeof(middle)) < 0) { //perror("connect failed. Error"); //return 1; } puts("Connected\n"); for (int i=0;i<iterations;i++){ char *program=(char *)malloc(PROGLIMIT); int prog_size; begin_time=clock(); C = readBRISCircuit(argv[3]); EncapsulateProgram(C,program,&prog_size); Encrypt(program,4, prog_size-4,1); // encrypt before sending com_key++; printf("Time for reading and serializing circuit :%f\n",float( clock () - begin_time ) / CLOCKS_PER_SEC); printf("size of program %d\n",prog_size); //exit(0); //Send the message to server printf("Sending the circuit to the server \n"); for(int i=0;i<PROGLIMIT/BUFSIZE;i++){ if ( send(sock , &program[i*BUFSIZE] ,BUFSIZE , 0) < 0) { puts("Send failed"); } int vv; recv(sock,&vv,4, 0); } //Receive a reply from the server int ans; //recv(sock,&ans,4,0); int bufcount=0;int buftot=0; printf("Recieving garbled circuit from the server\n"); for(int i=0;i<PROGLIMIT/BUFSIZE;i++){ if (recv(sock , &program[i*BUFSIZE] ,BUFSIZE , 0) <0 ) { puts("Error recv"); } int vv; send(sock,&vv,4, 0); } printf("Garbled Program received %d\n",*((int *)program)); int size = *((int *)program); GCircuit GC;key *ginput;key fixedkey; ginput = (key *)malloc(sizeof(key)* C.inpSize); if (ginput==NULL)printf("malloc problem\n"); Encrypt(program,4,size-4,2); // decrypt begin_time=clock(); decryptGProgram(program,size,&GC,ginput,&fixedkey); com_key++; printf("Time for deserializing garbeled circuit:%f\n",float( clock () - begin_time ) / CLOCKS_PER_SEC); //evaluate if (GC.ggates==NULL || GC.outWLabels==NULL) printf("Error Malloc\n"); begin_time=clock(); printf("Evaluating garbled circuit..\n"); key *goutput = (key *)calloc(C.outSize, sizeof(key)); bit *output1 = (bit *)calloc(C.outSize, sizeof(bit)); evalGCircuit(GC, ginput, goutput, fixedkey); printf("Time for evaluating garbled circuit:%f\n",float( clock () - begin_time ) / CLOCKS_PER_SEC); printkey(*goutput); send(sock,goutput,C.outSize*sizeof(key),0); int u; recv(sock,&u,4,0); /* printf("%d\n",GC.numGates); printf("%d\n",GC.numWires); printf("%d\n",GC.inpSize); printf("%d\n",GC.outSize); for(int i=0;i<GC.numGates;i++) printf("%d %d %d %d\n",GC.ggates[i].a,GC.ggates[i].b,GC.ggates[i].out , GC.ggates[i].GT.ciphers[3]); for(int i=0;i<GC.outSize;i++) printf("%d\n",GC.outWLabels[i]); */ // check output /* for(int j=0;j<C.outSize;j++){ for (int i = 0; i < sizeof(key); i++) { printf("%d", goutput[j].k[i]); } printf("\n"); }*/ //check ginput /* for(int j=0;j<C.inpSize;j++){ for (int i = 0; i < sizeof(key); i++) { printf("%d", ginput[j].k[i]); } printf("\n"); }*/ /* for (int i = 0; i < sizeof(key); i++) { printf("%d",fixedkey.k[i]); } printf("\n"); */ printf("Sending garbled output to Server %d...\n",C.outSize*sizeof(key)); free(program); free(GC.ggates); free(GC.outWLabels); free(C.inpSizes); free(C.gates); free(C.outWLabels); //recv(sock,&ans,4,0); free(ginput); free(goutput); free(output1); /* for(int j=0;j<C.inpSize;j++){ for (int i = 0; i < sizeof(key); i++) { printf("%d", ginput[j].k[i]); } printf("\n"); } */ } close(sock); return 0; } void show_usage(){ printf("program_owner <server_ip> <server_port> <program_file> [num_of_iterations]\n"); } void Encrypt(char *message,int start, int size,int op){ Encrypt_Com(message,start,size,op,com_key); /* for(int i=start;i<s;i++){ message[i] = message[i] ^ com_key; //memcpy(message+i*8,&r,8); }*/ } void EncapsulateProgram(Circuit C, char buffer[],int *size){ int counter=4; int numGate = C.numGates; memcpy(&buffer[counter],&numGate,sizeof(int)); counter+=4; int numWires = C.numWires; memcpy(&buffer[counter],&numWires,sizeof(int)); counter+=4; int num_of_clients = C.num_of_clients; memcpy(&buffer[counter],&num_of_clients,sizeof(int)); counter+=4; int inputsize = C.inpSize; memcpy(&buffer[counter],&inputsize,sizeof(int)); counter+=4; int outputsize = C.outSize; memcpy(&buffer[counter],&outputsize,sizeof(int)); counter+=4; for(int i=0;i<C.numGates;i++){ Gate g = C.gates[i]; memcpy(&buffer[counter],&g,sizeof(Gate)); counter+=sizeof(Gate); } for(int i=0;i< C.num_of_clients;i++){ int g = C.inpSizes[i]; memcpy(&buffer[counter],&g,sizeof(int)); counter+=sizeof(int); } for(int i=0;i< outputsize;i++){ int g = C.outWLabels[i]; memcpy(&buffer[counter],&g,sizeof(int)); counter+=sizeof(int); } memcpy(buffer,&counter,sizeof(int)); *size = counter; } void decryptGProgram(char buffer[],int size, GCircuit* GC, key* ginput, key * fixedkey){ int counter=4; int numGates = *((int*)(buffer+counter)); printf("Number of Gates: %d\n",numGates); counter+=4; int numWires = *((int*)(buffer+counter)); printf("Number of Wires: %d\n",numWires); counter+=4; int inputsize = *((int*)(buffer+counter)); printf("Input Size: %d\n",inputsize); counter+=4; int outputsize = *((int*)(buffer+counter)); printf("Output Size: %d\n",outputsize); counter+=4; GC->numGates= numGates; GC->numWires = numWires; GC->ggates = (GGate*)malloc(numGates*sizeof(GGate)); GC->outWLabels = (int *)malloc(outputsize * sizeof(int)); GC->inpSize = inputsize; GC->outSize = outputsize; for(int i=0;i<numGates;i++){ GGate g = *((GGate*)(buffer+counter)); GC->ggates[i] = g; //printf("%d %d %d\n",g.a,g.b,g.out); counter+=sizeof(GGate); } for(int i=0;i< outputsize;i++){ int g = *((int*)(buffer+counter)); GC->outWLabels[i]= g; //printf("Wire %d\n",g); counter+=sizeof(int); } memcpy(ginput, buffer+counter, inputsize*sizeof(key)); counter+= sizeof(key)*inputsize; memcpy(fixedkey ,buffer+counter,sizeof(key)); counter+= sizeof(key); //printf("done\n"); }
C
#define PRINT(int) printf( "int = %d ", int) main() { int x=03,y=02,z=01; PRINT (x | y & ~z); PRINT (x & y && z); PRINT (x ^ y & ~z); }
C
#include "DelaunayTable.Geometry.h" #include <stdbool.h> #include <stddef.h> #include <stdlib.h> #include <assert.h> #define nCase (1) #define nDim (4) static const size_t N = 100+1; static const double x_min = -6.0; static const double x_max = +6.0; static inline double range( const size_t i, const size_t N ) { const double r = (double) i / (double) (N-1); return (1-r) * x_min + r * x_max; } static inline double norm( const double* xs ) { double result = 0.0; for (size_t i = 0 ; i < nDim ; i++) { result += xs[i] * xs[i]; } return result; } const double coordinates[nCase][nDim+1][nDim] = { { // case1 { 5, 0, 0, 0}, { 0, 5, 0, 0}, { 0, 0, 5, 0}, { 0, 0, 0, 5}, {-4, -3, 0, 0} }, }; int main(int argc, char** argv) { for (size_t iCase = 0 ; iCase < nCase ; iCase++) { const double* polygon[nDim+1]; for (size_t i = 0 ; i < (nDim+1) ; i++) { polygon[i] = (const double*) &coordinates[iCase][i]; } const double R0 = norm(polygon[0]); for (size_t i = 1 ; i < nDim ; i++) { assert( double__compare(norm(polygon[i]), R0) == 0 ); } for (size_t ix = 0 ; ix < N ; ix++) for (size_t iy = 0 ; iy < N ; iy++) { const double point[nDim] = { range(ix, N), range(iy, N) }; const double R1 = norm(point); bool inside; assert( insideCircumsphereOfPolygon(nDim, polygon, point, &inside) == 0 ); if (double__compare(R0, R1) != 0) { assert( inside == (double__compare(R0, R1) > 0) ); } } } return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp; double d = 12.23; int i = 101; long l =123023L; if((fp=fopen("test", "wb+"))==NULL) { printf("Невозможно открыть файл.\n"); exit(1); } fwrite(&d, sizeof(double), 1, fp); fwrite(&d, sizeof(int), 1, fp); fwrite(&d, sizeof(long), 1, fp); rewind(fp); fread(&d, sizeof(double), 1, fp); fread(&i, sizeof(int), 1, fp); fread(&l, sizeof(long), 1, fp); printf("%f %d %ld", d, i, l); fclose(fp); return 0; }
C
/* ** EPITECH PROJECT, 2017 ** event ** File description: ** All that involve event managing */ #include <SFML/Graphics.h> #include <time.h> #include "structs.h" #include "function.h" #include "my.h" //Display the mouse and highlight the buttons void display_mouse(game_t *game) { sfSprite *sprite1 = game->sprites[33].sprite; sfSprite *sprite2 = game->sprites[34].sprite; sfSprite *mouseSprite = game->sprites[37].sprite; int mx = game->mousex; int my = game->mousey; sfVector2f nul = {0, 0}; sfVector2f pos = {game->mousex - 15, game->mousey - 15}; sfSprite_setScale(sprite1, (sfVector2f){4, 4}); sfSprite_setScale(sprite2, (sfVector2f){4, 4}); if (game->menu == 5) { //In main menu, check if buttons needs to be highlighted if (mx >= 342 && mx <= 680 && my >= 496 && my <= 580) image(game->window,sprite1, nul); else if (mx >= 342 && mx <= 680 && my >= 596 && my <= 680) image(game->window,sprite2, nul); } image(game->window,mouseSprite, pos); } int analyse_events(sfRenderWindow *window, game_t *game) { sfEvent event; while (sfRenderWindow_pollEvent(window, &event)) { switch ((int)event.type) { case (int)sfEvtClosed: close_window(window); break; case (int)sfEvtMouseButtonPressed: modify_mouse_pos_press(&event, window, game); manage_mouse_click(window, game); break; case (int)sfEvtMouseMoved: modify_mouse_pos(&event, window, game); } } display_mouse(game); return (0); } void play_music(game_t *game) { if (game->musics[0]) sfMusic_play(game->musics[0]); if (game->musics[7]) sfMusic_stop(game->musics[7]); } int manage_mouse_click(sfRenderWindow *window, game_t *game) { int mx = game->mousex; int my = game->mousey; if (game->menu == 1) { game->var = 1 + !game->ducks[0].hit * 0.8; modify_duck_speed(game); } else if (game->menu == 5) { if (mx >= 342 && mx <= 680 && my >= 496 && my <= 580) { game->menu = 0; play_music(game); } else if (mx >= 342 && mx <= 680 && my >= 596 && my <= 680) close_window(window); } return (0); } int close_window(sfRenderWindow *window) { sfRenderWindow_close(window); return (0); }
C
/*************************************************************** Copyright (c) Charles Childers **************************************************************/ /* | 001 | Data Stack Underflow | | 002 | Data Stack Overflow | | 003 | Address Stack Underflow | | 004 | Address Stack Overflow | | 005 | Invalid Memory Access | | 006 | Division by Zero | */ #ifdef ENABLE_ERROR void execute(NgaState *vm, CELL cell); void handle_error(NgaState *vm, CELL error) { CELL saved_ip = vm->cpu[vm->active].ip; if (vm->ErrorHandlers[error] != 0) { printf("\nHandling %lld\n", error); execute(vm, vm->ErrorHandlers[error]); } vm->cpu[vm->active].ip = saved_ip; } void register_error_handler(NgaState *vm) { CELL ErrorID = stack_pop(vm); CELL ErrorHandler = stack_pop(vm); vm->ErrorHandlers[ErrorID] = ErrorHandler; printf("Assigned %lld to %lld\n", ErrorID, ErrorHandler); } void io_error(NgaState *vm) { switch (stack_pop(vm)) { case 0: register_error_handler(vm); break; default: break; } } void query_error(NgaState *vm) { stack_push(vm, 0); stack_push(vm, 1234); } #endif
C
/* ** EPITECH PROJECT, 2017 ** bootstrap ** File description: ** bootstrap my screen saver */ #include <SFML/Graphics.h> #include <SFML/System.h> #include <SFML/Window.h> #include <SFML/Window/Export.h> #include "my.h" #include <math.h> #include <stdlib.h> #include <unistd.h> info_t *ini_info(void) { sfVideoMode mode = {1920, 1080, 32}; info_t *info = malloc(sizeof(info_t)); char *name = "My_screen_saver"; info->window = sfRenderWindow_create(mode, name, sfResize | sfClose | sfFullscreen, NULL); info->sprite = sfSprite_create(); info->texture = sfTexture_create(1920, 1080); info->tab = framebuffer_create(1920, 1080); info->width = 1920; info->length = 1080; info->head = NULL; ini_point(info); return (info); } int ini_point(info_t *info) { fill_list(info, (sfVector2i){600, 700}, sfRed); fill_list(info, (sfVector2i){100, 900}, sfYellow); fill_list(info, (sfVector2i){20, 400}, sfBlue); return (0); } void event_window_one(info_t *info) { while (sfRenderWindow_pollEvent(info->window, &info->event)){ if (info->event.type == sfEvtClosed) sfRenderWindow_close(info->window); if (sfKeyboard_isKeyPressed(sfKeyRight) == sfTrue) { sfRenderWindow_close(info->window); id_two(); } } } int id_one(void) { info_t *info = ini_info(); if (!info->window) return (84); while(sfRenderWindow_isOpen(info->window)) { event_window_one(info); opacity(info->tab); sfRenderWindow_clear(info->window, sfBlack); balls_info(info); sfTexture_updateFromPixels(info->texture, info->tab->pixels, 1920, 1080, 0, 0); sfSprite_setTexture(info->sprite, info->texture, sfTrue); sfRenderWindow_drawSprite(info->window, info->sprite, NULL); sfRenderWindow_display(info->window); } return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> int cmpfunc(const void *a, const void *b) { return (*(int*)a - *(int*)b); } int main() { int t; scanf("%d",&t); while(t--) { int n,p; unsigned int min=INT_MAX; scanf("%d",&n); int arr[n]; for(int i=0; i<n; i++) { scanf("%d",&arr[i]); } qsort(arr,n,sizeof(int),cmpfunc); for(int j=0; j<n; j++) { p = (arr[j] ^ arr[j+1]); if(p < min) { min = p; } } printf("%d\n",min); } }
C
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include "funciones.h" #define C 20 int obtenerEspacioLibre(EPersona lista[]) { int i; for(i=0;i<C;i++) { lista[i].estado=0; lista[i].edad=0; lista[i].dni=0; } } void alta (EPersona lista[]) { int i,j; long int auxdni; for(i=0;i<C;i++) { if(lista[i].estado==0) { printf("ingrese nombre: "); fflush(stdin); gets(lista[i].nombre); printf("ingrese edad: "); fflush(stdin); scanf("%d",&lista[i].edad); while(lista[i].edad<1||lista[i].edad>99) { printf("Error, reingrese la edad: "); scanf("%d",&lista[i].edad); } printf("ingrese dni: "); fflush(stdin); scanf("%ld",&auxdni); while(auxdni<1000000||auxdni>99999999) { printf("DNI invalido. Reingrese DNI: "); scanf("%ld",&auxdni); } for(j=0;j<C;j++) { while(auxdni==lista[j].dni) { printf("Error, DNI existente. Reingrese DNI: "); scanf("%ld",&auxdni); } } lista[i].dni=auxdni; lista[i].estado=1; break; } } if(i==C) { printf("espacio agotado.\n"); } } int buscarPorDni(EPersona lista[]) { int indice,i; long int auxdni; printf("Ingrese DNI a dar de baja: "); scanf("%ld",&auxdni); for(i=0;i<C;i++) { if(auxdni==lista[i].dni) { indice=i; break; } } return indice; } void baja (EPersona lista[]) { int i,auxindice; char opcion; auxindice=buscarPorDni(lista); for(i=0;i<C;i++) { if(auxindice==i && lista[auxindice].estado==1) { printf("Persona encontrada. Desea dar de baja? S/N \n"); opcion=getche(); if(opcion=='s') { lista[i].estado=0; lista[i].edad=0; lista[i].dni=0; printf("Datos eliminados.\n"); break; } else { printf("No se eliminaron datos.\n"); } } } if(i==C) { printf("persona no encontrada.\n"); } } void listar (EPersona lista[]) { int i,j; EPersona auxNombre; if(lista[i].estado==0) { printf("Error, no hay datos cargados.\n"); } else { for(i=0;i<C-1;i++) { for(j=i+1;j<C;j++) { if(strcmp(lista[i].nombre,lista[j].nombre)>0) { auxNombre=lista[i]; lista[i]=lista[j]; lista[j]=auxNombre; } } } printf("Nombre Edad DNI\n"); for(i=0;i<C;i++) { if(lista[i].estado==1) { printf("%s %d %ld\n",lista[i].nombre,lista[i].edad,lista[i].dni); } } } } void grafico (EPersona lista[]) { int menor_18=0,entre_18y35=0,mayor_35=0,i,mayor=0,bandera=0; for(i=0;i<C;i++) { if(lista[i].estado==1) { if(lista[i].edad<19) { menor_18++; } if(lista[i].edad>18&&lista[i].edad<36) { entre_18y35++; } if(lista[i].edad>35) { mayor_35++; } } } if(menor_18>entre_18y35&&menor_18>mayor_35) { mayor=menor_18; } else { if(entre_18y35>menor_18&&entre_18y35>mayor_35) { mayor=entre_18y35; } else { mayor=mayor_35; } } for(i=mayor;i>0;i--) { if(menor_18>=mayor) { printf("*"); } if(entre_18y35>=mayor) { bandera=1; printf("\t*"); } if(mayor_35>=mayor) { if(bandera==0) printf("\t\t*"); if(bandera==1) printf("\t*"); } printf("\n"); } printf("<18\t19-35\t>35\n"); }
C
#include <stdio.h> #include <string.h> int main () { char str[127]; char *pstr; char sy,msy; int len=0, i, count=0,maxcount=0; puts("Enter string:"); fgets(str,127,stdin); pstr=str; len=strlen(pstr)-1; for (i=0;i<len;i++) { if ( pstr[i+1] == pstr[i] ) { sy=pstr[i]; count++; } else { if (count>maxcount) { msy=sy; maxcount=count; } sy='\0'; count=0; } } printf("%d\t",maxcount+1); for(i=0;i<maxcount+1;i++) { printf("%c",msy); } putchar('\n'); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <pthread.h> int main(int argc, char *argv[]) { pid_t pid,wpid; int status; pid = fork(); if(pid==0) { printf("---child,my id = %d,going to sleep 10s\n",getpid()); sleep(10); printf("---------------child die--------------\n"); return 666; } else if (pid>0) { wpid = wait(&status); if(wpid==-1) { perror("wait error"); exit(1); } if(WIFEXITED(status)) { printf("child exit with %d\n",WEXITSTATUS(status)); } if(WIFSIGNALED(status)) { printf("child kill with signal %d\n",WTERMSIG(status)); } printf("---------parent wait finish: %d\n",wpid); } else { perror("fork"); return 1; } return 0; }
C
//RTC Dummy 1.0 2017-01-23 // Fin: //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ char RtcFechaHora[7]; // "AAMMDDHHmmSSDS", [3]=HH=Hora(0-23) // cada caracter es un numero en binario (AA,MM,DD,HH,mm,SS,DS) //------------------------------------------------------------------------------ void RtcInit (){ // Inicializa RTC RtcFechaHora [0] = 17; // 2017 RtcFechaHora [1] = 1; // enero RtcFechaHora [2] = 1; // 1 RtcFechaHora [3] = 14; // 14 horas (2pm) RtcFechaHora [4] = 0; // 0 min RtcFechaHora [5] = 0; // 0 seg RtcFechaHora [6] = 1; // domingo } // fin de RtcInit //------------------------------------------------------------------------------ /* Para pruebas iniciales, usamos solo 2 alternativas de c/u (seg,min,etc) void RtcLee () { // Lee hora actual // RTC -> RtcFechaHora // Dummy: sgte segundo RtcFechaHora[5] ++; // sgte Seg if (RtcFechaHora[5] >= 60) { RtcFechaHora[5] = 0; RtcFechaHora[4] ++; // sgte Min (0-59) if (RtcFechaHora[4] >= 60) { RtcFechaHora[4] = 0; RtcFechaHora[3] ++; // sgte Hora (0-23) if (RtcFechaHora[3] >= 24) { RtcFechaHora[3] = 0; RtcFechaHora[2] ++; // sgte Dia del Mes if (RtcFechaHora[2] >= 30) { RtcFechaHora[2] = 1; RtcFechaHora[1] ++; // sgte Mes if (RtcFechaHora[1] > 12) { RtcFechaHora[1] = 1; RtcFechaHora[0] ++; // sgte Anio } } } } } } // fin de RtcLee / **/ //------------------------------------------------------------------------------ void RtcLee () { // Lee hora actual // RTC -> RtcFechaHora // Dummy: sgte segundo. Solo 2 alternativas c/u RtcFechaHora[5] ++; // sgte Seg (0-1) if (RtcFechaHora[5] >= 2) { RtcFechaHora[5] = 0; RtcFechaHora[4] ++; // sgte Min (0-1) if (RtcFechaHora[4] >= 2) { RtcFechaHora[4] = 0; RtcFechaHora[3] ++; // sgte Hora (0,1,14=0xE) if (RtcFechaHora[3] == 2) {RtcFechaHora[3] = 14;} if (RtcFechaHora[3] >= 15) { RtcFechaHora[3] = 0; RtcFechaHora[2] ++; // sgte Dia del Mes (1-2) if (RtcFechaHora[2] >= 3) { RtcFechaHora[2] = 1; RtcFechaHora[1] ++; // sgte Mes (1-2) if (RtcFechaHora[1] >= 3) { RtcFechaHora[1] = 1; RtcFechaHora[0] ++; // sgte Anio } } } } } } // fin de RtcLee //------------------------------------------------------------------------------ void RtcEsc () { // Esc hora actual // RtcFechaHora -> RTC } // fin de RtcEsc //------------------------------------------------------------------------------
C
#include <stdio.h> int sum_and_diff (int a, int b, int *res, int *prod, float *div) { int sum; sum = a + b; *res = a - b; *prod = a * b; *div = a / b; printf("Location of div = %d\n",&div); printf("Value of div = %f\n",*div); return sum; } void main (void) { int a = 9; int b = 2; int diff; int prod; float div; printf("The sum of %d and %d is %d\n",a, b, sum_and_diff(a, b, &diff, &prod, &div)); printf("The difference of %d and %d is %d\n",a, b, diff); printf("The product of %d and %d is %d\n",a, b, prod); printf("The division of %d and %d is %f\n",a, b, div); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <signal.h> #define MAX_LINE 128 #define TRUE 0 #define FALSE 1 static int getLine(char *input, char **toks, char *tok); static void printError(); static void insertProcess(int process); static void exitProgram(); static void printPrompt(int counter); int processes[20]; //keep track of 20 background processes char error_message[30] = "An error has occurred\n"; int backgroundIndex = 0; int main(int argc, char*argv[]) { int commandHistory = 0; if(argc > 1) { printError(); return(1); } while(1){ //pseudobooleans for redirection int inRedir = FALSE; int outRedir = FALSE; int needPipe = FALSE; int background = FALSE; int pipeAccess[2]; int inFile, outFile; char fileName[128]; commandHistory++; char *redirCommands[MAX_LINE]; //using as redir and 1st part ofpip char *pipe2[MAX_LINE]; //second part of the pipe int stdInput = dup(STDIN_FILENO); int stdOut = dup(STDOUT_FILENO); fflush(stdout); //printf("mysh (%i)> ", commandHistory); printPrompt(commandHistory); char *toks[MAX_LINE]; char *tok; char buff[10000]; if(fgets(buff, 10000, stdin) == NULL){ printError(); continue; } if(strcmp(buff, "\n") == 0){ //printError(); commandHistory--; continue; } if(strlen(buff) > MAX_LINE){ printError(); continue; } //format the command int __numArgs = 0; __numArgs = getLine(buff, toks, tok); if(__numArgs == 0){ //printError(); commandHistory--; continue; } //doing built ins //breaking upon "exit" if(strcmp(toks[0], "exit") == 0){ if(toks[1] != NULL){ printError(); continue; } else break; } else if (strcmp(toks[0], "pwd") == 0){ //pwd shouldn't have anything behind it if(toks[1] != NULL){ printError(); continue; } else{ //create buffer char *buf2; buf2 = malloc(sizeof(char) * 512); getcwd(buf2, 512); printf("%s\n", buf2); free(buf2); } } else if(strcmp(toks[0], "cd") == 0){ if(toks[1] == NULL) { char *home = malloc(sizeof(char) * 512); strcpy(home, getenv("HOME")); if(chdir(home) != 0){ printError(); continue; } free(home); } else{ if(toks[2] != NULL){ printError(); continue; } if(chdir(toks[1]) != 0){ printError(); continue; } } } else { //look for background process & int backgroundIndex = 0; while(toks[backgroundIndex] != NULL){ if(strcmp(toks[backgroundIndex], "&") == 0){ background = TRUE; toks[backgroundIndex] = NULL; } backgroundIndex++; } //look for < and > redirections and | piping int index = 0; int inIndex = 0; int outIndex = 0; int needContinue = FALSE; while(toks[index] != NULL){ if(strcmp(toks[index], "<") == 0){ inRedir = TRUE; if(toks[index+2] != NULL && strcmp(toks[index+2], ">") != 0){ printError(); needContinue = TRUE; } inIndex = index; } if(strcmp(toks[index], ">") == 0){ outRedir = TRUE; if(toks[index+2] != NULL && strcmp(toks[index+2], "<") != 0){ printError(); needContinue = TRUE; } outIndex = index; } if(strcmp(toks[index], "|") == 0){ needPipe = TRUE; if(index == 0 || toks[index + 1] == NULL){ printError(); needContinue = TRUE; } break; } index++; } if(needContinue == TRUE) continue; //have to send different things to the execvp command in the child if(outRedir == TRUE){ if(inRedir == FALSE) { for (int i = 0; i < outIndex; i++) { redirCommands[i] = toks[i]; } } //file name will be at index++ strcpy(fileName, toks[outIndex + 1]); inFile = open(fileName, O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU); if(inFile < 0){ printError(); continue; } close(1); //close stdout and reassing w/ dup2 dup2(inFile, 1); } if(inRedir == TRUE){ if(outRedir == FALSE) { for (int i = 0; i < inIndex; i++) { redirCommands[i] = toks[i]; } } //file name will be at index++ strcpy(fileName, toks[inIndex + 1]); outFile = open(fileName, O_RDONLY); if(outFile < 0){ printError(); continue; } close(0); //close the input dup2(outFile, 0); } if(inRedir == TRUE && outRedir == TRUE){ int firstRedir = inIndex; if(outIndex < inIndex) firstRedir = outIndex; for(int i = 0; i < firstRedir; i++){ redirCommands[i] = toks[i]; } } if(needPipe == TRUE) { //piping int pipe2Counter = 0; if (pipe(pipeAccess) == -1) { printError(); continue; } for(int i = 0; i < __numArgs; i++){ if(i < index){ redirCommands[i] = toks[i]; } else if(i > index){ pipe2[pipe2Counter] = toks[i]; pipe2Counter++; } } } //if there is a pipe, nothing is displayed in the console int pid = fork(); if (pid == 0) { if(needPipe == TRUE){ close(STDIN_FILENO); close(pipeAccess[0]); dup2(pipeAccess[1], STDOUT_FILENO); //stdout -> pipe //dup2(pipeAccess[1], 2); //stderr -> pipe } if(inRedir == TRUE || outRedir == TRUE || needPipe == TRUE) { if(execvp(redirCommands[0], redirCommands) == -1){ printError(); exit(1); } } else { if (execvp(toks[0], toks) == -1) { printError(); exit(1); } } } else if (pid < 0) { printError(); continue; } else { //parent if (background == TRUE) { insertProcess(pid); } else if(needPipe == FALSE){ int status; if(waitpid(pid, &status, 0) != pid){ printError(); } } else { close(pipeAccess[1]); //close write end in parent //need to fork again int child = fork(); if(child == 0) { close(STDIN_FILENO); close(pipeAccess[1]); //in the child process dup2(pipeAccess[0], STDIN_FILENO); //pipe other stdout to stdin of child if(execvp(pipe2[0], pipe2) == -1){ printError(); exit(0); } } else if (child < 0){ printError(); continue; } else{ int status2; waitpid(child, &status2, 0); kill(pid, SIGINT); //kill parent process. Ignore output, this means the that child is finished close(pipeAccess[1]); close(pipeAccess[0]); dup2(STDIN_FILENO, pipeAccess[0]); dup2(STDOUT_FILENO, pipeAccess[1]); } } if(needPipe == TRUE){ close(pipeAccess[0]); close(pipeAccess[1]); dup2(STDIN_FILENO, pipeAccess[0]); dup2(STDOUT_FILENO, pipeAccess[1]); fflush(stdout); } } } //all this closing is probably unnessiary but its thorough close(0); close(1); close(pipeAccess[0]); close(pipeAccess[1]); fflush(stdout); dup2(stdInput, 0); dup2(stdOut, 1); } exitProgram(); return 0; } int getLine(char *input, char **toks, char *tok){ tok = strtok(input, " \t\n"); int index = 0; while(tok != NULL){ toks[index] = tok; tok = strtok(NULL, " \t\n"); index++; } toks[index] = NULL; //null terminate return index; } void printError(){ write(STDERR_FILENO, error_message, strlen(error_message)); fflush(stdout); } void insertProcess(int process) { //shitty insert because the right way isn't fast enough processes[backgroundIndex] = process; if(backgroundIndex < 19) backgroundIndex++; else backgroundIndex = 0; } void exitProgram(){ for(int i =0; i < 20; i++){ if(processes[i] != NULL) { kill(processes[i], SIGINT); } } } void printPrompt(int counter){ char first[] = "mysh ("; char end[] = ")> "; char intBuff[100]; snprintf(intBuff, sizeof(int), "%i", counter); int outputLen = strlen(first) + strlen(end) + strlen(intBuff); char output[outputLen]; strcpy(output, first); strcat(output, intBuff); strcat(output, end); write(STDOUT_FILENO, output, outputLen); }
C
/* prints bases and quals */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <bam.h> #ifndef BAM_CIGAR_SHIFT #define BAM_CIGAR_SHIFT 4 #endif #ifndef BAM_CIGAR_MASK #define BAM_CIGAR_MASK 0xf #endif int main(int argc,char** argv) { int i; uint8_t *s, *t; bam_header_t *header; bamFile in = bam_open(argv[1], "r"); if(in == NULL) { fprintf(stderr, "Cannot open bam file!\n"); return -1; } bam1_t* b=bam_init1(); if(b == NULL) { fprintf(stderr, "Cannot init bam structure!\n"); return -1; } header = bam_header_read(in); while(bam_read1(in, b) >= 0) { const bam1_core_t *c = &b->core; s = bam1_seq(b); t = bam1_qual(b); // 1 - QNAME fprintf(stderr, "%s\t", bam1_qname(b)); // 2 - FLAG fprintf(stderr, "%d\t", c->flag); // 3 - RNAME fprintf(stderr, "%s\t", header->target_name[c->tid]); // 4 - POS fprintf(stderr, "%d\t", c->pos); // 5 - MAPQ fprintf(stderr, "%d\t", (int)(c->qual)); // 6 - CIGAR for (i = 0; i < c->n_cigar; ++i) fprintf(stderr, "%d%c", bam1_cigar(b)[i]>>BAM_CIGAR_SHIFT, "MIDNSHP"[bam1_cigar(b)[i]&BAM_CIGAR_MASK]); fprintf(stderr, "\t"); // 10 - SEQ for(i = 0; i < c->l_qseq; ++i) fprintf(stderr, "%c", bam_nt16_rev_table[bam1_seqi(s, i)]); fprintf(stderr, "\t"); // 11 - QUAL if(t[0] == 0xff) { fprintf(stderr, "*"); } else { fprintf(stderr, "------------------------\n"); for(i = 0; i < c->l_qseq; ++i) fprintf(stderr, "%c\t", t[i] + 33); fprintf(stderr, "\n"); for(i = 0; i < c->l_qseq; ++i) fprintf(stderr, "%u\t", (unsigned short)t[i]); fprintf(stderr, "------------------------\n"); } fprintf(stderr, "\n"); return 0; } bam_header_destroy(header); bam_close(in); bam_destroy1(b); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int checkList[700] = {0}; char *text; int acc = 0; int cur = 1; int line = 1; void nextLine() { while (text[cur] != '\n') cur++; cur++; //line++; } void startLine() { cur--; while (text[cur] != '\n') cur--; cur++; } void prevLine() { while (text[cur] != '\n') cur--; cur--; while (text[cur] != '\n') cur--; cur++; //line--; } int readvalue() { while (text[cur] != '-' && text[cur] != '+') cur++; char temp[6] = {0}; int ind = 1; temp[0] = text[cur]; cur++; while (text[cur] >= '0' && text[cur] <= '9') { temp[ind] = text[cur]; ind++; cur++; } temp[ind] = 0; startLine(); return (atoi(temp)); } void jump(int n) { int i = 0; if (n > 0) { while (i < n) { nextLine(); i++; } } else { while (i > n) { prevLine(); i--; } } line += n; } void readLine() { int value = 0; checkList[line] = 1; if (text[cur] == 'j') { value = readvalue(); jump(value); } else if (text[cur] == 'a') { value = readvalue(); acc += value; nextLine(); line++; } else { nextLine(); line++; } printf("line %d: %c %d\n", line, text[cur], value); } int main() { FILE *fp; int i = 0; fp = fopen("src.txt", "r"); long fsize = 10000; text = malloc(fsize + 1); fseek(fp, 0, SEEK_SET); fread(text, 1, fsize, fp); fclose(fp); while (checkList[line] != 1) { readLine(); } printf("%d\n", acc); }
C
#include "prototipos.h" #define T 10 //Definir un valor que luego va a ser un remplazado en el codigo //(constante)Elemento de la programacion que va a valer el mismo valor, toda la vida del programa. int main() { int vectorDeNumeros[T]= {10,-5,10,-6,-1,-4,10,5,4,-6}; int i; int opcion; do { printf( "1 cargar numeros\n"); printf( "2 mostar todo\n"); printf( "3 mostrar negativos\n"); printf( "4 mostrar promedio positivos\n"); printf( "5 Mostrar Maximo\n"); printf( "6 Mostrar Minimo\n"); printf( "7 salir\n"); printf("Elija una opcion: "); scanf("%d",&opcion); switch(opcion) { case 1: cargarVector(vectorDeNumeros,T); break; case 2: mostrarVector(vectorDeNumeros,T); break; case 3: mostrarNegativos(vectorDeNumeros,T); case 4: mostrarPromedio(vectorDeNumeros,T); break; case 5: mostrarMaximo(vectorDeNumeros,T); break; case 6: mostrarMinimo(vectorDeNumeros,T); break; } system("pause"); system("cls"); } while(opcion!=7); return 0; }
C
/* *Name - Nikhil Ranjan Nayak *Regd No - 1641012040 *Desc - Dispense Change */ #include<stdio.h> #include<math.h> void cal_change(double ,int*, int*, int*, int*); void main() { int dollars, quaters = 0, dimes = 0, nickels = 0, pennies = 0; double amount_paid , amount_due, amount_change, coin_change; printf("Enter amount paid:\n"); scanf("%lf", &amount_paid); printf("Enter amount due:\n"); scanf("%lf", &amount_due); amount_change = amount_paid - amount_due; dollars = floor(amount_change); coin_change = (int)((amount_change - floor(amount_change)) * 100 * 0.5); printf("%f", coin_change); cal_change(coin_change, &quaters, &dimes, &nickels, &pennies); printf("\nChange in dollars - %d $", dollars); printf("\nQuaters: - %d", quaters); printf("\nQimes - %d", dimes); printf("\nNickels - %d", nickels); printf("\nPennies - %d", pennies); } void cal_change(double coin_change, int *quaters, int *dimes, int *nickels, int *pennies) { int q = 1,d = 1,n = 1,p = 1; do { if(coin_change>=25) { *quaters += q; coin_change -= 25; } else if(coin_change>=10) { *dimes += d; coin_change -= 10; } else if(coin_change>=5) { *nickels += n; coin_change -= 5; } else if(coin_change >= 1) { *pennies += p; coin_change--;; } }while(coin_change >= 1); }
C
#include <stdio.h> #include "common.h" static int cb_update_tips(const char *ref, const git_oid *old, const git_oid *new) { char *hex; fprintf(stderr, "%s:\t", ref); hex = git_oid_allocfmt(old); fprintf(stderr, "%s -> ", hex); free(hex); hex = git_oid_allocfmt(new); fprintf(stderr, "%s\n", hex); free(hex); return 0; } int cmd_fetch(git_repository *repo, int argc, const char **argv) { int error; git_remote *r; git_off_t bytes = 0; git_indexer_stats stats; if (argc < 1) die("usage: ./git fetch <remote>"); error = git_remote_load(&r, repo, argv[0]); if (error < 0) die_giterror(); error = git_remote_connect(r, GIT_DIR_FETCH); if (error < 0) die_giterror(); error = git_remote_download(r, &bytes, &stats); if (error < 0) die_giterror(); git_remote_disconnect(r); fprintf(stderr, "Received %d/%d objects in %" PRId64 " bytes\n", stats.processed, stats.total, bytes); error = git_remote_update_tips(r, cb_update_tips); if (error < 0) die_giterror(); git_remote_free(r); return error; }
C
#ifdef HAVE_CONFIG_H #include <config.h> #endif #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <string.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #define REQUEST_MSG_SIZE 1024 #define REPLY_MSG_SIZE 500 #define SERVER_PORT_NUM 5001 char comunicar(char* msg){ //Subrutina de comunicaciones. //Define las variables necesarias para poder establecer una conexión con el servidor. struct sockaddr_in serverAddr; char serverName[] = "88.6.4.147"; //Adreça IP on est� el servidor int sockAddrSize; int sFd; int mlen; int result; char buffer[256]; char recibo[256]; /*Crear el socket*/ sFd=socket(AF_INET,SOCK_STREAM,0); /*Construir l'adreça*/ sockAddrSize = sizeof(struct sockaddr_in); bzero ((char *)&serverAddr, sockAddrSize); //Posar l'estructura a zero serverAddr.sin_family=AF_INET; serverAddr.sin_port=htons (SERVER_PORT_NUM); serverAddr.sin_addr.s_addr = inet_addr(serverName); /*Conexió*/ result = connect (sFd, (struct sockaddr *) &serverAddr, sockAddrSize); if (result < 0) { printf("Error en establir la connexió\n"); exit(-1); } printf("\nConnexió establerta amb el servidor: adreça %s, port %d\n", inet_ntoa(serverAddr.sin_addr), ntohs(serverAddr.sin_port)); /*Enviar*/ strcpy(buffer,msg); //Copiar missatge a buffer result = write(sFd, buffer, strlen(buffer)); printf("\nMensaje enviado al servidor (bytes %d): %s", result, msg); /*Rebre*/ result = read(sFd, buffer, 256); printf("\nRespuesta del servidor (bytes %d): %s\n", result, buffer); strcpy(recibo,buffer); //printf("\n\n\nRECIBO: %s\n\n\n", recibo); //Una vez que se recibe el mensaje, contenido en el buffer, se separa para presentrlo al usuario. printf("\n================================================================================"); if(recibo[2]=='0'){ //Si el codigo de error es 0 (no hay error), se muestra la información al usuario. switch(recibo[1]){ case 'M': printf("\nRegistrador en marcha\n"); //Confirmación de marcha. break; case 'U': printf("\nTemperatura más antigua registrada (ºC): "); //Se imprime la temperatura más antigua. printf("%c",recibo[3]); printf("%c",recibo[4]); printf("%c",recibo[5]); printf("%c",recibo[6]); printf("%c",recibo[7]); printf("\n"); break; case 'X': printf("\nTemperatura máxima registrada (ºC): "); //Se imprime el valor máximo de temperatura. (Recibido como caracteres). printf("%c",recibo[3]); printf("%c",recibo[4]); printf("%c",recibo[5]); printf("%c",recibo[6]); printf("%c",recibo[7]); printf("\n"); break; case 'Y': printf("\nTemperatura mínima registrada (ºC): "); //Se imprime el valor mínimo de temperatura. printf("%c",recibo[3]); printf("%c",recibo[4]); printf("%c",recibo[5]); printf("%c",recibo[6]); printf("%c",recibo[7]); printf("\n"); break; case 'R': printf("\nValores máximo y mínimo reseteados\n"); //Confirmación de reinicio de valores máximo y mínimo. break; case 'B': printf("\nMuestras guardadas: "); //Se imprime la cuenta de valores almacenados recibida como caracteres desde el servidor. printf("%c",recibo[3]); printf("%c",recibo[4]); printf("%c",recibo[5]); printf("%c",recibo[6]); printf("\n"); break; } } else if(recibo[2]=='1'){ //Si el codigo de error es 1, se imprime el texto del error correspondiente. printf("\nError 1: Error de protocolo\n"); } else if(recibo[2]=='2'){ //Si es 2, se imprime el mensaje que corresponde. printf("\nError 2: Error en parámetros\n"); } printf("================================================================================"); /*Tancar el socket*/ close(sFd); return 0; } //ImprimirMenu void ImprimirMenu(void) { //printf("\e[1;1H\e[2J"); printf("\n\nREGISTRADOR DE TEMPERATURA"); printf("\n\nMenú principal\n"); printf("--------------------\n"); printf("1: Muestra más antigua\n"); printf("2: Muestra máxima\n"); printf("3: Muestra mínima\n"); printf("4: Reset máximo y mínimo\n"); printf("5: Número muestras almacenadas\n"); printf("6: Marcha / Restablecer parámetros\n"); printf("7: Paro\n"); printf("s: Terminar programa\n"); printf("--------------------\n"); printf("\nIntroduzca opción deseada: "); } //Función main. Menú de selección. int main(int argc, char **argv) { //Definición de variables para el funcionamiento del menú. char missatge[8]=""; char input; char tiempo[2]=""; char muestras[1]=""; char condiciones[3]=""; ImprimirMenu(); //Se llama a la función que imprime el texto del menú. input = getchar(); while (input != 's') //Presionando la s se puede abortar la ejecución del programa. { switch (input) //Se e la tecla que ha pulsado el usuario. A continuación se muestran las diferentes opciones. { case '1': printf("\n\n\nSolicitado valor más antiguo al servidor...\n"); strcpy(missatge,"{U}"); //printf("\n\n\nEl mensaje enviado es: %s\n\n\n",missatge); comunicar(missatge); ImprimirMenu(); break; case '2': printf("\n\n\nSolicitado valor máximo al servidor...\n"); strcpy(missatge,"{X}"); //printf("\n\n\nEl mensaje enviado es: %s\n\n\n",missatge); comunicar(missatge); ImprimirMenu(); break; case '3': printf("\n\n\nSolicitado valor mínimo al servidor...\n"); strcpy(missatge,"{Y}"); //printf("\n\n\nEl mensaje enviado es: %s\n\n\n",missatge); comunicar(missatge); ImprimirMenu(); break; case '4': printf("\n\n\nReiniciando valores máximo y mínimo...\n"); strcpy(missatge,"{R}"); //printf("\n\n\nEl mensaje enviado es: %s\n\n\n",missatge); comunicar(missatge); ImprimirMenu(); break; case '5': printf("\n\n\nSolicitado número muestras almacenadas al servidor...\n"); strcpy(missatge,"{B}"); //printf("\n\n\nEl mensaje enviado es: %s\n\n\n",missatge); comunicar(missatge); ImprimirMenu(); break; case '6': //Este caso es diferente, muestra un submenú en el que configurar los valores de tiempo de muestreo y promedio. printf("\n\n Introduzca tiempo de muestreo (s): "); scanf("%s",tiempo); if (strlen(tiempo)<2){ tiempo[1]=tiempo[0]; tiempo[0]='0'; tiempo[2]='\0'; } strcat(condiciones, tiempo); printf(" Introduzca número muestras promedio: "); scanf("%s",muestras); strcat(condiciones, muestras); missatge[0]='{'; missatge[1]='M'; missatge[2]='1'; missatge[3]=condiciones[0]; missatge[4]=condiciones[1]; missatge[5]=condiciones[2]; missatge[6]='}'; //printf("\n\n\nEl mensaje enviado es: %s\n\n\n", missatge); printf("\n\n\nIniciando el registro...\n"); comunicar(missatge); ImprimirMenu(); break; case '7': printf("\n\n\nParando el registro...\n"); strcpy(missatge,"{M0000}"); //printf("\n\n\nEl mensaje enviado es: %s\n\n\n",missatge); comunicar(missatge); ImprimirMenu(); break; case 0x0a: break; default: //Se ejecuta en caso de que se pulse una tecla no contemplada en el menú. printf("\nOpción incorrecta\n"); printf("\nIntroduzca una opción válida\n"); ImprimirMenu(); break; } input = getchar(); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include "udp.h" #include "mfs.h" #include "server.h" int image_fd; Bitmap_t Inode_BitMap; Bitmap_t Data_BitMap; Inode_t *inode_table; Block_t *data_region; int main(int argc, char *argv[]) { if(argc != 3){ fprintf(stderr,"usage: server [portnum] [file-system-image]\n"); fprintf(stderr,"you supplied %d args\n", argc); exit(1); } int portnum = atoi( argv[1] ); if( ! (portnum > 0 ) ) { fprintf(stderr, " portnum = %d; this should be a pos number",portnum); } const int sd = UDP_Open(portnum); assert(sd > -1); inode_table = (Inode_t *)malloc(MFS_BLOCK_NUMS * sizeof(Inode_t)); data_region = (Block_t *)malloc(MFS_BLOCK_NUMS * sizeof(Block_t)); if(inode_table == NULL || data_region == NULL){ fprintf(stderr, "malloc error\n"); exit(-1); } if( (image_fd = open(argv[2],O_RDWR)) == -1){ image_fd = Image_Init(argv[2]); } int rc = -1; struct sockaddr_in s; char buffer_read[ UDP_BUFFER_SIZE]; char buffer_reply[UDP_BUFFER_SIZE]; char buffer[BUFFER_SIZE]; char * ptr = buffer_read; int block = -1; int blocks = -1; int pinum = -1; int inum = -1; int size = -1; int status = -1; int type = -1; char * name = NULL; int * iptr = NULL; char * cptr = NULL; MFS_Stat_t * mptr = NULL; while (1) { block = -1; blocks = -1; pinum = -1; inum = -1; size = -1; status = -1; type = -1; name = NULL; iptr = NULL; cptr = NULL; rc = UDP_Read(sd, &s, buffer_read, UDP_BUFFER_SIZE); ptr = buffer_read; if (rc < 1) { rc = -1; continue; } iptr = (int*) ptr; int * op_id = iptr; iptr++; switch(*op_id) { case 0: printf("op_id == 0 \n"); break; case 1: pinum = *( iptr ); iptr++; cptr = (char*)iptr; name = cptr; inum = Server_LookUp(pinum, name ); iptr = (int*) buffer_reply; *iptr = inum; break; case 2: inum = *( iptr ); iptr++; mptr = (MFS_Stat_t*)iptr; status = Server_Stat(inum, mptr ); iptr = (int*) buffer_reply; *iptr = status; iptr++; memcpy((void*) iptr, (void*)mptr, sizeof( MFS_Stat_t ) ); break; case 3: inum = *( iptr ); iptr++; cptr = (char*)iptr; memcpy( buffer, cptr, BUFFER_SIZE ); cptr += BUFFER_SIZE; iptr = (int*) cptr; block = *iptr; status = Server_Write( inum, buffer, block ); iptr = (int *) buffer_reply; *iptr = status; break; case 4: inum = *( iptr ); iptr++; cptr = (char*)iptr; memcpy( buffer, cptr, BUFFER_SIZE ); cptr += BUFFER_SIZE; iptr = (int*) cptr; block = *iptr; status = Server_Read( inum, buffer, block ); iptr = (int *) buffer_reply; *iptr = status; iptr++; cptr = (char*) iptr; memcpy(cptr, buffer, BUFFER_SIZE); break; case 5: pinum = *( iptr ); iptr++; type = *iptr; iptr++; name = (char*) iptr; status = Server_Creat( pinum, type, name ); iptr = (int *) buffer_reply; *iptr = status; break; case 6: pinum = *(iptr++); name = (char*)(iptr); status = Server_Unlink( pinum, name ); iptr = (int*) buffer_reply; *iptr = status; break; default: fprintf(stderr, "bad function number %d\n", *op_id ); exit(1); } rc = UDP_Write(sd, &s, buffer_reply, UDP_BUFFER_SIZE); } return 0; } void Set_Bit(Bitmap_t *map, int index){ if(index < 0 || index >= MFS_BLOCK_NUMS){ fprintf(stderr, "index error\n"); exit(-1); } map->bits[index] = true; } void Unset_Bit(Bitmap_t *map, int index){ if(index < 0 || index >= MFS_BLOCK_NUMS){ fprintf(stderr, "index error\n"); exit(-1); } map->bits[index] = false; } int First_Empty(Bitmap_t *map){ int index; for(index = 0; index < MFS_BLOCK_NUMS; index++){ if(map->bits[index] == false){ break; } } if(index == MFS_BLOCK_NUMS){ index = -1; } return index; } void BitMap_Init(Bitmap_t *map){ int idx; for (idx = 0; idx < MFS_BLOCK_NUMS; idx ++){ map->bits[idx] = false; } } void Inode_Init(Inode_t *inode){ inode->type = MFS_REGULAR_FILE; inode->size = 0; inode->blocks = 0; int i; for(i = 0; i < MFS_PTR_NUMS; i++){ inode->ptr[i] = -1; } } int Image_Init(const char * filename){ int fd, i; if((fd = open(filename,O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) == -1){ exit(-1); } BitMap_Init(&Inode_BitMap); BitMap_Init(&Data_BitMap); for(i = 0; i < MFS_BLOCK_NUMS; i++){ Inode_Init(&inode_table[i]); } inode_table[0].type = MFS_DIRECTORY; inode_table[0].size = 2 * sizeof(MFS_DirEnt_t); inode_table[0].blocks = 1; inode_table[0].ptr[0] = 0; MFS_DirEnt_t *root_dot = (MFS_DirEnt_t *)data_region[0].data; MFS_DirEnt_t *root_dotdot = root_dot + 1; root_dot -> inum = 0; strcpy(root_dot -> name,"."); root_dotdot -> inum = 0; strcpy(root_dotdot -> name, ".."); int j; for(j = 2; j < MFS_BLOCK_SIZE / sizeof(MFS_DirEnt_t); j ++){ (root_dot + j) -> inum = -1; } Set_Bit(&Inode_BitMap, 0); Set_Bit(&Data_BitMap,0); if(write(fd, &Inode_BitMap, sizeof(Bitmap_t)) != sizeof(Bitmap_t)){ fprintf(stderr, "write error\n"); exit(-1); } if(write(fd,&Data_BitMap, sizeof(Bitmap_t)) != sizeof(Bitmap_t)){ fprintf(stderr,"write error\n"); exit(-1); } if(write(fd,inode_table, MFS_BLOCK_NUMS*sizeof(Inode_t)) != MFS_BLOCK_NUMS*sizeof(Inode_t)){ fprintf(stderr,"write error\n"); exit(-1); } if(write(fd,data_region, MFS_BLOCK_NUMS*sizeof(Block_t)) != MFS_BLOCK_NUMS*sizeof(Block_t)){ fprintf(stderr,"write error\n"); exit(-1); } fsync(fd); return fd; } void Data_Init(){ if(lseek(image_fd,0,SEEK_SET) != 0){ fprintf(stderr,"lseek error\n"); exit(-1); } if(read(image_fd, &Inode_BitMap, sizeof(Bitmap_t)) != sizeof(Bitmap_t)){ fprintf(stderr,"read error\n"); exit(-1); } if(read(image_fd, &Data_BitMap,sizeof(Bitmap_t)) != sizeof(Bitmap_t)){ fprintf(stderr,"read error\n"); exit(-1); } if(read(image_fd,inode_table, MFS_BLOCK_NUMS*sizeof(Inode_t)) != MFS_BLOCK_NUMS*sizeof(Inode_t)){ fprintf(stderr,"read error\n"); exit(-1); } if(read(image_fd,data_region, MFS_BLOCK_NUMS*sizeof(Block_t)) != MFS_BLOCK_NUMS*sizeof(Block_t)){ fprintf(stderr,"read error\n"); exit(-1); } } int Server_LookUp(int pinum, char *name){ if(pinum < 0){ return -1; } int idx; Data_Init(); //return -2 if invalid pinum if(Inode_BitMap.bits[pinum] == false){ return -1; }else if(inode_table[pinum].type != MFS_DIRECTORY){ return -1; } int curr_blk_num; for(idx = 0; idx < MFS_PTR_NUMS; idx++){ if((curr_blk_num = inode_table[pinum].ptr[idx]) == -1){ continue; } int entries_in_curr_blk = MFS_BLOCK_SIZE / sizeof(MFS_DirEnt_t); MFS_DirEnt_t *entries = (MFS_DirEnt_t *)data_region[curr_blk_num].data; int j; for (j = 0; j < entries_in_curr_blk; j++){ if(entries[j].inum == -1){ continue; } if(strcmp(entries[j].name, name) == 0){ return entries[j].inum; } } } //return -3 if name doesn't exist in pinum return -1; } int Server_Stat(int inum, MFS_Stat_t *m){ Data_Init(); if(Inode_BitMap.bits[inum] == false){ return -1; } m -> type = inode_table[inum].type; m -> size = inode_table[inum].size; m -> blocks = inode_table[inum].blocks; return 0; } int Server_Write(int inum, char * buffer, int block){ int i; Data_Init(); if(Inode_BitMap.bits[inum] == false){ return -1; } if(inode_table[inum].type != MFS_REGULAR_FILE){ return -1; } if(block < 0 || block > 9){ return -1; } int to_write_block; if(inode_table[inum].ptr[block] == -1){ to_write_block = First_Empty(&Data_BitMap); Set_Bit(&Data_BitMap,to_write_block); for(i = 0; i <= block; i++){ if(inode_table[inum].ptr[i] == -1){ inode_table[inum].size += MFS_BLOCK_SIZE; inode_table[inum].blocks ++; } } inode_table[inum].ptr[block] = to_write_block; }else{ to_write_block = inode_table[inum].ptr[block]; } for(i = 0; i < MFS_BLOCK_SIZE; i++){ data_region[to_write_block].data[i] = buffer[i]; } Data_Write(); return 0; } void Data_Write(){ if(lseek(image_fd,0,SEEK_SET) != 0){ fprintf(stderr,"lseek error\n"); exit(-1); } if(ftruncate(image_fd,0) != 0){ fprintf(stderr,"truncate error\n"); exit(-1); } if(write(image_fd, &Inode_BitMap, sizeof(Bitmap_t)) != sizeof(Bitmap_t)){ fprintf(stderr, "write error\n"); exit(-1); } if(write(image_fd,&Data_BitMap, sizeof(Bitmap_t)) != sizeof(Bitmap_t)){ fprintf(stderr,"write error\n"); exit(-1); } if(write(image_fd,inode_table, MFS_BLOCK_NUMS*sizeof(Inode_t)) != MFS_BLOCK_NUMS*sizeof(Inode_t)){ fprintf(stderr,"write error\n"); exit(-1); } if(write(image_fd,data_region, MFS_BLOCK_NUMS*sizeof(Block_t)) != MFS_BLOCK_NUMS*sizeof(Block_t)){ fprintf(stderr,"write error\n"); exit(-1); } fsync(image_fd); } int Server_Read(int inum, char *buffer, int block){ Data_Init(); if(Inode_BitMap.bits[inum] == false){ return -1; } if(block < 0 || block > 9){ return -1; }else if(inode_table[inum].ptr[block] == -1){ return -1; } int to_read_block = inode_table[inum].ptr[block]; int j; for(j = 0; j < MFS_BLOCK_SIZE; j++){ buffer[j] = data_region[to_read_block].data[j]; } return 0; } int Server_Creat(int pinum, int type, char *name){ Data_Init(); if(Inode_BitMap.bits[pinum] == false || inode_table[pinum].type != MFS_DIRECTORY){ return -1; } if(Server_LookUp(pinum,name) >= 0){ return 0; } int inum = First_Empty(&Inode_BitMap); Set_Bit(&Inode_BitMap, inum); if(Add_Entry(pinum, inum, name, inode_table, data_region) != 0){ fprintf(stderr,"add entry error\n"); } if(type == MFS_REGULAR_FILE){ inode_table[inum].type = type; inode_table[inum].size = 0; inode_table[inum].blocks = 0; int i; for(i = 0; i < MFS_PTR_NUMS; i++){ inode_table[inum].ptr[i] = -1; } } if(type == MFS_DIRECTORY){ int to_write_block = First_Empty(&Data_BitMap); Set_Bit(&Data_BitMap,to_write_block); inode_table[inum].type = type; inode_table[inum].size = 2 * sizeof(MFS_DirEnt_t); inode_table[inum].blocks = 1; inode_table[inum].ptr[0] = to_write_block; int i; for(i = 1; i < MFS_PTR_NUMS; i++){ inode_table[inum].ptr[i] = -1; } MFS_DirEnt_t * entries = (MFS_DirEnt_t *) data_region[to_write_block].data; entries[0].inum = inum; strcpy(entries[0].name, "."); entries[1].inum = pinum; strcpy(entries[1].name, ".."); for(i = 2; i < MFS_BLOCK_SIZE / sizeof(MFS_DirEnt_t); i++){ entries[i].inum = -1; } } Data_Write(); return 0; } int Add_Entry(int pinum, int inum, char *name, Inode_t *inode_table, Block_t *data_region){ int idx1, idx2; int curr_blk_num; bool insert = false; retry_add_entry: for(idx1 = 0; idx1 < MFS_PTR_NUMS; idx1 ++){ if(inode_table[pinum].ptr[idx1] == -1){ continue; } curr_blk_num = inode_table[pinum].ptr[idx1]; MFS_DirEnt_t *entries = (MFS_DirEnt_t *)data_region[curr_blk_num].data; for(idx2 = 0; idx2 < MFS_BLOCK_SIZE / sizeof(MFS_DirEnt_t); idx2 ++){ if(entries[idx2].inum == -1){ entries[idx2].inum = inum; strcpy(entries[idx2].name, name); insert = true; break; } } if(insert == true){ break; } } if(insert == false){ add_block(pinum); goto retry_add_entry; } inode_table[pinum].size += sizeof(MFS_DirEnt_t); return 0; } void add_block(int inum){ if(Inode_BitMap.bits[inum] == false){ fprintf(stderr,"error\n"); exit(-1); } if(inode_table[inum].type != MFS_DIRECTORY ){ fprintf(stderr, "error\n"); exit(-1); } int i; for(i = 0; i < MFS_PTR_NUMS; i ++){ if(inode_table[inum].ptr[i] == -1){ break; } } int curr_block = First_Empty(&Data_BitMap); inode_table[inum].ptr[i] = curr_block; Set_Bit(&Data_BitMap, curr_block); inode_table[inum].blocks++; MFS_DirEnt_t *entries = (MFS_DirEnt_t *)data_region[curr_block].data; for(i = 0; i < MFS_BLOCK_SIZE / sizeof(MFS_DirEnt_t); i++){ entries[i].inum = -1; } } int Server_Unlink(int pinum, char *name){ Data_Init(); if(Inode_BitMap.bits[pinum] == false){ return -1; } if(inode_table[pinum].type != MFS_DIRECTORY){ return -1; } int inum = Server_LookUp(pinum, name); if(inum < 0){ return 0; } if(inode_table[inum].type == MFS_DIRECTORY){ if(inode_table[inum].size > 2 * sizeof(MFS_DirEnt_t)){ return -1; } } int i; for(i = 0; i < MFS_PTR_NUMS; i++){ if(inode_table[inum].ptr[i] != -1){ Unset_Bit(&Data_BitMap, inode_table[inum].ptr[i]); } } Unset_Bit(&Inode_BitMap, inum); Remove_Entry(pinum, inum, name, inode_table, data_region); Data_Write(); return 0; } int Remove_Entry(int pinum, int inum, char *name, Inode_t *inode_table, Block_t *data_region){ int idx1, idx2; int curr_blk_num; bool found = false; for(idx1 = 0; idx1 < MFS_PTR_NUMS; idx1 ++){ if(inode_table[pinum].ptr[idx1] == -1){ continue; } curr_blk_num = inode_table[pinum].ptr[idx1]; MFS_DirEnt_t *entries = (MFS_DirEnt_t *)data_region[curr_blk_num].data; for(idx2 = 0; idx2 < MFS_BLOCK_SIZE / sizeof(MFS_DirEnt_t); idx2 ++){ if(entries[idx2].inum == inum && strcmp(entries[idx2].name, name) == 0){ entries[idx2].inum = -1; found = true; break; } } if(found == true){ break; } } inode_table[pinum].size -= sizeof(MFS_DirEnt_t); return 0; }
C
#include <stdio.h> #include <stdlib.h> struct node { int data; struct node *next; }; void insert(struct node **head_ref, int new_data) { struct node *new_node = (struct node*)malloc(sizeof(struct node)); struct node *last= *head_ref; new_node->data = new_data; new_node->next = NULL; if(*head_ref == NULL) { *head_ref = new_node; return; } while (last->next != NULL) last = last->next; last->next = new_node; return; } struct node* deleteN(struct node *head, int n) { if (head == NULL) return NULL; if (n == 1) { struct node *temp = head; head = temp->next; free(temp); return head; } head->next = deleteN(head->next, n-1); return head; } void duplicacy(struct node *head) { struct node *node = NULL; struct node *compare = NULL; node =head; compare=head->next; int count=2; while(node!=NULL) { while (compare!=NULL) { if (node->data==compare->data) { printf("duplicacy found at %d\n", count); head = deleteN(head, count); display(head); } compare = compare->next; count = count+1; } node = node->next; } } void display (struct node *node) { while(node!=NULL) { printf("%d ", node-> data); node= node->next; } printf("\n"); } int main(void) { struct node *head = NULL; insert(&head, 5); insert(&head, 10); insert(&head, 15); insert(&head, 5); insert(&head, 25); display(head); duplicacy(head); return 0; }
C
/* * SPECS * ---------------------------- * Segregated (explicit) lists. Each list is maintained in an ascending order. * * VITAL STATISTICS * ----------------- * Minimum block size: 24 bytes * * * ANATOMY OF BLOCKS: * * size of header = 4 bytes * size of footer = 4 bytes * size of next free block ptr = 8 bytes * size of next prev block ptr = 8 bytes * * >>>> Free Block * +-----------+-----------------------+-----------------------+-----------------------+-----------+ * | header | previous block | next block | ..... | footer | * +-----------+-----------------------+-----------------------+-----------------------+-----------+ * * >>>> Allocated Block * +-----------+-----------------------+-----------------------+-----------------------+-----------+ * | header | data | footer | * +-----------+-----------------------+-----------------------+-----------------------+-----------+ * * >>>> Prologue Block * +-----------+-----------------------+-----------------------+-----------+ * | header | previous block | next block | footer | * +-----------+-----------------------+-----------------------+-----------+ * * >>>> Epilogue Block * +-----------+ * | header | * +-----------+ * * MALLOC * --------------------- * In this approach, a block is allocated by first finding the free list of the same size class. * Then the list is traversed to find the first block that's big enough for the allocation request. * If a free block is too big (unused poriton is big enough to be a free block), split the block. * * FREEING: * ---------------------- * Newly freed blocks are inserted into the free list in such a way that the list remains sorted. * */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include "mm.h" #include "memlib.h" /********************************************************* * NOTE TO STUDENTS: Before you do anything else, please * provide your group information in the following struct. ********************************************************/ group_t group = { /* Project group number (You're required to join a group on Canvas) */ "34", /* First member's full name */ "NDER Sesugh", /* First member's email address */ "samuender2-c@my.cityu.edu.hk", /* Second member's full name (leave blank if none) */ "SIVAKUMAR Srinivas", /* Second member's email address (leave blank if none) */ "ssivakuma2-c@my.cityu.edu.hk", /* Third member's full name (leave blank if none) */ "", /* Third member's email address (leave blank if none) */ "" }; /* Basic constants and macros */ #define WSIZE 4 /* Word and header/footer size (bytes) */ #define DSIZE 8 /* Doubleword size (bytes) */ #define CHUNKSIZE (1<<12) /* Extend heap by this amount (bytes) */ #define MIN_BLK_SIZE 24 #define START_SHIFT 5 #define INIT_CHUNK_SIZE CHUNKSIZE/WSIZE #define NUM_CLASSES 300 #define MAX(x, y) ((x) > (y)? (x) : (y)) #define ALIGN(size) (DSIZE * ((size + (DSIZE) + (DSIZE-1)) / DSIZE)) /* Pack a size and allocated bit into a word */ #define PACK(size, alloc) ((size) | (alloc)) /* Read and write a word at address p */ #define GET(p) (*(int*)(p)) #define PUT(p, val) (*(int*)(p) = (val)) /* Read the size and allocated fields from address p */ #define GET_SIZE(p) (GET(p) & ~0x7) #define GET_ALLOC(p) (GET(p) & 0x1) /* Given block ptr bp, compute address of its header and footer */ #define HDRP(bp) ((void*)(bp) - WSIZE) #define FTRP(bp) ((void*)(bp) + GET_SIZE(HDRP(bp)) - DSIZE) /* Given block ptr bp, compute address of (physically) next and previous blocks */ #define NEXT_BLKP(bp) ((void* )(bp) + GET_SIZE(HDRP(bp))) #define PREV_BLKP(bp) ((void* )(bp) - GET_SIZE(HDRP(bp) - WSIZE)) /* Given free block ptr, bp, compute address of next and previous blocks*/ #define NEXT_FREEP(bp) (*(void**)(bp + DSIZE)) #define PREV_FREEP(bp) (*(void**)(bp)) /* Given a free block ptr, bp, compute the POINTER to the address of next and previous blocks*/ #define BLK_NEXT(bp) ((void*)bp + DSIZE) #define BLK_PREV(bp) ((void*)bp) /* Global variables */ static void *heap_listp = 0; /* Pointer to first block */ static void *free_list[NUM_CLASSES]; // Each list is maintained in ascending order // static void *epilogue = NULL; /* Function prototypes for internal helper routines */ static void *extend_heap(size_t words); static void *place(void *bp, size_t asize); static void *find_fit(size_t asize); static void *coalesce(void *bp); static inline int get_size_class(size_t asize); static inline void insert_block(void *ptr); static void delete_block(void *ptr); /* * mm_init - Initialize the memory manager * */ int mm_init(void) { /* Create the initial empty heap */ if ((heap_listp = mem_sbrk(4 * DSIZE)) == (void *) -1) return -1; for (int i = 0; i < NUM_CLASSES; i++) { free_list[i] = NULL; } /* Padding */ PUT(heap_listp, 0); /* Prologue */ PUT(heap_listp + WSIZE, PACK(MIN_BLK_SIZE, 1)); // header PUT(heap_listp + DSIZE, 0); // prev PUT(heap_listp + DSIZE * 2, 0); // next PUT(heap_listp + DSIZE * 3, PACK(MIN_BLK_SIZE, 1)); // footer /* Epilogue */ PUT(heap_listp + DSIZE * 3 + WSIZE, PACK(0, 1)); // header only //------------------------------------------------------- //epilogue = heap_listp + DSIZE * 3 + WSIZE; /* Extend the empty heap with a free block of CHUNKSIZE bytes */ // if (extend_heap(INIT_CHUNK_SIZE) == NULL) // return -1; return 0; } /* * mm_malloc - Allocate a block with at least size bytes of payload */ void *mm_malloc(size_t size) { size_t asize; /* Adjusted block size */ size_t extendsize; /* Amount to extend heap if no fit */ char *bp; if (heap_listp == 0) { mm_init(); } /* Ignore spurious requests */ if (size == 0) return NULL; asize = MAX(ALIGN(size), MIN_BLK_SIZE); /* Search the free list for a fit */ if ((bp = find_fit(asize)) != NULL) { return place(bp, asize); } /* No fit found. Get more memory and place the block */ extendsize = MAX(asize, CHUNKSIZE); if ((bp = extend_heap(extendsize / WSIZE)) == NULL) return NULL; return place(bp, asize); } /* * mm_free - Free a block, bp */ void mm_free(void *bp) { if (bp == 0) return; if (heap_listp == 0) { mm_init(); } size_t size = GET_SIZE(HDRP(bp)); PUT(HDRP(bp), PACK(size, 0)); PUT(FTRP(bp), PACK(size, 0)); coalesce(bp); } /* * coalesce - Boundary tag coalescing. * Inserts into segregated list and returns ptr to coalesced block */ static void *coalesce(void *ptr) { size_t prev_alloc = GET_ALLOC(HDRP(PREV_BLKP(ptr))); size_t next_alloc = GET_ALLOC(HDRP(NEXT_BLKP(ptr))); size_t size = GET_SIZE(HDRP(ptr)); /* * Case 1 */ if (prev_alloc && next_alloc) { // do nothing } /* * Case 2: increase block right */ else if (prev_alloc && !next_alloc) { size += GET_SIZE(HDRP(NEXT_BLKP(ptr))); delete_block(NEXT_BLKP(ptr)); PUT(HDRP(ptr), PACK(size, 0)); PUT(FTRP(ptr), PACK(size, 0)); } /* * Case 3: increase block left */ else if (!prev_alloc && next_alloc) { size += GET_SIZE(HDRP(PREV_BLKP(ptr))); delete_block(PREV_BLKP(ptr)); ptr = PREV_BLKP(ptr); PUT(HDRP(ptr), PACK(size, 0)); PUT(FTRP(ptr), PACK(size, 0)); } /* * Case 4: increase block in both directions */ else { delete_block(PREV_BLKP(ptr)); delete_block(NEXT_BLKP(ptr)); size += GET_SIZE(HDRP(PREV_BLKP(ptr))) + GET_SIZE(HDRP(NEXT_BLKP(ptr))); ptr = PREV_BLKP(ptr); PUT(HDRP(ptr), PACK(size, 0)); PUT(FTRP(ptr), PACK(size, 0)); } insert_block(ptr); return ptr; } /* * The remaining routines are internal helper routines */ /* * extend_heap - Extend heap with free block and return its block pointer */ static void *extend_heap(size_t words) { char *bp; size_t size; /* Allocate an even number of words to maintain alignment */ size = (words % 2) ? (words + 1) * WSIZE : words * WSIZE; size = MAX(size, MIN_BLK_SIZE); if ((long) (bp = mem_sbrk(size)) == -1) return NULL; /* Initialize free block header/footer and the epilogue header */ PUT(HDRP(bp), PACK(size, 0)); /* Free block header */ PUT(FTRP(bp), PACK(size, 0)); /* Free block footer */ PUT(HDRP(NEXT_BLKP(bp)), PACK(0, 1)); /* New epilogue header */ // epilogue = HDRP(NEXT_BLKP(bp)); return coalesce(bp); } /* * place - Place block of asize bytes at start of free block bp * and split if remainder would be at least minimum block size */ static void *place(void *bp, size_t asize) { size_t csize = GET_SIZE(HDRP(bp)); size_t remainder = csize - asize; delete_block(bp); // No splitting if (remainder < MIN_BLK_SIZE) { PUT(HDRP(bp), PACK(csize, 1)); PUT(FTRP(bp), PACK(csize, 1)); } // Split block - place in upper address space else if (asize > 100){ PUT(HDRP(bp), PACK(remainder, 0)); PUT(FTRP(bp), PACK(remainder, 0)); PUT(HDRP(NEXT_BLKP(bp)), PACK(asize, 1)); PUT(FTRP(NEXT_BLKP(bp)), PACK(asize, 1)); coalesce(bp); bp = NEXT_BLKP(bp); } // Split block - place in lower address space else { PUT(HDRP(bp), PACK(asize, 1)); PUT(FTRP(bp), PACK(asize, 1)); PUT(HDRP(NEXT_BLKP(bp)), PACK(remainder, 0)); PUT(FTRP(NEXT_BLKP(bp)), PACK(remainder, 0)); coalesce(NEXT_BLKP(bp)); } return bp; } /* * find_fit - Find a fit for a block with asize bytes. * Implements "first-fit" search */ static void *find_fit(size_t asize) { for (int size_class = get_size_class(asize); size_class < NUM_CLASSES; size_class++) { for (void *bp = free_list[size_class]; bp != NULL && GET_ALLOC(HDRP(bp)) == 0; bp = NEXT_FREEP(bp)) { if (asize <= (size_t)GET_SIZE(HDRP(bp))) return bp; } } return NULL; // No fit } /* * get_size_class - Returns the appropriate size size_class or * class given a (word-aligned) size. */ static inline int get_size_class(size_t asize) { int size_class = 0; // Powers of two less than 5 (START_SHIFT), {2, 4, 6, 16}, do not make for // valid size classes as the minimum block size is 24 bytes. asize >>= START_SHIFT; while (size_class < NUM_CLASSES - 1 && asize > 1) { asize >>= 1; size_class++; } return size_class; } /* * insert_block - Inserts a newly acquired (free) memory (either from coalescing or heap extension) * into the segregated list. * */ static inline void insert_block(void *bp) { size_t size = GET_SIZE(HDRP(bp)); int size_class = get_size_class(size); void *current_ptr = free_list[size_class]; void *insert_ptr = NULL; while ((current_ptr != NULL) && (GET_SIZE(HDRP(current_ptr)) < size)) { insert_ptr = current_ptr; current_ptr = NEXT_FREEP(current_ptr); } // #1: 1st node if (current_ptr == NULL && insert_ptr == NULL) { PREV_FREEP(bp) = NULL; NEXT_FREEP(bp) = NULL; free_list[size_class] = bp; } // #2: Insert at start of list else if (current_ptr != NULL && insert_ptr == NULL) { NEXT_FREEP(bp) = free_list[size_class]; PREV_FREEP(bp) = NULL; PREV_FREEP(free_list[size_class]) = bp; free_list[size_class] = bp; } // #3: End of list else if (current_ptr == NULL && insert_ptr != NULL) { NEXT_FREEP(insert_ptr) = bp; NEXT_FREEP(bp) = NULL; PREV_FREEP(bp) = insert_ptr; } // #4: Middle of list else { NEXT_FREEP(insert_ptr) = bp; PREV_FREEP(current_ptr) = bp; NEXT_FREEP(bp) = current_ptr; PREV_FREEP(bp) = insert_ptr; } } /* * Removes a free block from the segregated list */ static void delete_block(void *bp) { int size_class = get_size_class(GET_SIZE(HDRP(bp))); if (PREV_FREEP(bp) != NULL) NEXT_FREEP(PREV_FREEP(bp)) = NEXT_FREEP(bp); else free_list[size_class] = NEXT_FREEP(bp); if (NEXT_FREEP(bp)) PREV_FREEP(NEXT_FREEP(bp)) = PREV_FREEP(bp); NEXT_FREEP(bp) = NULL; PREV_FREEP(bp) = NULL; }
C
/* * openmp_problem.c * * Created on: Dec 10, 2013 * Author: ricardo */ #include <stdio.h> #include <stdlib.h> #include <omp.h> #include "omp_implementations.h" void delay(int delayTimes); void Dynamic(int timeDelay,int nowait){ int id,i; double initTime,finalTime,result; omp_set_num_threads(4); printf("Initializing the process....\n\n"); #pragma omp parallel private(id,initTime,finalTime,result) { id = omp_get_thread_num(); initTime = omp_get_wtime(); switch(nowait){ case 0: #pragma omp for schedule(dynamic) nowait ordered for(i = 0;i<timeDelay;i++){ printf("Working from thread %d\n",omp_get_thread_num()); delay(1); } finalTime = omp_get_wtime(); result = finalTime - initTime; printf("The process from Thread %d took %f seconds\n\n",id,result); break; case 1: #pragma omp for schedule(dynamic) ordered for(i = 0;i<timeDelay;i++){ printf("Working from thread %d\n",omp_get_thread_num()); delay(1); } finalTime = omp_get_wtime(); result = finalTime - initTime; printf("The process from Thread %d took %f seconds\n\n",id,result); break; } } } void Static(int timeDelay,int nowait){ int id,i; double initTime,finalTime,result; omp_set_num_threads(4); printf("Initializing the process....\n\n"); #pragma omp parallel private(id,initTime,finalTime,result) { id = omp_get_thread_num(); initTime = omp_get_wtime(); switch(nowait){ case 0: #pragma omp for schedule(static) nowait ordered for(i = 0;i<timeDelay;i++){ printf("Working from thread %d\n",omp_get_thread_num()); delay(1); } finalTime = omp_get_wtime(); result = finalTime - initTime; printf("The process from Thread %d took %f seconds\n\n",id,result); break; case 1: #pragma omp for schedule(static) ordered for(i = 0;i<timeDelay;i++){ printf("Working from thread %d\n",omp_get_thread_num()); delay(1); } finalTime = omp_get_wtime(); result = finalTime - initTime; printf("The process from Thread %d took %f seconds\n\n",id,result); break; } } } void Guided(int timeDelay,int nowait){ int id,i; double initTime,finalTime,result; omp_set_num_threads(4); printf("Initializing the process....\n\n"); #pragma omp parallel private(id,initTime,finalTime,result) { id = omp_get_thread_num(); initTime = omp_get_wtime(); switch(nowait){ case 0: #pragma omp for schedule(guided) nowait ordered for(i = 0;i<timeDelay;i++){ printf("Working from thread %d\n",omp_get_thread_num()); delay(1); } finalTime = omp_get_wtime(); result = finalTime - initTime; printf("The process from Thread %d took %f seconds\n\n",id,result); break; case 1: #pragma omp for schedule(guided) ordered for(i = 0;i<timeDelay;i++){ printf("Working from thread %d\n",omp_get_thread_num()); delay(1); } finalTime = omp_get_wtime(); result = finalTime - initTime; printf("The process from Thread %d took %f seconds\n\n",id,result); break; } } } //the delay function .... still think i should make something more complex that this though void delay(int delayTimes){ while(delayTimes != 0){ int i; for(i = 0;i<50000;i++); delayTimes--; } }
C
#include <stdio.h> int main(){ int A,B; scanf("%d%d",&A,&B); if(A==B){ printf("%d",A+B); }else if(A < B){ printf("%d",B+(B-1)); }else{ printf("%d",A+(A-1)); } }
C
#include <limits.h> #include <string.h> #include "FirstCProgram.h" /*Iterates through the list of elements, * and determines if the current element is * less than the current min. Returns the * maximum if the array is empty. */ int smallest(int elements[], int size) { int i; int min = INT_MAX; if (size <= 0) { return min; } for (i = 0; i < size; i++){ if (elements[i] < min){ min = elements[i]; } } return min; } /*Replaces the destination array with the * characters of the source array in backwards order. */ void reverse(const char source[], char destination[]) { int i = 0; int j = 0; while (source[i] != 0){ i++; } for (i = i - 1; i >= 0; i--){ destination[j] = source[i]; j++; } destination[j] = 0; } int addOK(int a, int b) { int sum = a + b; int sign_a = a >> 31; int sign_b = b >> 31; int sign_sum = sum >> 31; return !~((~sign_sum | sign_a | sign_b) & (sign_sum | ~sign_a | ~sign_b)); }
C
/* ** EPITECH PROJECT, 2019 ** my_print_params ** File description: ** Task 04 */ int my_putstr(char const *c); void my_putchar(char c); void *my_print_params(int argc, char **argv) { int i = 0; while (i != argc) { my_putstr(argv[i]); my_putchar('\n'); i++; } } int main(int argc, char **argv) { my_print_params(argc, argv); return (0); }
C
#include <stdio.h> #include <stdlib.h> unsigned gateL[3][3] = { { 0, 0 ,0 }, { 0, 0 ,0 }, { 0, 0 ,0 } }; unsigned gateR[3][3] = { { 0, 0 ,0 }, { 0, 0 ,0 }, { 0, 0 ,0 } }; unsigned initL = 0; unsigned initR = 0; static inline void calc_gate(unsigned iL, unsigned iR, unsigned *oL, unsigned *oR) { *oL = gateL[iL][iR]; *oR = gateR[iL][iR]; } int main(int argc, char *argv[]) { unsigned seq[] = { 0, 1, 2, 0, 2, 1, 0, 1, 2, 1, 0, 2, 0, 1, 2, 0, 2 }; unsigned seq_len = sizeof(seq)/sizeof(seq[0]); unsigned id = atoi(argv[1]); unsigned total = atoi(argv[2]); unsigned long k = 387420489L * id / total; unsigned long l = k + 387420489L / total + 1; printf("SEQ %lu-%lu\n", k, l); for (unsigned long z = k; z < l; z++) { unsigned long v = z; initL = v % 3; v /= 3; initR = v % 3; v /= 3; for (int a = 0; a < 3; a++) { for (int b = 0; b < 3; b++) { gateL[a][b] = v % 3; v /= 3; gateR[a][b] = v % 3; v /= 3; } } unsigned AoL = 0, AoR = initR; unsigned BoL = initL, BoR = 0; unsigned CoL = 0, CoR = initR; unsigned DoL = initL, DoR = 0; printf("%u%u=", initL, initR); for (int a = 0; a < 3; a++) { for (int b = 0; b < 3; b++) { printf("%u%u.", gateL[a][b], gateR[a][b]); } } for (int n = 0; n < seq_len; n++) { calc_gate(seq[n], AoR, &AoL, &AoR); calc_gate(seq[n], BoL, &BoL, &BoR); calc_gate(CoR, seq[n], &CoL, &CoR); calc_gate(DoL, seq[n], &DoL, &DoR); printf("%u%u%u%u-", AoL, BoR, CoL, DoR); } printf("\n"); } }
C
#include <stdio.h> int fib(int n){ int f[n]; f[0] = 0; f[1] = 1; for(int i =2;i<n;i++){ f[i] = f[i-1] + f[i-2]; } return f[n-1]; } int main(){ int n; printf("Enter a number\n"); scanf("%d",&n); printf("the fib of %d is %d\n",n,fib(n)); return 0; }
C
#include<stdio.h> int main() { int i,k,j,large,small,m=0,n=0,o; int arr[100]; printf(" how many elements to be in array ="); scanf("%d",&o); printf("Enter the elements\t"); for (i=0;i<o;i++) scanf("%d",&arr[i]); printf(" array before interchanged="); for (i=0;i<o;i++) printf("%d\t",arr[i]); printf("\n"); k=0; large=small=arr[0]; for(j=0;j<o;j++) { if(arr[j]>large) {m=j; large=arr[j]; } if(arr[j]<small) { n=j; small=arr[j]; } } k=arr[m]; arr[m]=arr[n]; arr[n]=k; printf("the smallest and largest numbers in array is = %d and %d\n",small,large); printf("the location of largest and smallest is interchanged ="); for (i=0;i<o;i++) printf("%d\t",arr[i] ); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ typedef int /*<<< orphan*/ pthread_t ; /* Variables and functions */ int EXIT_SUCCESS ; int /*<<< orphan*/ free (int /*<<< orphan*/ *) ; int /*<<< orphan*/ * malloc (int) ; int nthread ; int /*<<< orphan*/ perror (char*) ; int pthread_create (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int /*<<< orphan*/ ,void*) ; int pthread_join (int /*<<< orphan*/ ,int /*<<< orphan*/ *) ; int /*<<< orphan*/ sigfuz_test ; __attribute__((used)) static int signal_fuzzer(void) { int t, rc; pthread_t *threads; threads = malloc(nthread * sizeof(pthread_t)); for (t = 0; t < nthread; t++) { rc = pthread_create(&threads[t], NULL, sigfuz_test, (void *)&t); if (rc) perror("Thread creation error\n"); } for (t = 0; t < nthread; t++) { rc = pthread_join(threads[t], NULL); if (rc) perror("Thread join error\n"); } free(threads); return EXIT_SUCCESS; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lst_triangle.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: antoine <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/23 18:12:00 by antoine #+# #+# */ /* Updated: 2021/03/21 16:11:03 by pompier ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <float.h> #include "struct.h" #include "exit_err.h" #include "read_line.h" #include "libft.h" #include "vector.h" void add_end_lst_triangle(t_triangle *new_triangle, t_obj *obj) { t_triangle *tmp_triangle; if (!obj->lst_triangle) obj->lst_triangle = new_triangle; else { tmp_triangle = obj->lst_triangle; while (tmp_triangle->next) tmp_triangle = tmp_triangle->next; tmp_triangle->next = new_triangle; } } void init_lst_triangle(char *line, t_obj *obj) { t_triangle *triangle; triangle = (t_triangle *)malloc(sizeof(t_triangle)); if (!triangle) return (exit_errcode(MALLOC_ERROR)); triangle->coord1 = read_line_to_vector(&line); if (triangle->coord1.x == DBL_MIN || triangle->coord1.y == DBL_MIN || triangle->coord1.z == DBL_MIN) return (exit_errcode(TRIANGLE_ERROR_LINE)); triangle->coord2 = read_line_to_vector(&line); if (triangle->coord2.x == DBL_MIN || triangle->coord2.y == DBL_MIN || triangle->coord2.z == DBL_MIN) return (exit_errcode(TRIANGLE_ERROR_LINE)); triangle->coord3 = read_line_to_vector(&line); if (triangle->coord3.x == DBL_MIN || triangle->coord3.y == DBL_MIN || triangle->coord3.z == DBL_MIN) return (exit_errcode(TRIANGLE_ERROR_LINE)); triangle->edge1 = sub_vector(triangle->coord2, triangle->coord1); triangle->edge2 = sub_vector(triangle->coord3, triangle->coord1); triangle->color = read_line_to_color(&line); triangle->next = NULL; if (*line || triangle->color.depth) return (exit_errcode(TRIANGLE_ERROR_LINE)); add_end_lst_triangle(triangle, obj); } void free_lst_triangle(t_obj *obj) { t_triangle *triangle; t_triangle *next_triangle; triangle = obj->lst_triangle; while (triangle) { next_triangle = triangle->next; free(triangle); triangle = next_triangle; } obj->lst_triangle = NULL; } t_vector triangle_albedo(t_triangle *lst_triangle, int id_triangle) { while (id_triangle-- > 0) lst_triangle = lst_triangle->next; return (color_to_vector(lst_triangle->color)); }
C
/* 內容宣告: 以下程式碼由 李翼全 提供 練習題 使用者輸入半徑 求圓面積 和 圓周長 求到 小數點第二位 */ /* #include <stdio.h> #include <math.h> int main(){ float rad; printf("請輸入半徑: "); scanf("\n%f",&rad); float area = 3.14*rad*rad; float circle = 2*3.14*rad; //printf("圓面積為:%.2f\t 圓周長為:%.2f",3.14*pow(rad,2.0),2*3.14*rad); printf("圓面積為:%.2f\t 圓周長為:%.2f",area,circle); return 0; } */
C
/** * @file include/kernel/int.h * Kernel operations for enabling and disabling interrupts. * @author Conlan Wesson */ #ifndef __INCLUDE_KERNEL_INT_H_ #define __INCLUDE_KERNEL_INT_H_ /** * Enable interrupts. */ static inline void sti(){ asm volatile("sti"); } /** * Disable interrupts. */ static inline void cli(){ asm volatile("cli"); } #endif
C
#include <stdio.h> int main(void){ int num, cont; float media; scanf("%d", &num); cont = 1; media = num; while(num >= 0){ scanf("%d", &num); cont++; media = media + num; } printf("%.2f\n", (media - num) / (cont -1)); return 0; }
C
//***************************************************************---C76-->| #include <stdio.h> #include <stdlib.h> #include <math.h> /* Created by Manoj Soni on Thursday, October 10, 2019 */ /* Description: Static and Global Variables in Recursion */ // TODO: Explain why there is a difference between the outputs int fun(int n){ static int x=0; // Static Variable, It will have a separate section // inside the code section if (n>0){ x++; return fun(n-1)+x; } return 0; } int main() { /*Code here*/ int x =5; int fun(int); printf("%d\n",fun(x)); // Answer is 25 printf("%d\n",fun(x)); // Why this is not 25 ? //getch(); return 0; } //** L49, A4 Paper ends, leave L50 empty //***************************************************************---C76-->|
C
#include "hash.c" #define ENCRYPTION_ROUNDS 12 #define initialize_state(a, b, c, d, t, iv, key, extra_data, extra_data_size)({\ WORDSIZE hash_output[8];\ hash_function(extra_data, extra_data_size, hash_output);\ load_register(a, hash_output, 0);\ load_register(b, hash_output, 4);\ load_register(t, iv, 0);\ a ^= t;\ load_register(t, iv, 4);\ b ^= t;\ load_register(c, key, 0);\ load_register(d, key, 4);\ permutation(a, b, c, d, t, ENCRYPTION_ROUNDS);}) void encrypt(WORDSIZE* data, WORDSIZE* key, WORDSIZE* iv, WORDSIZE* extra_data, WORDSIZE* tag, unsigned long data_size, unsigned long extra_data_size){ REGISTER a, b, c, d, t; unsigned long index; initialize_state(a, b, c, d, t, iv, key, extra_data, extra_data_size); unsigned long block_number; for (block_number = 0; block_number < data_size / 8; block_number++){ load_register(a, data, (block_number * 8)); load_register(b, data, ((block_number * 8) + 4)); permutation(a, b, c, d, t, ENCRYPTION_ROUNDS); store_register(a, data, (block_number * 8)); store_register(b, data, ((block_number * 8) + 4));} load_register(t, key, 0); c ^= t; load_register(t, key, 4); d ^= t; store_register(c, tag, 0); store_register(d, tag, 4);} int decrypt(WORDSIZE* data, WORDSIZE* key, WORDSIZE* iv, WORDSIZE* extra_data, WORDSIZE* tag, unsigned long data_size, unsigned long extra_data_size){ REGISTER a, b, c, d, t; unsigned long index; load_register(d, tag, 4); load_register(c, tag, 0); load_register(t, key, 4); d ^= t; load_register(t, key, 0); c ^= t; unsigned long block_number = data_size / 8; while (block_number-- > 0){ load_register(a, data, (block_number * 8)); load_register(b, data, (block_number * 8) + 4); invert_permutation(a, b, c, d, t, ENCRYPTION_ROUNDS); store_register(a, data, (block_number * 8)); store_register(b, data, (block_number * 8) + 4);} REGISTER tag_c, tag_d; tag_c = c; tag_d = d; initialize_state(a, b, c, d, t, iv, key, extra_data, extra_data_size); REGISTER valid; valid[0] = 0xFFFFFFFF; valid[1] = 0xFFFFFFFF; valid[2] = 0xFFFFFFFF; valid[3] = 0xFFFFFFFF; valid = (c ^ tag_c ^ 0xFFFFFFFF) & valid; valid = (d ^ tag_d ^ 0xFFFFFFFF) & valid; return valid[0] & valid[1] & valid[2] & valid[3];} void test_encrypt_decrypt(){ WORDSIZE data[8], key[8], iv[8], extra_data[8], tag[8]; unsigned long index; for (index = 0; index < 8; index++){ data[index] = 0; key[index] = 0; iv[index] = 0; extra_data[index] = 0;} data[0] = 1; key[0] = 1; iv[0] = 1; extra_data[0] = 1; encrypt(data, key, iv, extra_data, tag, 8, 8); //iv[0] = 0; //tag[0] = 0; //extra_data[0] = 0; if (decrypt(data, key, iv, extra_data, tag, 8, 8) == 0xFFFFFFFF){ printf("%lu%lu%lu%lu%lu%lu%lu%lu\n", data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7]);} else{ printf("Decryption failed\n");}} void test_encrypt_time(){ WORDSIZE message[8], key[8], iv[8], extra_data[8], tag[8]; unsigned long index; for (index = 0; index < 8; index++){ message[index] = 1; key[index] = 0; iv[index] = 0; extra_data[index] = 0;} printf("Encrypting and authenticating 3,000,000 256-bit blocks (~91MB)\n"); clock_t begin = clock(); for (index = 0; index < 3000000; index++){ encrypt(message, key, iv, extra_data, tag, 8, 8);} clock_t end = clock(); double time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("Time required: %.2fs\n", time_spent); printf("%lu%lu%lu%lu%lu%lu%lu%lu\n", message[0], message[1], message[2], message[3], message[4], message[5], message[6], message[7]);} int main(){ test_encrypt_decrypt(); test_encrypt_time(); return 0;}
C
#include "protos.h" #define nb_max_antecedent 3 // une tâche a au maximum nb_max_antecedent int max_tab(int *tab, int nelt) { int i, maxv; maxv = tab[0]; for( i = 1 ; i < nelt ; i++ ) { if (tab[i] > maxv) { maxv = tab[i]; } } return maxv; } struct table *read_data(char *name_file) { FILE *entry = fopen(name_file,"r"); int i,j,h; char donnees[MAX] = {0}; struct table *t = (struct table*)malloc(sizeof(struct table)*MAX); t->nb_tasks = 0; printf("Le fichier à ouvrir est : %s\n", name_file); if(entry != NULL){ printf("L'ouverture du fichier %s a reussi !\n", name_file); while (fgets(donnees, MAX, entry) != NULL) t->nb_tasks++; printf("Le fichier contient %d tâches.\n", t->nb_tasks); t->tasks = malloc(t->nb_tasks * sizeof(int)); t->duree = malloc(t->nb_tasks * sizeof(int)); t->antecedent = malloc(nb_max_antecedent*t->nb_tasks * sizeof(int)); t->nb_antecedents = malloc(t->nb_tasks * sizeof(int)); if (t->tasks == NULL && (t->duree == NULL) && (t->antecedent == NULL) && (t->nb_antecedents == NULL)) { printf("Erreur allocation !"); exit(0); } else { printf("Allocation reussie !\n"); } rewind(entry); // on se place au début du fichier d'entrée for (h=0; h<MAX; h++){ t->tasks[h] = 0.0; t->duree[h] = 0.0; t->antecedent[h] = 0.0; t->nb_antecedents[h] = 0.0; } char s[6] = ", ,"; char *token; t->stock_antecedent[t->nb_tasks][nb_max_antecedent]; memset(t->stock_antecedent,0,t->nb_tasks*nb_max_antecedent*sizeof(int)); int inc=0; for (i=0; i<t->nb_tasks; i++) { fgets(donnees, MAX, entry); printf("données : %s\n", donnees); t->tasks[i] = atoi(donnees); t->duree[t->tasks[i]] = atoi(donnees+1); t->nb_antecedents[t->tasks[i]] = atoi(donnees+3); t->antecedent[t->tasks[i]] = atoi(donnees+5); t->stock_antecedent[t->tasks[i]][0] = t->antecedent[t->tasks[i]]; inc = 1; while (inc <= t->nb_antecedents[t->tasks[i]]-1) { token = strtok(donnees+7, s); //printf("%s\t",token); if(inc == 2){ token = strtok(donnees+10, s); t->stock_antecedent[t->tasks[i]][nb_max_antecedent-1] = atoi(token); }else { t->stock_antecedent[t->tasks[i]][1] = atoi(token); } t->antecedent[t->tasks[i]] = atoi(token); inc++; } } for (j=0; j<t->nb_tasks; j++){ printf("\n"); printf("tâche : %d\n", t->tasks[j]); printf("duree : %d\n", t->duree[t->tasks[j]]); printf("nombre d'antecedents : %d\n", t->nb_antecedents[t->tasks[j]]); } }else printf("L'ouverture du fichier %s a echouee !\n", name_file); return t; } int *date_au_plus_tot(struct table *t) { static int c_t[MAX]; //date au plus tôt for(int a=0;a<t->nb_tasks;a++){ if(t->nb_antecedents[t->tasks[a]] == 0){ c_t[t->tasks[a]] = 0; }else if(t->nb_antecedents[t->tasks[a]] == 1){ c_t[t->tasks[a]] = t->duree[t->stock_antecedent[t->tasks[a]][0]] + c_t[t->stock_antecedent[t->tasks[a]][0]]; }else { if(t->nb_antecedents[t->tasks[a]]==2){ c_t[t->tasks[a]] = max(t->duree[t->stock_antecedent[t->tasks[a]][1]]+c_t[t->stock_antecedent[t->tasks[a]][1]], t->duree[t->stock_antecedent[t->tasks[a]][0]]+c_t[t->stock_antecedent[t->tasks[a]][0]]); }else { int tableau[3] = {t->duree[t->stock_antecedent[t->tasks[a]][0]]+c_t[t->stock_antecedent[t->tasks[a]][0]], t->duree[t->stock_antecedent[t->tasks[a]][1]]+c_t[t->stock_antecedent[t->tasks[a]][1]], t->duree[t->stock_antecedent[t->tasks[a]][2]]+c_t[t->stock_antecedent[t->tasks[a]][2]]}; c_t[t->tasks[a]] = max_tab(tableau,3); } } } // for (int k=0; k<t->nb_tasks; k++){ // for(int col=0;col<3;col++){ // printf("col %d stock_antecedent : %d\n",col, t->stock_antecedent[k][col]); // } // printf("-------------------\n"); // } printf("date au plus tôt: \n"); for(int i=0;i<t->nb_tasks;i++){ printf("%d ",c_t[t->tasks[i]]); } printf("\n"); return c_t; } int *date_au_plus_tard(struct table *t,int *daptot) { int c_t_prime[MAX]; //date au plus tard memset(c_t_prime,0,t->nb_tasks*sizeof(int)); static int result[MAX]; memset(result,0,t->nb_tasks*sizeof(int)); c_t_prime[t->tasks[t->nb_tasks-1]] = daptot[t->tasks[t->nb_tasks-1]]; result[t->tasks[t->nb_tasks-1]] = c_t_prime[t->tasks[t->nb_tasks-1]]; int stock_task1[MAX]; int stock_task2[MAX]; int iter = 0; // stockage des tâches et de leur antécédent for(int a=t->nb_tasks-2;a>=0;a--){ for(int k=0;k<t->nb_tasks;k++){ for(int j=0;j<nb_max_antecedent;j++){ if(t->tasks[a] == t->stock_antecedent[t->tasks[k]][j] ){ //printf("%d antécédent de %d\n",t->tasks[a],t->tasks[k]); stock_task1[iter] = t->tasks[a]; stock_task2[iter] = t->tasks[k]; iter++; } } } } int stock_daptard[t->nb_tasks][2]; // matrice pour stocker toutes les dates au plus tard de chaque tâche memset(stock_daptard,0,t->nb_tasks*sizeof(int)); int taille = 0; int indice[MAX]; //tableau d'indice // calcul des dates au plus tard for(int index=0;index<iter;index++){ if(stock_task1[index] != stock_task1[index+1] && (stock_task1[index] != stock_task1[index-1])){ c_t_prime[stock_task1[index]] = c_t_prime[stock_task2[index]] - t->duree[stock_task1[index]]; result[stock_task1[index]] = c_t_prime[stock_task1[index]]; } else { if(stock_task1[index] != stock_task1[index+1]){ c_t_prime[stock_task1[index]] = min(c_t_prime[stock_task2[index]],c_t_prime[stock_task2[index-1]]) - t->duree[stock_task1[index]]; stock_daptard[taille][0] = c_t_prime[stock_task1[index]]; indice[taille] = stock_task1[index]; taille++; }else { c_t_prime[stock_task1[index]] = min(c_t_prime[stock_task2[index]],c_t_prime[stock_task2[index+1]]) - t->duree[stock_task1[index]]; stock_daptard[taille][1] = c_t_prime[stock_task1[index]]; } } } for(int i=0;i<taille;i++){ result[indice[i]] = min(stock_daptard[i][0],stock_daptard[i][1]); } printf("date au plus tard: \n"); for(int i=0;i<t->nb_tasks;i++){ printf("%d ",result[t->tasks[i]]); } printf("\n"); return result; } int *marge_totale(int *daptot,int *daptard,struct table *t){ static int mt[MAX]; // marge totale printf("marge totale:\n"); for(int i=0;i<t->nb_tasks;i++){ mt[i] = daptard[t->tasks[i]] - daptot[t->tasks[i]]; printf("%d ",mt[i]); } printf("\n"); return mt; } void marge_libre(int *mt,int *daptot,struct table *t){ static int ml[MAX]; int stock_task1[MAX]; int stock_task2[MAX]; int iter = 0; for(int index = 0;index<t->nb_tasks;index++){ if(mt[index] == 0){ ml[t->tasks[index]] = 0; }else { for(int a=t->nb_tasks-2;a>=0;a--){ for(int j=0;j<nb_max_antecedent;j++){ if(t->tasks[index] == t->stock_antecedent[t->tasks[a]][j] ){ stock_task1[iter] = t->tasks[index]; stock_task2[iter] = t->tasks[a]; iter++; } } } // calcul des marges libres for(int i=0;i<iter;i++){ if(stock_task1[i] == stock_task1[i+1] && (stock_task1[i] != stock_task1[i-1])){ ml[stock_task1[i]] = min(daptot[stock_task2[i]],daptot[stock_task2[i+1]]) - daptot[stock_task1[i]] - t->duree[stock_task1[i]]; }else if(stock_task1[i] != stock_task1[i+1] && (stock_task1[i] == stock_task1[i-1])) { ml[stock_task1[i]] = min(daptot[stock_task2[i]],daptot[stock_task2[i-1]]) - daptot[stock_task1[i]] - t->duree[stock_task1[i]]; }else { ml[stock_task1[i]] = daptot[stock_task2[i]] - daptot[stock_task1[i]] - t->duree[stock_task1[i]]; } } } } printf("MARGE LIBRE: \n"); for(int i=0;i<t->nb_tasks;i++){ printf("%d ",ml[t->tasks[i]]); } printf("\n"); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include "func.h" Status InitList_Sq(pSqList L) { //һյԱ Status Result = Error; L->elem = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType)); if (!L->elem) //洢ռʧ exit(OverFlow); L->length = 0; //ʼձΪ 0 L->listsize = LIST_INIT_SIZE; //ʼһ洢ռС Result = OK; return Result; } void UnInitList_Sq(pSqList L) { free(L->elem); L->elem = NULL; L->length = 0; L->listsize = 0; } void ListClear(pSqList L) { L->length = 0; L->listsize = LIST_INIT_SIZE; } Status ListInsert_Sq(pSqList L, int i, ElemType e) { //ѭԱLеiλ֮ǰµԪeiĺϷֵΪ 1 <= i <= ListLength_Sq(L) + 1 Status Result = Error; if ((i < 1) || (i > L->length + 1)) //iֵϷ return Error; if (L->length >= L->listsize) //洢ռ˾ʹӷ { ElemType *newbase = (ElemType *)realloc(L->elem, (L->listsize+LISTINCREMENT)*sizeof(ElemType)); if (!newbase) //洢ʧ exit(OverFlow); L->elem = newbase; //»ַ L->listsize += LISTINCREMENT; //ӵĴ洢 } ElemType *q = &(L->elem[i - 1]); //qΪλ ElemType *p; for (p = &(L->elem[L->length - 1]); p >= q; --p) //λü֮Ԫ { *(p + 1) = *p; } *q = e; //봫 e ++L->length; // 1 Result = OK; return Result; } Status ListDelete_Sq(pSqList L, int i, ElemType *e) { //˳ԱLɾiԪأ e ֵ //i ĺϷֵΪ 1 <= i <= ListLength_Sq(L) Status Result = Error; if ((i < 1) || (i > L->length)) // i ֵϷ { return Error; } ElemType *p = &(L->elem[i - 1]); //pΪɾԪصλ *e = *p; //ɾԪصֵ e ElemType *q = L->elem + L->length - 1; //βԪصλ for (++p; p <= q; ++p) { *(p - 1) = *p; //ɾԪ֮Ԫ } --L->length; // 1 Result = OK; return Result; } int LocateElem_Sq(pSqList L, ElemType E) { //˳ԱLвҵ1ֵecompare()Ԫصλҵ򷵻Lеλ򣬷򷵻0 int I = 1; //iijֵΪ1Ԫصλ ElemType *P = L->elem; //pijֵΪ1ԪصĴ洢λ while (I <= L->length) { if (Compare(*P, E)) { break; } else { ++P; } ++I; } if (I <= L->length) { return I; } else { return 0; } } Status Compare(ElemType E1, ElemType E2) { return E1 == E2 ? 1 : 0; } void ShowList(char *str, pSqList L, bool IsChar) { int i; ElemType V; printf(str); printf("( "); for (i = 0; i < L->length; i++) { V = L->elem[i]; IsChar ? printf("%d ", V) : printf("%c ", V); } printf(")\n"); }
C
/** * @file * Contains function declarations for Semantic Analysis of a move list and associated utility functions. * * @author Santhosbaala RS * @copyright 2012 64cloud * @version 0.1 */ #ifndef SEMANTIC_ANALYZER #define SEMANTIC_ANALYZER #include "ssandef.h" #include "bitboard.h" #include "offsetboard.h" #include "boardformatconvertutil.h" #pragma mark - Semantic analysis and legality verification functions /** * Enum defines the error codes for the semantic_analyze() function. */ enum { sskSemanticAnalyzerErrorNone = 0, /** No error */ sskSemanticAnalyzerErrorProvidedMoveListEmpty, /** The given move list was empty */ sskSemanticAnalyzerErrorFirstPositionNotSpecified, /** The initial position was not supplied */ sskSemanticAnalyzerErrorIllegalMove, /** An illegal move was found */ sskSemanticAnalyzerErrorAmbiguousMove, /** An ambiguos move was found */ sskSemanticAnalyzerErrorMovesExistAfterGameEnd /** Moves exist even if the game had ended */ }; typedef unsigned short sskSemanticAnalyzerError; /** Custom typedef for semantic analysis error code */ /** * Function analyses the given move list for semantic correctness * and completes the fromSquare-toSquare pair. If the ambiguity * was encountered, then the ambiguosHalfmoveNumber iVar is filled. * * @param moveList The input move list. * @param startingPosition The starting position, specified as an xFEN string. * @param ambiguousHalfmoveNumber Out parameter, filled if a move was found ambigous. (optional, can be NULL) * * @return Returns the error code: * 0 - No error. * 1 - Provided Move list was empty. * 2 - Position not specified for first move. * 3 - Illegal move. * 4 - Piece movement ambiguity. * 5 - Movelist continues after logical game end. */ sskSemanticAnalyzerError sskSemanticAnalyze(sskMoveList moveList, char * startingPosition, int * ambiguousHalfmoveNumber); /** * Function verifies if the move is pseudo legal and returns * the fromSquare variable of the given move. Additionaly it fills * fromSquare and other information it discovers during analysis. * * @param bitboardPosition The current position in bitboard format. * @param offsetPosition The current position in offset format. * @param move A pointer to the move to be checked. * @param ambiguity Out variable filled with kTrue if ambiguity was found. * * @return kTrue on success, kFalse on failure. */ kBool sskFillFromSquare(sskBitboardPosition bitboardPosition, sskOffsetPosition offsetPosition, sskMove * move, kBool * ambiguity); /** * Function verifies if the move is completely legal, i.e) whether the move puts * the king under check. Note that the given move should be complete in the sense that * the fromSquare and toSquare fields should be filled. If the move was not checked for * pseudoLegality, then set the param to kFalse. The caller has to check if the move * is a castle and must set the appropriate field in the move token * * @param bitboardPosition The current position in Bitboard format. * @param move A pointer to the move to be verified. * @param moveWasPseudoLegalChecked Set to true if the move's pseudo legallity was checked beforehand. * * @return Returns the updated bitboard position if legal or NULL. */ sskBitboardPosition * sskCheckLegal(sskBitboardPosition bitboardPosition, sskMove * move, kBool moveWasPseudoLegalChecked); #pragma mark - Piece and board status query function /** * Function verifies if a side's king is under check for the given position. * * @param bitboardPosition The current position in bitboard format. * @param kingColor The color of the king that needs to be checked. * @param shouldIncludeKing If set to TRUE, will also consider opponent king issuing check. * @param checkingPieceSquare Out param, can be NULL. Filled with the square of the piece * issuing check. In case of multiple pieces, the last piece is filled. * * @return The number of pieces putting the king under check or 0 for no check. */ unsigned short sskIsKingUnderCheck(sskBitboardPosition bitboardPosition, sskChessColor kingColor, kBool shouldIncludeKing, sskChessSquare * checkingPieceSquare); /** * Function verifies if a side's king is under checkmate for the given position. * Note that isKingUnderCheck() should be called before calling this function. * * @param bitboardPosition The current position in bitboard format. * @param kingColor The color of the king that needs to be checked. * @param numChecks Set this > 0 if the number of checks is known, else set to -1 * @param enpassantTarget If any enpassant target is there for kingColor. Set to -1 if inapplicable. * * @return kTrue if checkmate else kFalse. * * NOTE: We need an enpassant target to handle a rare situation where in a pawn is * double pushed to issue check. Example: 7k/5p1b/7q/4P3/6K1/r7/8/8. Black * can play f5+, wKing has no escape squares, but ef6 is possible! */ kBool sskIsKingUnderCheckMate(sskBitboardPosition bitboardPosition, sskChessColor kingColor, int numChecks, int enpassantTarget); /** * Function verifies if a side's king is under stalemate for the given position. * note that checkPseudoLegal() and isKingUnderCheck() should have been called * before calling this function. * * @param bitboardPosition The current position in bitboard format. * @param kingColor The color of the king that needs to be checked. * @param enpassantTarget If any enpassant target is there for kingColor. Set to -1 if inapplicable. * * @return kTrue if stalemate else kFalse. */ kBool sskIsKingUnderStalemate(sskBitboardPosition bitboardPosition, sskChessColor kingColor, int enpassantTarget); /** * Function checks if king can move to adjacent squares without getting into check. * * @param bitboardPosition The current position in bitboard format. * @param kingColor The color of the king that needs to be checked. * * @return kTrue if king can escape and kFalse if king does not have any escape square. */ kBool sskCanKingEscape(sskBitboardPosition bitboardPosition, sskChessColor kingColor); /** * Function verifies whether a piece on a square can make A->B move in the given position. (Reachability) * The method supports enpassant and castling verification as well. Additionaly castling is generic for * normal chess as well as chess960. * * @param bitboardPosition The position in Bitboard format. * @param offsetPosition The position in Offset format. * @param fromSquare Source square. * @param toSquare Destination square. * @param isCastlingOrEnpassantTarget If the moving piece is a king and the argument is set to 0-7, indicating the rook's file. The function shall * consider the move as castling. If the moving piece is a pawn and the argument is set to a square, the function * shall consider enpassant. In normal cases, set this argument to -1. * * @return kTrue if the piece can travel fromSquare to toSquare, else kFalse. */ kBool sskIsSquareReachable(sskBitboardPosition bitboardPosition, sskChessSquare fromSquare, sskChessSquare toSquare, int isCastlingOrEnpassantTarget, sskBitmap * attackMap); /** * Function verifies if a particular piece under pin for the blocked piece. * * @param bitboardPosition The position in Bitboard format. * @param offsetPosition The position in Offset format. * @param pinnedSquare The square on which the probably pinned piece is sitting. * @param behindSquare The square to which the pin x-ray is radiated. * @param color The color of the pinned piece. * @param pinCausingPieceSquare If the function returns kTrue, filled with the square number of the pinner's square. * * @return kTrue if the given piece is under pin, kFalse if not. */ kBool sskIsSquarePinned(sskBitboardPosition bitboardPosition, sskOffsetPosition offsetPosition, sskChessSquare pinnedSquare, sskChessSquare behindSquare, sskChessColor color, sskChessSquare * pinCausingPieceSquare); #pragma mark - Move ambiguity handling functions /** * Enum to mark the common attributes among two or more squares. * The enum values can be bitwise ORed if the squares have both * file and rank in common. */ enum { sskSquareCommonalityNone = 0, /** Nothing is common between the squares */ sskSquareCommonalityRank = 1, /** Squares have rank in common */ sskSquareCommonalityFile = 2, /** Squares have file in common */ }; typedef unsigned short sskSquareCommonality; /** Custom type to represent square commonality */ /** * Function checks the squares of the given set of squares and finds out the commonalities * in them, like same file, same rank, etc., when the feature is shared by atleast two squares * among the provided set. * */ sskSquareCommonality sskGetSquareCommonality(sskChessSquare squares[], int numSquares); /** * Function checks if the given move token is ambiguous. Additionaly, the function fills the given * move token with the computed fromSquare value if the move was not ambiguos. * * @param offsetPosition The current position in offset format for lookup. * @param reachablePiecesFromSquares An array of calculatedFromSquare. * @param numReachablePieces The number of reachabe pieces found during semantic analysis. Should be > 0. * @param move The move token representing the move. * @param Out parameter filled with the attack map calculated, can be NULL. * * @return kTrue if ambiguous, kFalse if not ambiguous. */ kBool sskCheckMoveAmbiguityAndFillFromSquare(sskOffsetPosition offsetPosition, sskChessSquare reachablePiecesFromSquares[], unsigned short numReachablePieces, sskMove * move); #endif
C
/** * \author CHARARA Othmane * \date 12/04/2016 * \version 1.0 * \brief Déclaration de la structure Menu et en-tête des fonctions */ #ifndef __menu__ #define __menu__ #include "bouton.h" #include "listeChoix.h" #include "jauge.h" /** * \brief Structure qui permet de créer un menu graphique * \details La structure Menu est composée de : */ typedef struct Menu Menu; struct Menu { char* titre; /*!< Intitulé de la fenetre */ int width; /*!< Largeur de la fenetre */ int height; /*!< Hauteur de la fenetre */ Bouton *boutons; /*!< Collection de boutons contenus dans le menu */ int nbreBoutons; /*!< Nombre de boutonns */ ListeChoix *listesChoix; /*!< Collection de listes choix */ int nbreListesChoix; /*!< Nombre de listes Choix */ Jauge *jauges; /*!< Collection de jauges */ int nbreJauges; /*!< Nombre de jauges */ }; /** * \brief Intialise le menu * \param nom Intitulé du * \param width Largeur * \param height Hauteur * \return Une structure menu */ Menu *creerMenu(char *nom, int width, int height); /** * \brief Ajoute un bouton au menu * \param this Menu * \param bouton Bouton à ajouter * \return (void) */ void ajouterBouton(Menu *this, Bouton bouton); /** * \brief Ajoute une liste choix au menu * \param this Menu * \param listeChoix Liste choix à ajouter * \return (void) */ void ajouterListeChoix(Menu *this, ListeChoix listeChoix); /** * \brief Ajoute une jauge au menu * \param this Menu * \param listeChoix Jauge à ajouter * \return (void) */ void ajouterJauge(Menu *this, Jauge jauge); /** * \brief Génère le menu avec Ez_draw ainsi que chaque élément qui le compose * \param this Menu * \param fenetre Fenêtre sur laquelle sera affiché le menu * \return (void) */ void dessinerMenu(Menu *this, Ez_window fenetre); #endif
C
#include "inttree.h" int main(int argc, char *argv[]) { struct rb_root root; struct int_rb_node *ze_root = NULL, *ze_pred = NULL; struct rb_node *prev = NULL; inttree_init_tree(&root); rb_insert(&root, 1); rb_insert(&root, 12); rb_insert(&root, 25); rb_insert(&root, 9); rb_insert(&root, 6); ze_root = rb_entry(root.root, struct int_rb_node, node); printf("Root is : %d\n", ze_root->k); prev = rb_predecessor(root.root); ze_pred = rb_entry(prev, struct int_rb_node, node); printf("Prev is : %d (%p)\n->l : %p | ->r : %p\n", ze_pred->k, prev, prev->l, prev->r); rb_erase_raw(root.root, &root); inttree_dump(&root); return 0; }
C
#include<stdio.h> void main(){ int n, i, j, f = 0; printf("Enter size: "); scanf("%d", &n); for(i = 0; i<n; i++){ for(j = 0;j<=i;j++){ f++; if(i%2 != 0){ printf("%d", f); }else{ printf("%d", (f+i-j*2)); } } printf("\n\n"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_digit_type.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vpelivan <vpelivan@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/02/02 15:36:24 by vpelivan #+# #+# */ /* Updated: 2019/02/02 15:36:36 by vpelivan ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static void set_function1(t_lst *lst, va_list ptr, int *flag, intmax_t *i) { set_arg(lst, ptr); *i = set_size(lst, ptr); *flag = set_flag(lst, *i); } static void set_function2(t_lst *lst, intmax_t i, char **nb, int *len) { if (i == 0 && lst->precision == 0 && lst->width <= 0) *nb = ft_strdup(""); else if (i == 0 && lst->precision == 0 && lst->width > 0) *nb = ft_strdup(" "); else if (lst->type == 'b' && i > 0) *nb = ft_itoa_base_p(lst, i, 0, 2); else *nb = ft_itoa_base_p(lst, i, 0, 10); *len = (int)ft_strlen((*nb)); } void ft_print_width_digit(t_lst *lst, intmax_t i) { if (((lst->flags != '-') && (lst->width > 0 && lst->flags == '0' && lst->precision < 0)) || ((lst->flags != '-') && (lst->width <= 0 && lst->precision < 0)) || (i == 0 && lst->precision == 0 && lst->prior_space == ' ')) ft_print_flag(lst, i); if (lst->width <= 0) return ; if (lst->flags == '0' && lst->precision < 0) { while (lst->width > 4096) { ft_print_str_of_char(4096, '0'); lst->width -= 4096; } ft_print_str_of_char(lst->width, '0'); } else { while (lst->width > 4096) { ft_print_str_of_char(4096, ' '); lst->width -= 4096; } ft_print_str_of_char(lst->width, ' '); } } void ft_print_precision_digit(t_lst *lst, intmax_t i, int j) { if (lst->flags == '-' && j == 0 && lst->precision < 0) ft_print_flag(lst, i); if ((lst->precision >= 0) || (lst->precision < 0 && lst->width >= 0 && lst->flags != '0' && lst->flags != '-')) ft_print_flag(lst, i); if (lst->precision < 0) return ; if (j > 0) ft_print_str_of_char(j, '0'); } void ft_print_i_d(t_lst *lst, va_list ptr) { char *nb; int flag; int len; intmax_t i; int j; set_function1(lst, ptr, &flag, &i); set_function2(lst, i, &nb, &len); j = lst->precision - len; (j < 0) ? (j = 0) : 0; lst->width = lst->width - flag - j - len; if (lst->flags == '-') { ft_print_precision_digit(lst, i, j); ft_fill_buff(nb, len); ft_print_width_digit(lst, i); } else { ft_print_width_digit(lst, i); ft_print_precision_digit(lst, i, j); ft_fill_buff(nb, len); } free(nb); }
C
/* * paths.c * * Created on: 28.05.2017 * Author: pascal */ #include "assert.h" #include "string.h" #include "stdlib.h" #include "path.h" bool path_isRelative(const char *path) { assert(path != NULL); if(path[0] == '/') return false; return true; } bool path_elementIsValid(const char *element) { return strchr(element, '/') == NULL; } char *path_getAbsolute(const char *path, const char *pwd) { if(path == NULL) return NULL; if(path_isRelative(path)) return path_append(pwd, path); else return strdup(path); } char *path_append(const char *path1, const char *path2) { size_t path1_len = strlen(path1); size_t path2_len = strlen(path2); char *res_path = malloc(path1_len + path2_len + 1); if(res_path == NULL) return NULL; strcpy(res_path, path1); switch((path1[path1_len - 1] == '/') + (path2[0] == '/')) { case 2: memcpy(res_path + path1_len, path2 + 1, path2_len); break; case 1: memcpy(res_path + path1_len, path2, path2_len + 1); break; default: res_path[path1_len] = '/'; memcpy(res_path + path1_len + 1, path2, path2_len + 1); } return res_path; } char *path_removeLast(const char *path, char **element) { char *new_path = strdup(path); char *last_slash = strrchr(new_path, '/'); if(last_slash == NULL) { if(element != NULL) *element = strdup(new_path); *new_path = '\0'; } else { if(*(last_slash + 1) == '\0') { if(last_slash == new_path) { if(element != NULL) *element = strdup(new_path + 1); } else { *last_slash = '\0'; char *returned_path = path_removeLast(new_path, element); free(new_path); new_path = returned_path; } } else { *last_slash = '\0'; if(element != NULL) *element = strdup(last_slash + 1); } } return new_path; } int path_split(const char *path, char ***elements, size_t *count) { if (path == NULL) return -1; size_t element_count = 0; size_t allocated_elements = 2; const char *current_element = path; *elements = malloc(allocated_elements * sizeof(*elements)); if (*elements == NULL) return -1; while (*current_element != '\0') { char *element_end = strchr(current_element, '/'); bool last_element = false; if (element_end == NULL) { element_end = strchr(current_element, '\0'); last_element = true; } if (element_count + 1 > allocated_elements) { allocated_elements *= 2; char **new_elements = realloc(*elements, allocated_elements * sizeof(*elements)); if (new_elements == NULL) goto error; *elements = new_elements; } size_t element_len = element_end - current_element; // Skip empty elements if (element_len != 0) { (*elements)[element_count] = malloc(element_len + 1); if ((*elements)[element_count] == NULL) goto error; memcpy((*elements)[element_count], current_element, element_len); (*elements)[element_count][element_len] = '\0'; element_count++; } current_element = element_end + !last_element; } *count = element_count; return 0; error: for (size_t i = 0; i <= element_count; i++) { free((*elements)[i]); } free(*elements); return -1; }
C
#include<stdio.h> float main() { float x,y,a; x=10.5;y=5.5; a=xশ্রy; printf("Result of the expression is:%f",a); return 10.50; }
C
/* version 0.2 (PM, 12/5/19) : La discussion est un tableau de messages, couplé en mémoire partagée. Un message comporte un auteur, un texte et un numéro d'ordre (croissant). Le numéro d'ordre permet à chaque participant de détecter si la discussion a évolué depuis la dernière fois qu'il l'a affichée. La discussion est couplée à un fichier dont le nom est fourni en premier argument de la commande, le second étant le pseudo du participant. */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <sys/mman.h> /* définit mmap */ #include <signal.h> #define TAILLE_AUTEUR 25 #define TAILLE_TEXTE 128 #define NB_LIGNES 20 /* message : numéro d'ordre, auteur (25 caractères max), texte (128 caractères max) */ struct message { int numero; char auteur [TAILLE_AUTEUR]; char texte [TAILLE_TEXTE]; }; /* discussion (20 derniers messages) (la mémoire nécessaire est allouée via mmap(-)) */ struct message * discussion; /* dernier message en position 0 */ int dernier0 = 0 ; /* afficher la discussion */ void afficher() { int i; system("clear"); /* nettoyage de l'affichage simple, à défaut d'être efficace */ printf("==============================(discussion)==============================\n"); for (i=1; i<NB_LIGNES; i++) { printf("[%s] : %s\n", discussion[i].auteur, discussion[i].texte); } printf("------------------------------------------------------------------------\n"); } /* traitant : rafraichir la discussion, s'il y a lieu, toutes les secondes */ void traitant (int sig) { /* à faire */ } int main (int argc, char *argv[]) { struct message m; int i,taille,fdisc; char qq [1]; FILE * fdf; if (argc != 3) { printf("usage: %s <discussion> <participant>\n", argv[0]); exit(1); } /* ouvrir et coupler discussion */ if ((fdisc = open (argv[1], O_RDWR | O_CREAT, 0666)) == -1) { printf("erreur ouverture discussion\n"); exit(2); } /* mmap ne spécifie pas quel est le resultat d'une ecriture *apres* la fin d'un fichier couple (SIGBUS est une possibilite, frequente). Il faut donc fixer la taille du fichier destination à la taille du fichier source avant le couplage. Le plus simple serait d'utiliser truncate, mais ici on prefere lseek(a la taille du fichier source) + write d'un octet, qui sont deja connus des etudiants */ qq[0]='x'; taille = sizeof(struct message)*NB_LIGNES; lseek (fdisc, taille, SEEK_SET); write (fdisc, qq, 1); /* à compléter : - couplage et initialisations - boucle : lire une ligne au clavier, décaler la discussion d'une ligne vers le haut et insérer la ligne sasie en fin. - Note : le rafraîchissement peut être géré par un traitant. */ close(fdisc); exit(0); }
C
#ifndef __LOGGER_H__ #define __LOGGER_H__ typedef enum { wbLogLevel_unknown = -1, wbLogLevel_OFF = 0, wbLogLevel_FATAL, wbLogLevel_ERROR, wbLogLevel_WARN, wbLogLevel_INFO, wbLogLevel_DEBUG, wbLogLevel_TRACE } wbLogLevel_t; struct st_wbLogEntry_t { int line; char * msg; uint64_t time; const char * fun; const char * file; wbLogLevel_t level; struct st_wbLogEntry_t * next; }; #define wbLogEntry_getMessage(elem) ((elem)->msg) #define wbLogEntry_getTime(elem) ((elem)->time) #define wbLogEntry_getLevel(elem) ((elem)->level) #define wbLogEntry_getNext(elem) ((elem)->next) #define wbLogEntry_getLine(elem) ((elem)->line) #define wbLogEntry_getFunction(elem) ((elem)->fun) #define wbLogEntry_getFile(elem) ((elem)->file) #define wbLogEntry_setMessage(elem, val) (wbLogEntry_getMessage(elem) = val) #define wbLogEntry_setTime(elem, val) (wbLogEntry_getTime(elem) = val) #define wbLogEntry_setLevel(elem, val) (wbLogEntry_getLevel(elem) = val) #define wbLogEntry_setNext(elem, val) (wbLogEntry_getNext(elem) = val) #define wbLogEntry_setLine(elem, val) (wbLogEntry_getLine(elem) = val) #define wbLogEntry_setFunction(elem, val) (wbLogEntry_getFunction(elem) = val) #define wbLogEntry_setFile(elem, val) (wbLogEntry_getFile(elem) = val) extern wbLogEntry_t wbLogEntry_new(); extern wbLogEntry_t wbLogEntry_initialize(wbLogLevel_t level, const char * msg, const char * file, const char * fun, int line); extern void wbLogEntry_delete(wbLogEntry_t elem); extern json_t * wbLogEntry_toJSON(wbLogEntry_t elem); struct st_wbLogger_t { int length; wbLogEntry_t head; wbLogLevel_t level; }; #define wbLogger_getLength(log) ((log)->length) #define wbLogger_getHead(log) ((log)->head) #define wbLogger_getLevel(log) ((log)->level) #define wbLogger_setLength(log, val) (wbLogger_getLength(log) = val) #define wbLogger_setHead(log, val) (wbLogger_getHead(log) = val) #define wbLogger_setLevel(log, val) (wbLogger_getLevel(log) = val) #define wbLogger_incrementLength(log) (wbLogger_getLength(log)++) #define wbLogger_decrementLength(log) (wbLogger_getLength(log)--) #define wbLog(logger, level, msg) wbLogger_append(logger, wbLogLevel_##level, msg, wbFile, wbFunction, wbLine) extern wbLogger_t wbLogger_new(); extern void wbLogger_delete(wbLogger_t logger); extern void wbLogger_clear(wbLogger_t logger); extern void wbLogger_append(wbLogger_t logger, wbLogLevel_t level, const char * msg, const char * file, const char * fun, int line); extern json_t * wbLogger_toJSON(wbLogger_t logger); #endif /* __LOGGER_H__ */
C
#include<iostream>//http://stackoverflow.com/questions/17761704/suffix-array-algorithm #include<stdio.h> #include<algorithm> #include<string.h> using namespace std; struct suffix { int index; int rank[2]; }; bool comp(struct suffix r1,struct suffix r2) { if (r1.rank[0] == r2.rank[0]) { if (r1.rank[1] < r2.rank[1]) return true; else return false; } else { if (r1.rank[0] < r2.rank[0]) return true; else return false; } } void suffix_array(char *txt,int n,int A[]) { struct suffix suffixes[n]; for (int i=0;i<n;i++) { suffixes[i].index=i; suffixes[i].rank[0]=txt[i] - 'a'; suffixes[i].rank[1]=((i+1) < n)? (txt[i+1] - 'a'):-1; } sort(suffixes,suffixes+n,comp); for (int i=0;i<n;i++) { cout<<"Index is : "<<suffixes[i].index<<endl; } for(int k=4;k<2*n;k=k*2) { int prev_rank=suffixes[0].rank[0]; suffixes[0].rank[0]=0; A[suffixes[0].index]=0; int rank=0; for (int i=1;i<n;i++) { int temp=0; if(suffixes[i].rank[0] == prev_rank && suffixes[i].rank[1] == suffixes[i-1].rank[1]) { prev_rank=suffixes[i].rank[0]; suffixes[i].rank[0]=rank; } else { prev_rank=suffixes[i].rank[0]; suffixes[i].rank[0]=++rank; } A[suffixes[i].rank[0]]=i; } for (int i=0;i<n;i++) { int next_index=suffixes[i].index+k/2; suffixes[i].rank[1]=(next_index < n) ? suffixes[A[next_index]].rank[0]:-1; } sort(suffixes,suffixes+n,comp); } cout<<endl; for (int i=0;i<n;i++) { cout<<"Index is : "<<suffixes[i].index<<endl; } } int main() { char *txt="banana"; int n=strlen(txt); int A[n]; suffix_array(txt,n,A); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include "../libdartv2i2c/dartv2i2c.h" void delay(float dt) { unsigned int idt; idt = ( unsigned int) (dt*1000000.0); usleep(idt); } int main(int argc, char *argv[]) { int leftEnc, rightEnc; int status; float batlvl; float distFront, distBack, distLeft, distRight; // init i2c int i2c_fd = -1; // file descriptor const char *i2c_fname = "/dev/i2c-2"; // device name i2c_fd = dartv2i2c_open(i2c_fname); int mode = 1; status = dartv2i2c_sonars_set_mode_cardinal(i2c_fd, mode, mode, mode, mode); delay (0.25); float dmax = 2.0; status = dartv2i2c_sonars_set_dmax_cardinal(i2c_fd, dmax, dmax, dmax, dmax, dmax); delay (0.25); status = dartv2i2c_sonars_get_cardinal (i2c_fd, &distFront, &distBack, &distLeft, &distRight); printf ("dist f=%.2f b=%.2f, l=%.2f, r=%.2f\n",distFront, distBack, distLeft, distRight); delay (0.25); status = dartv2i2c_trex_get_front_encoders (i2c_fd,&leftEnc, &rightEnc); printf ("front encoders l=%5d, r=%5d\n",leftEnc,rightEnc); delay (0.25); status = dartv2i2c_get_rear_encoders (i2c_fd,&leftEnc, &rightEnc); printf ("rear encoders l=%5d, r=%5d\n",leftEnc,rightEnc); delay (0.25); status = dartv2i2c_trex_cmd_motors (i2c_fd,80,80); delay (0.25); status = dartv2i2c_trex_cmd_motors (i2c_fd,0,0); delay (0.25); status = dartv2i2c_trex_get_front_encoders (i2c_fd,&leftEnc, &rightEnc); printf ("encoders l=%5d, r=%5d\n",leftEnc,rightEnc); delay (0.25); status = dartv2i2c_get_rear_encoders (i2c_fd,&leftEnc, &rightEnc); printf ("rear encoders l=%5d, r=%5d\n",leftEnc,rightEnc); delay (0.25); status = dartv2i2c_get_battery_level (i2c_fd,&batlvl); printf ("Battery level is %.2f V\n",batlvl); // close i2c (not mandatory) dartv2i2c_close(i2c_fd); }
C
#include <stdio.h> #include "funcoes_auxiliares.h" void sort(int *array,int n){ int aux; int temp; for (int i=1;i<n;i++){ temp = i; while( ( *(array+temp-1) > *(array+temp) ) && (temp>=0) ){ aux = *(array+temp); *(array+temp) = *(array+temp-1); *(array+temp-1) = aux; temp--; } } } int main(int argc,char *argv[]){ int array[9] = {5.0,9.0,3.0,1.0,2.0,8.0,4.0,7.0,6.0}; printIntArray(array,9); sort(array,9); printIntArray(array,9); }
C
// // Created by Ritik garg on 07-09-2020. // #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <unistd.h> #include <netinet/in.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <ctype.h> #define PORT 9099 int main() { int sock =0; // file descriptor struct sockaddr_in server; char textToSend[1024]; char textToRec[1024]; server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; sock = socket(AF_INET, SOCK_STREAM, 0); if(sock <0) { perror("Error in opening socke"); exit(1); } // here the socket is craeeted connect(sock, (struct sockaddr * )&server, sizeof(server)); printf("You are now connected to the server\n"); printf("Enter the file name you want: \n"); scanf("%s", textToSend); char *filename = textToSend; FILE *receivedFile; int words; send(sock, textToSend, strlen(textToSend),0); printf("Checking for the file: "); printf("%s\n",filename); read(sock,textToRec,1024); // read(sock,&words,sizeof(int)); //printf("%s\n", textToRec); char *a = textToRec; // char *z = "-1"; // printf("%s %s\n",a,z); if(a[0] == '-') { fprintf(stderr, "File not Found\n"); exit(EXIT_FAILURE); } else { receivedFile = fopen(filename, "w"); read(sock,&words,sizeof(int)); int ch = 0; while(ch!=words) { read(sock, textToRec, 1024); fprintf(receivedFile, "%s ", textToRec); ch++; } printf("File received successfully\n"); fclose(receivedFile); } printf("Now closing \n"); close(sock); }
C
/******************************************************************* * Recommended compiler options: * * -v -O3 -march=native -funroll-loops * * 250 million integers in the range [-2147483647,2147483647] 2.42s * * 100 million integers in the range [-2147483647,2147483647] 0.98s * *******************************************************************/ #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <sys/shm.h> #include <time.h> //#include "project2.c" void sort(int *,int); /******************************************************************* * Flips all the bits if negative. * * Flips only the sign bit if positive. * * Alilows for both negative and positive values. * * Returns one of the two bytes of the integer. * *******************************************************************/ int cmpfunc (const void * a, const void * b) { return ( *(int*)a - *(int*)b ); } void generaterand(int a[],int n) { int i; // int g = n; for(i = 0;i<n;i++) { // a[i] = i; // g--; a[i] = rand() % 1000000 - 1000000; } } int main(void) { int n = 1000000; int a[n]; int i; srand(clock()); generaterand(a,n); clock_t tic = clock(); qsort(a, n, sizeof(int), cmpfunc); clock_t toc = clock(); printf("Size : %d\n\n", n); for(i = 0;i<n;i++) { if(i != n-1) if(a[i] > a[i+1]) printf("Problem"); } printf("\nQsort:\n"); printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC); generaterand(a,n); tic = clock(); sort(a,n); toc = clock(); for(i = 0;i<n;i++) { if(i != n-1) if(a[i] > a[i+1]) printf("Problem"); } printf("\nMysort:\n" ); printf("Elapsed: %f seconds\n", (double)(toc - tic) / CLOCKS_PER_SEC); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <math.h> #include "EstruturasDeDados.h" // TODO: INICIALIZAÇÃO DOS TAD tTree * createTree(tQuadrante quad) { tTree * tree = malloc(sizeof (tTree)); tree->quadtree = quad; return tree; } tPonto createPoint(int x, int y) { tPonto * point = malloc(sizeof (tPonto)); point->x = x; point->y = y; return *point; } tQuadrante createQuad(tPonto point, int width, int height, int level) { tQuadrante * quad = malloc(sizeof (tQuadrante)); quad->pBase = point; quad->width = width; quad->height = height; quad->nivel = level; return *quad; }
C
/* Nome: Mônica Emediato #Its job is to initiate communication with a server that is passively waiting to be contacted Para a implementação dos códigos, foram utilizados um main para o cliente, um main para o servidor e uma biblioteca “files.h” que o servidor utilizou para tratar as mensagens. */ #include <stdio.h> #include <stdlib.h> #include <sys/socket.h> #include <arpa/inet.h> #include <unistd.h> #include <netinet/in.h> #include <netdb.h> #include <string.h> int main(int argc, char** argv) { int client_socket, bytes, rv; char buffer[256]; /* Esta é a nova estrutura que vamos utilizar!*/ struct addrinfo hints, *list, *item; /* Checking the arguments */ if(argc != 3) { printf("\n[TCP Client] Argument error.\n\n"); exit(1); } /* ------------------------------------------------------------ // ------------------------------------------------------------ // Neste ponto, usaremos a getaddrinfo para "traduzir" // o que vier pelo argumento para um IPv4 ou IPv6. // o argv[1] pode ser: // um IPv4 puro, por exemplo: 127.0.0.1 (própria máquina), 201.12.43.12 // um IPv6 puro, por exemplo: ::1 (prória máquina), 2001:db8:1::2 // um host, por exemplo: teste.com */ memset(&hints, 0, sizeof hints); /* Enche de zeros na nova estrutura */ hints.ai_family = AF_UNSPEC; /* aceitar IPv4 ou IPv6*/ hints.ai_socktype = SOCK_STREAM; /* Apenas TCP*/ if((rv = getaddrinfo(argv[1], argv[2], &hints, &list)) != 0) { /* Chama a função passando os dois argumentos*/ printf("[TCP Client] getaddrinfo error: %s\n", gai_strerror(rv)); exit(1); } /* ------------------------------------------------------------ // Essa função retorna uma lista de IPs. Por isso, é feito // este laço de repetição tentando abrir o socket com cada item // retornado. Se o socket for criado com sucesso e a conexão for // bem sucedida, sai do laço. // IMPORTANTE: Lembre-se que esta lista precisa ser "liberada" // de volta, pois está usando memória RAM. Eu estou fazendo // isso chamando a função "freeaddrinfo" lá no final do código. // ------------------------------------------------------------ // Para cada item obtido da função.... */ for(item = list; item != NULL; item = item->ai_next) { /* Tenta criar o socket*/ if((client_socket = socket(item->ai_family, item->ai_socktype, item->ai_protocol)) == -1) { printf("[TCP Client]: socket error\n"); /* Não deu certo, tenta criar outro socket com novos valores.*/ continue; } /*Se criar o socket, tenta realizar a conexão:*/ if(connect(client_socket, item->ai_addr, item->ai_addrlen) == -1) { close(client_socket); /* Não deu certo a conexão! Fecha o socket criado e tenta de novo.*/ printf("[TCP Client]: connect error\n"); continue; } break; } if(item == NULL) exit(1); /*Caso todos os itens falhem, será o fim da lista.*/ /* ------------------------------------------------------------ // A partir deste ponto, estamos conectados! // ------------------------------------------------------------ */ while(1) { memset(&buffer, 0, sizeof(buffer)); fgets(buffer, 128, stdin); /* Lê a mensagem*/ bytes = strlen(buffer); buffer[--bytes] = '\0'; write(client_socket, buffer, bytes); /* Envia a mensagem*/ if(buffer[0] == 'q' && buffer[1] == '\0') break; /* Teste pra sair com o "q"*/ bytes = recv(client_socket, buffer, sizeof(buffer), 0); /* Esperando por uma resposta do servidor*/ printf("%s\n", buffer); } close(client_socket); /* liberando o socket.*/ freeaddrinfo(list); /* liberando a memória!!*/ return 0; }
C
int incr(int a) { return a + 1; } int main() { int a = 2; a = (1+2) + incr(a+1); return a; }
C
#include "draw.h" void DrawPic32(uint32 x, uint32 y, uint32 width, uint32 height, uint8* image) { backbuffer_t* mem = Vid.BackBuffer + (Vid.BufferWidth * y + x); // move to first pixel for (uint32 i = 0; i < height; i++) { for (uint32 j = 0; j < width; j++) { if (*image != 0xFF) { backbuffer_t color = Vid.ColorData[*image]; *mem = color; } image++; mem++; } mem += Vid.BufferWidth - width; // skip row and move to first column } }
C
#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> int main() { int sum=0; int count=0; int shmid,status; int *a,*b; int inp; pid_t pid1=1,pid2=1; int pfd1[2]; pipe(pfd1); pid_t ppid=getpid(); inp=getchar(); while(inp!=10){ if (getpid()==ppid){ if (inp==32) continue; inp=inp-48; inp*=inp; write(pfd1[1],&inp,4); write(pfd1[1],&sum,4); if(pid1=fork()==0){ int temp; int no; read(pfd1[0],&no,4); read(pfd1[0],&temp,4); temp += no; write(pfd1[1],&temp,4); exit(0); } else{ wait(&status); read(pfd1[0],&sum,4); write(pfd1[1],&count,4); if(pid2=fork()==0){ int cnt=0; read(pfd1[0],&cnt,4); cnt++; write(pfd1[1],&cnt,4); exit(0); } else{ wait(&status); read(pfd1[0],&count,4); } } } inp=getchar(); } int mean=sum/count; printf("mean = %d\n",mean ); }
C
#include <unistd.h> #include <stdio.h> #include <sys/wait.h> #include <string.h> int main(int argc, char **argv) { int fork_ret, exec_ret, i; for(i = 1; i < argc; i++) { fork_ret = fork(); if(fork_ret == 0) { printf("filho - %d e vou executar o comando - %s\n\n", getpid(), argv[i]); exec_ret = execlp(argv[i], argv[i], NULL); perror("reached return"); _exit(exec_ret); } } for(i = 1; i < argc; i++) { //printf("pai à espera de um filho...\n"); wait(NULL); } printf("\n\ntodos os filhos executaram\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* execute_pipes.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: frthierr <frthierr@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/15 10:16:23 by qfeuilla #+# #+# */ /* Updated: 2020/08/10 13:12:17 by frthierr ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/minishell.h" t_list *copy_command_p(t_list *command_start) { t_list *command_copy; char *token_copy; t_list *nav; t_list *node_copy; nav = command_start; token_copy = NULL; command_copy = NULL; while (nav && nav->content && ((char*)nav->content)[0] != '|') { if (!(token_copy = ft_strdup((char*)nav->content)) || !(node_copy = ft_lstnew(token_copy))) return (NULL); if (!command_copy) command_copy = node_copy; else ft_lstadd_back(&command_copy, node_copy); nav = nav->next; } return (command_copy); } t_list *get_command_list_p(t_list *token_list) { t_list *command_list; t_list *nav; t_list *new_node; t_list *new_node_content; nav = token_list; command_list = NULL; while (nav) { if (nav->content && ((char*)nav->content)[0] != '|') { if (!(new_node_content = copy_command_p(nav)) || !(new_node = ft_lstnew(new_node_content))) return (NULL); if (!command_list) command_list = new_node; else ft_lstadd_back(&command_list, new_node); while (nav && nav->content && ((char*)nav->content)[0] != '|') nav = nav->next; } if (nav) nav = nav->next; } return (command_list); } int execute_pipes(t_list **commandlist) { t_list *unpiped_commandlist; t_list *nav; t_list *tmp_list; nav = *commandlist; while (nav) { tmp_list = (t_list*)nav->content; unpiped_commandlist = get_command_list_p(tmp_list); execute_commands(&unpiped_commandlist); free_commandlist(&unpiped_commandlist); nav = nav->next; } return (1); }
C
/* Vishnu Kamaraju 77vishnu.k@gmail.com */ /* The key is 26 characters long and only contains alphabets. This means A-Z alphabets assign themselves to the exact same position in the key. For example, if Key: VCHPRZGJNTLSKFBDQWAXEUYMOI Then A corresponds to V, B to C, C to H, and so on. To achieve this output, simply add 13 to the input string's character if the character is a capital letter or add 7 if lower and modulo the sum by 26. The result will be between 0-25. Match this number with that element in the KEY array and that is your cipher character for the given character. */ #include <stdio.h> #include <cs50.h> #include <ctype.h> #include <string.h> int substitution(char key[],string message); // function that performs encryption. int main (int argc, string argv[]) { char k[26]; if (argc<2) // if key is not mentioned. { printf("Usage: ./substitution key\n"); return 1; } else if (argc>2) // if more than 2 arguments are mentioned. { printf("Only 2 arguments \n"); return 1; } else { int n = strlen(argv[1]); if(n%26 !=0) // key length checker. { printf("Key must contain 26 characters\n"); return 1; } int counter=0; while(counter<26) { if (!isalpha(argv[1][counter])) // check if any character of key is not alphabet. { printf("Key must only contain alphabetic characters\n"); return 1; } k[counter]=argv[1][counter]; for(int i =0; i<counter;i++) // check for repeated characters { if(argv[1][counter] == k[i]) { printf("Key must not contain repeated characters\n"); return 1; } } counter++; } } string input = get_string("plaintext: "); substitution(k,input); } int substitution(string key,string message) { char alpha_cap[26],alpha_small[26]; // storing capital letters and small letters. for(int i =0; i<26; i++) { alpha_cap[i] = 65 +i; alpha_small[i] = 97 +i; } printf("ciphertext: "); for (int j =0, n = strlen(message); j<n; j++) { int counter =0; if (!isalpha(message[j])) // if the character is not alphabet. { printf("%c",message[j]); } else { if(isupper(message[j])) { counter = message[j] + 13; // add 13 and modulo the whole sum with 26 (below) gets a value between 0-25. printf("%c",toupper(key[counter%26])); // print that corresponding letter's key value. } else { counter = message[j] + 7; printf("%c",tolower(key[counter%26])); // print that corresponding letter's key value in lower case. } } } printf("\n"); return 0; }
C
#include <stdio.h> #include <math.h> int main(){ int x, i, p; i = 0; printf("Digite o número desejado: "); scanf("%d", &x); for(i; i <= 10; i++){ p = pow(x, i); printf("%d\n", p); } }
C
#include<stdio.h> int a[101]; int b[100]; void merge(int l,int m,int h) { int l1,l2,i; for(l1=l,l2=m+1,i=l;l1<=m && l2<=h;i++) { if(a[l1]<=a[l2]) b[i]=a[l1++]; else b[i]=a[l2++]; } while(l1<=m) b[i++]=a[l1++]; while(l2<=h) b[i++]=a[l2++]; for(i=l;i<=h;i++) a[i]=b[i]; } void sort(int l,int h) { int m; if(l<h) { m=(l+h)/2; sort(l,m); sort(m+1,h); merge(l,m,h); } else return; } int main() { int i,n; printf("enter the number of elements\n"); scanf("%d",&n); printf("enter the elements of the array\n"); n=n-1; for(i=0;i<=n;i++) scanf("%d",&a[i]); printf("\narray after sorting\n"); sort(0,n); for(i=0;i<=n;i++) printf("%d\n",a[i]); }
C
// // Created by Александр Баташев on 02.12.16. // #include <stdlib.h> #include <time.h> #include <stdio.h> #include <string.h> #include <limits.h> #include "algorithms.h" /** * Классическая пузырьковая сортировка * @param arr Массив значений для сортировки * @param n Длина массива */ void bubble_sort(int *arr, int n) { int i, l, hasChanged; l = n - 1; do { hasChanged = 0; for (i = 0; i < l; ++i) { if (arr[i] > arr[i + 1]) { arr[i] ^= arr[i + 1]; arr[i + 1] ^= arr[i]; arr[i] ^= arr[i + 1]; hasChanged = 1; } } l--; } while (hasChanged); } /** * Улучшенная сортировка пузырьком с проходом в обе стороны * @param arr Массив данных * @param n Количество элементов */ void better_bubble_sort(int *arr, int n) { int i, start, finish, hasChanged; start = 0; finish = n - 1; do { hasChanged = 0; for (i = start; i < finish; ++i) { if (arr[i] > arr[i + 1]) { arr[i] ^= arr[i + 1]; arr[i + 1] ^= arr[i]; arr[i] ^= arr[i + 1]; hasChanged = 1; } } --finish; if (hasChanged) { for (i = finish - 1; i >= start; --i) { if (arr[i] > arr[i + 1]) { arr[i] ^= arr[i + 1]; arr[i + 1] ^= arr[i]; arr[i] ^= arr[i + 1]; hasChanged = 1; } } start++; } } while (hasChanged); } /** * Сортировка Шелла * @param arr Массив данных * @param n Количество элементов */ void shell_sort(int *arr, int n) { int i, hasChanged; int d = n; do { d = (d + 1) / 2; hasChanged = 0; for (i = 0; i < n - d; ++i) { if (arr[i] > arr[i + d]) { arr[i] ^= arr[i+d]; arr[i + d] ^= arr[i]; arr[i] ^= arr[i + d]; hasChanged = 1; } } } while (d != 1 || hasChanged); } /** * Поиск минимального элемента в массиве * @param arr Массив * @param n Количество элементов * @return Индекс минимального */ int min(int *arr, int n) { int i, min_idx = 0; for (i = 0; i < n; ++i) { if (arr[i] < arr[min_idx]) { min_idx = i; } } return min_idx; } /** * Поиск максимального элемента в массиве * @param arr Массив * @param n Количество элементов * @return Индекс минимального */ int max(int *arr, int n) { int i, max_idx = 0; for (i = 0; i < n; ++i) { if (arr[i] > arr[max_idx]) { max_idx = i; } } return max_idx; } /** * Сортировка выбором * @param arr Массив данных * @param n Количество элементов */ void selection_sort(int *arr, int n) { int i, j, pos; for (i = 0; i < n - 1; ++i) { pos = i; for (j = i + 1; j < n; ++j) { if (arr[pos] > arr[j]) { pos = j; } } if (pos != i) { arr[i] ^= arr[pos]; arr[pos] ^= arr[i]; arr[i] ^= arr[pos]; } } } /** * Сортировка вставками * @param arr Массив * @param n Количество элементов */ void insertion_sort(int *arr, int n) { int i, j, b; for (i = 0; i < n - 1; ++i) { b = arr[i + 1]; j = i; while ((j >= 0) && (b < arr[j])) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = b; } } /** * Алгоритм слияния двух упорядоченных массивов * @param first Первая часть * @param nf Размер * @param second Вторая часть * @param ns Размер * @param result Результат * @param k Количество */ void merge ( int * first, int nf, int * second, int ns, int * result, int k ) { int count = 0, i = 0, j = 0; first[nf] = INT_MAX; second[ns] = INT_MAX; while (count < nf + ns) { if (first[i] < second[j]) { result[k + count] = first[i++]; count++; } else { result[k + count] = second[j++]; count++; } } } /** * Сортировка слиянием * @param arr Исходный массив * @param n Количество элементов */ void merge_sort ( int * arr, int n ) { int i; int h = 1; int begin; int nf, ns; int *first, *second; first = (int *) calloc (n, sizeof(int)); second = (int *) calloc (n / 2 + 1, sizeof(int)); while (h < n) { begin = 0; while (begin < n - 1) { nf = 0; for (i = 0; (i < h) && (begin + i < n); i++) { first[i] = arr[begin + i]; nf++; } ns = 0; for (i = 0; (i < h) && (begin + h + i < n); i++) { second[i] = arr[begin + h + i]; ns++; } merge(first, nf, second, ns, arr, begin); begin += 2 * h; } h *= 2; } } /** * Быстрая сортировка * В данном случае используется деление не на 2, а на 3 части * Подробности: * http://www.geeksforgeeks.org/3-way-quicksort/ * https://www.toptal.com/developers/sorting-algorithms/quick-sort-3-way * https://ru.wikipedia.org/wiki/Быстрая_сортировка * @param arr Массив данных * @param start Начало * @param end Конец * @param counter Счетчик вложенности рекурсии. При первом вызове всегда равен 0. */ void quick_sort(int *arr, int start, int end, int counter) { /* * Специальная оптимизация, предотвращающая переполнение стека * и увеличивающая скорость работы алгоритма */ if (counter >= 100) { insertion_sort(arr, end + 1); return; } if (start >= end) { return; } int tmp; if (end - start <= 1) { if (arr[start] > arr[end]) { tmp = arr[start]; arr[start] = arr[end]; arr[end] = tmp; } return; } // Выбор опорного элемента случайным образом srand((unsigned int) time(0)); int pos; do { pos = start + rand() % end; } while (pos < start && pos > end); int divider = arr[pos]; int lo = start, mid = start; int hi = end; while (mid <= hi) { if (arr[mid] < divider) { tmp = arr[lo]; arr[lo] = arr[mid]; arr[mid] = tmp; mid++; lo++; } else if (arr[mid] == divider) { mid++; } else if (arr[mid] > divider) { tmp = arr[hi]; arr[hi--] = arr[mid]; arr[mid] = tmp; } } quick_sort(arr, start, lo - 1, ++counter); quick_sort(arr, mid, end, counter); } void improved_selection_sort(int *arr, int n) { const int split = 2; int * mins = (int *) calloc((size_t) n*2, sizeof(int)); int mins_count = 0; int i, j, min_idx, delta, t, incr; for (i = 0; i < n / split; ++i) { mins[mins_count++] = min(arr + i * split, split); } if (n - (n / split) * split > 0) { for (i = (n / split) * split; i < n; ++i) { mins[mins_count++] = i; } } for (i = 0; i < n; i++) { min_idx = 0; for (j = 1; j < mins_count; j++) { if (arr[mins[j]] > arr[mins[min_idx]]) { min_idx = j; } } // переформатируем массив минимальных delta = (mins[min_idx] / split) * split; t = mins[min_idx]; incr = split; if (t == delta) { delta++; incr--; } mins[min_idx] = delta; for (j = delta; j < delta + incr; j++) { mins[mins_count++] = j; } arr[t] ^= arr[i]; arr[i] ^= arr[t]; arr[t] ^= arr[i]; } free(mins); }
C
//#include <stdio.h> //#include <stdlib.h> // //int main(void) //{ // //λĶʼ // // int arry_2d[2][3]={ {2,5,4},{6,9} }; //23 δֵԪĬΪ0,ʹöϵԿֵ // //ʱϵвУҪöϵһУ // //int arry[2][2]={1,2,3,4} ʼҲ // printf("%d\n", sizeof(arry_2d) / sizeof(arry_2d[0][0])); //ʾĸ // printf("%p,%p,%p,%p,%p,%p\n", &arry_2d[0][0], &arry_2d[0][1], &arry_2d[0][2], &arry_2d[1][0], &arry_2d[1][1], &arry_2d[1][2]); // printf("%p,%p\n", &arry_2d[0], &arry_2d[1]); //&a[0]==&a[0][0],&a[1]==&a[1][0] // printf("%p\n", arry_2d); // a ʾa׵ַ // printf("%p\n", &arry_2d); //a ൱ &a ʾa׵ַ // // printf("%p,%p,%p", &arry_2d + 1, &arry_2d[0] + 1, &arry_2d[0][0] + 1); // // &aʾһСĵַ &a+1ʾһСĵַ&a[0]ʾСһ¥ĵַ &a[0]+1ʾڶ¥ַ // //&a[0][0]ʾһ¥һĵַ &a[0][0]+1ʾڶסַ // // // // return 0; //}
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "recdata.h" typedef struct { int* n_userdata; int** i_userdata; double** r_userdata; int* n_itemdata; int** i_itemdata; double** r_itemdata; int binary; } recdata_simple_args_t; int recdata_simple_userdata_size(int uid, void* args) { recdata_simple_args_t* a = args; return a->n_userdata[uid]; } int recdata_simple_itemdata_size(int iid, void* args) { recdata_simple_args_t* a = args; return a->n_itemdata[iid]; } idpairs_t* recdata_simple_userdata(int uid, void* args) { recdata_simple_args_t* a = args; return idpairs_create(a->n_userdata[uid], a->i_userdata[uid], a->binary ? NULL : a->r_userdata[uid]); } idpairs_t* recdata_simple_itemdata(int iid, void* args) { recdata_simple_args_t* a = args; return idpairs_create(a->n_itemdata[iid], a->i_itemdata[iid], a->binary ? NULL : a->r_itemdata[iid]); } void recdata_simple_close(void* args) { recdata_simple_args_t* a = args; free(a->n_userdata); free(a->i_userdata[0]); free(a->i_userdata); if (!a->binary) { free(a->r_userdata[0]); free(a->r_userdata); } free(a->n_itemdata); free(a->i_itemdata[0]); free(a->i_itemdata); if (!a->binary) { free(a->r_itemdata[0]); free(a->r_itemdata); } free(a); } #define MAX_LEN_LINE 256 void read_data(int** n, int*** v, double*** r, FILE* data, int N, int N_prefs, int binary) { char line[MAX_LEN_LINE]; int last_x; int* last_p; int x; int y; double z; int* p; double* q; *n = calloc(N, sizeof(int)); *v = calloc(N, sizeof(int*)); p = malloc(N_prefs * sizeof(int)); if (!binary) { *r = calloc(N, sizeof(double*)); q = malloc(N_prefs * sizeof(double)); } else { *r = NULL; q = NULL; } last_x = -1; last_p = p; while (fgets(line, MAX_LEN_LINE, data) != NULL) { x = atoi(strtok(line, "\t")); y = atoi(strtok(NULL, "\t")); if (!binary) { z = atof(strtok(NULL, "\t")); } if (x != last_x) { if (last_x != -1) { (*n)[last_x] = p - last_p; } (*v)[x] = p; if (!binary) { (*r)[x] = q; } last_x = x; last_p = p; } *p = y; if (!binary) { *q = z; } p++; if (!binary) { q++; } } (*n)[x] = p - last_p; } recdata_t* recdata_simple_create(FILE* user_data, FILE* item_data, int N_users, int N_items, int N_prefs, int binary) { recdata_t* recdata; recdata_simple_args_t* args; recdata = malloc(sizeof(recdata_t)); recdata->N_users = N_users; recdata->N_items = N_items; recdata->N_prefs = N_prefs; recdata->userdata_size = recdata_simple_userdata_size; recdata->itemdata_size = recdata_simple_itemdata_size; recdata->userdata = recdata_simple_userdata; recdata->itemdata = recdata_simple_itemdata; recdata->close = recdata_simple_close; args = malloc(sizeof(recdata_simple_args_t)); recdata->args = args; args->binary = binary; read_data(&(args->n_userdata), &(args->i_userdata), &(args->r_userdata), user_data, N_users, N_prefs, binary); read_data(&(args->n_itemdata), &(args->i_itemdata), &(args->r_itemdata), item_data, N_items, N_prefs, binary); return recdata; }
C
#include <iostream> using namespace std; //二叉树的结构 // Definition for binary tree struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { public: //任意一条路径上的最大值 int maxPathSum(TreeNode *root) { int max_path = 0; _maxPathSum(root,max_path);//用这个函数完成递归 return max_path; } int _maxPathSum(TreeNode* root,int maxPath) { if(root == NULL) { return 0; } //最大路径之和 = 左子树最大路径 + 根结点 + 右子树最大路径 int left = max(_maxPathSum(root->left,maxPath),0);//左子树的最大路径(结点值可能为负,所以要和0比较) int right = max(_maxPathSum(root->right,maxPath),0);//右子树的最大路径 maxPath = max(maxPath,left + right + root->val);//将当前最大路径和重新计算后的路径中的较大值赋给最大路径 return max(left,right) + root->val;//左右子树路径中较大的 + 根结点 }; }; int main() { return 0; }
C
#include <stdio.h> #include<string.h> int main(void) { char a[37],b[69]; int i,k; printf("enter the string"); scanf("%s",a); printf("enter the k values"); scanf("%d",&k); for(i=0;i<k;i++) { b[i]=a[i]; } printf("%s",b); return 0; }
C
#include <stdio.h> #include <cs50.h> #include <stdlib.h> void cambio(void); int numero; int main(void){ numero = 12; printf("El numero es %d\n",numero); cambio(); printf("El numero es %d\n",numero); return 0; } void cambio(void){ numero = 2; }
C
//Marcus Vinícius Souza Fernandes - 19.1.4046 - BCC201-61P #include <stdio.h> #include <stdlib.h> #include <string.h> #define T 50 #define TA 100 typedef struct{ char nomecomida[T]; double peso; double cal; } Dieta; Dieta *lerarquivo(int *n); int main() { int n, cont; double maior=0.00; Dieta *ler= lerarquivo(&n); double *caloriaporgrama=malloc(n * sizeof(double)); for(int i=0; i<n; i++){ caloriaporgrama[i] = (ler[i].cal / ler[i].peso); if (caloriaporgrama[i] > maior){ maior=caloriaporgrama[i]; cont=i; } } printf("Alimento \t\tcal/grama\n"); printf("-----------------------------------\n"); for (int i=0; i<n; i++){ printf ("%s \t%.2lf", ler[i].nomecomida, caloriaporgrama[i]); if (cont==i){ printf ("*"); } printf ("\n"); } printf ("\n"); return 0; } Dieta *lerarquivo(int *n){ char arquivo[TA]; printf("Digite o nome do arquivo: "); scanf("%s", arquivo); printf("\n"); FILE *file = fopen(arquivo, "r"); fscanf(file, "%d", n); Dieta *v = malloc(*n * sizeof(Dieta)); for(int i=0; i<*n; i++){ fscanf (file, "%s %lf %lf", v[i].nomecomida, &v[i].peso, &v[i].cal); } fclose(file); return v; }
C
#include <stdlib.h> #include <stdio.h> #include <time.h> // needed for initializing srand int main() { // Allows you to generate random number srand(time(NULL)); // Allows user to specify the original array size, stored in variable n1. printf("Enter original array size:"); int n1 = 0; scanf("%d", &n1); // Create a new array of n1 ints /* We have to allocate the memory for the array. Here I use malloc, as it will be more efficient than calloc in this context. Malloc takes size of memory to be allocated in bytes, that is why I multiply n1 by size of integer. I explicitly cast void* produced by malloc to int*. */ int* a1 = (int*)malloc(sizeof(int) * n1); int i; for (i = 0; i < n1; i++) { // Set each value in a1 to 100 /*Compiler knows that a1 is a pointer to integer, thus integers in a memory block associated * with this pointer can be accessed using square brackets notation. In pointer arithmetics * it is equivalent to *(a1 + i * sizeof(int))*/ a1[i] = 100; // Print each element out (to make sure things look right) /* Accessing ith element of a1 using brackets notation*/ printf("%d ", a1[i]); } // User specifies the new array size, stored in variable n2. printf("\nEnter new array size: "); int n2 = 0; scanf("%d", &n2); // Dynamically change the array to size n2 a1 = realloc(a1, sizeof(int) * n2); /* reallocating memory*/ // If the new array is a larger size, set all new members to 0. Reason: dont want to use // uninitialized variables. if (n2 > n1) { // // n1 is the index of the first undefined array element for (int i = n1; i < n2; ++i) { a1[i] = 0; } } for (i = 0; i < n2; i++) { // Print each element out (to make sure things look right) printf("%d ", a1[i]); // just indexating elements } printf("\n"); // Done with array now, done with program :D free(a1); // I dislike leaving a garbage;) return 0; }
C
/* - Numerical Gradient decent reinforcment PID Tuning */ #include <stdio.h> #include <stdlib.h> #include <linux/i2c-dev.h> #include <sys/ioctl.h> #include <fcntl.h> #include <unistd.h> #include <math.h> #include <sys/time.h> #include <pigpio.h> #include <string.h> #include <assert.h> #include "Sensors.h" #include "Motor.h" #define DT 0.005 #define RAD_TO_DEG 57.2957795131 //GLobal Variabels double Data[9] ={0.0}; int K[3][3]; //returns millisecond accurate time readings int mymillis() { struct timeval tv; gettimeofday(&tv, NULL); return (tv.tv_sec) * 1000 + (tv.tv_usec)/1000; } //Reads the Sensor Data void ReadData(file){ RawAccel(file); RawMagnet(file); //Roll double Gyrobuffer = GyroRead('r',file); Data[0] += Gyrobuffer*DT*RAD_TO_DEG-0.032; Data[1] = AccelRead('r'); Data[2] = Gyrobuffer; //Pitch Gyrobuffer = GyroRead('p',file); Data[3] += Gyrobuffer*DT*RAD_TO_DEG-0.0063; Data[4] = AccelRead('p')+6.5; Data[5] = Gyrobuffer; //Yaw Gyrobuffer = GyroRead('y',file); Data[6] += Gyrobuffer*DT*RAD_TO_DEG-0.029; Data[7] = MagnetRead(file); Data[8] = Gyrobuffer; } int main(){ //Setup for the Motors int Settings[4]={0}; double BaseThrust = 40.0; int MaxThrust = 35; //Setup for the Data Input int file = setupSensors(); int startInt = mymillis(); //Defines Test length int Epochs = 100; int Test_Length = 1000; int Test,Iteration; int axis,index; //Sets up the reward measures double oldReward=0,newReward=0; double instantReward; double h = 0.005; double alpha = 0.001; int State; //initiates the Konstants randomly srand(clock()); for(axis = 0;axis<3;axis++){ for(index = 0;index<3;index++){ K[axis][index] = 1.0-2.0*(double)rand()/RAND_MAX; } } //Training for(Test =0;Test<Epochs;Test++){ for(axis =0;axis<3;axis++){ for(index = 0;index<3;index++){ for(State = 0;State<2;State++){ //Adjusts Konstants if(State == 1){ K[axis][index] += h; printf("Increased the Parameter!\n"); sleep(3); } //Restes the Gyrotrackervariables RawAccel(file); RawMagnet(file); Data[0] = AccelRead('r'); Data[3] = AccelRead('p')+6.5; Data[6] = 0; //starts the Motors endStandby(); //zeros the Basethrust BaseThrust = 0; //zeros the clock startInt = mymillis(); for(Iteration=1;Iteration<(int)(Test_Length);Iteration++){ ReadData(file); double PitchDelta,Pitch; double RollDelta,Roll; double YawDelta,Yaw; //Combines the Angle Measumrments Pitch = 0.02*Data[4] + 0.98*Data[3]; Roll = 0.02*Data[1] + 0.98*Data[0]; Yaw = Data[6]; //stores reward //reward: Angle(squared)+half the rotaional Velocity instantReward = pow(Pitch,2.0)+pow(Roll,2.0)+pow(Yaw,2.0)+(Data[5]/2.0)+(Data[2]/2.0)+(Data[8]/2.0); if(State == 0){ oldReward += ((instantReward-oldReward)/Iteration); } else { newReward += ((instantReward-newReward)/Iteration); } //PID Deltas PitchDelta = K[0][0]*Pitch + K[0][1]*Data[5] + K[0][2]*PitchDelta; RollDelta = K[1][0]*Roll + K[1][1]*Data[2] + K[1][2]*RollDelta; YawDelta = K[2][0]*Yaw + K[2][1]*Data[8] + K[2][2]*YawDelta; if(BaseThrust<MaxThrust&&Iteration<(Test_Length)-MaxThrust){ BaseThrust += 1; } else if(Iteration>(Test_Length)-MaxThrust){ BaseThrust -= 1; } //Sets the Motrs Settings Settings[0] = (int)BaseThrust + PitchDelta + RollDelta - YawDelta; Settings[1] = (int)BaseThrust + PitchDelta - RollDelta + YawDelta; Settings[2] = (int)BaseThrust - PitchDelta - RollDelta - YawDelta; Settings[3] = (int)BaseThrust - PitchDelta + RollDelta + YawDelta; //Sends Motor Signal SetMotors(Settings); printf("Test:%d\tAxis:%d\tindex:%d\tState:%d\tIteration:%d\n",Test,axis,index,State,Iteration); //ensures constant cycle length while(mymillis()-startInt<DT*1000.0){ usleep(100); } startInt = mymillis(); } printf("-------------------reseting!-----------------\n"); end(); if(State == 1){ K[axis][index] -= h; printf("Decreased the parameter!\n"); } sleep(3); } //Adjusts the Konstants K[axis][index] += alpha*((oldReward-newReward)/h); printf("Adjusted the Constants!\n"); sleep(3); oldReward = 0; newReward = 0; } } } return 0; }
C
#include<stdio.h> int main() { int m,i; printf("Enter a Number\n"); scanf("%d",&m); for(i=0; i<m; i++) { printf("Hello\n"); } return 0; }
C
//autorzy: XYZ #include <iostream> #include <string> using namespace std; // wazny komentarz // Oblicza sum podanych liczb //---------------------------- string dodaj(string & x, string & y) { string z; int p,w,i,j,k,n; i = x.length(); j = y.length(); n = i; if(j < i) n = j; p = 0; z = ""; for(k = 1; k <= n; k++) { w = (int)(x[--i]) + (int)(y[--j]) + p - 96; p = w / 10; z = (char)((w % 10) + 48) + z; } while(i) { w = x[--i] + p - 48; p = w / 10; z = (char)((w % 10) + 48) + z; } while(j) { w = y[--j] + p - 48; p = w / 10; z = (char)((w % 10) + 48) + z; } if(p) z = (char)(p + 48) + z; if(z == "") z = "0"; return z; // zwracamy wynik dodawania } // Mnoy du liczb a przez ma b //--------------------------------- string mnoz_ab(string a, unsigned int b) { string w; w = "0"; // zerujemy acuch wyjciowy while(true) // wykonujemy mnoenie { if(b & 1) w = dodaj(w,a); if(b >>= 1) a = dodaj(a,a); else break; } return w; // zwracamy wynik mnoenia } // Mnoy dwie due liczby //----------------------- string mnoz(string & a, string & b) { string c,w,z; int i; // mnoymy w = "0"; z = ""; for(i = b.length()-1; i >= 0; i--) { c = mnoz_ab(a,b[i]-48) + z; w = dodaj(w,c); z = z + "0"; } return w; // zwracamy wynik mnoenia } //******************** //** PROGRAM GWNY ** //******************** int main() { string a,w; unsigned int b; // odczytujemy dane cin >> a; // dua liczba cin >> b; // maa liczba // potgujemy w = "1"; while(true) { if(b & 1) w = mnoz(w,a); if(b >>= 1) a = mnoz(a,a); else break; } // wypisujemy wynik cout << w << endl; }
C
#include "lib/header.h" int main(int argc, char *argv[]) { if(argc != 2) { fprintf(stderr, "Usage: %s <port>\n", argv[0]); exit(1); } int listen_fd; int clients[FD_SETSIZE]; int client_maxi = 0; int max_fd; memset(clients, 0xFF, sizeof(clients)); struct sockaddr_in listen_addr; memset(&listen_addr, 0, sizeof(listen_addr)); listen_addr.sin_family = AF_INET; listen_addr.sin_addr.s_addr = htonl(INADDR_ANY); listen_addr.sin_port = htons(atoi(argv[1])); listen_fd = socket(AF_INET, SOCK_STREAM, 0); if(listen_fd == -1) { fputs("Cannot create socket.\n", stderr); exit(2); } if(bind(listen_fd, (struct sockaddr *) &listen_addr, sizeof(listen_addr)) == -1) { fputs("Cannot bind.\n", stderr); exit(2); } if(listen(listen_fd, 1024) == -1) { fputs("Cannot listen.\n", stderr); exit(2); } fd_set all_set, r_set; FD_SET(listen_fd, &all_set); max_fd = listen_fd + 1; while(1) { r_set = all_set; int nready = select(max_fd, &r_set, NULL, NULL, NULL); printf("nready after select = %d\n", nready); if(FD_ISSET(listen_fd, &r_set)) { struct sockaddr_in client_addr; int client_len = sizeof(client_addr); int client_fd = accept(listen_fd, (struct sockaddr *) &client_addr, &client_len); /* boardcast to welcome this client */ boardcast(clients, client_maxi, "Someone is coming!"); int i; for(i=0; i<FD_SETSIZE; i++) { if(clients[i] < 0) { clients[i] = client_fd; break; } } /* hello to this client */ user_init(clients, i, &client_addr); if(i == FD_SETSIZE) { printf("Too many clients!\n"); exit(2); } if(i > client_maxi) { client_maxi = i; } if(client_fd >= max_fd) { max_fd = client_fd + 1; } FD_SET(client_fd, &all_set); printf("before nready = %d\n", nready); if(--nready){ puts("nready = 0 continue"); continue; } } printf("nready = %d\n", nready); int i; for(i=0; i<=client_maxi && nready; i++) { if(FD_ISSET(clients[i], &r_set)) { puts("minus the nready"); --nready; char buf[CMD_MAX]; int n = read(clients[i], buf, 999); if(n == 0) { close(clients[i]); FD_CLR(clients[i], &all_set); clients[i] = -1; user_down(clients, client_maxi, i); } else { buf[n] = '\0'; proc_cmd(clients, client_maxi, i, buf); } } } } }
C
#include <stdio.h> int main(void) { char c,d; c='d'; d=c; printf("d=%c\n",d); return 0; }
C
/*Lucas Botoni de Souza 04) Faa um programa que leia dois nmeros inteiros e os escreva em ordem crescente.*/ #include<stdio.h> #include<stdlib.h> main() { int x, y; printf("digite o primeiro numero: \n"); scanf("%d", &x); printf("digite o segundo numero: \n"); scanf("%d", &y); if (x<y) { printf("%d \t %d \n",x, y); } else { printf("%d \t %d \n", y, x); } system("pause"); }
C
#include "makeTable.h" void initTable() { makeTablePoint(); } int dispTable(int player, int no) { if (player == SENTE) return senteTable(no); else if (player == GOTE) return goteTable(no); return 0; } int senteTable(int no) { int line, col; int lineP = 0, colP = 0; printf(" "); for (line = 0; line < SIZE; ++line) printf("%3d", line); printf("\n"); for (line = 0; line < 29; ++line) printf("-"); printf("\n"); for (line = 0; line < 29; ++line) printf(" "); printf("\n"); for (line = 0; line < SIZE; ++line) { printf("%2d|", line); if (no == line) { printf("[ "); } else { printf(" "); } for (col = 0; col < SIZE; ++col) { if (table[line][col] == -99) { printf(" **"); } else { printf("%3d", table[line][col]); } } if (no == line) { printf(" ]\n"); } else { printf("\n"); } } puts(""); puts(""); for (line = 0; line < 29; ++line) printf("-"); puts(""); printf("先手の点数: %d点\n", score[0]); puts(""); printf("後手の点数: %d点\n", score[1]); puts(""); for (line = 0; line < 29; ++line) printf("-"); puts(""); puts(""); while (input(&lineP, &colP, SENTE, no) == 0); score[SENTE] += table[lineP][colP]; table[lineP][colP] = -99; return colP; } int goteTable(int no) { int line, col; int lineP = 0, colP = 0; printf(" "); for (line = 0; line < SIZE; ++line) printf("%3d", line); puts(""); for (line = 0; line < 29; ++line) printf("-"); puts(""); printf(" "); for (line = 0; line < SIZE; ++line) { if (line == no){ printf(" ##"); } else { printf(" "); } } puts(""); for (line = 0; line < SIZE; ++line) { printf("%2d|", line); printf(" "); for (col = 0; col < SIZE; ++col) { if (table[line][col] == -99) { printf(" **"); } else { printf("%3d", table[line][col]); } } printf("\n"); } printf(" "); for (line = 0; line < SIZE; ++line) { if (line == no) { printf(" ##"); } else { printf(" "); } } puts(""); puts(""); for (line = 0; line < 29; ++line) printf("-"); puts(""); printf("先手の点数: %d点\n", score[0]); puts(""); printf("後手の点数: %d点\n", score[1]); puts(""); for (line = 0; line < 29; ++line) printf("-"); puts(""); puts(""); while (input(&lineP, &colP, GOTE, no) == 0); score[GOTE] += table[lineP][colP]; table[lineP][colP] = -99; return lineP; } void makeTablePoint() { srand(time(NULL)); int line, col; for (line = 0; line < SIZE; ++line) { for (col = 0; col < SIZE; ++col) { table[line][col] = rand() % 19 - 9; } } }
C
/* * binary_tree_node_queue.h * * Created on: Mar 7, 2017 * Author: Negin Mortazavi */ #ifndef BINARY_TREE_NODE_QUEUE_H_ #define BINARY_TREE_NODE_QUEUE_H_ #include "binary_tree_node.h" #include <stdbool.h> /** * A struct representing a BinaryTreeNodeQueue. */ typedef struct _BinaryTreeNodeQueue{ int size; // length of allocated array int numElement; // number of elements in the queue BinaryTreeNode** nodes; // array of node pointers }BinaryTreeNodeQueue; /** * Create a new node queue */ BinaryTreeNodeQueue* newBinaryTreeNodeQueue(void); /** * Deallocate the memory for the queue. */ void deleteBinaryTreeNodeQueue(BinaryTreeNodeQueue* queue); /** * Add a number to the queue. */ void enqueueBinaryTreeNodeQueue(BinaryTreeNodeQueue* queue, BinaryTreeNode* node); /** * Remove and return the first element in the queue. */ BinaryTreeNode* dequeueBinaryTreeNodeQueue(BinaryTreeNodeQueue* queue); /** * Check if the queue is empty */ bool isEmptyBinaryTreeNodeQueue(BinaryTreeNodeQueue* queue); /** * Get the current number of elements in the queue. */ int getNumElementsBinaryTreeNodeQueue(BinaryTreeNodeQueue* queue); #endif /* BINARY_TREE_NODE_QUEUE_H_ */
C
#include <stdio.h> int up(int *arr, int n){ int res = 0; int swap = 0; int i,j; for (i=0; i<(n-1); i++){ for(j=(i+1); j<n; j++){ int check = 0; if(arr[i] > arr[j]){ swap = arr[i]; arr[i] = arr[j]; arr[j] = swap; check = 1; } if(check == 1){ res = res+1; check = 0; } } } for(i=0; i<n; i++){ printf(" arr[%d] = %d\n ", i, arr[i]); } return res; }
C
#define _BSD_SOURCE #include <pthread.h> #include <string.h> #include <unistd.h> #include "display.h" #include "racer.h" // A converter from milliseconds to microseconds #define MILLI_SEC_TO_MICRO_SEC 1000 /// global max wait time between each movement static long waitTime; /// sets the wait time each racer should make. void initRacers( long milliseconds ) { // sets the wait to the milliseconds specified waitTime = milliseconds; } /// creates a heap allocated racer with name and position. Racer *makeRacer(char *name, int position) { // the racer we will eventually return Racer * racer = NULL; // allocates a new racer racer = malloc(sizeof(Racer)); // if malloc hit an error, we report it and return null if(racer == NULL) { perror("Error allocating racer"); return NULL; } // if we make it here, malloc was successful racer->dist = 1; racer->row = position; // allocate space for the name + NUL racer->graphic = malloc(MAX_NAME_LEN + 1); // make sure the allocation succeeded if(racer->graphic == NULL) { perror("Error allocating racer name"); return NULL; } // copy in the name strcpy(racer->graphic, name); // we've finished creating the racer, we can return it now return racer; } /// destroys the heap usage of the racer. void destroyRacer(Racer *racer) { // nothing we need to do if the racer is alread null if(racer == NULL) return; // frees the graphic (since it was allocated on the heap) free(racer->graphic); racer->graphic = NULL; // free the racer itself; racer destroyed free(racer); } /// thread run function which is used to simulate the race. void *run( void *racer ) { // casts our racer to something we know Racer * rcr = (Racer *)racer; // makes a mutex which is static to all threads static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // keeps going until we're at the finish line while(rcr->dist < FINISH_LINE) { // locks the mutex so we can print ourself out pthread_mutex_lock(&mutex); // BEGIN CRITIAL REGION set_cur_pos(rcr->row, rcr->dist++); /* the space before is to remove the trailing underscore (makes sure that the only printed characters are the 9 wanted */ printf(" %s", rcr->graphic); fflush(stdout); // END CRITIAL REGION // unlocks the critical region for a racer to go in pthread_mutex_unlock(&mutex); // sleeps for a random amount of time (max wait) usleep((rand() % waitTime) * MILLI_SEC_TO_MICRO_SEC); } return NULL; }
C
/* * client.c * * Created on: Feb 25, 2012 * Author: davisl */ #include <stdio.h> #include <string.h> #include <assert.h> #include "dkp.h" const int STR_SIZE = 128; int usage(char* progName); int main(int argc, char *argv[]) { if (argc < 2) { return usage(argv[0]); } int sock = dkp_connect(argv[1]); if (sock < 0) { fprintf(stderr, "ERROR: Invalid socket received from dkp_connect().\n"); return 2; } printf("Client connected to server at %s on socket %d.\n", argv[1], sock); char *line = NULL; size_t linecap = 0; printf("Please type in text to send to server as a message (then press ENTER):\n--> "); //gets(line); ssize_t linelen = getline(&line, &linecap, stdin); if (linelen < 0) { fprintf(stderr, "getline() returned %d. Possible error?\n", (int)linelen); line = ""; linelen = 0; } printf("String: \"%s\"\n", line); printf("Calculated size of line = %d\n", (int)linelen); int error = dkp_send(sock, line, linelen); dkp_close(sock); if(error == SUCCESS) { printf("The client was successful in sending the line.\n"); return 0; } else { printf("The client FAILED in sending the line (error %d).\n", error); return 3; } } int usage(char* progName) { printf("usage: %s <IP.address.of.client>\n", progName); return 1; }
C
#include <stdio.h> int main() { int n; scanf("%d",&n); int a[n],nodd=0,neven=0; for(int i=0;i<n;i++){ scanf("%d",&a[i]); if(a[i]%2==0)neven++; else nodd++; } neven+=nodd/2; nodd=nodd%2; while(neven>1){ neven=(neven+1)/2; } if(nodd+neven==1)printf("YES"); else printf("NO"); return 0; } ./Main.c: In function main: ./Main.c:6:5: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&n); ^ ./Main.c:9:9: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%d",&a[i]); ^
C
#include<stdio.h> #include<conio.h> int lcstr(char *,char*,int,int); int max(int a,int b); int max(int a,int b){ return ((a > b) ? a : b);} void main () { char str1[20],str2[20]; int len1,len2,cl; printf("Enter str1:" ); gets(str1); printf("Enter str1:" ); gets(str2); len1 = strlen(str1); len2 = strlen(str2); cl=lcstr(str1,str2,len1,len2); printf("common string lenght = %d\n",cl); } int lcstr(char *x,char *y,int m,int n){ // create a 2d array to store the matching char int cl[m+1][n+1],result=0,i,j; for(i=0;i<=m;i++){ for(j=0;j<=n;j++){ if(i==0 || j==0) { cl[i][j] = 0; } else if(x[i-1] == y[j-1]){ cl[i][j] = cl[i-1][j-1] + 1; // if previous is match then increment result = max(result,cl[i][j]); } else cl[i][j]=0; } } printf("\n\n"); for(i=0;i<=m;i++){ for(j=0;j<=n;j++){ printf("%d\t",cl[i][j]); } printf("\n"); } return result; }
C
/* ** EPITECH PROJECT, 2017 ** test_main.c ** File description: ** A main test file */ #include <criterion/criterion.h> const char *str = "Hello world"; const int len = 11; Test(utils, returns_a_float) { cr_assert(my_float(6625), 66.25); } Test(utils, returns_a_floatV2) { cr_assert_eq(98775, 98.775); } Test(utils, is_str_length_equal_to_len_v3) { cr_assert_not(my_float(0), 0); }
C
#include <stdio.h> int CheckPalindrome(char * str, int len) { int i; for(i=0; i<len/2; i++) { if(str[i]!=str[len-(i+1)]) { return 0; } } return 1; } int main(void) { char str[50]; int strLen=0; printf("문자열 입력: "); scanf("%s", str); while(str[strLen]!='\0') strLen++; if(CheckPalindrome(str, strLen)) printf("회문입니다. \n"); else printf("회문이 아닙니다 \n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <signal.h> void ignore(int signum) { printf("ignore signal %d\n", signum); } int main() { if (signal(SIGABRT, ignore) == SIG_ERR) { printf("cannot catch signal %d\n", SIGABRT); return 1; } abort(); printf("after abort\n"); }
C
/* * clTable.h * * Representation of Cluster Neighbour Table. */ #ifndef CLTABLE_H_ #define CLTABLE_H_ // Data types for a Cluster Neighbour Table typedef enum{RELAX, ACTIVE, DEAD} State_t; struct CTableEntry { Node *node_; // Address of node double distance_to_me_; double distance_to_BS_; // Energy can be extracted from 'node' State_t currentState_; Node *assistantNode_; }; struct CTable { CTable() { entryCounter_ = maxEntries_ = 0; } CTable(int entries); int entryCounter_, maxEntries_; CTableEntry **entry_; void addEntry(CTableEntry*); void sortByBSDistance(); CTableEntry* maxEnergyEntry(); }; #endif
C
#include<stdio.h> #define MOD 1000000007 long long mod(long long a1, long long b1) { return (a1%b1+b1)%b1; } long long expo(long long base, long long exp) { long long res=1; while(exp>0) { if(exp%2==1) res=(res*base)%MOD; base=(base*base)%MOD; exp/=2; } return res%MOD; } int main() { long long n,m,q; int t,k; scanf("%d",&t); while(t--) { scanf("%lld%lld%lld%d",&n,&m,&q,&k); long long a=q-1,b=q+1,c=q,ans=0; if(q>=m || (n==1 && q!=0)) printf("0\n"); else { a=expo(a,n); b=expo(b,n); c=expo(c,n); /*ans=(a+b)%MOD; ans=mod((ans-2*c),1000000007);*/ ans=(a+b)%MOD - (2*c)%MOD + MOD; ans=(ans*(m-q))%1000000007; printf("%lld\n",ans); } } return 0; }
C
#include"lazy.h" int step = 0; int move(char a, char b) { step++; printf("move %c to %c\n", a, b); return 0; } int hanno(int tomove,char a,char via, char b){ if(tomove==1){ move(a, b); return 0; } hanno(tomove - 1, a, b, via); move(a, b); hanno(tomove - 1, via, a, b); return 0; } int main(){ int a; GET(a); hanno(a, 'A', 'B', 'C'); CK(step); }
C
#include<stdio.h> void ft_ultimate_ft(int *********nbr); int main(void) { int x; ft_ultimate_ft(&&&&&&&&x); printf("%d", x); return 0; }
C
void taskFour(void) { char originalText[1000]; char key[26]; printf("\nPlease enter text to be decrypted:\n"); scanf (" %[^\n]%*c", originalText); printf("\nPlease enter the encryption key used in capitals:\n(E.g.: QWERTYUIOPASDFGHJKLZXCVBNM)\n"); scanf(" %[^\n]%*c", key); int stringLength = strlen(originalText); char decryptedText[stringLength]; int i; int c; for (i = 0; i < stringLength + 1; i++) { if (originalText[i] > 64 && originalText[i] < 91) { for (c = 0; c < 26; c++) { if (originalText[i] == key[c]) { decryptedText[i] = c + 65; } } } else decryptedText[i] = originalText[i]; } printf("\nDecrypted text:\n%s", decryptedText); }
C
#include "a_nm_1.h" // euler numbers of first kind // / n \ // \ m / // // alike stirling numbers, catalan numbers, binomial coefficients and other // animals of the mathematical zoo, euler numbers mean something in combinatorics: they // represent the number of permutations with exactly m ascents of a set of size n // // (1) iterative formula: // a1(n, m) = sum( (-1)^(m - i + 1) * c(n + 1, m - j + 1) * i^n | i <- [1..m + 1] ) // (2) recursive formula: // a1(n, m) = { // 0 | m > n // 1 | m == n // 1 | m=0, n=0 // (m + 1) * a(n - 1, m) + (n - m) * a(n - 1, m - 1) // } static void misc_mpz_manip_fac_ui(mpz_t src, unsigned long val, void (*manip)(mpz_t, const mpz_t, const mpz_t)) { mpz_t fac; mpz_init(fac); mpz_fac_ui(fac, val); manip(src, src, fac); mpz_clear(fac); } void calc_anm1(size_t n, size_t m, mpz_visitor visitor_func) { if(m > n) { mpz_t res; mpz_init(res); mpz_set_si(res, 0); visitor_func(&res); mpz_clear(res); return; } mpz_t euler_nm, // accumulated value cur, // current term pow_n; // i^N mpz_inits(euler_nm, cur, pow_n, NULL); mpz_set_si(pow_n, 1); mpz_set_si(euler_nm, 0); mpz_set_si(cur, (m & 1) ? 1 : -1); misc_mpz_manip_fac_ui(cur, n + 1, mpz_mul); misc_mpz_manip_fac_ui(cur, m + 1, mpz_div); misc_mpz_manip_fac_ui(cur, (n + 1) - (m + 1), mpz_div); for(size_t i = 1; i <= (m + 1); ++i) { /* (-1)^.. */ mpz_mul_si(cur, cur, -1); /* i^N */ mpz_div(cur, cur, pow_n); mpz_ui_pow_ui(pow_n, i, n); mpz_mul(cur, cur, pow_n); /* c(n, k) */ const size_t moved = (m - i + 1) + 1; mpz_mul_ui(cur, cur, moved); mpz_fdiv_q_ui(cur, cur, (n + 1) - moved + 1); /* add cur to a_n_k */ mpz_add(euler_nm, euler_nm, cur); } visitor_func(&euler_nm); mpz_clears(euler_nm, cur, pow_n, NULL); }
C
/* write_int, write_char, pointer '*', '&' test */ int main(){ int *a; int b; int bb; char *c; char d; char dd; b = 10; write_int(*a); /* 0 */ write_string("\n"); write_int(b); /* 10 */ write_string("\n"); write_int(bb); /* 0 */ write_string("\n====================\n"); a = &b; write_int(*a); /* 10 */ write_string("\n"); write_int(b); /* 10 */ write_string("\n"); write_int(bb); /* 0 */ write_string("\n====================\n"); bb = *a; write_int(*a); /* 10 */ write_string("\n"); write_int(b); /* 10 */ write_string("\n"); write_int(bb); /* 10 */ write_string("\n====================\n"); b = 5; write_int(*a); /* 5 */ write_string("\n"); write_int(b); /* 5 */ write_string("\n"); write_int(bb); /* 10 */ write_string("\n====================\n"); d = 'a'; write_char(*c); /* 0 */ write_string("\n"); write_char(d); /* a */ write_string("\n"); write_char(dd); /* 0 */ write_string("\n====================\n"); c = &d; write_char(*c); /* a */ write_string("\n"); write_char(d); /* a */ write_string("\n"); write_char(dd); /* 0 */ write_string("\n====================\n"); dd = *c; write_char(*c); /* a */ write_string("\n"); write_char(d); /* a */ write_string("\n"); write_char(dd); /* a */ write_string("\n====================\n"); d = 'b'; write_char(*c); /* b */ write_string("\n"); write_char(d); /* b */ write_string("\n"); write_char(dd); /* a */ write_string("\n"); }
C
#include "../push_swap.h" int ft_strncmp(const char *s1, const char *s2, size_t n) { unsigned long i; unsigned char *casted_s1; unsigned char *casted_s2; casted_s1 = (unsigned char *)s1; casted_s2 = (unsigned char *)s2; i = 0; if (n == 0) return (0); while (casted_s1[i] == casted_s2[i] && casted_s1[i] && casted_s2[i] && i < n) { if (i + 1 == n) return (casted_s1[i] - casted_s2[i]); if (casted_s1[i] != casted_s2[i] && casted_s1[i] && casted_s2[i]) return (casted_s1[i] - casted_s2[i]); i++; } return (casted_s1[i] - casted_s2[i]); } int ft_strlen(const char *str) { int i; i = 0; while (str[i]) i++; return (i); } int ft_isdigit(int c) { if (c >= '0' && c <= '9') return (1); return (0); } int ft_atoi(const char *str) { int return_value; int i; int sign; sign = 1; return_value = 0; i = 0; while ((str[i] == ' ') || (str[i] >= 9 && str[i] <= 13)) i++; if (str[i] == '+' || str[i] == '-') { if (str[i] == '-') sign = -sign; i++; } while (str[i] >= '0' && str[i] <= '9') { return_value = return_value * 10 + str[i] - '0'; i++; } return (return_value * sign); }
C
#include <GL/GL.h> #include <GL/GLU.h> #include <GL/glut.h> #include <Windows.h> #include <stdio.h> void DDA(int x0, int y0, int xn, int yn) { int dx = xn - x0; int dy = yn - y0; int step = max(abs(dx), abs(dy)); float x_inc = dx / (float)step; float y_inc = dy / (float)step; float x = x0; float y = y0; glBegin(GL_POINTS); for (int i = 0; i < step; ++i) { x = x + x_inc; y = y + y_inc; glVertex2f(x, y); } // glVertex2f(x,y); //Sample for ploting pixel at (x,y) glEnd(); } void DrawPattern(int x0, int y0, int x_inc, int y_inc, int count) { // Note that if x0 is 30 // And x_inc is 20 // We first Draw a Line from 30 to 50 // Then from 50 to 70 // In X Axis for (int i = 0; i < count; ++i) { DDA(x0, y0, x0 + x_inc, y0 + y_inc); x0 = x0 + x_inc; DDA(x0, y0 + y_inc, x0 + x_inc, y0); x0 = x0 + x_inc; } } void disp(void) { glClearColor(0, 0, 0, 1); glClear(GL_COLOR_BUFFER_BIT); glColor3f(1, 1, 1); // We Need to Draw A Weird Kind of Pattern. // As such let us choose a few points to draw it on // Let us draw it at (0,0) -> (30,30) -> (60, 0) -> (90, 30) -> (120, 0) // As such we first set Position at Origin // And then Add and Subtract the x_inc and y_inc DrawPattern(0, 100, 30, 30, 5); glFlush(); } // disp int main(int argv, char** argc) { glutInit(&argv, argc); glutInitWindowSize(300, 300); glutCreateWindow("window"); gluOrtho2D(0, 300, 0, 300); glutDisplayFunc(disp); glutMainLoop(); return 0; }
C
#include "sock-lib.h" #define MAXDATASIZE 4096/* mxima cantidad de bytes que puede recibir en una transaccin*/ int main (int argc, char * argv[]) { int sockfd; /* File Descriptor del socket por el que el servidor "escuchar" conexiones*/ char frase[255]; int sockdup; int numbytes;/*Contendr el nmero de bytes recibidos por read () */ char buf[MAXDATASIZE]; /*Para el select*/ fd_set descriptoresLectura; int maximo; if( argc < 2 ) { fprintf(stderr,"uso: %s port\n",argv [0]); exit(1); } if ((sockfd = servidor_abrirConexion ( atoi(argv[1]))) == -1) { perror ("Fall la creacin de la conexin"); exit (1); } while(1) { sockdup = servidor_aceptarPedidos (sockfd); FD_ZERO (&descriptoresLectura); FD_SET (sockdup, &descriptoresLectura); FD_SET (fileno(stdin), &descriptoresLectura); if( fileno(stdin) < sockdup ) maximo = sockdup; else maximo = fileno(stdin); while( strcmp(frase, "fin\n") ) { select (maximo+1, &descriptoresLectura, NULL, NULL, NULL); if (FD_ISSET (sockdup, &descriptoresLectura)) { /* Recibimos los datos del servidor */ if ((numbytes = read (sockdup, buf, MAXDATASIZE)) <= 0) { perror("error de lectura en el socket"); exit(1); } /* Visualizamos lo recibido */ buf[numbytes] = '\0'; printf("Recibido: %s",buf); strcpy(frase, buf); } else if (FD_ISSET ( fileno(stdin) , &descriptoresLectura)) { /* Recibimos los datos del servidor */ fgets(frase, 255, stdin); /* Visualizamos lo recibido */ if (write (sockdup, frase , sizeof (frase)) == -1) { perror("Error escribiendo mensaje en socket"); exit (1); } printf("Enviado: %s",frase); } FD_ZERO (&descriptoresLectura); FD_SET (sockdup, &descriptoresLectura); FD_SET (fileno(stdin), &descriptoresLectura); } close(sockdup); strcpy(frase, ""); } exit(0); }