language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> int fib(int n) { if(n==1||n==2) return 1; return(fib(n-1)+fib(n-2)); } main() { int n,x,i; printf("enter nth no. of fibonacci"); scanf("%d",&n); printf("%d",fib(n)); printf("\nenter no. to print fibonacci"); scanf("%d",&x); for(i=1;i<=x;i++) { printf(" %d ",fib(i)); } }
C
/* acc.c Purpose: An integer accumulation and calculation program. Allows for the user to enter any integer in binary, octal, hexadecimal, or decimal mode, and have that integer displayed in binary, octal, hex, and decimal bases. Also allows simple bit-level calculations including negation, bitwise boolean operations, and addition. @author Jeremy Elkayam */ #include <stdio.h> #include <string.h> /* The below include statement is commented out because the assignment required students to only use the stdio.h and string.h built-in libraries. On the William & Mary CS department's lab machines, tolower is a member of string.h and not ctype.h. If you get errors or warnings when trying to compile, just un-comment the line below and it should work. */ //#include <ctype.h> //read in numeric value in mode, return value short get_operand(char mode); //print out accumulator values void print_acc(short acc); //print menu and get option char print_menu(void); // convert bin str to short; return value unsigned short get_binary_op (char *bin); // convert acc to binary str for output void convert_to_binary (short acc, char *bin); // call get_operand to get val in mode to add to accum; detect pos/neg overflow void add (short *acc, char mode); // similar to add, but subtract void subtract (short *acc, char mode); //minimum and maximum short const short MIN_SHORT=-32768; const short MAX_SHORT=32767; //main menu loop; execute option or call appropriate function int main(void) { //mode defaults to decimal and accumulator to 0 char mode='d'; short stored_value=0; char result; do{ print_acc(stored_value); result=print_menu(); switch(result) { case 'b': mode=result; printf("Mode is Binary\n"); break; case 'd': mode=result; printf("Mode is Decimal\n"); break; case 'h': mode='x'; printf("Mode is Hexadecimal\n"); break; case 'o': mode=result; printf("Mode is Octal\n"); break; case 'c': stored_value=0; break; case 'n': //just use built-in negation as the machine does two's complement for us stored_value=-stored_value; break; case '~': //once again, C has built-in bitwise negation so no need to do anything //fiddly stored_value=~stored_value; break; case '<': printf("Enter number of positions to left shift accumulator: "); //built-in left shift stored_value = stored_value << get_operand('d'); break; case '>': printf("Enter number of positions to right shift accumulator: "); //built-in right shift stored_value = stored_value >> get_operand('d'); break; case '&': switch(mode) { case 'b': printf("Enter binary value: "); break; case 'd': printf("Enter decimal value: "); break; case 'o': printf("Enter octal value: "); break; case 'x': printf("Enter hex value: "); break; } //just use the built-in bitwise and for the current value and the //entered value stored_value = stored_value & get_operand(mode); break; case '|': switch(mode) { case 'b': printf("Enter binary value: "); break; case 'd': printf("Enter decimal value: "); break; case 'o': printf("Enter octal value: "); break; case 'x': printf("Enter hex value: "); break; } //this assignment was much easier for me than the first one, since you //mostly just need to use a bunch of built-in operators, as seen below. stored_value = stored_value | get_operand(mode); break; case '^': switch(mode) { case 'b': printf("Enter binary value: "); break; case 'd': printf("Enter decimal value: "); break; case 'o': printf("Enter octal value: "); break; case 'x': printf("Enter hex value: "); break; } //bitwise xor stored_value = stored_value ^ get_operand(mode); break; case '+': switch(mode) { case 'b': printf("Enter binary value: "); break; case 'd': printf("Enter decimal value: "); break; case 'o': printf("Enter octal value: "); break; case 'x': printf("Enter hex value: "); break; } //call appropriate function add(&stored_value,mode); break; case '-': switch(mode) { case 'b': printf("Enter binary value: "); break; case 'd': printf("Enter decimal value: "); break; case 'o': printf("Enter octal value: "); break; case 'x': printf("Enter hex value: "); break; } //call appropriate function subtract(&stored_value,mode); break; case 's': switch(mode) { case 'b': printf("Enter binary value: "); break; case 'd': printf("Enter decimal value: "); break; case 'o': printf("Enter octal value: "); break; case 'x': printf("Enter hex value: "); break; } //call appropriate function stored_value=get_operand(mode); break; } }while(result!='q'); printf("\n"); return 0; } short get_operand(char mode) { short result; char bin[200]; int count; switch(mode) { case 'b': do{ scanf("%s",bin); printf("%s\n",bin); for(count=0;bin[count]!=0;count++); if(count>16) { printf("Invalid input: %s \n",bin); printf("Input must be 16 digits or less, without spaces.\n\nEnter binary value: "); } }while(count>16); //We have a separate function for binary conversion. result=get_binary_op(bin); break; case 'x': //h to denote that this value is a short; x for hexadecimal scanf("%hx",&result); printf("%hX\n",result); break; case 'd': //h -> short, d -> decimal scanf("%hd",&result); printf("%hd\n",result); break; case 'o': //o -> octal, h -> short scanf("%ho",&result); printf("%ho\n",result); break; } return result; } void print_acc(short acc) { int decimal_digits=snprintf(NULL, 0, "%d", acc) - (acc < 0); int octal_digits=snprintf(NULL, 0, "%o", acc) - (acc < 0); int hex_digits=snprintf(NULL, 0, "%x", acc) - (acc < 0); printf("\n**************************************\n"); printf("* Accumulator: *\n"); char bin_str[20]; convert_to_binary(acc,bin_str); printf("* Binary : %s *\n",bin_str); printf("* Hex : "); int z=0; //count the 0's you add until it's correct padding for all of these for(z=0;z<4-hex_digits;z++) { printf("0"); } printf("%hX",acc); for(z=0;z<18;z++) { printf(" "); } printf("*\n* Octal : "); for(z=0;z<6-octal_digits;z++) { printf("0"); } printf("%ho",acc); for(z=0;z<16;z++) { printf(" "); } printf("*\n* Decimal : %d",acc); for(z=0;z<22-decimal_digits-(acc<0);z++) { printf(" "); } printf("*\n**************************************\n"); } char print_menu(void) { printf("\nPlease select one of the following options: \n\n"); printf("B Binary Mode & AND with Accumulator + Add to Accumulator\n"); printf("O Octal Mode | OR with Accumulator - Subtract from Accumulator\n"); printf("H Hexadecimal Mode ^ XOR with Accumulator N Negate Accumulator\n"); printf("D Decimal Mode ~ Complement Accumulator\n\n"); printf("C Clear Accumulator < Shift Accumulator Left\n"); printf("S Set Accumulator > Shift Accumulator Right\n\n"); printf("Q Quit \n\n"); printf("Option: "); char output[110]; scanf("%s",output); printf("%s\n",output); char lower_output=tolower(output[0]); //the correct options while(strlen(output)!=1 || (lower_output!='+' && lower_output!='-' && lower_output!='^' && lower_output!='|' && lower_output!='&' && lower_output!='>' && lower_output!='<' && lower_output!='~' && lower_output!='n' && lower_output!='b' && lower_output!='o' && lower_output!='h' && lower_output!='d' && lower_output!='c' && lower_output!='s' && lower_output!='q')){ printf("\nInvalid option: %s\n",output); printf("\nPlease select one of the following options: \n\n"); printf("B Binary Mode & AND with Accumulator + Add to Accumulator\n"); printf("O Octal Mode | OR with Accumulator - Subtract from Accumulator\n"); printf("H Hexadecimal Mode ^ XOR with Accumulator N Negate Accumulator\n"); printf("D Decimal Mode ~ Complement Accumulator\n\n"); printf("C Clear Accumulator < Shift Accumulator Left\n"); printf("S Set Accumulator > Shift Accumulator Right\n\n"); printf("Q Quit \n\n"); printf("Option: "); scanf("%s",output); printf("%s\n",output); lower_output=tolower(output[0]); } return lower_output; } //TODO: implement the following unsigned short get_binary_op (char *bin) { int total=0; int dex; for(dex=0;bin[dex]!=0;dex++) { total *= 2; if(bin[dex]=='1') { total++; } } return total; } void convert_to_binary (short acc, char *bin) { //convert acc to an unsigned short unsigned short max_u_short=-1; unsigned short u_acc=acc+max_u_short+1; short rem; int dex; for(dex=18;dex>=0;dex--) { if(dex==4 || dex==9 || dex==14) { //account for proper spacing between groups of 4 digits bin[dex]=' '; } else { rem=u_acc%2; u_acc=u_acc/2; //remainder will be 0 or 1, so advancing 1 in the ascii table gets us //the digit 1 bin[dex]=rem+'0'; } } bin[19]=0; } void add (short *acc, char mode) { short part=get_operand(mode); if(part > 0)//adding a positive { if(part > MAX_SHORT - *acc) { printf("Overflow Error\n"); } } else if(part < 0)//adding a negative { if(part < MIN_SHORT - *acc) { printf("Negative Overflow Error\n"); } } *acc+=part; } void subtract (short *acc, char mode) { short part=get_operand(mode); if(part > 0) // subtract a positive { if(*acc < MIN_SHORT + part ) { printf("Negative Overflow Error\n"); } } else if(part < 0)// subtract a negative { if(*acc > MAX_SHORT + part ) { printf("Overflow Error\n"); } } *acc-=part; }
C
/*====================================================================================================*/ /*====================================================================================================*/ #include "drivers\stm32f3_system.h" #include "modules\module_serial.h" #include "main.h" /*====================================================================================================*/ /*====================================================================================================*/ void System_Init( void ) { HAL_Init(); GPIO_Config(); Serial_Config(); delay_ms(100); printf("\fHello World!\r\n\r\n"); } int main( void ) { static uint8_t i = 0; static uint8_t recvData = 0; static int8_t state = ERROR; System_Init(); while(1) { LED_Toggle(); state = Serial_RecvDataWTO(&recvData, 1, 500); if(state == ERROR) { printf("timeout ... %d\r\n", i); i = (i == 255) ? 0 : i + 1; } else if(recvData == 0x0D) // if press enter Serial_SendStr("\r\n"); else Serial_SendData(&recvData, 1); } } /*====================================================================================================*/ /*====================================================================================================*/
C
// Maciej Poleski #ifndef DEBUG #ifndef NDEBUG #define NDEBUG #endif #define init(x,y) #define end() #define check(x) #else #include <stdio.h> #include <stdlib.h> void init(int argc,char**argv) { if(argc!=3) { fprintf(stderr,"Potrzebne są dwa argumenty <wejście> <wyjście>\n"); exit(1); } freopen(argv[1],"r",stdin); freopen(argv[2],"w",stdout); } void end(void) { } #define check(x) assert(x) #endif #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <stdbool.h> #include <limits.h> #include <string.h> #include <ctype.h> #include <assert.h> #include <time.h> #include <stdarg.h> #include <math.h> typedef struct { int left,right; long long value; } Node; Node *tree; void nadsumuj(int v, long long value) { if(v==0) return; tree[v].value+=value; nadsumuj(tree[v].left,tree[v].value); nadsumuj(tree[v].right,tree[v].value); } long long podsumuj(int v) { if(v==0) return 0LL; return tree[v].value+=podsumuj(tree[v].left)+podsumuj(tree[v].right); } void preorder(int v) { if(v==0) return; printf("%lld ",tree[v].value); preorder(tree[v].left); preorder(tree[v].right); } void inorder(int v) { if(v==0) return; inorder(tree[v].left); printf("%lld ",tree[v].value); inorder(tree[v].right); } void postorder(int v) { if(v==0) return; postorder(tree[v].left); postorder(tree[v].right); printf("%lld ",tree[v].value); } void bfs(int v) { int *queue=malloc(sizeof(int)*2000000); int *begin=queue; int *end=queue; *end++=v; while(begin!=end) { v=*begin++; printf("%lld ",tree[v].value); if(tree[v].left!=0) *end++=tree[v].left; if(tree[v].right!=0) *end++=tree[v].right; } printf("\n"); free(queue); } #ifdef DEBUG #else #endif inline void solution(void) { tree=malloc(sizeof(Node)*2000000); int z; scanf("%d",&z); while(z--) { int n; scanf("%d",&n); int i; for(i=1;i<=n;++i) { int l,r; long long v; scanf("%lld%d%d",&v,&l,&r); tree[i].value=v; tree[i].left=l; tree[i].right=r; } char first[10]; char second[10]; scanf("%s%s",first,second); if(*first=='N') { check(strcmp(first,"NADSUMUJ")==0); nadsumuj(1,0LL); } else { check(strcmp(first,"PODSUMUJ")==0); podsumuj(1); } switch(second[1]) { case 'R': check(strcmp(second,"PREORDER")==0); preorder(1); printf("\n"); break; case 'N': check(strcmp(second,"INORDER")==0); inorder(1); printf("\n"); break; case 'O': check(strcmp(second,"POSTORDER")==0); postorder(1); printf("\n"); break; default: check(strcmp(second,"BFS")==0); bfs(1); break; } } } #ifdef DEBUG inline void checkAll(void) { } #endif // DEBUG int main(int argc,char**argv) { #ifdef DEBUG init(argc,argv); checkAll(); #endif // DEBUG solution(); #ifdef DEBUG end(); #endif // DEBUG return 0; }
C
/* - Questão 3.20 - */ /* diretivas ao pré-processador */ #include <stdio.h> /* necessária para as funções printf e scanf */ # include <stdlib.h> /* necessária para a função system */ /* início da função main (execução principal do programa) */ int main( void ) { /* declaração das variáveis do tipo ponto flutuante */ float juros, principal, taxa; /* declaração da variável do tipo inteiro */ int dias; /* muda a página de código do console para UTF-8 para fins de acentuação gráfica */ system( "chcp 65001 > NUL" ); /* valor principal do empréstimo, prompt e leitura a partir do teclado */ printf( "Informe o valor principal do empréstimo (-1 para terminar): " ); scanf( "%f", &principal ); while( principal != -1 ) /* enquanto o valor principal do empréstimo for diferente de -1 */ { /* início da estrutura de controle de repetição while */ /* taxa de juros anual, prompt e leitura a partir do teclado */ printf( "Informe a taxa de juros: " ); scanf( "%f", &taxa ); /* prazo do empréstimo em dias, prompt e leitura a partir do teclado */ printf( "Informe o prazo do empréstimo em dias: " ); scanf( "%d", &dias ); /* calcula os juros simples do empréstimo */ juros = principal * taxa * (float) dias / 365; /* apresenta o resultado de cálculo */ printf( "O valor dos juros é de R$%.2f\n\n", juros ); /* próximo valor principal do empréstimo, prompt e leitura a partir do teclado */ printf( "Informe o valor principal do empréstimo (-1 para terminar): " ); scanf( "%f", &principal ); } /* fim da estrutura de controle de repetição while */ /* pausa a execução do programa possibilitando a visualização dos resultados no modo de execução standalone */ system( "pause" ); /* informa ao sistema operacional que o programa foi executado completamente ou seja nenhum erro fatal ocorreu */ return 0; } /* fim da função main */
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> void *tfn1(void *arg) { printf("the thread\n"); sleep(3); printf("the thread done\n"); return NULL; } int main(void) { int err; pthread_t tid; err=pthread_create(&tid,NULL,tfn1,NULL); if(err!=0) { printf("can't create thread %d\n",strerror(err)); exit(1); } err=pthread_detach(tid); if(err!=0) { printf("can't detach thread %d\n",strerror(err)); exit(1); } err=pthread_join(tid,NULL); if(err!=0) printf("thread has been detached\n"); sleep(5); printf("the main thread done\n"); return 0; }
C
#include "holberton.h" #include <stdlib.h> /** *string_nconcat - Concatenate two strings * * */ char *string_nconcat(char *s1, char *s2, unsigned int n) { char *p; unsigned int i, j, counter = 0; if (s1 == '\0') { s1 = ""; } if (s2 == '\0') { s2 = ""; } for (i = 0; s1[i]; i++) { } for (j = 0; s2[j]; j++) { } if (n >= j) { counter = i + j + 1; { else { counter = i + n + 1; } p = malloc(sizeof(char) * counter); if (p == '\0') { return (NULL); } for (i = 0; s1[i]; i++) { p[i] = s1[i]; } if (n >= j) { for (j = 0; s2[j]; j++) { p[i + j] = s2[j] } } else { for (j = 0; s2[j]; j++) { p[i + j] = s2[j]; } } p[i + j] = '\0'; return (p); }
C
// HTTP GET request handlers typedef struct { char *fileName; void (*fn)(void); } getRequestType; // HTTP parameter setting handlers typedef struct { char *paramName; void (*fn)(char *); } httpParamType; // CLI command typedef struct { char *cmdName; void (*fn)(void); } cmdType; // Somewhere to store the time and date typedef struct { int tm_sec; int tm_min; int tm_hour; int tm_mday; int tm_mon; int tm_year; int tm_wday; int tm_yday; int tm_isdst; } timeNow_t; // Configuration data typedef struct { char ssid[40]; char password[70]; char ntpServer[32]; unsigned long int eepromValid; } eepromData; // State machine states typedef enum clockState_e { STATE_INIT, STATE_CONNECTING, STATE_CONNECTED, STATE_TIMING, STATE_STOPPED } clockStateType; // LED display typedef struct { int colSelectPins[MAX_COLS]; int colDataSize[MAX_COLS]; int rowDataPins[MAX_ROWS]; int data[MAX_COLS]; int colSelect; } ledDisplay_t;
C
#include <fcntl.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include "holberton.h" /** *read_textfile - 0 *@filename: filename *@letters: number of letters *Return: ssize_t */ ssize_t read_textfile(const char *filename, size_t letters) { char *c; int file, b; unsigned long int a; if (!filename) { return (0); } c = malloc(sizeof(char) * letters); if (!c) { return (0); } file = open(filename, O_RDONLY); if (file == -1) { return (0); } a = read(file, c, letters); b = write(STDOUT_FILENO, c, a); if (b == -1) { return (0); } close(file); return (a); }
C
/* : osccal.c * : Christian Starkjohann * : microsin.ru * : 2008-04-10 * : 4 * Copyright: (c) 2008 by OBJECTIVE DEVELOPMENT Software GmbH * : GNU GPL v2 (. License.txt) (CommercialLicense.txt) * : $Id: osccal.c 553 2008-04-17 19:00:20Z cs $ */ #include <avr/io.h> /* ------------------------------------------------------------------------- */ /* -------------------- -------------------- */ /* ------------------------------------------------------------------------- */ /* RC-. - * SOF, Start Of Frame ( SE0), * USB RESET. * OSCCAL, . * RC- * 12 MHz ( , * AVR), OSCCAL * 12 ! RC-, 12 * ! */ void calibrateOscillator(void) { uchar step = 128; uchar trialValue = 0, optimumValue; int x, optimumDev, targetValue = (unsigned)(1499 * (double)F_CPU / 10.5e6 + 0.5); /* : */ do{ OSCCAL = trialValue + step; x = usbMeasureFrameLength(); /* */ if(x < targetValue) /* */ trialValue += step; step >>= 1; }while(step > 0); /* +/- 1 OSCCAL */ /* */ optimumValue = trialValue; optimumDev = x; /* */ for(OSCCAL = trialValue - 1; OSCCAL <= trialValue + 1; OSCCAL++){ x = usbMeasureFrameLength() - targetValue; if(x < 0) x = -x; if(x < optimumDev){ optimumDev = x; optimumValue = OSCCAL; } } OSCCAL = optimumValue; } /* : OSCCAL 192, 192. , CPU ! , , , CPU. RC- 5.x ( 2x128 , ATTiny25, ATTiny45, ATTiny85), . */
C
//Most functions taken from Neill_sdl.c, these have Neill in the function name, added draw_turtle here to avoid having SDL in my main parser.c function. #include "ashley_sdl.h" void Neill_SDL_Init(SDL_Simplewin *sw) { if (SDL_Init(SDL_INIT_VIDEO) != 0) { fprintf(stderr, "\nUnable to initialize SDL: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } sw->finished = 0; sw->win= SDL_CreateWindow("Turtle", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN); if(sw->win == NULL){ fprintf(stderr, "\nUnable to initialize SDL Window: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } sw->renderer = SDL_CreateRenderer(sw->win, -1, 0); if(sw->renderer == NULL){ fprintf(stderr, "\nUnable to initialize SDL Renderer: %s\n", SDL_GetError()); SDL_Quit(); exit(1); } // Set screen to black Neill_SDL_SetDrawColour(sw, 0, 0, 0); SDL_RenderClear(sw->renderer); SDL_RenderPresent(sw->renderer); } void Neill_SDL_RenderDrawCircle(SDL_Renderer *rend, int cx, int cy, int r) { double dx, dy; dx = floor(sqrt((2.0 * r ) )); SDL_RenderDrawLine(rend, cx-dx, cy+r, cx+dx, cy+r); SDL_RenderDrawLine(rend, cx-dx, cy-r, cx+dx, cy-r); for (dy = 1; dy <= r; dy += 1.0) { dx = floor(sqrt((2.0 * r * dy) - (dy * dy))); SDL_RenderDrawPoint(rend, cx+dx, cy+r-dy); SDL_RenderDrawPoint(rend, cx+dx, cy-r+dy); SDL_RenderDrawPoint(rend, cx-dx, cy+r-dy); SDL_RenderDrawPoint(rend, cx-dx, cy-r+dy); } } void draw_turtle(Prog *program){ SDL_Simplewin sw; double startx, starty, endx, endy; Neill_SDL_Init(&sw); program->coordinate = &program->start_coordinate; do{ //Checks the program still contains instruction to draw, otherwise the loop waits for the user to stop it. if(program->coordinate->next != NULL){ startx = program->coordinate->current_x; starty = program->coordinate->current_y; Neill_SDL_SetDrawColour(&sw, program->coordinate->red, program->coordinate->green, program->coordinate->blue); program->coordinate = program->coordinate->next; endx = program->coordinate->current_x; endy = program->coordinate->current_y; SDL_RenderDrawLine(sw.renderer, startx, starty, endx, endy); SDL_Delay(MILLISECONDDELAY); // Update window - no graphics appear on some devices until this is finished SDL_RenderPresent(sw.renderer); SDL_UpdateWindowSurface(sw.win); } // Has anyone pressed ESC or killed the SDL window ? // Must be called frequently - it's the only way of escaping Neill_SDL_Events(&sw); }while(!sw.finished); } // Gobble all events & ignore most void Neill_SDL_Events(SDL_Simplewin *sw) { SDL_Event event; while(SDL_PollEvent(&event)) { switch (event.type){ case SDL_QUIT: case SDL_MOUSEBUTTONDOWN: case SDL_KEYDOWN: sw->finished = 1; } } } // Trivial wrapper to avoid complexities of renderer & alpha channels void Neill_SDL_SetDrawColour(SDL_Simplewin *sw, Uint8 r, Uint8 g, Uint8 b) { SDL_SetRenderDrawColor(sw->renderer, r, g, b, SDL_ALPHA_OPAQUE); }
C
#include <stdio.h> void squeeze(char *s1, char *s2) { char *temp = s1; //用于存储每次修改的值 char *newstr = temp; //用于初始化修改后的值 while ('\0' != *s2){ s1 = newstr; temp = newstr; while ('\0' != *s1){ if (*s1 != *s2){ *temp++ = *s1; } s1++; } *temp = '\0'; s2++; } } int main(void) { char s1[] = "hello world i love this world"; char s2[] = "els"; squeeze( s1, s2 ); printf("%s\n", s1 ); return 0; }
C
// error.c // Řešení IJC-DU1, příklad b), 25.3.2015 // Autor: Radovan Sroka, FIT // Přeloženo: gcc 4.9.2 20150204 #include "error.h" #include <stdio.h> #include <stdarg.h> #include <string.h> #include <stdlib.h> const int max_lenght_of_message = 500; void FatalError(const char *fmt, ...){ va_list arguments; va_start (arguments, fmt); char error[500] = "CHYBA: "; strncat(error, fmt, max_lenght_of_message - strlen(error)); vfprintf(stderr, error , arguments); va_end(arguments); exit(1); } int FatalError_i(const char *fmt, ...){ va_list arguments; va_start (arguments, fmt); FatalError(fmt, arguments); va_end(arguments); return 1; } void Warning(const char *fmt, ...){ va_list arguments; va_start (arguments, fmt); char error[500] = "CHYBA: "; strncat(error, fmt, max_lenght_of_message - strlen(error)); vfprintf(stderr, error , arguments); va_end(arguments); }
C
/* * @Author: zero * @Date: 2021-07-14 08:29:21 * @Description: Evaluate the value of an arithmetic expression in Reverse Polish Notation. * Valid operators are +, -, *, and /. * Each operand may be an integer or another expression. * Division between two integers should truncate toward zero. */ #include <string.h> #include <stdio.h> int evaluate(int a, int b, char c) { if (c == '+') return a + b; if (c == '-') return a - b; if (c == '*') return a * b; if (c == '/') return a / b; return 0; } int stringToInt(char *s) { if (s[0] == '-') return 0 - stringToInt(++s); int value = 0; while (*s != '\0') { value *= 10; value += *s - '0'; s++; } return value; } int evalRPN(char **tokens, int tokensSize) { int stack[tokensSize]; int top = -1; while (tokensSize) { if (**tokens < '0' && strlen(*tokens) == 1) { top -= 1; stack[top] = evaluate(stack[top], stack[top + 1], **tokens); } else stack[++top] = stringToInt(*tokens); tokens++; tokensSize--; } return stack[top]; } int main() { char *test[] = {"3","-200","+"}; printf("%d", evalRPN(test, 3)); return 0; }
C
// PROGRAMAÇÃO IMPERATIVA // 50 QUESTÕES #include <stdio.h> #include <stdlib.h> #include <string.h> // 1 int main1 () { int x; int maior = 0; scanf("%d", &x); while (x != 0) { if (x > maior) { maior = x; } scanf("%d", &x); } printf("%d\n", maior); return 0; } // 2 int main2 () { int x; int soma = 0; int i = 0; double media = 0; scanf("%d", &x); while (x != 0) { soma += x; i++; scanf("%d", &x); } media = soma / i; printf("%d\n", media); return 0; } // 3 int main3 () { int x; int maior1 = 0; int maior2 = 0; scanf("%d", &x); while (x != 0) { if (x > maior1 && x > maior2) { maior2 = maior1; maior1 = x; } if (x < maior1 && x > maior2) { maior2 = x; } scanf("%d", &x); } printf("%d\n", maior2); return 0; } // 4 int bitsUm (unsigned int n) { int r = 0; while (n != 0) { if (n % 2 == 0) { n /= 2; } else { n /= 2; r++; } } return r; } // 5 int trailingZ (unsigned int n) { int r = 0; while (n != 0) { if (n % 2 == 0) { n /= 2; r++; } else { break; } } return r; } // 6 int qDig (unsigned int n) { int r = 0; while (n != 0) { n /= 10; r++; } return r; } // 7 int len (char *s) { int i; for (i = 0; s[i] != '\0'; i++); return i; } char *mystrcat (char s1[], char s2[]) { int i; int s1len = len(s1); for (i = 0; s2[i] != '\0'; i++, s1len++) { s1[s1len] = s2[i]; } s1[s1len] = '\0'; return s1; } // 8 char *mystrcpy (char *dest, char source[]) { int i; for (i = 0; source[i] != '\0'; i++) { dest[i] = source[i]; } dest[i] = '\0'; return dest; } // 9 int mystrcmp(char s1[], char s2[]) { int i = 0; while ((s1[i] == s2[i]) && (s1[i] != '\0')) i++; return (s1[i] - s2[i]); } // 10 char *mystrstr (char s1[], char s2[]) { int i; int j = 0; int pos = 0; if (s2[0] == '\0') return s1; for (i = 0; s1[i] != '\0'; i++) { if (s1[i] == s2[0]) pos = i; if (s1[i] == s2[j]) j++; if (s2[j] == '\0') return (s1 + pos); } return NULL; } // 11 int len (char *s) { int i; for (i = 0; s[i] != '\0'; i++); return i; } char *mystrcpy (char *dest, char source[]) { int i; for (i = 0; source[i] != '\0'; i++) { dest[i] = source[i]; } dest[i] = '\0'; } void strrev (char s[]) { int i; int slen = len(s); int stop = slen; char copy[slen]; mystrcpy(copy,s); slen--; for (i = 0; i < stop; i++, slen--) { s[i] = copy[slen]; } s[i] = '\0'; } // 12 void strnoV (char s[]) { int i; int j = 0; for (i = 0; s[i] != '\0'; i++) { if (s[i] != 'a' && s[i] != 'e' && s[i] != 'i' && s[i] != 'o' && s[i] != 'u' && s[i] != 'A' && s[i] != 'E' && s[i] != 'I' && s[i] != 'O' && s[i] != 'U') { s[j] = s[i]; j++; } } s[j] = '\0'; } // 13 void truncW (char t[], int n) { int i, j = 0, repetir = n,p; for (i = 0; t[i] != '\0'; i++) { if (t[i] == ' ') { repetir = n; t[j] = ' '; j++; } else { p = i; while (repetir > 0 && t[p] != ' ') { t[j] = t[p]; p++; j++; if (t[p] != ' ') i++; repetir -= 1; } } } t[j] = '\0'; } // 14 char charMaisfreq (char s[]) { int i; int j; int count = 0; int max = 0; char c; for (i = 0; s[i] != '\0'; i++) { for (j = 0; s[j] != '\0'; j++) { if (s[i] == s[j]) count++; if (count > max) { max = count; c = s[i]; } } count = 0; } return c; } // 15 int iguaisConsecutivos (char s[]) { int i; int count = 1; int max = 0; for (i = 0; s[i] != '\0'; i++) { if (s[i] == s[i+1]) count++; else { if (count > max) max = count; count = 1; } } return max; } // 16 int diferente (char s[], int i, int j) { while (i < j) { if (s[i] == s[j]) return 0; i++; } return 1; } int difConsecutivos (char s[]) { int i; int j; int count = 0; int max = 0; for (i = 0; s[i] != '\0'; i++) { count = 0; for (j = i; s[j] != '\0' && diferente(s, i, j); j++) { count++; } if (count > max) { max = count; } } return max; } // 17 int maiorPrefixo (char s1 [], char s2 []) { int i, pref = 0; for (i = 0; s1[i] == s2[i]; i++) pref++; return pref; } // 18 int len (char *s) { int i; for (i = 0; s[i] != '\0'; i++); return i; } int maiorSufixo (char s1 [], char s2 []) { int i = len(s1) - 1; int j = len(s2) - 1; int suf = 0; for ( ; s1[i] == s2[j]; i--, j--) suf++; return suf; } // 19 int sufPref (char s1[], char s2[]) { int i, j = 0; for (i = 0; s1[i] != '\0'; i++) { if (s1[i] == s2[j]) j++; else j = 0; } return j; } // 20 int contaPal (char s[]) { int i, pal = 0; for (i = 0; s[i] != '\0'; i++) { if ((!(isspace(s[i]))) && ((isspace(s[i+1])) || (s[i+1] == '\0'))) pal++; } return pal; } // 21 int contaVogais (char s[]) { int i, vogais = 0; for (i = 0; s[i] != '\0'; i++) { if (s[i] == 'a' || s[i] == 'e' || s[i] == 'i' || s[i] == 'o' || s[i] == 'u' || s[i] == 'A' || s[i] == 'E' || s[i] == 'I' || s[i] == 'O' || s[i] == 'U') vogais++; } return vogais; } // 22 int charContido (char a, char b[]) { int i; for (i = 0; b[i] != '\0'; i++) { if (b[i] == a) return 1; } return 0; } int contida (char a[], char b[]) { int i; for (i = 0; a[i] != '\0'; i++) { if (charContido(a[i],b) == 0) return 0; } return 1; } // 23 int len (char *s) { int i; for (i = 0; s[i] != '\0'; i++); return i; } int palindroma (char s[]) { int i = 0; int j = len(s) - 1; for ( ; s[i] != '\0'; i++, j--) { if (s[i] != s[j]) return 0; } return 1; } // 24 int remRep (char x[]) { int i, j = 0; for (i = 0; x[i] != '\0'; i++) { if (x[i] != x[i+1]) { x[j] = x[i]; j++; } } x[j] = '\0'; return j; } // 25 int limpaEspacos (char t[]) { int i, j = 0; for (i = 0; t[i] != '\0'; i++) { if (t[i] == ' ' && t[i+1] == ' '); else { t[j] = t[i]; j++; } } t[j] = '\0'; return j; } // 26 void insere (int v[], int N, int x) { int i, j; for (i = 0; i < N && v[i] < x; i++); for (j = N; j != i; j--) { v[j] = v[j-1]; } v[i] = x; } // 27 void merge (int r [], int a[], int b[], int na, int nb) { int i, aCount, bCount; for (i = 0, aCount = 0, bCount = 0; i < na + nb; i++) { if (na == aCount) { r[i] = b[bCount]; bCount++; } else if (nb == bCount) { r[i] = a[aCount]; aCount++; } else { if (a[aCount] < b[bCount]) { r[i] = a[aCount]; aCount++; } else { r[i] = b[bCount]; bCount++; } } } } // 28 int crescente (int a[], int i, int j) { int n; for (n = i; n < j; n++) { if (a[n] > a[n+1]) return 0; } return 1; } // 29 int retiraNeg (int v[], int N) { int i, j = 0; for (i = 0; i < N; i++) { if (v[i] >= 0) { v[j++] = v[i]; } } return j; } // 30 int menosFreq (int v[], int N) { int i, count = 1, min = N, mf = v[0]; for (i = 0; i < N; i++) { if (v[i] == v[i+1]) { count++; } else { if (count < min) { min = count; mf = v[i]; } count = 1; } } return mf; } // 31 int maisFreq (int v[], int N) { int i, count = 1, max = 0, mf = v[0]; for (i = 0; i < N; i++) { if (v[i] == v[i+1]) { count++; } else { if (count > max) { max = count; mf = v[i]; } count = 1; } } return mf; } // 32 int maxCresc (int v[], int N) { int i, count = 1, max = 0; for (i = 0; i < N; i++) { if (v[i] <= v[i+1]) { count++; } else { if (count > max) { max = count; } count = 1; } } return max; } // 33 int temRep (int v[], int N, int x) { int i; for (i = 0; i < N; i++) { if (v[i] == x) return 1; } return 0; } int elimRep (int v[], int N) { int i, j; for (i = 0; i < N; i++) { if (temRep(v,i,v[i])) { for (j = i; j < N; j++) { v[j] = v[j+1]; } N--; i--; } } return N; } // 34 int elimRepOrd (int v[], int N) { int i, j = 0; for (i = 0; i < N; i++) { if (v[i] != v[j]) { j++; v[j] = v[i]; } } return j+1; } // 35 int comunsOrd (int a[], int na, int b[], int nb) { int i = 0, j = 0, comuns = 0; while (i < na && j < nb) { if (a[i] < b[j]) i++; else if (b[j] < a[i]) j++; else if (a[i] == b[j]) { i++; j++; comuns++; } } return comuns; } // 36 int comuns (int a[], int na, int b[], int nb) { int i, j, comuns = 0; for (i = 0; i < na; i++) { for (j = 0; j < nb; j++) { if (a[i] == b[j]) { comuns++; break; } } } return comuns; } // 37 int minInd (int v[], int N) { int i, min = v[0], p = 0; for (i = 0; i < N; i++) { if (v[i] < min) { min = v[i]; p = i; } } return p; } // 38 void somasAc (int v[], int Ac [], int N) { int i; Ac[0] = v[0]; for (i = 1; i < N; i++) { Ac[i] = Ac[i-1] + v[i]; } } // 39 int triSup (int N, int m [N][N]) { int i, j, r = 1; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { if (i > j) { if (m[i][j] != 0) r = 0; } } } return r; } // 40 void transposta (int N, float m [N][N]) { int i, j; float t[N][N]; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { t[i][j] = m[i][j]; } } for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { m[i][j] = t[j][i]; } } } // 41 void addTo (int N, int M, int a [N][M], int b[N][M]) { int i, j; for (i = 0; i < N; i++) { for (j = 0; j < M; j++) { a[i][j] += b[i][j]; } } } //42 int unionSet (int N, int v1[N], int v2[N], int r[N]) { int i; for (i = 0; i < N; i++) { if (v1[i] == 1 || v2[i] == 1) r[i] = 1; else r[i] = 0; } } // 43 int intersectSet (int N, int v1[N], int v2[N], int r[N]) { int i; for (i = 0; i < N; i++) { if (v1[i] == 1 && v2[i] == 1) r[i] = 1; else r[i] = 0; } } // 44 int intersectMSet (int N, int v1[N], int v2[N], int r[N]) { int i; for (i = 0; i < N; i++) { if (v1[i] > v2[i]) r[i] = v2[i]; else r[i] = v1[i]; } } // 45 int unionMSet (int N, int v1[N], int v2[N], int r[N]) { int i; for (i = 0; i < N; i++) { if (v1[i] > v2[i]) r[i] = v1[i]; else r[i] = v2[i]; } } // 46 int cardinalMSet (int N, int v[N]) { int i, soma = 0; for (i = 0; i < N; i++) { soma += v[i]; } return soma; } // typedef enum movimento {Norte, Oeste, Sul, Este} Movimento; typedef struct posicao { int x, y; } Posicao; // 47 Posicao posFinal (Posicao inicial, Movimento mov[], int N) { int i; for (i = 0; i < N; i++) { if (mov[i] == Norte) inicial.y++; if (mov[i] == Sul) inicial.y--; if (mov[i] == Este) inicial.x++; if (mov[i] == Oeste) inicial.x--; } return inicial; } // 48 int caminho (Posicao inicial, Posicao final, Movimento mov[], int N){ int i, r = 0; for (i = 0; (inicial.x != final.x) || (inicial.y != final.y); i++) { if (inicial.y < final.y) { mov[i] = Norte; inicial.y++; r++; } else if (inicial.y > final.y) { mov[i] = Sul; inicial.y--; r++; } else if (inicial.x < final.x) { mov[i] = Este; inicial.x++; r++; } else if (inicial.x > final.x) { mov[i] = Oeste; inicial.x--; r++; } } if (r > N) r = -1; return r; } // 49 int distancia (Posicao n) { int dis = 0; dis = abs(n.x) + abs(n.y); return dis; } int maiscentral (Posicao pos[], int N) { int i, p = 0; int min = distancia(pos[0]); for (i = 0; i < N; i++) { if (distancia(pos[i]) < min) { min = distancia(pos[i]); p = i; } } return p; } // 50 int vizinhos (Posicao p, Posicao pos[], int N) { int i, v = 0; for (i = 0; i < N; i++) { if ((p.x == pos[i].x) && (p.y == pos[i].y + 1)) v++; else if ((p.x == pos[i].x) && (p.y == pos[i].y - 1)) v++; else if ((p.y == pos[i].y) && (p.x == pos[i].x + 1)) v++; else if ((p.y == pos[i].y) && (p.x == pos[i].x - 1)) v++; } return v; }
C
/* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SINGLE-HEADER C/++ IMGUI LIBRARY ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DESCRIPTION This is a single-header library that provides the input groundwork for an immediate-mode GUI system. It has support for both mouse and keyboard controls. The library DOES NOT take care of tasks like rendering or getting input from the user (it only interprets input that you provide it). This library has no dependencies. WHAT IS IMMEDIATE MODE GUI? Immediate mode GUI is a style of GUI that does not follow the retained mode paradigm of GUI development. It is best demonstrated with an example: // retained mode example { Button button = init_button(BUTTON_ID, x, y, w, h, "Button Text"); add_button_to_gui(&button); while(1) { update_gui(); if(gui_button_clicked(BUTTON_ID)) { // the button was clicked } render_gui(); } } // immediate mode example { while(1) { ui_begin(); { if(do_button(BUTTON_ID, x, y, w, h, "Button Text")) { // if this if-block is entered, // the button was clicked. // this block also renders the // button, and if you don't want // the button anymore, just don't // call do_button, and it'll // magically disappear } } ui_end(); } } In the above example, you can see a clear centralization effort being made by the immediate-mode GUI approach. ALL code pertaining to the button, initialization, rendering, handling, etc., is in one spot. This is opposed to the retained-mode approach, where the programmer must be concerned about initialization, updating, handling, and rendering separately. As you might imagine, this makes designing UIs in code pretty trivial, as the logic code for handling UI input is identical to the code that adds/removes/renders the UI widgets. RF_UI UNIQUE FEATURES rf_ui has a few unique features that have been really useful to me in the past. They have some specific names and/or reasoning behind them, so I'll cover them here (so you know what they are). NOTE: I use "widget" and "element" interchangably, so keep that in mind! * floating-point IDs rf_ui uses floating-point (specifically double-sized) IDs for each widget. This is done for a specific reason. Usually, to avoid large enums of IDs (or the like), I #define a GEN_ID macro to generate a unique ID that uses the __LINE__ macro to be generated. This poses a problem, though, because there are times when one wants to create elements in a loop, like so: for(int i = 0; i < 10; i++) { if(do_button(GEN_ID, x, y+i*h, w, h, "Button")) { // do something } } The problem is that GEN_ID will generate the same ID for all buttons generated by the loop (which effectively breaks the input system). The advantage in using floating-point IDs is the ability to treat the decimal portion of the number as a "sub-ID"... like so: for(int i = 0; i < 10; i++) { if(do_button(GEN_ID + (i/100.f), x, y+i*h, w, h, "Button")) { } } Notice how GEN_ID is being added to (i/100.f), which is loop variant, to generate the ID for the widget. This makes each widget have a unique ID, while also not overlapping with IDs for other widgets. * ui "focus" rf_ui provides the concept of a ui "focus" which is implemented to allow super easy keyboard-support. Basically, the UI's "focus" is the set of all elements in the UI that can be currently navigated through using the keyboard (usually with arrowkeys or something similar). Any non-focused elements can NOT be navigated to using the keyboard. * ui "focus" groups UI focus also includes the concept of "focus groups". These are most useful when, for example, the GUI you're designing has multiple columns of widgets. It's pretty nice on the end-user to only "focus" one column at a time, so they can navigate through only one column. They can then switch between these columns to change "focus". The "focus group" of the UI is the set of elements that are currently focused. Different focus groups are designated with different numbers. There's a special case: 0. When a UI focus has an ID of 0, it means it's always focused, no matter the current focus group of the UI. Here's an example that'll hopefully make it clearer: // focus group: | // | // v rf_ui_focus(ui, 1); // ONLY focused when the focus group is 1 { if(do_button(...)) { } } rf_ui_unfocus(); rf_ui_focus(ui, 2); // ONLY focused when the focus group is 2 { if(do_button(...)) { } } rf_ui_unfocus(); rf_ui_focus(ui, 0); // ALWAYS focused { if(do_button(...)) { } } rf_ui_unfocus(); USAGE To use this library, you must #define RF_UI_IMPLEMENTATION in ONE .c or .cpp file before #include'ing this file. Then, you must create an rf_UIState object and initialize it with rf_ui_init: rf_UIState ui = rf_ui_init(); During the main loop of your program, when you want to begin allowing UI capabilities, you must call rf_ui_begin, passing the rf_UIState you made earlier. When you want to end the current loop (with regards to UI functionality), you then must call rf_ui_end: while(1) { // ... rf_ui_begin(&ui); { // UI stuff goes here } rf_ui_end(&ui); // ... } The rf_UIState holds variables that track the input to be used in the UI. These are input-implementation agnostic, so you'll need to set them yourself each loop AFTER rf_ui_begin: // suppose that I have mouse_x and mouse_y // tracking mouse input in screen coordinates. // also suppose that I am tracking my two // primary mouse buttons with "left_mouse_down" // and "right_mouse_down". // suppose that key press states are stored in a // boolean array called key_press, and // key hold states are stored in a boolean array // called key_down. // I'll let the UI state know about all that. rf_ui_begin(&ui); ui.cursor_x = mouse_x; ui.cursor_y = mouse_y; ui.controls[RF_UI_CONTROL_LEFT_MOUSE] = left_mouse_down; ui.controls[RF_UI_CONTROL_RIGHT_MOUSE] = right_mouse_down; ui.controls[RF_UI_CONTROL_UP_HOLD] = key_down[KEY_UP]; ui.controls[RF_UI_CONTROL_UP_PRESS] = key_press[KEY_UP]; ui.controls[RF_UI_CONTROL_LEFT_HOLD] = key_down[KEY_LEFT]; ui.controls[RF_UI_CONTROL_LEFT_PRESS] = key_press[KEY_LEFT]; ui.controls[RF_UI_CONTROL_DOWN_HOLD] = key_down[KEY_DOWN]; ui.controls[RF_UI_CONTROL_DOWN_PRESS] = key_press[KEY_DOWN]; ui.controls[RF_UI_CONTROL_RIGHT_HOLD] = key_down[KEY_RIGHT]; ui.controls[RF_UI_CONTROL_RIGHT_PRESS] = key_press[KEY_RIGHT]; ui.controls[RF_UI_CONTROL_ACTIVATE] = key_press[KEY_ENTER]; ui.controls[RF_UI_CONTROL_BACKSPACE] = key_press[KEY_BACKSPACE]; // this might seem cumbersome, but... // it is pretty powerful from the library user's perspective, // because you can do a lot to control each UI action. // for example, if I want Tab and Shift+Tab to also act as // navigation: ui.controls[RF_UI_CONTROL_UP_PRESS] = key_press[KEY_UP] || (key_down[KEY_SHIFT] && key_press[KEY_TAB]); ui.controls[RF_UI_CONTROL_DOWN_PRESS] = key_press[KEY_DOWN] || key_press[KEY_TAB]; Once you've called rf_ui_begin and set up the input for the loop, you're all ready to go! You can call widget functions now. if(rf_button(0, 32, 32, 128, 64)) { printf("Hello, World!"); } Keep in mind, though, that this is only the INPUT side of things. The rendering stuff is intentionally left out to allow maximum control over the way things look and behave visually. I'll be writing a sample front-end for this UI library to provide a basic framework for rendering, but I think it's pretty important to separate the input side from the visual side, because UI USUALLY behaves the same across applications (buttons fire when you release the mouse, etc.) but one application will want to look totally different from another. This is also discounting the vast number of visual libraries there are out there; someone might be directly using OpenGL, and someone else might be using SDL, Allegro5, or SFML. I didn't want to trap anyone! The IMGUI nature of the UI can be preserved with a front-end attached. In my experience, the front-end will naturally mirror the back-end; a front-end might have a function do_button that will internally call rf_button (and use that to handle input), while also doing rendering stuff in the same call. DEFAULTLY SUPPORTED WIDGETS * Buttons Buttons are created/handled using the rf_button function. rf_button returns an integer, 1 if the button was clicked, and 0 if it was not. It takes the following as parameters: - a pointer to the rf_UIState with which it should be used - a (should be) unique floating-point ID - x, y coordinates of the button - width and height of the button * Sliders Sliders are created/handled using the rf_slider function. rf_slider returns a float in the range 0-1 that determines how "full" the slider is. It takes the following as parameters: - a pointer to the rf_UIState with which it should be used - a (should be) unique floating-point ID - x, y coordinates of the slider - width and height of the slider - a float that holds the current [0-1] value of the slider * Line Edits Line-Edits are created/handled using the rf_line_edit function. rf_line_edit returns a char * to the text that was passed in. It takes the following as parameters: - a pointer to the rf_UIState with which it should be used - a (should be) unique floating-point ID - x, y coordinates of the line-edit - width and height of the line-edit - a char * pointing to a character array to be modified by the widget - an unsigned int that holds the maximum number of characters that the text can hold LICENSE INFORMATION IS AT THE END OF THE FILE */ #ifndef _RF_UI_H #define _RF_UI_H #ifndef RF_UI_MAX_ELEMENTS #define RF_UI_MAX_ELEMENTS 1000 #endif #define _rf__ui_id_equ(id1, id2) ((int)(id1 * 10000) == (int)(id2 * 10000)) #define _rf__ui_cursor_over(ui, x, y, w, h) (ui->cursor_x >= x && ui->cursor_x <= x+w && ui->cursor_y >= y && ui->cursor_y <= y+h) typedef double rf_ui_id; enum { RF_UI_CONTROL_LEFT_MOUSE, RF_UI_CONTROL_RIGHT_MOUSE, RF_UI_CONTROL_UP_PRESS, RF_UI_CONTROL_LEFT_PRESS, RF_UI_CONTROL_DOWN_PRESS, RF_UI_CONTROL_RIGHT_PRESS, RF_UI_CONTROL_UP_HOLD, RF_UI_CONTROL_LEFT_HOLD, RF_UI_CONTROL_DOWN_HOLD, RF_UI_CONTROL_RIGHT_HOLD, RF_UI_CONTROL_ACTIVATE, RF_UI_CONTROL_BACKSPACE, RF_MAX_UI_CONTROL }; typedef struct rf_UIState { rf_ui_id hot, active; rf_ui_id focus_ids[RF_UI_MAX_ELEMENTS]; unsigned int focus_id_count; long int current_focus_id, current_focus_group; int focusing; float cursor_x, cursor_y; int controls[RF_MAX_UI_CONTROL]; char char_input; } rf_UIState; rf_UIState rf_ui_init(void); void rf_ui_begin(rf_UIState *ui); void rf_ui_end(rf_UIState *ui); int rf_button(rf_UIState *ui, rf_ui_id id, float x, float y, float w, float h); float rf_slider(rf_UIState *ui, rf_ui_id id, float x, float y, float w, float h, float value); char *rf_line_edit(rf_UIState *ui, rf_ui_id id, float x, float y, float w, float h, char *text, unsigned int max_chars); #ifdef RF_UI_IMPLEMENTATION unsigned int _rf__ui_strlen(char *s) { unsigned int len = 0; while(*s++) { ++len; } return len; } rf_UIState rf_ui_init(void) { rf_UIState ui; ui.hot = -1; ui.active = -1; ui.focus_id_count = 0; ui.current_focus_id = -1; ui.current_focus_group = 0; ui.focusing = 0; ui.cursor_x = 0; ui.cursor_y = 0; for(int i = 0; i < RF_MAX_UI_CONTROL; ++i) { ui.controls[i] = 0; } ui.char_input = 0; return ui; } void rf_ui_begin(rf_UIState *ui) { ui->cursor_x = 0; ui->cursor_y = 0; for(int i = 0; i < RF_MAX_UI_CONTROL; ++i) { ui->controls[i] = 0; } ui->focus_id_count = 0; } void rf_ui_end(rf_UIState *ui) { if(ui->current_focus_id < 0) { if(ui->focus_id_count && (ui->controls[RF_UI_CONTROL_UP_PRESS] || ui->controls[RF_UI_CONTROL_LEFT_PRESS] || ui->controls[RF_UI_CONTROL_DOWN_PRESS] || ui->controls[RF_UI_CONTROL_RIGHT_PRESS])) { ui->current_focus_id = 0; } } else { if(ui->focus_id_count) { int focus_update = 0; if(ui->controls[RF_UI_CONTROL_DOWN_PRESS]) { if(++ui->current_focus_id >= ui->focus_id_count) { ui->current_focus_id = 0; } focus_update = 1; } if(ui->controls[RF_UI_CONTROL_UP_PRESS]) { if(--ui->current_focus_id < 0) { ui->current_focus_id = ui->focus_id_count-1; } focus_update = 1; } if(focus_update) { if(ui->current_focus_id < 0 || ui->current_focus_id >= ui->focus_id_count) { ui->current_focus_id = 0; } ui->hot = ui->focus_ids[ui->current_focus_id]; } } else { ui->current_focus_id = -1; } } } void rf_ui_focus(rf_UIState *ui, long int group) { ui->focusing = (ui->current_focus_group == group || !group); } void rf_ui_unfocus(rf_UIState *ui) { ui->focusing = 0; } int rf_button(rf_UIState *ui, rf_ui_id id, float x, float y, float w, float h) { int activated = 0; if(ui->focusing && ui->focus_id_count < RF_UI_MAX_ELEMENTS) { ui->focus_ids[ui->focus_id_count++] = id; } if(ui->current_focus_id < 0) { if(_rf__ui_cursor_over(ui, x, y, w, h)) { if(ui->hot < 0) { ui->hot = id; } if(_rf__ui_id_equ(ui->active, id) && !ui->controls[RF_UI_CONTROL_LEFT_MOUSE]) { activated = 1; } } else { if(_rf__ui_id_equ(ui->hot, id)) { ui->hot = -1; } } if(_rf__ui_id_equ(ui->hot, id)) { if(ui->controls[RF_UI_CONTROL_LEFT_MOUSE]) { ui->active = id; } } } else { if(_rf__ui_id_equ(ui->hot, id)) { if(ui->controls[RF_UI_CONTROL_ACTIVATE]) { activated = 1; } } } return activated; } float rf_slider(rf_UIState *ui, rf_ui_id id, float x, float y, float w, float h, float value) { if(ui->focusing && ui->focus_id_count < RF_UI_MAX_ELEMENTS) { ui->focus_ids[ui->focus_id_count++] = id; } if(ui->current_focus_id < 0) { if(_rf__ui_id_equ(ui->active, id)) { if(ui->controls[RF_UI_CONTROL_LEFT_MOUSE]) { value = (ui->cursor_x - x)/w; } else { ui->active = -1; } } else { if(_rf__ui_cursor_over(ui, x, y, w, h)) { if(ui->hot < 0) { ui->hot = id; } } else { if(_rf__ui_id_equ(ui->hot, id)) { ui->hot = -1; } } if(_rf__ui_id_equ(ui->hot, id)) { if(ui->controls[RF_UI_CONTROL_LEFT_MOUSE]) { ui->active = id; } } } } else { if(_rf__ui_id_equ(ui->hot, id)) { ui->active = id; if(ui->controls[RF_UI_CONTROL_RIGHT_HOLD]) { if((value += 0.05) > 1) { value = 1; } } if(ui->controls[RF_UI_CONTROL_LEFT_HOLD]) { if((value -= 0.05) < 0) { value = 0; } } } } if(value < 0) { value = 0; } else if(value > 1.f) { value = 1.f; } return value; } char *rf_line_edit(rf_UIState *ui, rf_ui_id id, float x, float y, float w, float h, char *text, unsigned int max_chars) { unsigned int text_len = _rf__ui_strlen(text); if(ui->focusing && ui->focus_id_count < RF_UI_MAX_ELEMENTS) { ui->focus_ids[ui->focus_id_count++] = id; } if(ui->current_focus_id < 0) { if(_rf__ui_cursor_over(ui, x, y, w, h)) { if(ui->hot < 0) { ui->hot = id; } } else { if(_rf__ui_id_equ(ui->hot, id)) { ui->hot = -1; } } if(_rf__ui_id_equ(ui->hot, id)) { if(ui->controls[RF_UI_CONTROL_LEFT_MOUSE]) { ui->active = id; } } } else { if(_rf__ui_id_equ(ui->hot, id)) { ui->active = id; } } if(_rf__ui_id_equ(ui->active, id)) { if(ui->char_input && text_len < max_chars-1) { text[text_len++] = ui->char_input; } if(ui->controls[RF_UI_CONTROL_BACKSPACE] && text_len > 0) { text[--text_len] = 0; } } return text; } #endif /* RF_UI_IMPLEMENTATION */ #endif /* ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MIT License Copyright (c) 2017 Ryan Fleury Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ */
C
/* ** free.c for epitech in /home/chapui_s/travaux/malloc/ ** ** Made by chapui_s ** Login <chapui_s@epitech.eu> ** ** Started on Sun Feb 15 19:50:03 2015 chapui_s ** Last update Sun Feb 15 23:03:29 2015 chapui_s */ #include "rbmalloc.h" extern t_malloc g_info; static void invalid_pointer(void *ptr) { printf("Error in '%s': free(): invalid pointer: %p\n", ((__progname) ? (__progname) : ("Unknow")), ptr); abort(); } static void double_free(void *ptr) { printf("Error in '%s': free(): double free: %p\n", ((__progname) ? (__progname) : ("Unknow")), ptr); abort(); } static inline t_metadata *try_fusion(t_metadata *node) { while (IS_FREE(node->prev)) { g_info.root_rbtree = remove_from_freed_list(g_info.root_rbtree, node->prev); node = fusion(node->prev, node); } while (IS_FREE(node->next)) { g_info.root_rbtree = remove_from_freed_list(g_info.root_rbtree, node->next); node = fusion(node, node->next); } return (node); } static inline void change_break(t_metadata *node) { size_t pages_to_remove; if (node->prev) { node->prev->next = (t_metadata*)0; g_info.last_node = node->prev; g_info.end_in_page = (void*)g_info.last_node + g_info.last_node->size; } else { g_info.end_in_page = g_info.last_node; g_info.last_node = (t_metadata*)0; } g_info.page_remaining += node->size; pages_to_remove = g_info.page_remaining / g_info.page_size; brk((sbrk(0) - (pages_to_remove * g_info.page_size))); g_info.page_remaining = g_info.page_remaining - (pages_to_remove * g_info.page_size); } void rbfree(void *ptr) { t_metadata *node; if (!ptr) return ; pthread_mutex_lock(&(g_info.mutex)); node = GET_NODE(ptr); if (ptr < g_info.first_block || ptr > g_info.end_in_page || !IS_VALID(node)) invalid_pointer(ptr); if (node->free == YFREE) double_free(ptr); node = try_fusion(node); if (!node->next) change_break(node); else g_info.root_rbtree = insert_in_freed_list(g_info.root_rbtree, node); pthread_mutex_unlock(&(g_info.mutex)); }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <string.h> #include <fcntl.h> void *print_message_function (void *ptr); main () { pthread_t thread1, thread2; pthread_attr_t attr; int ret; pthread_attr_init(&attr); ret=pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); /*if i comment above line then this program work same as first program o/p will be like first it will print msg and then retrun value*/ char *message1 = "I am Thread 1"; char *message2 = "I am Thread 2"; int iret1=5, iret2=10; //printf("Ret value after setting attribute is %d\n",ret); /* Create independent threads each of which will execute function */ printf("my pid = %d\n",getpid()); iret1 = pthread_create (&thread1, &attr, print_message_function, (void *) message1); iret2 = pthread_create (&thread2, &attr, print_message_function, (void *) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */ /* */ pthread_join (thread1, NULL); pthread_join (thread2, NULL); /* */ printf ("Thread 1 returns: %d\n", iret1); printf ("Thread 2 returns: %d\n", iret2); exit (0); } void *print_message_function (void *ptr){ char *message; //int fd=open("hello.txt",O_WRONLY); message = (char *) ptr; //pthread_detach(pthread_self()); //write(fd,message,strlen(message)); printf ("%s \n", message); }
C
/* $NetBSD: expr_binary.c,v 1.7 2023/03/28 14:44:34 rillig Exp $ */ # 3 "expr_binary.c" /* * Test binary operators. */ /* lint1-only-if: lp64 */ /* lint1-extra-flags: -X 351 */ struct incompatible { /* just to generate the error message */ int member; }; void sink(struct incompatible); /* * Test the usual arithmetic conversions. * * C99 6.3.1.8 "Usual arithmetic conversions" */ void cover_balance(void) { /* expect+1: ... 'pointer to void' ... */ sink((void *)0 + 0); /* expect+1: ... 'pointer to void' ... */ sink(0 + (void *)0); /* expect+1: ... 'int' ... */ sink(1 + 1); /* expect+1: ... 'const int' ... */ sink((const int)1 + (volatile int)1); /* expect+1: ... 'volatile int' ... */ sink((volatile int)1 + (const int)1); long double _Complex cldbl = 0.0; double _Complex cdbl = 0.0; float _Complex cflt = 0.0f; /* expect+1: error: invalid type for _Complex [308] */ _Complex invalid = 0.0; /* expect+1: ... 'long double _Complex' ... */ sink(cldbl + 0); /* expect+1: ... 'long double _Complex' ... */ sink(0 + cldbl); /* expect+1: ... 'long double _Complex' ... */ sink(cldbl + cdbl); /* expect+1: ... 'long double _Complex' ... */ sink(cdbl + cldbl); /* expect+1: ... 'double _Complex' ... */ sink(cdbl + 0); /* expect+1: ... 'double _Complex' ... */ sink(0 + cdbl); /* expect+1: ... 'double _Complex' ... */ sink(cdbl + cflt); /* expect+1: ... 'double _Complex' ... */ sink(cflt + cdbl); /* expect+1: ... 'float _Complex' ... */ sink(cflt + 0); /* expect+1: ... 'float _Complex' ... */ sink(0 + cflt); /* expect+1: ... 'float _Complex' ... */ sink(cflt + (__uint128_t)0); /* expect+1: ... 'float _Complex' ... */ sink((__uint128_t)0 + cflt); /* * The type specifier '_Complex' is only used during parsing, it does * not make it to the expression. */ /* expect+1: ... 'double _Complex' ... */ sink(invalid + 0); /* expect+1: ... 'long double' ... */ sink(0.0L + 0); /* expect+1: ... 'long double' ... */ sink(0 + 0.0L); /* expect+1: ... 'long double' ... */ sink(0.0L + 0.0); /* expect+1: ... 'long double' ... */ sink(0.0 + 0.0L); /* expect+1: ... 'double' ... */ sink(0.0 + 0); /* expect+1: ... 'double' ... */ sink(0 + 0.0); /* expect+1: ... 'double' ... */ sink(0.0 + 0.0f); /* expect+1: ... 'double' ... */ sink(0.0f + 0.0); /* expect+1: ... 'float' ... */ sink(0.0f + 0); /* expect+1: ... 'float' ... */ sink(0 + 0.0f); /* expect+1: ... 'float' ... */ sink(0.0f + (__uint128_t)0); /* expect+1: ... 'float' ... */ sink((__uint128_t)0 + 0.0f); /* expect+1: ... 'unsigned long long' ... */ sink(0ULL + 0); /* expect+1: ... 'unsigned long long' ... */ sink(0 + 0ULL); /* expect+1: ... 'unsigned long long' ... */ sink(0ULL + 0LL); /* expect+1: ... 'unsigned long long' ... */ sink(0LL + 0ULL); /* If the bit-width is the same, prefer the unsigned variant. */ /* expect+1: ... 'unsigned long long' ... */ sink(0UL + 0LL); /* expect+1: ... 'unsigned long long' ... */ sink(0LL + 0UL); /* * Ensure that __int128_t is listed in the integer ranks. This table * only becomes relevant when both operands have the same width. */ /* expect+1: ... '__uint128_t' ... */ sink((__uint128_t)1 + (__int128_t)1); /* expect+1: ... '__uint128_t' ... */ sink((__int128_t)1 + (__uint128_t)1); }
C
#pragma once #ifndef main_h #define main_h ///////////////////////////////////////////////// /// Definicion De Firmas de Funciones ///////////////////////////////////////////////// /** * Encargada de obtener el primer valor del archivo recibido con el Fin * de poder acceder a la cantidad de vertices que posee el nodo. * * @return int vertices Cantidad de vertices totales del grafo. */ int cantVertices(); /** * Encargada de obtener el valor del primer vertice. * * @return int inicial Primer nodo del grafo. */ int inicial(); /** * Funcion encargada generar la busqueda de un grupo de mejores amigos, esta recorre toda * la combinatoria de posibles soluciones de grupos de mejores amigos sin repeticiones. * * @param grafoMatriz ptr Puntero que apunta a la matriz. * @param int vertices Cantidad de vertices totales en el grafo. * @return void */ void buscarCliques(grafoMatriz * ptr,int vertices); /** * Funcion principal del funcionamiento del codigo con matrices. * * @return void */ void matriz(); /** * Funcion principal del funcionamiento del codigo con listas. * * @return void */ void lista(); /** * Funcion principal que llama tanto a la matriz como a la lista * y genera el funcionamiento del programa. * * @return int 0 */ int main(); #endif
C
#include <stdio.h> #include <SDL2/SDL.h> #include "./constants.h" int game_is_running = FALSE; SDL_Window *window = NULL; SDL_Renderer *renderer = NULL; int initialize_window(void) { if (SDL_Init(SDL_INIT_EVERYTHING) != 0) { fprintf(stderr, "Erro ao iniciar o SDL.\n"); return FALSE; } window = SDL_CreateWindow( NULL, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_BORDERLESS); if (!window) { fprintf(stderr, "Erro ao criar uma janela em SDL.\n"); return FALSE; } renderer = SDL_CreateRenderer(window, -1, 0); if (!renderer) { fprintf(stderr, "Erro ao criar um Render SDL.\n"); return FALSE; } return TRUE; } void process_input() { SDL_Event event; SDL_PollEvent(&event); switch (event.type) { case SDL_QUIT: game_is_running = FALSE; break; case SDL_KEYDOWN: if (event.key.keysym.sym == SDLK_ESCAPE) { game_is_running = FALSE; break; } } } void setup() {} void update() {} void render() {} void destroy_window() { SDL_DestroyRenderer(renderer); SDL_DestroyWindow(window); SDL_Quit(); } int main() { game_is_running = initialize_window(); setup(); while (game_is_running) { process_input(); update(); render(); } destroy_window(); return FALSE; }
C
//To count the digits in a number #include<stdio.h> int main() { int a,b=0; printf("Enter the number = "); scanf("%d",&a); while(a>0) { a/=10; ++b; } printf("No. of digits is %d",b); return(0); }
C
/****************************************************************************** ** Student name: Jia Jun Yong ** Student number: s3688090 ** Course: Advanced Programming Techniques - S2 2018 ******************************************************************************/ #ifndef POP_H #define POP_H #include "gene.h" #include "invector.h" #define MUTATE_RATE 5 #define HEAD_OFFSET 1 #define RANDOM_MAX 100 typedef struct pop_node { Gene *gene; struct pop_node *next; } Pop_node; typedef struct pop_list { /* the head of the population list */ Pop_node *head; /* the size of the population */ int count; /* pointers to functions to perform * gene chromosome creation, mutation, * crossover and evaluation */ CreateFn create_rand_chrom; MutateFn mutate_gene; CrossOverFn crossover_genes; EvalFn evaluate_fn; } Pop_list; /* Create and initialise the population list to a safe state. * Returns TRUE on success */ Boolean pop_init(Pop_list **); /* Set the function pointers of a population list */ void pop_set_fns(Pop_list *p,CreateFn cf,MutateFn mf,CrossOverFn cof,EvalFn ef); /* This function causes details of the fittest gene of the generation to * be printed out. * The function also prints out the number of the current generation. * This function must not be able to access any generation value outside * of the function. */ void pop_print_fittest(Pop_list *p); /* TO DO - other functions as appropriate */ void pop_insert(Pop_list *, Gene *); void pop_free(Pop_list *); void pop_normalise(Pop_list *); Gene * selectGene (Pop_list *); void pop_generate(Pop_list *, int , InVTable *, int); void evolve(Pop_list *, Pop_list *, InVTable *, int); void cloneList(Pop_list *, Pop_list*); void pop_freeAll(Pop_list *); #endif
C
#include <stdio.h> #include <stdlib.h> #ifndef WIN32 #include <sys/time.h> #include <unistd.h> #include <pthread.h> #include <signal.h> #else #include <process.h> #include <Windows.h> #include <ShlObj.h> #endif // !WIN32 #include "common.h" int platform_is_admin(void) { #ifndef WIN32 return (int)(0 == getuid()); #else return (int)IsUserAnAdmin(); #endif // !WIN32 } void platform_create_thread(void *param, void *func) { #ifndef WIN32 pthread_t *pid = param; void *(*start)(void *) = (void *(*)(void *))func; if (0 != pthread_create(pid, NULL, start, NULL)) { printf("[%s] Error: Failed to create thread!\n", __FUNCTION__); exit(EXIT_FAILURE); } #else HANDLE *handle_ptr = (HANDLE *)param; unsigned int WINAPI(*start)(void *) = \ (unsigned int WINAPI(*)(void *))func; *handle_ptr = (HANDLE)_beginthreadex(NULL, 0, start, NULL, 0, NULL); if (NULL == *handle_ptr) { printf("[%s] Error: Failed to create thread!\n", __FUNCTION__); exit(EXIT_FAILURE); } #endif // !WIN32 } void platform_destroy_thread(void *param) { #ifndef WIN32 pthread_t *pid = (pthread_t *)param; pthread_t cur_pid = pthread_self(); if (*pid == cur_pid) { pthread_exit(NULL); } else { pthread_kill(*pid, SIGKILL); } #else HANDLE *handle_ptr = (HANDLE *)param; HANDLE cur_handle = GetCurrentThread(); if (*handle_ptr == cur_handle) { ExitThread(1); } else { TerminateThread(*handle_ptr, 1); } #endif // !WIN32 } void platform_wait_thread(void *param) { #ifndef WIN32 pthread_t *pid = (pthread_t *)param; pthread_join(*pid, NULL); #else HANDLE *handle_ptr = (HANDLE *)param; WaitForSingleObject(*handle_ptr, INFINITE); #endif // !WIN32 } int platform_is_current_thread(void *param) { #ifndef WIN32 pthread_t *pid = (pthread_t *)param; return (int)(*pid == pthread_self()); #else HANDLE *handle_ptr = (HANDLE *)param; return (int)(*handle_ptr == GetCurrentThread()); #endif // !WIN32 } void platform_mutex_init(void *param) { #ifndef WIN32 pthread_mutex_t *mutex = (pthread_mutex_t *)param; pthread_mutex_init(mutex, NULL); #else HANDLE *handle_ptr = (HANDLE *)param; *handle_ptr = CreateMutex(NULL, FALSE, NULL); #endif // !WIN32 } void platform_mutex_destroy(void *param) { #ifndef WIN32 pthread_mutex_t *mutex = (pthread_mutex_t *)param; pthread_mutex_destroy(mutex); #else HANDLE *handle_ptr = (HANDLE *)param; CloseHandle(*handle_ptr); #endif // !WIN32 } void platform_mutex_lock(void *param) { #ifndef WIN32 pthread_mutex_t *mutex = (pthread_mutex_t *)param; pthread_mutex_lock(mutex); #else HANDLE *handle_ptr = (HANDLE *)param; WaitForSingleObject(*handle_ptr, INFINITE); #endif // !WIN32 } void platform_mutex_unlock(void *param) { #ifndef WIN32 pthread_mutex_t *mutex = (pthread_mutex_t *)param; pthread_mutex_unlock(mutex); #else HANDLE *handle_ptr = (HANDLE *)param; ReleaseMutex(*handle_ptr); #endif // !WIN32 } void platform_wait_us(int us) { #ifndef WIN32 struct timeval tv_start; struct timeval tv_end; long diff_time = 0; long threshold = (long)us; gettimeofday(&tv_start, NULL); while (1) { gettimeofday(&tv_end, NULL); diff_time = (tv_end.tv_sec - tv_start.tv_sec) * 1e6 \ + tv_end.tv_usec - tv_start.tv_usec; if (diff_time >= threshold) { break; } } #else LARGE_INTEGER frequency = { 0 }; if (!QueryPerformanceFrequency(&frequency)) { printf("[%s] Error: QueryPerformanceFrequency not support for this machine!\n",\ __FUNCTION__); exit(EXIT_FAILURE); } LARGE_INTEGER timeStart = { 0 }; QueryPerformanceCounter(&timeStart); LARGE_INTEGER timeEnd = { 0 }; while (1) { QueryPerformanceCounter(&timeEnd); double time = ((timeEnd.QuadPart - timeStart.QuadPart) * 1e6 \ / (double)frequency.QuadPart); if (time >= us) { break; } } #endif // !WIN32 }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> #include "input.h" #include "interface.h" #include "processo.h" #ifndef COMUM #define COMUM #include "comum.h" #endif int lin, col; tempo t; frame frames[FRAMES]; processo processos[PROCESSOS]; pthread_t tid[PROCESSOS]; int ultimo_proc = 0; // processo que fez a ultima acao int modo_texto = 0; // modo de texto simples ou modo dinamico // variáveis de exclusão mútua pthread_mutex_t print_mutex; // mutex para printfs que precisam estar em sequencia pthread_mutex_t mp_mutex; // memória principal // mutex e cond para bloquear as threads no modo de apertar espaco pra ver a próxima acao pthread_mutex_t mutex; pthread_cond_t cond; // mutex e cond para bloquear para mostrar o antes e depois das tabelas, durante cada acao /* ex: p00 solicita uma pv tp e memória do p00 são mostradas, antes da acao ocorrrer pausa para o usuário ver as tabelas antes da modificadao <----- aqui tabelas são alteradas tp e memória modificadas são mostradas */ pthread_mutex_t mutex2; pthread_cond_t cond2; int ok = 0; // sisteminha de ticket para garantir uma ordem de fila no wait e no mutex int ticket = 0; // ticker para ser pego int prox_ticket = 0; // ticket chamado void inicio() { int i, j; // relógio t = (tempo) {0, 0}; // inicializando memória, com -1 indicando que o frame está livre for(i = 0; i < FRAMES; i++) frames[i] = (frame) {-1, -1}; // inicializando processos, com -1 nas entradas da TP, indicando que não estão alocadas for(i = 0; i < PROCESSOS; i++) { for(j = 0; j < PAGINAS_VIRTUAIS; j++) { processos[i].tabela[j] = -1; } for(j = 0; j < WORKING_SET; j++) { processos[i].working_set[j] = -1; } processos[i].entrada = INF; } // inicialização das variáveis de exclusão mútua pthread_mutex_init(&print_mutex, NULL); pthread_mutex_init(&mp_mutex, NULL); pthread_mutex_init(&mutex, NULL); pthread_cond_init(&cond, NULL); pthread_mutex_init(&mutex2, NULL); pthread_cond_init(&cond2, NULL); if(!modo_texto) interface_inicio(); } void fim() { if(!modo_texto) interface_fim(); // liberação das variáveis de exclusão mútua pthread_mutex_destroy(&print_mutex); pthread_mutex_destroy(&mp_mutex); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); pthread_mutex_destroy(&mutex2); pthread_cond_destroy(&cond2); exit(0); } void uso(char *nome) { printf("Uso: %s MODO\n\n", nome); printf("MODO: \"basico\" ou \"completo\", indicando a forma da divisão das tarefas\n"); printf("\nExemplo: %s completo\n", nome); } int main(int argc, char *argv[]) { // verificação dos argumentos if(argc < 2) { // quantidade incorreta de argumentos uso(argv[0]); exit(0); } if(strcmp(argv[1], "basico") == 0) modo_texto = 1; else if(strcmp(argv[1], "completo") == 0) modo_texto = 0; else { uso(argv[0]); exit(0); } int i; inicio(); pthread_t tid2; // thread para pegar a entrada (não tem no modo texto) if(!modo_texto) { if(pthread_create(&tid2, NULL, thread_input, NULL)) { printf("Falha ao criar thread.\n"); exit(1); } } if(modo_texto) { printf("*****\n"); printf("Por favor, maximize sua janela.\n"); printf("*****\n"); sleep(2); ok = 1; } int segundos = 0; int meu_ticket; for(i = 0; i < PROCESSOS; i++) { meu_ticket = ticket++; pthread_mutex_lock(&mutex); // checagem do ok (esperando o input do espaco) não ocorre no modo básico, onde o ok é sempre 1 while(!ok || prox_ticket < meu_ticket) pthread_cond_wait(&cond, &mutex); novo_processo(); if(!modo_texto) { ok = 0; } prox_ticket++; if(!modo_texto) atualiza_hora2(segundos); segundos += TEMPO_NOVOPROC; pthread_mutex_unlock(&mutex); if(modo_texto) { pthread_cond_broadcast(&cond); sleep(TEMPO_NOVOPROC); } else // regra de 3 pegando o maior entre os 2 tempos e fazendo ele ser 500 ms, e diminuindo o outro proporcionalmente usleep(TEMPO_NOVOPROC > TEMPO_NOVAREQ ? 50000 : TEMPO_NOVOPROC*50000/TEMPO_NOVAREQ); } // esperando processos terminarem for(i = 0; i < PROCESSOS; i++) { pthread_join(tid[i], NULL); } fim(); pthread_exit(NULL); return 0; }
C
#include<stdio.h> #include<malloc/malloc.h> #include "PLIB2.h" #define N 6 //頂点の数 static int adj[N][N]={ //隣接行列:(隣接有り = 1, 隣接無し = 0) {0,1,0,1,1,0}, {1,0,1,0,1,0}, {0,1,0,0,1,0}, {1,0,0,0,1,1}, {1,1,1,1,0,1}, {0,0,0,1,1,0}, }; static char V[N+1]="S12345"; static int start=0; static int end=5; int main(void){ int i,n,visit[N]; //(未訪問 = 0, 訪問済 = 1) printf("/***(112頁)chap-6-4-2.グラフの探索(幅優先)***\n"); queuehead=queuetail=0; for(i=0;i<N;i++){ // 全ノード未訪問に設定 visit[i]=0; } visit[start]=1; Enqueue(0); while(queuehead!=queuetail) { n=Dequeue(); //キューからデータを一個取り出す printf("Visit:%c(%d)\n",V[n],n); if(n==end){ printf("***solved***Goal=%c(%d)\n",V[n],n); printf("\n"); return 0; } else{ for(i=0;i<N;i++){ if(visit[i]!=1 && adj[n][i]==1){ visit[i]=1; Enqueue(i); } } } } printf("\n*/\n"); return 0; }
C
/*********************************** * FileName: briupBasePeriph.c * CreateDate: 2017-8-24 * Author: Dennis Chen * Description: Իӿڵʵļ * Update: -------- ***********************************/ #include "briupBasePeriph.h" /****************** * FunctionName: basePeriphInit(); * Desciption: ʼ躯ӿ * Input: NULL * Output: NULL ******************/ void basePeriphInit(void) { //GPIOCʱ RCC->APB2ENR |= 1<<4 | 1<<8; //GPIOC Pin.0/1/2Ϊ50MHz GPIOC->CRL &= ~0xffff; GPIOC->CRL |= 0x3333; GPIOG->CRH &= 0xf00fffff; GPIOG->CRH |= 0x33<<20; resetLed( LED_ALL); resetBeep(); resetRelay(0x03); } /****************** * FunctionName: setLed(u8 ledStat); * Desciption: ledStatӦLED * Input: ledStat õ3λӦ3LEDƵ״̬ * Output: NULL ******************/ void setLed(u8 ledStat) { //ʹGPIOC Pin.0/1/2͵ƽ //ODR BSRR BRR GPIOC->ODR &= ~ledStat; } //ledStatϨӦLED void resetLed(u8 ledStat) { GPIOC->ODR |= ledStat; } void setBeep() { GPIOG->ODR |= 1<<14; } void resetBeep() { GPIOG->ODR &= ~(1<<14); } void setRelay(u8 choose) { if( choose & 0x01) GPIOG->ODR |= 1<<13; if( choose & 0x02) GPIOC->ODR |= 1<<3; } void resetRelay(u8 choose) { if( choose & 0x01) GPIOG->ODR &= ~(1<<13); if( choose & 0x02) GPIOC->ODR &= ~(1<<3); }
C
// Program uses for loop to take input and print elements of a one-dimensional array // Header Files #include<stdio.h> // Start of main function int main() { // variable and array Declaration int arr[5], i; /*for loop to take input elements from the user and store it in an array element*/ for(i = 0; i < 5; i++) { printf("Enter a[%d]: ", i); scanf("%d", &arr[i]); } printf("\nPrinting elements of the array: \n\n"); //for loop to print an individual element of an array. for(i = 0; i < 5; i++) { printf("%d ", arr[i]); } // signal to operating system program ran fine return 0; }
C
#include "holberton.h" #include <stdio.h> /** * _putchar - writes chars c to standard output stream * @c: char to print * * Return: if succesfull, 1 will be returned, else -1 if error */ int _putchar(char c) { return (write(1, &c, 1)); }
C
/* ** EPITECH PROJECT, 2019 ** minishell1 ** File description: ** some functions obviously */ #include "mysh.h" #include <stdlib.h> #include <stddef.h> void print_env(shell_t *shell) { for (int i = 0; shell->env_dup[i] != NULL; i++) { my_putstr(shell->env_dup[i]); my_putchar('\n'); } } int my_setenv(shell_t *shell, char **args) { if (args[1] == NULL) print_env(shell); else { int index = get_indexes(shell->env_dup); char *name = args[1]; char *value = calloc(1, 1); if (args[2] == NULL); else value = args[2]; if (!check_strings(args)) return (setenv_err()); char **dup_env = malloc(sizeof(char *) * index * 2); shell->env_dup = fill_env(dup_env, name, value, shell); update_path(name, value, shell); return (0); } return (0); } int my_unsetenv(shell_t *shell, char **args) { int rem_ind = 0; if (args[1] == NULL) { my_putstr_err("unsetenv: Too few arguments.\n"); return (0); } for (; args[rem_ind] != NULL; rem_ind++); for (int i = 1; rem_ind != 1; rem_ind--, i++) { shell->env_dup = remove_index(args[i], shell); update_path(args[i], NULL, shell); } return (0); } int functions(char *string, shell_t *shell, char **args, tree_t **right) { if (my_strcmp(string, "exit") == 0) my_exit(args, shell); if (my_strcmp(string, "cd") == 0) { my_cd(shell, args); return (1); } if (my_strcmp(string, "setenv") == 0) { my_setenv(shell, args); return (1); } if (my_strcmp(string, "env") == 0) { print_env(shell); return (1); } if (my_strcmp(string, "unsetenv") == 0) { my_unsetenv(shell, args); return (1); } if (my_strcmp(string, "alias") == 0) { my_alias(shell, args); return (1); } return (check_other_functions(string, shell, args)); }
C
#include "arrstack.h" static int max_l = STACKSIZE - 1; static int max_r = 0; int push_l(float num, float stack[], int pos, int side) { if(side == RIGHT) { if(pos <= max_r) printf("STACK IS FULL!"); else { pos--; stack[pos] = num; max_l--; } } else if(side == LEFT) { if(pos >= max_l) printf("STACK IS FULL!"); else { pos++; stack[pos] = num; max_r++; } } return pos; } int pop_l(float *num, float stack[], int pos, int side) { if(side == RIGHT) { if(pos == STACKSIZE) { printf("STACK IS EMPTY!"); return pos; } else { *num = stack[pos]; stack[pos] = 0; pos++; max_l++; } } else if(side == LEFT) { if(pos == -1) { printf("STACK IS EMPTY!"); return pos; } else { *num = stack[pos]; stack[pos] = 0; pos--; max_r--; } } return pos; }
C
/* \mainpage Linguagens Programao I \author Rui Moreira \author Daniel Mendes 26385 \author Gonalo Silva 26329 \version 1.0 \date 2016 R1. Permitir ao utilizador armazenar e gerir um ou mais conjuntos de peas de domin, i.e., inserir e/ou remover as peas iniciais dum jogo de mo usado no jogo; as peas tambm podem ser geradas de forma aleatria; em nenhum dos casos podem haver peas repetidas nos vrios conjuntos de peas mo envolvidos; (IMPLEMENTADO) R2. Dada uma representao de peas ou sequncias de peas recorrendo a tipos inteiros, permitir gerar as mesmas peas ou sequncia usando caracteres/strings, e vice-versa; (IMPLEMENTADO) R3. Dadas vrias sequncias de encaixe com tamanhos variveis (geradas por um algoritmo ou aleatoriamente) pretende-se permitir ordenar essas pesquisas por ordem de tamanho (comprimento da sequncia de encaixe); (IMPLEMENTADO) (FUNCIONA SE ESCOLHER UM BARALHO/MAO, CASO CONTRARIO ELE NO TEM ESPAO PARA MOSTRAR AS SEQUENCIAS) R4. Dadas vrias sequncias de encaixe com tamanhos variveis (geradas por um algoritmo ou aleatoriamente) pretende-se encontrar padres de encaixe nessas sequncias, ou seja, encontrar as posies de sub-sequncias pr-definidas de encaixe; (IMPLEMENTADO) R5. Dada um sequncia de encaixe com vrias peas, permitir substituir um padro de encaixe por outro padro (os padres podem ter tamanhos diferentes); dever ser possvel tambm substituir todas as ocorrncias de um padro por outro padro, numa dada sequncia; (IMPLEMENTADO) R6. A partir de um conjunto de peas do jogador e de uma sequncia de encaixe de peas inicial j colocada na mesa de jogo (esta sequncia pode ser vazia), pretende-se determinar a sequncia de encaixe final que utiliza todas as peas disponveis; podero existir uma ou mais sequncias de encaixe com todas as peas; se no for possvel encaixar todas as peas deve determinar-se a maior sequncia de encaixe possvel; (IMPLEMENTADO) R7. Dados dois ou mais conjuntos de peas ou jogos de mo e de uma sequncia de encaixe de peas inicial colocada na mesa de jogo (esta sequncia pode ser vazia), pretende-se determinar se possvel encaixar todas as peas desses conjuntos de mo (retiradas vez de cada mo do jogador) de forma a conseguir-se uma sequncia vlida; se no for possvel encaixar todas as peas ento deve determinar-se a maior sequncia de encaixe possvel; (IMPLEMENTADO) (FUNCIONA SE ESCOLHER MO MANUAL, CASO CONTRARIO ELE NO TEM ESPAO PARA MOSTRAR AS SEQUENCIAS) R8. Permitir a manipulao das estruturas de dados atravs da entrada e sada de dados via ficheiros de texto; (IMPLEMENTADO) R9. Permitir a manipulao das estruturas de dados atravs da entrada e sada de dados via ficheiros binrios; (IMPLEMENTADO) R10. Permitir a manipulao das estruturas de dados e das funcionalidades da aplicao atravs de uma estrutura de interao baseada em texto (menus); (IMPLEMENTADO) */ #include <stdio.h> //Biblioteca de entrada e saida #include <stdlib.h> //Biblioteca de funes padro #include <string.h> //Biblioteca para usar string #include <stdbool.h> //Biblioteca para usar booleana #include <time.h> //Biblioteca usada para o rand(),srand() #define COLSTRING 4 //Tamanho das colunas do array de strings #define COL 2 //Tamanho das colunas do array de inteiros #define LINSTRING 28 //Tamanho das linhas do array de strings typedef struct sequencia { char * seqstring; }SEQUENCIA; typedef struct pecaint { int dir; int esq; struct pecaint * pnextint; }PECAINT; typedef struct sobrou { char * sobroustr; struct sobrou * proximo; }SOBROU; typedef struct peca { char * pecastr; struct peca * pnext; }PECA; typedef struct iniciarpeca { int nbar; //baralho int nsob; //sobrou int npecasint; //pecas int int nseq; PECA * pfirst; SOBROU * psobrou; PECAINT * pfirstint; SEQUENCIA * pfirstseq; }INICIARPECA; //Assinatura das funes int main_projetolp1primparte(int argc, char * argv[]); void criarpecas(char pecas[][COLSTRING]); void imprimirpecas(char pecas[][COLSTRING]); void baralhos(INICIARPECA * b,char pecas[][COLSTRING],char baralho[][COLSTRING],char sobrou[][COLSTRING],int); void rempeca(INICIARPECA * b,int pecastotal,int npecasremover); void addpeca(INICIARPECA * b,int pecastotal,int npecas); void imprimirpecasint(char pecas[][COLSTRING],int pecasint[][COL]); int ordenarseq(INICIARPECA * b,int num); void procurar_padrao(char arrayfinalcompleto[][150],int); void seq_inicial(char baralho[][COLSTRING]); void retirar_mao_jogadores(char baralho[][COLSTRING],int); char * create_dyn_string(char str[]); void inserir_peca_baralho(INICIARPECA * b, char pecas[COLSTRING]); void inserir_sobrou_baralho(INICIARPECA * b, char pecas[COLSTRING]); PECA * find_peca_baralho(INICIARPECA * b, char novapeca[]); void inserir_pecaint_baralho(INICIARPECA * b, int dir, int esq); void convert_mao_string_to_int(INICIARPECA * b, int pecastotal); void convert_mao_int_to_string(INICIARPECA * b, int pecastotal); void create_array_pecas(INICIARPECA * b, unsigned int n); void inserir_seq_iniciarpeca(INICIARPECA * b, char seq[]); void save_txt_jogo(INICIARPECA b, char fname[]); void save_bin(INICIARPECA b, char fnome[]); void load_txt_jogo(INICIARPECA *b, char fname[]); void load_bin(INICIARPECA *b, char fname[]);
C
#include <stdlib.h> #include <stdio.h> #include "thinkgear.h" void wait() { printf( "\n" ); printf( "Press the ENTER key...\n" ); fflush( stdout ); getc( stdin ); } /** * Program which prints ThinkGear EEG_POWERS values to stdout. */ int main( void ) { char *comPortName = NULL; int dllVersion = 0; //动态库版本 int connectionId = 0;//连接ID int packetsRead = 0; //包数量 int errCode = 0; //错误码 /* Print driver version number */ dllVersion = TG_GetDriverVersion(); printf( "ThinkGear DLL version: %d\n", dllVersion ); //打印当前动态库版本 /* Get a connection ID handle to ThinkGear */ connectionId = TG_GetNewConnectionId(); //获取连接ID 跟文件描述符类似的功能 if( connectionId < 0 ) { fprintf( stderr, "ERROR: TG_GetNewConnectionId() returned %d.\n", connectionId ); wait(); exit( EXIT_FAILURE ); } /* Set/open stream (raw bytes) log file for connection */ // 原始数据日志 用于高级分析 errCode = TG_SetStreamLog( connectionId, "streamLog.txt" ); if( errCode < 0 ) { fprintf( stderr, "ERROR: TG_SetStreamLog() returned %d.\n", errCode ); wait(); exit( EXIT_FAILURE ); } /* Set/open data (ThinkGear values) log file for connection */ //ThinkGear数据日志 一种动态库已经封装好的数据 errCode = TG_SetDataLog( connectionId, "dataLog.txt" ); if( errCode < 0 ) { fprintf( stderr, "ERROR: TG_SetDataLog() returned %d.\n", errCode ); wait(); exit( EXIT_FAILURE ); } /* Attempt to connect the connection ID handle to serial port "COM5" */ comPortName = "\\\\.\\COM6"; //这个是要连接的COM端口 这个在那个计算机管理工具里面看 里面的COM端口多少这里就多少 errCode = TG_Connect( connectionId, comPortName, TG_BAUD_9600, TG_STREAM_PACKETS ); if( errCode < 0 ) { fprintf( stderr, "ERROR: TG_Connect() returned %d.\n", errCode ); wait(); exit( EXIT_FAILURE ); } if( 0==TG_EnableBlinkDetection(connectionId,1)) //启动眨眼检测 { printf("Success enable blink\n"); } /* 不停的读取数据 */ packetsRead = 0; while(1) { /* 读一个报文 */ errCode = TG_ReadPackets( connectionId, 1 ); /* 如果这个报文读取成功 */ if( errCode == 1 ) { int att, det, sig; if(( errCode = TG_GetValueStatus(connectionId, TG_DATA_ATTENTION)) != 0 ) { att = TG_GetValue(connectionId, TG_DATA_ATTENTION) ; det = TG_GetValue(connectionId, TG_DATA_MEDITATION); sig = TG_GetValue(connectionId, TG_DATA_POOR_SIGNAL); printf("attentin = %d, meditation=%d, signal=%d\n", att, det, sig); } } else { printf("ReadPackets:errcode=%d\n", errCode); } } //关闭连接 TG_FreeConnection( connectionId ); wait(); return( EXIT_SUCCESS ); }
C
//Rewrite the function so that it has just one return statement // double median (double x, double y, double z) { double result; if (x <= y) if (y <= z) result = y; else if (x <= z) result = z; else result = x; else { if (z <= y) result = y; else if (x <= z) result = x; else result = z; } return result; }
C
#include "0cc.h" void walk(Node* node) { switch (node->type) { case '=': walk(node->lhs); walk(node->rhs); break; case '+': if (node->lhs->type != ND_IDENT) break; if (node->lhs->dtype->type == PTR) { if (node->lhs->dtype->pointer_of->type == PTR) node->rhs->value *= 8; if (node->lhs->dtype->pointer_of->type == INT) node->rhs->value *= 4; } break; case '-': if (node->lhs->type != ND_IDENT) break; if (node->lhs->dtype->type == PTR) { if (node->lhs->dtype->pointer_of->type == PTR) node->rhs->value *= 8; if (node->lhs->dtype->pointer_of->type == INT) node->rhs->value *= 4; } break; } } void sema() { for (int i=0; code[i][0]; i++){ for (int j=1; code[i][j]; j++) { walk(code[i][j]); } } }
C
/* * @Author: Huang Yuhui * @Date: 2019-03-20 11:22:08 * @Last Modified by: Huang Yuhui * @Last Modified time: 2019-03-20 11:28:59 */ /* * 题目修改题-题目描述如下: * * 函数'fun'的功能是:根据整型形参'n',计算如下公式值: A1 = 1, A2 = 1/1+A1, A3 = 1/1+A2, ··· , An = 1/1+A(n-1). */ #include <stdlib.h> #include <conio.h> #include <stdio.h> /*************found**************/ float fun(int n) { float A = 1; int i; /*************found**************/ for (i = 2; i <= n; i++) //! (i<=n) For example:input 2. { A = 1.0 / (1 + A); } return A; } void main() { int n; system("CLS"); printf("\nPlease enter n: "); scanf("%d", &n); printf("A%d=%lf\n", n, fun(n)); system("pause"); } /*The result be showed as followed: Please enter n: 10 A10=0.617977 Press any key to continue . . . */
C
#include "all.h" /* context-lists.c 1211e */ /* private functions for updating lists of expressions in contexts 1212b */ static void fill_hole(Exp e, Value v) { assert(e->alt == HOLE); e->alt = LITERAL; e->u.literal = v; } /* private functions for updating lists of expressions in contexts 1212c */ static Explist find_explist_hole(Explist es) { while (es && es->hd->alt != HOLE) es = es->tl; return es; } /* context-lists.c 1212a */ Exp transition_explist(Explist es, Value v) { Explist p = find_explist_hole(es); assert(p); fill_hole(p->hd, v); return head_replaced_with_hole(p->tl); } /* context-lists.c 1212d */ Exp head_replaced_with_hole(Explist es) { static struct Exp a_copy; // overwritten by subsequent calls if (es) { a_copy = *es->hd; *es->hd = mkHoleStruct(); return &a_copy; } else { return NULL; } } /* context-lists.c 1212e */ Explist copyEL(Explist es) { if (es == NULL) return NULL; else { Exp e = malloc(sizeof(*e)); assert(e); *e = *es->hd; return mkEL(e, copyEL(es->tl)); } } /* context-lists.c 1213a */ void freeEL(Explist es) { if (es != NULL) { freeEL(es->tl); free(es->hd); free(es); } } /* context-lists.c 1213b */ void freeVL(Valuelist vs) { if (vs != NULL) { freeVL(vs->tl); free(vs); } } /* context-lists.c 1213c */ Valuelist asLiterals(Explist es) { if (es == NULL) return NULL; else return mkVL(asLiteral(es->hd), asLiterals(es->tl)); } /* context-lists.c 1213d */ Value asLiteral(Exp e) { assert(e->alt == LITERAL); return validate(e->u.literal); }
C
#include <iostream> #include <string> using namespace std; bool map[1001][1001]; int main() { int i, j, len, max; string str; getline(cin, str); len = str.length(); max = 1; for (j = 0; j < len; j++){ for (i = 0; i <= j; i++){ if (j - i < 2) map[i][j] = (str[i] == str[j]); else map[i][j] = (str[i] == str[j] && map[i + 1][j - 1]); if (map[i][j] && max < j - i + 1) max = j - i + 1; } } printf("%d\n", max); return 0; }
C
#ifndef LIB_H #define LIB_H /// <summary> /// Contains a series of functions as part of a library which is used /// by the driver program to accomplish the program goal. Some of the /// functions in this library includes file reading, parsing, and /// data structures. /// </summary> /// /// <author>Oliver Spryn</author> /// <date>2014-11-15</date> /// <project>On Screen Keyboard</project> #include "../header/constants.h" #include <ctype.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> /// /// Data structures /// ---------------------------------------- /// typedef struct Position { int x; int y; } Position; /// /// File reading /// ---------------------------------------- /// void openFile(FILE **fp, int argc, char **argv); void promptForFile(char *path); /// /// Parsing and calculations /// ---------------------------------------- /// void calculatePosition(int *ascii, int length, FILE *outStream); void lineToASCII(char *line, int *ascii, int *length); #endif
C
#pragma once #include <stdlib.h> #include "vec3.h" #define M_PI 3.1415927 double drand() { return (double)rand() / RAND_MAX; } vec3 random_in_unit_sphere() { vec3 p; do { p = 2.0 * vec3(drand(), drand(), drand()) - vec3(1.0, 1.0, 1.0); } while (p.sqrt_length() >= 1.0); return p; } vec3 random_in_unit_disk() { vec3 p; do { p = 2.0 * vec3(drand(), drand(), 0) - vec3(1, 1, 0); } while (dot(p, p) >= 1.0); return p; } double schlick(double cosine, double ref_idx) { double r0 = (1 - ref_idx) / (1 + ref_idx); r0 = r0 * r0; return r0 + (1 - r0)*pow((1 - cosine), 5); } vec3 reflect(const vec3& v, const vec3& n) { return v - 2 * dot(v, n)*n; } bool refract(const vec3& v, const vec3& n, double ni_over_nt, vec3& refracted) { vec3 uv = unit_vector(v); double dt = dot(uv, n); double discriminant = 1.0 - ni_over_nt * ni_over_nt*(1 - dt * dt); if (discriminant > 0) { refracted = ni_over_nt * (uv - n * dt) - n * sqrt(discriminant); return true; } else { return false; } }
C
#include <stdio.h> // This code demonstrates how getchar() works. // Point out another way of writing while-statements int main() { char in; while((in = getchar())!='Q') printf("%c", in); return 0; }
C
/* file: tokens.c Written by Anthony V. Edwards, TAVVE Software Co. This file contains the routine TOKENIZE that may be useful for various applications =Tokenize (var token_string: tline; pattern: tline; var tokens: StrPtrArr): byte; The value returned from Tokenize is the number of tokens found. =TokenStr (raw: TokPtr): tline; The value returned from TokenStr is the constructed token string. =Parse (var token_string: tline; var tokens: StrPtrArr; delim: char): byte; The value returned from Parse is the number of tokens found. =GetToken (token_string: tline; delim: tline): tline; The value returned is the characters in token_string up to (not incl.) the delimeter specified. =GetAlphaToken (token_string: tline): tline; Returns the leading alphabetical characters of token_string. =GetDigitToken (token_string: tline): tline; Returns the leading digits of token_string allowed in a number. =GetAlphaNumToken (token_string: tline): tline; Returns the leading characters of token_string that are alphanumeric. */ /* xon: tok.000 */ /* xtoc: #Tokenizing routines */ /* xpage */ /* TOKENIZING ROUTINES How to use Tokenize: The reason why token_string is passed by reference (var) is to prevent it from being the result of a function. Part of Tokenize's output, tokens, has pointers that point to parts of token_string. So, DO NOT CHANGE TOKEN_STRING UNTIL YOU ARE DONE WITH TOKENS. The pattern may contain any characters, with two characters being hot or special characters. By default, '*' is the wildcard variable. It means 0+ characters. You can force it to wildcard a minimum number of characters by putting a '?' per character preceding *. Example: ???* means 3 or more characters. The '?' symbol itself may be used to single out a token that has an expected length. For example, if you expect a token to be 5 long, use ????? . Note: although you may want to tokenize two tokens next to each other that are both 5 long, using ?????????? will make a token 10 characters long. It is up to you to subdivide (use COPY). All other symbols are taken to be distinct patterns and will be clustered together. Note that if the pattern was not found, Tokenize will terminate, putting all remaining text into the last token. */ /* xoff */ #include "tokP.h" #define onechar '?' #define anychar '*' extern char *strfn_nada; /* a little cheating... */ #define AddToken(pos,length) { \ if (length>0) { \ (tokens+no_tokens)->StrPtr= pos; \ (tokens+no_tokens)->len= length; \ no_tokens++; \ } \ } /* xon: tok.010 */ /* xtoc: tok_tokenize() */ int tok_tokenize (token_string, pattern, tokens) char *token_string; /* INPUT: string to be tokenized */ char *pattern; /* INPUT: general pattern of tokens */ struct TokPtr *tokens; /* OUTPUT: the tokens */ /* This routine returns the number of tokens that it created. */ /* xoff */ { char curr_patt[100]; int i, j, no_tokens= 0, tspos= 0, tslen, papos= 0, plen, cpos= 0, done= FALSE; /* TOKENIZE */ /* initialize everything */ tslen= strlen(token_string); plen= strlen(pattern); #define iswild(char) (char==onechar || char==anychar) /* grand loop to cycle through token_string */ do { /* fetch *, n?, or delimeter */ strcpy (curr_patt, ""); cpos= 0; if (iswild(pattern[papos])) { /* wild-card pattern next */ while (iswild(pattern[papos]) && papos<plen) curr_patt[cpos++]= pattern[papos++]; curr_patt[cpos]= '\0'; if (str_chrpos(anychar, curr_patt)>=0) { /* find terminating pattern to find next token */ j= cpos-1; /* the number of ?'s */ strcpy (curr_patt, ""); cpos= 0; /* figure out what the terminating text is */ while (! (iswild(pattern[papos]) && papos<plen)) curr_patt[cpos++]= pattern[papos++]; curr_patt[cpos]= '\0'; /* where is the terminating text? */ i= str_instr(curr_patt, token_string+tspos+j-1); /* i contains length of string that matched the wild card *, but does not include the n?'s (which is j) */ if (cpos==0 || i<0) done= TRUE; else { /* the wildcard part */ AddToken (token_string+tspos, i+j); /* the terminating string part */ AddToken (token_string+tspos+i+j, cpos); /* update current character position */ tspos += cpos+i+j; } } else { /* pattern is next n characters */ i= cpos; if (tspos+i-1>tslen) AddToken (token_string+tspos, tslen-tspos+1) else AddToken (token_string+tspos, strlen(curr_patt)); tspos++; } } else { /* match expected delimeter */ while (! (iswild(pattern[papos]) && papos<plen)) curr_patt[cpos++]= pattern[papos++]; curr_patt[cpos]= '\0'; if (cpos==0 || strcmp (str_left(token_string+tspos,cpos), curr_patt)) done= TRUE; else { AddToken (token_string+tspos, cpos); tspos += cpos; } } if (papos>=plen) papos= 0; } while (!(tspos>tslen || done)); if (tspos<=tslen) AddToken (token_string+tspos, tslen-tspos+1); return (no_tokens); } /* xon: tok.020 */ /* xtoc: tok_TokenStr() */ char * tok_token_str (raw) struct TokPtr *raw; /* INPUT: token description */ /* xoff */ { char *a; a= str_left (raw->StrPtr, raw->len); return (a); } /* xon: tok.030 */ /* xtoc: tok_Parse() */ int tok_parse (token_string, tokens, delim) char *token_string; /* INPUT: the string to be tokenized */ struct TokPtr *tokens; /* OUTPUT: the tokens */ int delim; /* INPUT: the delimiter between tokens */ /* This routine is a simplification of the tok_Tokenize routine. The input string is assumed to be a series of tokens separated by one or more delimeters. */ /* xoff */ { int lpos= 0, p, nt= 0; do { p= str_chrpos (delim, token_string+lpos); if (p>0) { (tokens+nt)->StrPtr= token_string+lpos; (tokens+nt)->len= p; nt++; lpos += p+1; } else if (p==0) lpos++; } while (p>=0); if (lpos+1<(p=strlen(token_string))) { /* more text on line */ (tokens+nt)->StrPtr= token_string+lpos; (tokens+nt)->len= p-lpos; nt++; } return (nt); } /* xon: tok.040 */ /* xtoc: tok_GetToken() */ char * tok_get_token (token_string, delim) char *token_string; /* INPUT: string in question */ char *delim; /* INPUT: token delimeter */ /* Return the first token in /token_string/. Return all characters up to the first occurrance of /delim/. */ /* xoff */ { int p; p= str_instr (delim, token_string); if (p>=0) return (str_midstr (token_string, 0, p)); else return (strfn_nada); } /* xon: tok.050 */ /* xtoc: tok_GetAlphaToken() */ char * tok_get_alpha_token (token_string) char *token_string; /* INPUT: string in question */ /* Return the first string of alphabetical characters, including '_'. */ /* xoff */ { int l, i= 0; l= strlen (token_string); while (i<l && (isalpha(token_string[i]) || token_string[i]=='_')) i++; return (str_midstr (token_string, 0, i)); } /* xon: tok.050 */ /* xtoc: tok_GetDigitToken() */ char * tok_get_digit_token (token_string) char *token_string; /* INPUT: string in question */ /* Return the first string of numeric characters. A + or a - may appear as the first character. */ /* xoff */ { int l,i= 0; l= strlen (token_string); if ((token_string[0]=='-' || token_string[0]=='+') && l>1) i++; while (i<l && isdigit(token_string[i])) i++; return (str_midstr (token_string, 0, i)); } /* xon: tok.060 */ /* xtoc: tok_GetAlphaNumToken() */ char * tok_get_alphanum_token (token_string) char *token_string; /* INPUT: string in question */ /* Return the first string of alphanumeric characters. Note that a + or a - may not be the first character, however _ is still considered an alphabetical character. */ /* xoff */ { int l,i= 0; l= strlen (token_string); while (i<l && (isalnum(token_string[i]) || token_string[i]=='_')) i++; return (str_midstr (token_string, 0, i)); }
C
#include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include "shm.h" main() { int shmid; char * ptr, *pData; int * pInt; if ((shmid = shmget(SHM_KEY, SHM_SIZE, SHM_MODE)) < 0) { perror("shmget"); exit(1); } if ((ptr = shmat(shmid, 0, 0)) == (void * ) - 1) { perror("shmat"); exit(1); } pInt = (int *)ptr; // shared Memory의 모든 값은 처음에 0으로 initialized 되있음. while ((*pInt) == 0) // Busy waiting (Spin lock): cpu를 계속 소비해가면서 wait함. ; // sipc2에서 *pInt에다가 1이라고 써서, while문에서 빠져나올 수 있음. // single cpu core라면, cpu가 번갈아가면서 sipc1, sipc2를 수행함. sipc1를 수행하다가, while문 계속 돌다가 Timer Interrupt걸리게 되서 운영체제가 수행되어 scheduling을 통해 sipc2가 수행되게 되는데, 거기서 pInt값 바꾸고, 다시 sipc1이 실행되게 되서 while문에서 벗어날 수 있음. // multi cpu core라면, cpu한개당 sipc1, sipc2를 각각 수행하게 되므로, sipc1이 while문 돌다가 바로 풀림. pData = ptr + sizeof(int); // 처음 4byte만큼은 int로 쓰고, 다음부터는 string으로 씀. printf("Received request: %s......", pData); sprintf(pData, "This is a reply from %d.", getpid()); *pInt = 0; printf("Replied.\n"); sleep(1); // 바로 shmctl해버리면 sicp2에서 shared memory를 사용하지 못하므로 sleep(1)함. printf("shared memory ptr : %x\n ", ptr); if (shmctl(shmid, IPC_RMID, 0) < 0) { perror("shmctl"); exit(1); } }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <error.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> // truct sockaddr_in { // sa_family_t sin_family; /* address family: AF_INET */ // in_port_t sin_port; /* port in network byte order */ // struct in_addr sin_addr; /* internet address */ // }; // struct in_addr { // uint32_t s_addr; /* address in network byte order */ // }; int main(void) { unsigned sockfd = socket(AF_INET, SOCK_STREAM, 0); if (-1 == sockfd) { perror("socket failed."); exit(-1); } struct sockaddr_in addr; addr.sin_family = AF_INET; addr.sin_port = htons(8001); addr.sin_addr.s_addr = inet_addr("192.168.1.113"); if (-1 == bind(sockfd, (struct sockaddr *)&addr,sizeof(addr))) { perror("socket bind failed."); exit(-1); } if (-1 == listen(sockfd, SOMAXCONN)) { //被动socket perror("socket listen failed."); exit(-1); } struct sockaddr_in connsockaddr; socklen_t connsockaddrlen = sizeof(connsockaddr); int connsockfd = accept(sockfd, (struct sockaddr *)&connsockaddr, &connsockaddrlen); if (-1 == connsockfd) { perror("socket accept failed."); exit(-1); } printf("peer socket ipaddress: %s, port is %d.\n", inet_ntoa(connsockaddr.sin_addr), ntohs(connsockaddr.sin_port)); char recbuf[1024] = {0}; while (1) { ssize_t reclen = read(connsockfd, recbuf, sizeof(recbuf)); if (-1 == reclen) { perror("socket read failed."); exit(-1); } ssize_t sendlen = write(connsockfd, recbuf, strlen(recbuf)); if (-1 == sendlen) { perror("socket write failed."); exit(-1); } fputs(recbuf, stdout); memset(recbuf, 0, sizeof(recbuf)); } close(connsockfd); close(sockfd); 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*/ u8 ; typedef int u32 ; struct os_time {int sec; int usec; } ; typedef scalar_t__ be32 ; /* Variables and functions */ scalar_t__ host_to_be32 (int) ; int /*<<< orphan*/ os_get_time (struct os_time*) ; int /*<<< orphan*/ os_memcpy (int /*<<< orphan*/ *,int /*<<< orphan*/ *,int) ; void wpa_get_ntp_timestamp(u8 *buf) { struct os_time now; u32 sec, usec; be32 tmp; /* 64-bit NTP timestamp (time from 1900-01-01 00:00:00) */ os_get_time(&now); sec = now.sec + 2208988800U; /* Epoch to 1900 */ /* Estimate 2^32/10^6 = 4295 - 1/32 - 1/512 */ usec = now.usec; usec = 4295 * usec - (usec >> 5) - (usec >> 9); tmp = host_to_be32(sec); os_memcpy(buf, (u8 *) &tmp, 4); tmp = host_to_be32(usec); os_memcpy(buf + 4, (u8 *) &tmp, 4); }
C
/* Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be: 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms. */ #include <stdio.h> #define MAX 4000000 int main(){ unsigned long a = 1; unsigned long b = 2; unsigned long fib = 0; // sum initialized because the first 3 values (1, 1, 2) are fixed unsigned long sum = 2; unsigned char i = 4; while(a+b < MAX){ fib = a + b; a = b; b = fib; // if result is even if(fib%2 == 0){ sum += fib; } printf("%d: value:%lu / sum:%lu\n",i, fib, sum); i++; } printf("\nRESULT: %lu\n", sum); return 0; }
C
/* ============================================================================ Name : kmeans.c Author : Noy Shabtay Version : 1.0 Copyright : Your copyright notice Description : Kmeans clustering algorithm implementation. ============================================================================ */ #define PY_SSIZE_T_CLEAN #include <Python.h> int k; int n; int d; int max_iter; static PyObject* kmeans_runner(PyObject*, PyObject*); static void kmeans(double**, double**); static void copy_centroids(double**, double**); static double squared_distance(int, int, double**, double**); static void update_centroids(double**, int*, double**); static int compare_centroids(double**, double**); static void print_centroids(double**); static PyObject* kmeans_runner(PyObject* self, PyObject* args) { int i; int j; int index; double **observations; double **centroids; long *indices; PyObject* py_observations; PyObject* py_indices; PyObject* py_item; PyObject* py_dim; if (!PyArg_ParseTuple(args, "iiiiOO:kmeans_runner", &k, &n, &d, &max_iter, &py_indices, &py_observations)) { return NULL; } observations = (double**)malloc(n*sizeof(double*)); assert(observations != NULL); for(i=0; i<n; i++){ observations[i] = (double*)malloc(d*sizeof(double)); assert(observations[i] != NULL); } centroids = (double**)malloc(k*sizeof(double*)); assert(centroids != NULL); for(j=0; j<k; j++){ centroids[j] = (double*)malloc(d*sizeof(double)); assert(centroids[j] != NULL); } for (i = 0; i < n; i++) { py_item = PyList_GetItem(py_observations, i); for (j = 0; j < d; j++) { py_dim = PyList_GetItem(py_item, j); observations[i][j] = PyFloat_AsDouble(py_dim); } } indices = (long*)malloc(k * sizeof(long)); for (i = 0; i < k; i++) { py_item = PyList_GetItem(py_indices, i); indices[i] = PyLong_AsLong(py_item); } for (j = 0; j < k; j++) { index = indices[j]; for (i = 0; i < d; i++) { centroids[j][i] = observations[index][i]; } } kmeans(observations, centroids); for(j=0; j<k; j++){ free(centroids[j]); } free(centroids); for(i=0; i<n; i++){ free(observations[i]); } free(observations); Py_RETURN_NONE; } static void kmeans(double** observations, double** centroids) { int i; int j; int obs; int iter; int* clusters_size; double min_d; int min_cluster; double **prev_centroids; double **clusters_sum; double distance; prev_centroids = (double**)malloc(k*sizeof(double*)); assert(prev_centroids != NULL); for(j=0; j<k; j++){ prev_centroids[j] = (double*)malloc(d*sizeof(double)); assert(prev_centroids[j] != NULL); } for(iter=0; iter<max_iter; iter++) { clusters_size = calloc(k, sizeof(int)); assert(clusters_size != NULL); clusters_sum = (double**)calloc(k, sizeof(double*)); assert(clusters_sum != NULL); for(j=0; j<k; j++){ clusters_sum[j] = (double*)calloc(d, sizeof(double)); assert(clusters_sum[j] != NULL); } copy_centroids(centroids ,prev_centroids); for(obs=0; obs<n; obs++){ min_d = 1.0 / 0.0; min_cluster = -1; for(j=0; j<k; j++) { distance = squared_distance(j, obs, observations, centroids); if (distance < min_d) { min_d = distance; min_cluster = j; } } clusters_size[min_cluster]++; for (i=0; i<d; i++) { clusters_sum[min_cluster][i] += observations[obs][i]; } } update_centroids(centroids, clusters_size, clusters_sum); for(j=0; j<k; j++){ free(clusters_sum[j]); } free(clusters_sum); free(clusters_size); if (compare_centroids(prev_centroids, centroids)) { break; } } print_centroids(centroids); for(j=0; j<k; j++){ free(prev_centroids[j]); } free(prev_centroids); } static void copy_centroids(double** centroids ,double** prev_centroids) { int i; int j; for(j=0; j<k; j++) { for(i=0; i<d; i++) { prev_centroids[j][i] = centroids[j][i]; } } } static double squared_distance(int j, int obs, double** observations, double** centroids) { int i; double sum_of_squares = 0; double tmp; for(i=0; i<d; i++) { tmp = observations[obs][i]-centroids[j][i]; sum_of_squares += tmp*tmp; } return sum_of_squares; } static void update_centroids(double** centroids, int* clusters_size, double** clusters_sum) { int i; int j; for(j=0; j<k; j++) { for(i=0; i<d; i++) { centroids[j][i] = (clusters_sum[j][i] / clusters_size[j]); } } } static int compare_centroids(double** prev_centroids, double** centroids) { int i; int j; for(j=0; j<k; j++) { for(i=0; i<d; i++) { if (prev_centroids[j][i] != centroids[j][i]) { return 0; } } } return 1; } static void print_centroids(double** centroids) { int i; int j; for (j=0; j<k; j++) { for (i=0; i<d; i++) { if (i < d-1) printf("%lf,", centroids[j][i]); else printf("%lf", centroids[j][i]); } printf("\n"); } } static PyMethodDef kmeansMethods[] = { {"kmeans_runner", (PyCFunction)kmeans_runner, METH_VARARGS, PyDoc_STR("A C Kmeans implementation")}, {NULL, NULL, 0, NULL} }; static struct PyModuleDef moduledef = { PyModuleDef_HEAD_INIT, "mykmeanssp", NULL, -1, kmeansMethods }; PyMODINIT_FUNC PyInit_mykmeanssp(void) { return PyModule_Create(&moduledef); }
C
#include<stdio.h> #include<windows.h> #include<stdlib.h> #include<string.h> int CompInt(const void* x, const void* y){ int* n1 = (int*)(x); int* n2 = (int*)(y); if (*n1 > *n2){ return 1; } else if (*n1 < *n2){ return -1; } else{ return 0; } } void PrintArr(int arr[], int size){ for (int i = 0; i < size; i++){ printf("%d\n", arr[i]); } printf("\n"); } PrintStr(char* str[], int num){ for (int i = 0; i < num; i++){ printf("%s\n", str[i]); } printf("\n"); } int CompStr(const void* x, const void* y){ char* s1 = *(char**)(x); char* s2 = *(char**)(y); return strcmp(s1, s2); } int main() { /* ǿָշ */ char* c[] = { "ENTER", "NEW", "POINT", "FIRST" }; char** cp[] = { c + 3, c + 2, c + 1, c }; char*** cpp = cp; printf("%s\n", **++cpp); printf("%s\n", *--*++cpp + 3); printf("%s\n", *cpp[-2] + 3); printf("%s\n", cpp[-1][-1] + 1); system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #include "FloydWarshall.h" #include "BFS.h" #include "BetweennessCentrality.h" #include "RandomGraph.h" int main(void) { printf("\n-------------------------------------------------------------------------------------------------" "\nTESTING BOTH BFS AND FW METHODS on GRAPHS OF SIZES:100, 200, 500, 1000, 2000, 5000, 10000, 20000" "\n-------------------------------------------------------------------------------------------------\n"); processedGraph* pg; float* betweenness_array; clock_t t; double time_taken; float prob; graph* randomGraph; int graph_sizes[] = {100, 200, 500, 1000, 2000}; //in case you are testing, 5k FW, 10k and 20k will lead to long waiting time. //int graph_sizes[] = {100, 200, 500, 1000, 2000, 5000,10000,20000}; for (int i = 0; i < sizeof(graph_sizes) / sizeof(int); ++i) { int graph_size = graph_sizes[i]; t = clock(); prob = log(graph_size) / graph_size; printf("\n------------------\nDOING TESTS ON RANDOM GRAPHS OF SIZE %d, with %f%% PROBABILITY OF EDGE\n------------------\n",graph_sizes[i],prob*100); randomGraph = random_connected_graph_generator(graph_size, prob); double time_taken = ((double) (clock() - t)) / CLOCKS_PER_SEC; // in seconds printf("Finished generating graph. Time Taken : %f\n", time_taken); t = clock(); printf("Going to run floydWarshall on graph of %d nodes\n",graph_size); pg = processGraphFWLowMem(randomGraph); time_taken = ((double) (clock() - t)) / CLOCKS_PER_SEC; // in seconds printf("Finished Floyd Warshall on %d nodes. Time Taken : %f\n", graph_size, time_taken); t = clock(); printf("Betweenness Centrality Values from FLoyd Warshall Method\n"); betweenness_array = betweenness_centralityLowMem(pg); print_betweenness(betweenness_array, graph_size); time_taken = ((double) (clock() - t)) / CLOCKS_PER_SEC; // in seconds printf("Finished Betweenness Centrality on %d nodes. Time Taken : %f", graph_size, time_taken); freeProcessedGraphwithoutGraph(pg); free(betweenness_array); t = clock(); printf("Going to run BFS on graph of size %d\n",graph_size); pg = processGraphBFS(randomGraph); time_taken = ((double) (clock() - t)) / CLOCKS_PER_SEC; // in seconds printf("Finished BFS to find nodes array on %d nodes. Time Taken : %f\n", graph_size, time_taken); t = clock(); printf("Betweenness Centrality Values from BFS Method\n"); betweenness_array = betweenness_centrality(pg); print_betweenness(betweenness_array, graph_size); time_taken = ((double) (clock() - t)) / CLOCKS_PER_SEC; // in seconds printf("Finished Betweenness Centrality on %d nodes. Time Taken : %f", graph_size, time_taken); freeProcessedGraph(pg); free(betweenness_array); } }
C
#include<stdio.h> int main() { int a,b,x,y,temp,ans; scanf("%d %d",&a,&b); x=a;y=b; while(x!=0) { temp=x; x=x%y; y=temp; } ans=(a*b)/y; printf("%d",ans); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "parser.c" // Polymorphism in C typedef struct Pixel{ unsigned int r; //create a pixel struct like discussed in class unsigned int g; unsigned int b; }Pixel; typedef struct Image{ //image struct that keeps track of the data in the input file int width; int height; int color; unsigned char *data; } Image; Image* RayCasting(char*, int, int, Object**); int writeImage(char*, char*, Image*); int main(int argc, char **argv) { if(argc > 5){ fprintf(stderr, "Error: Too many arguments!\n"); return(1); } char *width = argv[1]; char *height = argv[2]; char *inputFilename = argv[3]; char *outputFilename = argv[4]; Object** objects = malloc(sizeof(Object*) * 128); int w = atoi(width); int h = atoi(height); if(w<=0){ fprintf(stderr, "Error: width has to be a positive number!\n"); return 1; } if(h<=0){ fprintf(stderr, "Error: height has to be a positive number!\n"); return 1; } read_scene(inputFilename, objects); Image* buffer = RayCasting(inputFilename, w, h, objects); buffer->width = w; buffer->height = h; writeImage("P3", outputFilename, buffer); return 0; } static inline double sqr(double v) { return v*v; } static inline void normalize(double* v) { double len = sqrt(sqr(v[0]) + sqr(v[1]) + sqr(v[2])); v[0] /= len; v[1] /= len; v[2] /= len; } double sphere_intersection(double* Ro, double* Rd, double* Center, double r){ double a = sqr(Rd[0]) + sqr(Rd[1]) + sqr(Rd[2]); double b = 2*(Ro[0]*Rd[0] + Ro[1]*Rd[1] + Ro[2]*Rd[2] - Rd[0]*Center[0] - Rd[1]*Center[1] - Rd[2]*Center[2]); double c = sqr(Ro[0]) + sqr(Ro[1]) + sqr(Ro[2]) + sqr(Center[0]) + sqr(Center[1]) + sqr(Center[2]) - 2*(Ro[0]*Center[0] + Ro[1]*Center[1] + Ro[2]*Center[2]) - sqr(r); double d = sqr(b) - 4*a*c; if(d < 0){ return -1; } d = sqrt(d); double t1 = (-b - d) / (2 * a); double t2 = (-b + d) / (2 * a); if(t1 > 0){ return t1; } if(t2 > 0){ return t2; } return -1; } double planeIntersection(double* Ro, double* Rd, double* position, double* normal){ double t = - (normal[0]*Ro[0] + normal[1]*Ro[1] + normal[2]*Ro[2] - normal[0]*position[0] - normal[1]*position[1] - normal[2]*position[2]) / (normal[0]*Rd[0] + normal[1]*Rd[1] + normal[2]*Rd[2]); if (t > 0){ return t; } return -1; } int writeData(char ppmnum, FILE *outputFile, Image* buffer){ if(ppmnum == '6'){ fwrite(buffer->data, sizeof(Pixel), buffer->width*buffer->height, outputFile); printf("File saved successfully!\n"); return(0); } else if(ppmnum == '3'){ int i, j; for(i=0; i<buffer->height; i++){ for(j=0; j<buffer->width; j++){ fprintf(outputFile, "%d %d %d ", buffer->data[i*buffer->width*3+j*3], buffer->data[i*buffer->width*3+j*3+1], buffer->data[i*buffer->width*3+2]); } fprintf(outputFile, "\n"); } printf("The file saved successfully!\n"); return(0); } else{ fprintf(stderr, "Error: incorrect ppm version\n"); return(1); } } int writeImage(char* outnumber, char* outputFilename, Image* buffer){ int width = buffer->width; int height = buffer->height; char ppmNum = outnumber[1]; FILE *fh = fopen(outputFilename, "wb"); if(fh == NULL){ fprintf(stderr, "Error: cannot open the file\n"); return(1); } char *comment = "# output.ppm"; fprintf(fh, "P%c\n%s\n%d %d\n%d\n", ppmNum, comment, width, height, 255); writeData(ppmNum, fh, buffer); fclose(fh); return(0); } int intersect(double* Rd, int objectNum, Object** objects){ int closestObjectNum = -1; double closest_t = INFINITY; int i; double t; double Ro[3] = {0, 0, 0}; for(i=0; i<objectNum; i++){ if(objects[i]->type==1){ t=sphere_intersection(Ro, Rd, objects[i]->sphere.position, objects[i]->sphere.radius); if(t){ if(t>0 && t<=closest_t){ closest_t=t; closestObjectNum=i; } } else{ fprintf(stderr, "Error: cannot find distance\n"); return(1); } } else if(objects[i]->type == 2){ t=planeIntersection(Ro, Rd, objects[i]->plane.position, objects[i]->plane.normal); if(t){ if(t>0 && t<=closest_t){ closest_t=t; closestObjectNum=i; } } else{ fprintf(stderr, "Error: cannot find distance\n"); return (1); } } } return closestObjectNum; } Image* RayCasting(char* filename, int w, int h, Object** objects){ Image* buffer = (Image*)malloc(sizeof(Image)); if(objects[0] == NULL){ fprintf(stderr, "Error: no object found"); exit(1); } int cameraFound = 0; double width; double height; int i; for(i=0; objects[i] != 0; i+=1){ if(objects[i]->type==0){ cameraFound=1; width=objects[i]->camera.width; height=objects[i]->camera.height; if(width<=0 || height<=0){ fprintf(stderr, "Error: invalid size for camera/n"); exit(1); } } } if(cameraFound==0){ fprintf(stderr, "Error: Camera is not found\n"); exit(1); } buffer->data = (unsigned char*)malloc(w*h*sizeof(Pixel)); Pixel *pixel = (Pixel*)malloc(sizeof(Pixel)); if(buffer->data==NULL || buffer==NULL){ fprintf(stderr, "Error: cannot allocate memory\n"); exit(1); } double pixwidth = width/w; double pixheight = height / h; int j, k; for(k=0; k<h; k++){ int count = (h-k-1)*w*3; double vy = -height/2 + pixheight * (k+0.5); for(j=0; j<h; j++){ double vx = -width/2+pixwidth*(j+0.5); double Rd[3] = {vx, vy, 1}; normalize(Rd); int intersection = intersect(Rd, i, objects); if(intersection>=0){ pixel->r = (int)((objects[intersection]->color[0])*255); pixel->g = (int)((objects[intersection]->color[1])*255); pixel->b = (int)((objects[intersection]->color[2])*255); } else{ pixel->r = 0; pixel->g = 0; pixel->b = 0; } buffer->data[count++] = pixel->r; buffer->data[count++] = pixel->g; buffer->data[count++] = pixel->b; } } return buffer; }
C
/* ID: zeyuec1 LANG: C TASK: beads */ #include <stdio.h> #include <stdlib.h> #include <string.h> int N; int necklace[2000]; int isEqual(int next, int* now) { if (*now == 0) { *now = next; return 1; } if (next == *now || next == 0) { return 1; } return 0; } int cal() { int st = N, end = N+N-1, max = 1; int p, i, j; for (p = st; p<=end; p++) { i = p; j = p+1; int color = necklace[p]; while ((isEqual(necklace[i-1], &color) == 1 || necklace[i-1] == 0) && (p-(i-1)+1) <= N) { i--; } if ((p-i+1) == N) { return N; } color = necklace[p+1]; while ((isEqual(necklace[j+1], &color) == 1 || necklace[j+1] == 0) && (j+1-i+1) <= N) { j++; } if (j-i+1 > max) { max = j-i+1; } } return max; } int main() { freopen("beads.in", "r", stdin); freopen("beads.out", "w", stdout); int i, flag; char bread; scanf("%d\n", &N); for (i=0; i<N; i++) { scanf("%c", &bread); if (bread == 'w') { flag = 0; } if (bread == 'r') { flag = 1; } if (bread == 'b') { flag = 2; } necklace[i] = flag; necklace[i+N] = flag; necklace[i+N+N] = flag; } int ret = cal(); printf("%d\n", ret); return 0; }
C
#include <stdio.h> int N; int end; void f(int n, int board[]) { if (end == 1) { return; } if (n == N) { // end int i; for (i = 1; i < N; i++) { printf("%d", board[i]); } end = 1; } if (n == 1) { board[1] = 1; f(2, board); return; } // 1~3 üũ int num; // Ȯ int tmp_position; int pos; int check_position = n / 2; for (num = 1; num < 4; num++) { board[n] = num; for (tmp_position = 1; tmp_position < check_position + 1; tmp_position++) { // tmp_position == 1 // board[n] = board[n - 1] //tmp_position == 2 // board[n] = board[n - 2] // board[n - 1] = board[n - 3] //tmp_position == 3 // board[n] = board[n - 3] // board[n - 1] = board[n - 4] // board[n - 2] = board[n - 5] for (pos = 0; pos < tmp_position; pos++) { //printf("board[%d] = %d, board[%d] = %d\n", n- pos,board[n- pos],n - tmp_position - pos,board[n- tmp_position-pos] ); if (board[n - pos] != board[n - tmp_position - pos]) { break; } } if (pos == tmp_position) { break; } } if (tmp_position == check_position + 1) { f(n+1, board); } } } int main() { scanf("%d", &N); N++; end = 0; int board[81] = {1, }; f(1, board); return 1; }
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 scalar_t__ WCHAR ; typedef int DWORD ; typedef int /*<<< orphan*/ BOOL ; /* Variables and functions */ int ERROR_INVALID_PARAMETER ; int ERROR_SUCCESS ; int ICU_DECODE ; int ICU_ESCAPE ; int /*<<< orphan*/ TRUE ; int /*<<< orphan*/ memcpy (scalar_t__*,scalar_t__*,int) ; __attribute__((used)) static DWORD set_component( WCHAR **str, DWORD *str_len, WCHAR *value, DWORD len, DWORD flags, BOOL *overflow ) { if (*str && !*str_len) return ERROR_INVALID_PARAMETER; if (!*str_len) return ERROR_SUCCESS; if (!*str) { if (len && *str_len && (flags & (ICU_DECODE|ICU_ESCAPE))) return ERROR_INVALID_PARAMETER; *str = value; *str_len = len; } else { if (len >= *str_len) { *str_len = len+1; *overflow = TRUE; return ERROR_SUCCESS; } memcpy( *str, value, len * sizeof(WCHAR) ); (*str)[len] = 0; *str_len = len; } return ERROR_SUCCESS; }
C
/* * Host Dispatcher Shell Project for SOFE 3950U / CSCI 3020U: Operating Systems * * Copyright (C) 2015, Zeerak Ali Sachin Teckchandani Amal Parameswaran Mohtasim Siddiqui * All rights reserved. * */ #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <unistd.h> #include <signal.h> #include <sys/types.h> #include <sys/wait.h> #include "queue.h" #include "utility.h" #include "hostd.h" // Put macros or constants here using #define #define MEMORY 1024 // Put global environment variables here int indx; proc prcess; node_t *queue; node_t *dispatch_queue; node_t *real_time, priority_1, priority_2, priority_3; int dispatch_time = 0; // Define functions declared in hostd.h here int main(int argc, char *argv[]) { //set up resources resources resources; for (int i = 0; i < MEMORY; i++){ resources.mbytes[i] = 0; } resources.scanners = 1; resources.printers = 2; resources.modems = 1; resources.cds = 2; // ==================== YOUR CODE HERE ==================== // FILE file = "dispatchlist.txt"; node_t *cur_node; // Load the dispatchlist load_dispatch(file, queue); char *chars[256] = {0}; chars[0] = "./prcess"; // Add each prcess structure instance to the job dispatch list queue // Iterate through each item in the job dispatch list, add each prcess // to the appropriate queues cur_node = queue; while (cur_node != NULL){ //depending on priority value, push the respective prcess if ((cur_node -> p).arrival_time == dispatch_time){ if ((cur_node -> p).priority == 0) push(real_time, cur_node -> p); if ((cur_node -> p).priority == 1) push(priority_1, cur_node -> p); if ((cur_node -> p).priority == 2) push(priority_2, cur_node -> p); if ((cur_node -> p).priority == 3) push(priority_3, cur_node -> p); dispatch_time = dispatch_time + 1; } while (cur_node != NULL){ if (real_time != NULL){ indx = alloc_mem(res, (real_time -> p).mbytes); pid_t pid = fork(); if (pid == 0) execvp (chars[0], chars); else waitpid(pid, 0, 0); free_mem(res, indx, (real_time->p).mbytes); } } while(priority_1 != NULL){ indx.alloc_mem(res, priority_1->p).mbytes); pid_t pid = fork(); pop(priority_1); push(priority_2, prcess); // Run the prcesses for a second //Run the prcesses until the end if (pid == 0){ signal(SIGINT, SIG_DFL); signal(SIGCONT, SIG_DFL); signal(SIGSTP, SIG_DFL); execvp(chars[0], chars); } else if (pid != 0){ kill(pid,SIGINT); kill(pid,SIGCONT); kill(pid,SIGTSTP); waitpid(pid, 0, 0); } //after it is done, remove from queue and start the next push(priority_2, priority_1->p); free_mem(res, indx, (priority_1->p).mbytes); priority_1 = priority_1->next; } while(priority_2 != NULL){ indx.alloc_mem(res, priority_2->p).mbytes); pid_t pid = fork(); pop(priority_2); push(priority_2, prcess); //run prcess for 1 second if (pid == 0){ signal(SIGINT, SIG_DFL); signal(SIGCONT, SIG_DFL); signal(SIGSTP, SIG_DFL); execvp(chars[0], chars); } else if (pid != 0){ kill(pid,SIGINT); kill(pid,SIGCONT); kill(pid,SIGTSTP); waitpid(pid, 0, 0); } //after it is done, remove from queue and start the next push(priority_3, priority_2->p); free_mem(res, indx, (priority_2->p).mbytes); priority_2 = priority_2->next; } while(priority_3 != NULL){ indx.alloc_mem(res, priority_3->p).mbytes); pid_t pid = fork(); pop(priority_3); push(priority_3, prcess); //run prcess for 1 second //run the prcess till it is completed if (pid == 0){ signal(SIGINT, SIG_DFL); signal(SIGCONT, SIG_DFL); signal(SIGSTP, SIG_DFL); execvp(chars[0], chars); } else if (pid != 0){ kill(pid,SIGINT); kill(pid,SIGCONT); kill(pid,SIGTSTP); waitpid(pid, 0, 0); } //after it is done, remove from queue and start the next push(priority_3, priority_3->p); free_mem(res, indx, (priority_3->p).mbytes); priority_3 = priority_3->next; } } cur_node = cur_node->next; real_time = real_time->next; // Allocate the resources for each process before it's executed // Execute the process binary using fork and exec // Perform the appropriate signal handling / resource allocation and de-alloaction // Repeat until all processes have been executed, all queues are empty return EXIT_SUCCESS; } //Tokenize the characters void tokenize_char(char *input, char **tokens){ int cntr = 0; char *token = 0; char delim[1] = ","; char *new_line = strchr(input, "\n"); while (new_line){ *new_line = 0; new_line = strchr(input, "/n"); } token = strtok(input, delim); while (token != NULL){ tokens[cntr] = token; token = strtok(NULL, delim); cntr++; } }
C
#include<stdio.h> int main() { int k,i,j,r=1,c=1,n,a[5][5]; scanf("%d", &n); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d", &a[i][j]); for(i=0;i<n;i++) { if(a[i][0]==0) c=0; if(a[0][i]==0) r=0; } for(i=1;i<n;i++) for(j=1;j<n;j++) { if(a[i][j]==0) a[0][j]=a[i][0]=0; } for(i=0;i<n;i++) if(a[0][i]==0) for(j=0;j<n;j++) a[j][i]=0; for(i=0;i<n;i++) if(a[i][0]==0) for(j=0;j<n;j++) a[i][j]=0; if(r==0) { for(i=0;i<n;i++) a[0][i]=0; } if(c==0) { for(i=0;i<n;i++) a[i][0]=0; } for(i=0;i<n;i++) { for(j=0;j<n;j++) { printf("%d ", a[i][j]); } printf("\n"); } }
C
#include "holberton.h" /** * _strspn - Function that gets the length of a prefix substring. * @s: char *s * @accept: char *accept * * Return: unsigned int */ unsigned int _strspn(char *s, char *accept) { unsigned int i, j, counter; counter = 0, i = 0; while (s[i] != '\0') { if (counter != i) break; j = 0; while (s[j] != '\0') { if (s[i] == accept[j]) counter++; j++; } i++; } return (counter); }
C
#ifndef SPOOLER_SHARED_H #define SPOOLER_SHARED_H #include <stdbool.h> #include "spooler.h" /* * Function that initializes sp with a buffer of the provided size. */ void spool_init_shared(spool_t* sp, size_t size); /* * Function that returns if the buffer is empty. */ bool spool_empty(spool_t* sp); /* * Function that returns if the buffer is full. */ bool spool_full(spool_t* sp); /* * Function that inserts item into sp. It makes no check that there is * room in the buffer because it will be reused in different implementations * that will provide this check. This does not require making a deep copy of * the item. */ void spool_insert_unchecked(spool_t* sp, char* item); /* * Function that removes the least recently added item from sp. * It makes no check that there is data in the buffer because it * will be reused in different implementations that will provide * this check. */ char* spool_remove_unchecked(spool_t* sp); /* * Function that returns the buffer allocated for data in sp. */ char** reveal_buffer(spool_t* sp); #endif
C
#define _POSIX_SOURCE 1 /* = optenir valeur aleatoire = ecrire dans un fichier avec saute de la ligne ('\r') = filtrage des entier depuis char* */ #include<sys/types.h> #include<sys/wait.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include<stdlib.h> #include<stdio.h> #include<time.h> #include<errno.h> #include<string.h> #define SIZE 100 int main(int argc, char* argv[]){ int n,i,t,fd,cpt = 0; n = atoi(argv[1]); char buf[SIZE]; pid_t *pid = malloc(n * sizeof(pid_t)); if((fd = open(argv[2],O_TRUNC | O_CREAT | O_RDWR, 0600)) == -1){ perror("open"); return errno; } for(i=0;i<n;i++){ if((t = fork()) == 0){ srand(time(NULL)*i); int k = (int) (10*(float)rand()/ RAND_MAX); sprintf(buf,"%d",k); strcat(buf,"\r"); write(fd,buf,strlen(buf)); exit(0); } pid[i] = t; } for(i=0;i<n;i++) waitpid(pid[i],NULL,0); lseek(fd,SEEK_SET,0); t = read(fd,buf,SIZE); for(i=0;i<t;i++){ if(buf[i] != '\r') cpt += (buf[i] - 48); } printf("la somme est : %d\n",cpt); close(fd); printf("Fin\n"); return EXIT_SUCCESS; }
C
#ifndef EDIT_DISTANCE_GENERATOR_H #define EDIT_DISTANCE_GENERATOR_H #include <stddef.h> #include <stdbool.h> struct edit_iter_frame; struct edit_iter { const char *pattern; const char *alphabet; char *buffer; char *cigar; char *simplify_cigar_buffer; struct edit_iter_frame *frames; }; struct edit_pattern { const char *pattern; const char *cigar; }; // Do not muck about with the pattern between // creating an iterator and you deallocate it again. // The iterator code will get angry if you do, // and it will take it out on your program. void init_edit_iter( struct edit_iter *iter, const char *pattern, const char *alphabet, int max_edit_distance ); bool next_edit_pattern( struct edit_iter *iter, struct edit_pattern *result ); // This function frees the resources stored in the // iterator structor, not the struct itself. If it is // heap allocated you are responsible for freeing // the structure. void dealloc_edit_iter( struct edit_iter *iter ); #endif
C
#include <stdio.h> int main(void) { int i, j, tmp, total = 0; for (i = 1, j = 1; i < 4000000; ) { if (i % 2 == 0) total += i; tmp = i; i = i + j; j = tmp; } printf("%d\n", total); }
C
// 17 may 2015 #include "../ui.h" #include "uipriv.h" struct typeinfo { const char *name; uintmax_t parent; size_t size; }; static struct ptrArray *types = NULL; uintmax_t uiRegisterType(const char *name, uintmax_t parent, size_t size) { struct typeinfo *ti; if (types == NULL) { types = newPtrArray(); // reserve ID 0 ptrArrayAppend(types, NULL); } // TODO prevent our size from being smaller than our parent's ti = uiNew(struct typeinfo); ti->name = name; ti->parent = parent; ti->size = size; ptrArrayAppend(types, ti); return types->len - 1; } void *uiIsA(void *p, uintmax_t id, int fail) { uiTyped *t; struct typeinfo *ti, *ti2; uintmax_t compareTo; if (id == 0 || id >= types->len) complain("invalid type ID given to uiIsA()"); t = (uiTyped *) p; compareTo = t->Type; if (compareTo == 0) complain("object %p has no type in uiIsA()", t); for (;;) { if (compareTo >= types->len) complain("invalid type ID in uiIsA()", t); if (compareTo == id) return t; ti = ptrArrayIndex(types, struct typeinfo *, compareTo); if (ti->parent == 0) break; compareTo = ti->parent; } if (fail) { ti = ptrArrayIndex(types, struct typeinfo *, id); ti2 = ptrArrayIndex(types, struct typeinfo *, t->Type); complain("object %p not a %s in uiIsA() (is a %s)", t, ti->name, ti2->name); } return NULL; } void uninitTypes(void) { struct typeinfo *ti; if (types == NULL) // never initialized; do nothing return; // the first entry is NULL; get rid of it directly ptrArrayDelete(types, 0); while (types->len != 0) { ti = ptrArrayIndex(types, struct typeinfo *, 0); ptrArrayDelete(types, 0); uiFree(ti); } ptrArrayDestroy(types); } uiTyped *newTyped(uintmax_t type) { struct typeinfo *ti; uiTyped *instance; if (type == 0 || type >= types->len) complain("invalid type ID given to newTyped()"); ti = ptrArrayIndex(types, struct typeinfo *, type); instance = (uiTyped *) uiAlloc(ti->size, ti->name); instance->Type = type; return instance; }
C
/* hello1.c*/ #include <stdio.h> float multiplierpar2(float x) { return 2*x; } int main() { printf("le resultat de 2*5 est : %f\n",multiplierpar2(5)); return 0; }
C
#ifndef LIST_H #define LIST_H #include "include.h" struct node_t { // data should _always_ be self contained, that is, no other pointer should ever access it // while it is in the list void * restrict data; // next should never equal prev, if gcc is smart enough this may speed up list operations struct node_t * restrict next, * restrict prev; // size of data size_t size; // a label/name for this item char * restrict label; // misc info int misc; }; struct cache_t { struct node_t * node; }; struct list_t { struct node_t *head, *tail; volatile size_t size; pthread_mutex_t global_lock; pthread_cond_t work; int stop; }; void push_back(struct list_t* restrict list, void* restrict a, size_t s, char* restrict label, int misc); struct node_t* pop_front_n_c(struct list_t* restrict list, int* pass); void* pop_front_c(struct list_t* restrict list, int* pass); void* pop_front(struct list_t* restrict list); struct node_t* pop_front_n(struct list_t* restrict list); struct node_t* pop_back_n(struct list_t* restrict list); void destroy(struct list_t* restrict list); void init(struct list_t* restrict list); struct node_t* getval_n(struct list_t* restrict list, size_t i); #endif
C
#include <stdlib.h> #include "binary.h" struct b_binary_tree_t* b_binary_tree_new(struct b_binary_tree_t* self, int (*compare)(void*, void*), void* (*mallocFunc)(size_t), void (*selfFree)(void*), void (*keyFree)(void*), void (*valueFree)(void*)) { if (!mallocFunc) { mallocFunc = malloc; } if (!self) { self = (struct b_binary_tree_t*) mallocFunc(sizeof(struct b_binary_tree_t)); if (!self) { return 0; } } self->size = 0; self->root = 0; self->compare = compare; self->mallocFunc = mallocFunc; self->selfFree = selfFree; self->keyFree = keyFree; self->valueFree = valueFree; return self; } static void b_binary_tree_node_free(struct b_binary_tree_t* self, struct b_binary_tree_node_t* node) { if (self->keyFree) { self->keyFree(node->key); } if (self->valueFree) { self->valueFree(node->value); } if (self->selfFree) { self->selfFree(node); } if (node->left) { b_binary_tree_node_free(self, node->left); } if (node->right) { b_binary_tree_node_free(self, node->right); } } void b_binary_tree_free(struct b_binary_tree_t* self) { if (self->root) { b_binary_tree_node_free(self, self->root); } if (self->selfFree) { self->selfFree(self); } } unsigned int b_binary_tree_size(struct b_binary_tree_t* self) { return self->size; } void* b_binary_tree_get(struct b_binary_tree_t* self, void* key) { if (!self->root) { return 0; } struct b_binary_tree_node_t* node = self->root; while (node) { int compare = self->compare(key, node->key); if (!compare) { return node->value; } else if (compare < 0) { node = node->left; } else { node = node->right; } } return 0; } unsigned char b_binary_tree_set(struct b_binary_tree_t* self, struct b_binary_tree_node_t* node, void* key, void* value) { if (!self->root) { if (!node) { node = (struct b_binary_tree_node_t*) self->mallocFunc(sizeof(struct b_binary_tree_node_t)); if (!node) { return 1; } } node->key = key; node->value = value; node->parent = 0; node->left = 0; node->right = 0; self->root = node; return 0; } struct b_binary_tree_node_t* aux = self->root; while (aux) { int compare = self->compare(key, aux->key); if (!compare) { if (self->keyFree) { self->keyFree(aux->key); } if (self->valueFree) { self->valueFree(aux->key); } aux->key = key; aux->value = value; } else if (compare < 0) { if (aux->left) { aux = aux->left; } else { if (!node) { node = (struct b_binary_tree_node_t*) self->mallocFunc(sizeof(struct b_binary_tree_node_t)); if (!node) { return 1; } } node->key = key; node->value = value; node->parent = aux; node->left = 0; node->right = 0; aux->left = node; return 0; } } else { if (aux->right) { aux = aux->right; } else { if (!node) { node = (struct b_binary_tree_node_t*) self->mallocFunc(sizeof(struct b_binary_tree_node_t)); if (!node) { return 1; } } node->key = key; node->value = value; node->parent = aux; node->left = 0; node->right = 0; aux->right = node; return 0; } } } return 0; } static void b_binary_tree_node_del(struct b_binary_tree_t* self, struct b_binary_tree_node_t* node) { if (!node->left && !node->right) { struct b_binary_tree_node_t* parent = node->parent; if (parent) { if (parent->left == node) { parent->left = 0; } else { parent->right = 0; } } else { self->root = 0; } if (self->selfFree) { self->selfFree(node); } } else if (node->left) { struct b_binary_tree_node_t* aux = node->left; while (aux->right) { aux = aux->right; } node->key = aux->key; node->value = aux->value; b_binary_tree_node_del(self, aux); } else if (node->right) { struct b_binary_tree_node_t* aux = node->right; while (aux->left) { aux = aux->left; } node->key = aux->key; node->value = aux->value; b_binary_tree_node_del(self, aux); } } void b_binary_tree_del(struct b_binary_tree_t* self, void* key) { if (!self->root) { return; } struct b_binary_tree_node_t* node = self->root; while (node) { int compare = self->compare(key, node->key); if (!compare) { if (self->keyFree) { self->keyFree(node->key); } if (self->valueFree) { self->valueFree(node->value); } b_binary_tree_node_del(self, node); break; } else if (compare < 0) { node = node->left; } else { node = node->right; } } self->compare(key, key); }
C
/* * Types.h * * Created on: 30 wrz 2016 * Author: Uzume */ #ifndef TYPES_TYPES_H_ #define TYPES_TYPES_H_ #include "stdint.h" struct colortype { colortype() : color(0) { } colortype(uint32_t c) { color = c; } inline uint32_t getColor32(){ return color; } operator uint32_t() const { return (uint32_t)color; } uint32_t color; }; typedef uint8_t Aligment; static const Aligment LEFT = 0; static const Aligment CENTER = 1; static const Aligment RIGHT = 2; typedef uint8_t TextDirection; static const TextDirection TEXT_DIRECTION_LTR = 0; static const TextDirection TEXT_DIRECTION_RTL = 1; typedef uint16_t TypedTextId; #endif /* TYPES_TYPES_H_ */
C
/* Hash table interface. */ /* We implement the hash table as an opaque type, all the work will be done * inside hashtable.c. */ struct hash_table; /* Hash table indexed by null terminated strings. If copy_keys is false then * keys must have lifetime at least equal to that of the associated value, * otherwise every inserted key will be copied. */ struct hash_table *hash_table_create(bool copy_keys); /* Release all resources consumed by hash table. */ void hash_table_destroy(struct hash_table *table); /* Look up key in hash table, return NULL if not found. */ void *hash_table_lookup(struct hash_table *table, const void *key); /* Look up key in hash table, return true if found. Equivalent to * hash_table_lookup() except when value is NULL. */ bool hash_table_lookup_bool( struct hash_table *table, const void *key, void **value); /* Inserts (key,value) pair in hash table. If value is already present its old * value is returned before being overwritten with the new value, otherwise NULL * is returned. */ void *hash_table_insert(struct hash_table *table, const void *key, void *value); /* Inserts const value into hashtable. */ #define hash_table_insert_const(table, key, value) \ hash_table_insert(table, key, CAST_FROM_TO(const void *, void *, value)) /* Deletes key from hash table, returning the old value if present, otherwise * NULL. */ void *hash_table_delete(struct hash_table *table, const void *key); /* Returns the number of entries in the table. */ size_t hash_table_count(struct hash_table *table); /* Resizes hash table to have at least the given number of slots. Can also be * used after deleting entries to compress table. */ void hash_table_resize(struct hash_table *table, size_t min_size); /* Iterator for walking all entries in hash table. The table *must* remain * unchanged during the walk. Start by initialising ix to zero, each call * will increment ix and return the associated (key,value) pair and return * true until the entire table has been walked, when false will be returned. * Either key or value can be null if the result is not required. */ bool hash_table_walk( struct hash_table *table, size_t *ix, const void **key, void **value); #define hash_table_walk_const(table, ix, key, value) \ hash_table_walk(table, ix, key, CAST_FROM_TO(const void **, void **, value)) /* Sanity checking of hash table consistency, raises assert fail if any error is * found. Should only fail in presence of hash table bug, memory overwrite, or * key lifetime mismanagement. */ void hash_table_validate(struct hash_table *table); /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* Optional generic hash table interface. */ /* Hashes are long integers, 64-bits on the right architecture. */ typedef long unsigned int hash_t; /* Computes sensible hash function over given memory area. */ hash_t hash_memory_area(const void *key, size_t length); /* Abstract key management interface so hash table can support key types other * than null terminated strings. */ struct hash_table_ops { /* Returns hash value for given key. */ hash_t (*hash)(const void *key); /* Returns true iff both keys compare equal. */ bool (*compare)(const void *key1, const void *key2); /* Key lifetime is either under control of the user of the hash table or the * hash table. Caller control is indicated by leaving copy_key() and * release_key() NULL, otherwise these will be called when keys are added * and removed respectively. */ /* Creates a copy of key for storage in hash table. */ void *(*copy_key)(const void *key); /* Releases a previously copied key. */ void (*release_key)(void *key); }; /* Create fresh hash table. Most general form with generic key ops table. */ struct hash_table *hash_table_create_generic(const struct hash_table_ops *ops); /* Hash table keyed by pointers. Also use this for integer indexed tables. */ struct hash_table *hash_table_create_ptrs(void);
C
// This program copies text array with dynamic memory allocation. #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> #define N 180 #define M 180 void ReplaceStr(char* Target, char* Source) { int* Memory_Block; //Pointer for a memory block for memory allocaton Memory_Block = (int*)malloc(M * sizeof(char)); printf("The size of memory given is %d\n\n", M * sizeof(char)); if (Memory_Block == NULL) { printf("Memory has not been given!\n\n"); system("Pause"); exit(EXIT_FAILURE); } memcpy(Target, Source, N * sizeof(char)); free(Memory_Block); } int main() { char SourceArray[N] = "Long time ago in a Galaxy far away"; printf("Source Array contents: %s\n\n", SourceArray); printf(" The size of SourceArray is %d\n\n", N * sizeof(char)); char TargetArray[N]; //memcpy(TargetArray, SourceArray, N * sizeof(char)); ReplaceStr(TargetArray, SourceArray); printf("TargetArray contents: %s\n\n", TargetArray); getchar(); }
C
/** * 2lkup.c * * Computer Science 50 * Problem Set 6 * lookup function * * The sole intention of this program is to undertand how const char* works * and dynamically allocate memory for array * */ #include <stdio.h> #include <stdbool.h> #include <ctype.h> #include <stdlib.h> #include <cs50.h> #include <string.h> #include <strings.h> //for printing pointers #include <inttypes.h> const char* func1(const char* ruta); int main(void) { char path[6]; for (int i = 0; i < 5; i ++) { path[i] = 'a'+ i; } path[2] = '.'; path[5] = '\0'; const char* type = func1(path); printf("%s\n", type); } const char* func1(const char* path) { int largo = strlen(path); char extension[3]; for (int index = 2, index2 = 0; index2 < 3; index --, index2 ++) { extension[index] = path[largo - 1 - index2]; } printf("%s\n", extension); char l[4] = ".de"; //Al parecer, char sí aplica el signo de "palabra terminada" automaticamente pero "const char" no, ni aunque se quiera incluir //por ello, con l[] no se puede pues es .,d,e,\0 y extension es .,d,e. //sin embargo quiero que el array extensión, el número de variables sea dinámica. printf("%s\n", l); int one = strcmp("l","l");//para entender cómo funciona la función "strcmp" int two = strcmp("a","l"); int three = strcmp("z","l"); printf("%i,%i,%i\n", one, two, three); char* point = strrchr(path,'.'); int cuanto = strlen(point); printf("%i\n", cuanto); if (strcmp(point,".de")==0) { return ".de"; } else if (strcasecmp(point,l)==0) { return "l"; } else { return NULL; } }
C
/** ****************************************************************************** * @file driver_timer.c * @author Florent Dumazel Clement Souyri Gabriel Aygalenq * @version V1.0.0 * @date 30-Septembre-2014 * @bref Ce fichier fournit des fonctions pour gerer * les fonctionnalites du timer: * - Initialiser les GPIO pour Timer * - Initialiser les Timer * - Lancer et arreter les Timer * * * * =================================================================== * Comment utiliser ce driver * =================================================================== * * Ce driver necessite 4 etapes pour fonctionner: * * 1. Initialiser le Gpio sur lequel sortir le Timer: * void InitGpioxTimer(GPIO_InitConfTime* Gpio_InitTimer, GPIO_InitTypeDef* GPIO_InitStructure, FunctionalState NewState) * - Configurer la structure GPIO_InitConfTime. * - Configurer la structure GPIO_InitTypeDef. * - Activer les Timer. * * 2. Initialiser et configurer le Timer: * void InitTimer(TIM_TypeDef* TIMx, uint16_t TIM_Prescaler, uint32_t TIM_Period, uint8_t TIM_RepetitionCounter) * - Selectionner le Timer (TM1, TM2..). * - Selectionner le Timer (TM1, TM2..). * - Clock sortie = 65 Mhz /( (PSC+1)*(ARR+1)*(RCR+1) ). * * 3. Configurer le PWM: * void InitPwm(TIM_TypeDef* TIMx, uint16_t TIM_OCMode, uint32_t TIM_Pulse); * - Selectionner le Timer (TM1, TM2..). * - Selectionner le mode de fonctionnement. * - Selectionner le pourcentage d'etat haut. * * 4. To get the level of a pin configured in input mode use GPIO_ReadInputDataBit() * void StartOrStopTimer(TIM_TypeDef* TIMx, FunctionalState NewState); * - Lancer ou arreter le Timer. * * @endverbatim * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include <stm32f4xx_rcc.h> #include <stm32f4xx_tim.h> #include <stm32f4xx.h> #include <stm32f4xx_gpio.h> #include <driver_timer.h> /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* Private function prototypes -----------------------------------------------*/ /* Private functions ---------------------------------------------------------*/ /** * @brief Configure, initialise le Timer et Gpio de sortie. * @note Remplir la structure GPIO_InitConfTime* * Remplir la structure GPIO_InitTypeDef* * @param Gpio_InitTimer: Pointer qur la structure GPIO_InitConfTime qui * contient les parametres du Timer et de la Gpio. * @param GPIO_InitStruct: Pointer sur la stucture GPIO_InitTypeDef qui * contient les parametres de la broche GPIO. * @param NewState: Nouvel etat d'activation * Ce parametre peut etre: ENABLE or DISABLE. * @retval None */ void InitGpioxTimer(GPIO_InitConfTime* Gpio_InitTimer, GPIO_InitTypeDef* GPIO_InitStructure, FunctionalState NewState) { RCC_APB1PeriphClockCmd(Gpio_InitTimer->RCC_APB1Periph, NewState); RCC_AHB1PeriphClockCmd(Gpio_InitTimer->RCC_AHB1Periph, NewState); GPIO_Init(Gpio_InitTimer->GPIOx, &(*GPIO_InitStructure)); GPIO_PinAFConfig(Gpio_InitTimer->GPIOx, Gpio_InitTimer->GPIO_PinSource, Gpio_InitTimer->GPIO_AF); } /** * @brief Configure le timer. * @note Remplir la structure GPIO_InitConfTime* * Remplir la structure GPIO_InitTypeDef* * @param Gpio_InitTimer: Pointer qur la structure GPIO_InitConfTime qui * contient les parametres du Timer et de la Gpio. * @param GPIO_InitStruct: Pointer sur la stucture GPIO_InitTypeDef qui * contient les parametres de la broche GPIO. * @param NewState: Nouvel etat d'activation * Ce parametre peut etre: ENABLE or DISABLE. * @retval None */ void InitTimer(TIM_TypeDef* TIMx, uint16_t TIM_Prescaler, uint32_t TIM_Period, uint8_t TIM_RepetitionCounter) { TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure; TIM_TimeBaseStructure.TIM_Prescaler =TIM_Prescaler;// psc TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up; TIM_TimeBaseStructure.TIM_Period = TIM_Period;// arr TIM_TimeBaseStructure.TIM_ClockDivision = 0; TIM_TimeBaseStructure.TIM_RepetitionCounter=TIM_RepetitionCounter;// rcc TIM_TimeBaseInit(&(*TIMx), &TIM_TimeBaseStructure); } void InitPwm(TIM_TypeDef* TIMx, uint16_t TIM_OCMode, uint32_t TIM_Pulse) { TIM_OCInitTypeDef TIM_OCInitStructure; TIM_OCInitStructure.TIM_OCMode = TIM_OCMode; TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable; TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High; TIM_OCInitStructure.TIM_Pulse = TIM_Pulse;//(PreCalPeriod * Duty_Cycle) / 100; TIM_OC1Init(&(*TIMx), &TIM_OCInitStructure); TIM_OC1PreloadConfig(&(*TIMx), TIM_OCPreload_Enable); TIM_ARRPreloadConfig(&(*TIMx), ENABLE); } void StartOrStopTimer(TIM_TypeDef* TIMx, FunctionalState NewState) { TIM_Cmd(&(*TIMx), NewState); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msoares <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/21 17:04:32 by msoares #+# #+# */ /* Updated: 2020/02/13 14:58:48 by msoares ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_H # define LIBFT_H # include <stdlib.h> # include <unistd.h> typedef struct s_list { void *content; struct s_list *next; } t_list; char *ft_chartostr(char c); /* ** Bonus */ int ft_lstsize(t_list *lst); t_list *ft_lstnew(void *content); void ft_lstadd_front(t_list **lst, t_list *new); int ft_lst(t_list *lst); t_list *ft_lstlast(t_list *lst); void ft_lstadd_back(t_list **lst, t_list *new); void ft_lstdelone(t_list *lst, void (*del)(void *)); void ft_lstclear(t_list **lst, void (*del)(void *)); void ft_lstiter(t_list *lst, void (*f)(void *)); t_list *ft_lstmap(t_list *lst, void *(*f)(void *), void (*del)(void *)); /* ** Part 1 */ void ft_bzero(void *str, size_t n); int ft_isalpha(int i); int ft_isascii(int i); int ft_isdigit(int i); int ft_isprint(int i); void *ft_memcpy(void *str1, const void *str2, size_t size); void *ft_memccpy(void *dest, const void *src, int c, size_t n); void *ft_memchr(const void *str, int c, size_t n); int ft_memcmp(const void *str1, const void *str2, size_t n); void *ft_memmove(void *str1, const void *str2, size_t n); void *ft_memset(void *str1, int c, size_t size); char *ft_strchr(char const *str, int c); size_t ft_strlcat(char *dest, char const *src, size_t size); size_t ft_strlcpy(char *dest, char const *src, size_t size); size_t ft_strlen(char const *str); int ft_strncmp(char const *s1, char const *s2, size_t n); int ft_tolower(int i); int ft_toupper(int i); int ft_isalnum(int i); char *ft_strrchr(char const *str, int c); int ft_atoi(char const *str); char *ft_strnstr(char const *big, char const *little, size_t len); void *ft_calloc(size_t num, size_t size); char *ft_strdup(char const *str); /* ** Part 2 - Adicional Functions */ char *ft_substr(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); char *ft_strtrim(char const *s1, char const *set); void ft_putchar_fd(char c, int fd); void ft_putstr_fd(char *s, int fd); void ft_putendl_fd(char *s, int fd); void ft_putnbr_fd(int n, int fd); char **ft_split(char const *s, char c); char *ft_strmapi(char const *s, char (*f)(unsigned int, char)); char *ft_itoa(int nb); #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <libgen.h> #include "archiver.h" void print_info(void) { printf("Info:\n"); } void print_usage(char *app_path) { char *app_name = basename(app_path); printf("\n\tUsage:\n\n" ">> %s [-h]: \n\tprint application information;\n\n" ">> %s [-a] archive_file file_1 .. file_n: \n\tadd files to an existing archive (create it otherwise);\n\n" ">> %s [-x] archive_file file_1 .. file_n: \n\textract files from an existing archive;\n\n" ">> %s [-xall] archive_file: \n\textract all files from an existing archive;\n\n" ">> %s [-d] archive_file file_1 .. file_n: \n\tdelete files from an existing archive;\n\n" ">> %s [-dall] archive_file: \n\tdelete all files from an existing archive;\n\n" ">> %s [-l] archive_file: \n\ttest archive integrity;\n\n" ">> %s [-t] archive_file: \n\tprint archive information.\n\n", app_name, app_name, app_name, app_name, app_name, app_name, app_name, app_name); } int main(int argc, char *argv[]) { //print info if (argc >= 2 && !strcmp(argv[1], "-h")) { print_info(); exit(0); } //print usage if (argc <= 2) { print_usage(argv[0]); exit(0); } MenuOption opt = InvalidOption; //add to archive if (!strcmp(argv[1], "-a")) { opt = AddToArchive; } //extract from archive else if (!strcmp(argv[1], "-x")) { opt = ExtractFromArchive; } //extract all files from archive else if (!strcmp(argv[1], "-xall")) { opt = ExtractAll; } //remove from archive else if (!strcmp(argv[1], "-d")) { opt = RemoveFromArchive; } //remove all files from archive else if (!strcmp(argv[1], "-dall")) { opt = RemoveFromArchive; } //check archive's integrity else if (!strcmp(argv[1], "-t")) { opt = CheckIntegrity; } //print archive's info else if (!strcmp(argv[1], "-l")) { opt = PrintInfo; } if (opt == InvalidOption) { //print usage print_usage(argv[0]); } else { choice_menu(argv[2], argv + 3, argc - 3, opt); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "structs.h" #include "utils.h" short cost(int x) { int i, n_iter = 20; double dcost = 0; for(i = 0; i < n_iter; i++) dcost += pow(sin((double) x),2) + pow(cos((double) x),2); return (short) (dcost / n_iter + 0.1); } /* c[i,j] 0 if i=0 or j=0 c[i-1,j-1]+1 if i,j>0 and xi=yj max(c[i,j-1], c[i-1,j]) if i,j>0 and xi!=yj */ /*-------------------------------------------------- Função: funct_parallel Objectivo: percorrer toda a diagonal em paralelo de modo a completar a matriz da forma mais eficiente possivel Devido a dependencias de dados, cada diagonal da matriz tem de ser feita em série, pois uma diagonal é sempre dependente da anterior. No entanto, quando a completar cada diagonal, ja se pode executar em paralelo, pois cada valor de uma diagonal é independente dos outros. Variaveis: matrix -> variavel auxiliar que aponta para a matriz de dados criada em readFile control -> a trabalhar em sincronia com as threads e o for, control percorre a diagonal de 0 a counter(tamanho da diagonal actual) ii, jj -> variavies auxiliares que se asseguram de que i e j sao dependentes de control ---------------------------------------------------*/ void funct_parallel(LcsMatrix *lcsMtx, int i, int j, int counter) { int **matrix = lcsMtx->mtx; int control; int ii=i,jj=j; #pragma omp for schedule(dynamic) private(control) //percorrer a diagonal em paralelo. Cada thread tem no seu stack um valor de control for(control = 0; control < counter; control++) { i = ii + control; j = jj - control; if(lcsMtx->seqLine[i] == lcsMtx->seqColumn[j]) { //caso os valores sejam iguais, incrementa o dado do ponto i-1, j-1 e guarda matrix[i][j] = matrix[i-1][j-1] + cost(control); } else { matrix[i][j] = matrix[i][j-1] >= matrix[i-1][j] ? matrix[i][j-1] : matrix[i-1][j]; //caso sejam diferentes, ve o maior de dois elementos e guarda } } return; } /*---------------------------------------- Função: fillMatrix Objectivo: Completar a matriz com os dados necessários para, a seguir, obter a sequencia similar das duas strings Variaveis: maxDiag -> contem o tamanho maximo que a diagonal pode ter maxAbs, incCounterVertical, aux -> variaveis auxiliares usadas para controlar o counter Counter -> antes de entrar na função funct_parallel, contem o numero de elementos que serão lidos na diagonal Nota: nesta função todas as threads estão a executar o mesmo codigo, sendo o "verdadeiro paralelismo" executado na funçao funct_parallel. Apesar do codigo desnecessário a ser corrido, é mais eficiente do que criar e remover threads sempre que se entrava na função funct_parallel -----------------------------------------*/ void fillMatrix(LcsMatrix *lcsMtx) { int i=1; int j, maxDiag, maxAbs; int counter=1; int incCounterVertical=1; int aux; /*maxDiag vai conter o minimo dos dois, pois é a a dimensao max de uma diagonal, maxAbs contem o maximo dos dois, para ajuda no calculo do counter caso nºcolunas < nºlinhas*/ maxDiag = (lcsMtx->cols >= lcsMtx->lines) ? lcsMtx->lines : lcsMtx->cols; maxAbs = (lcsMtx->cols > lcsMtx->lines) ? lcsMtx->cols : lcsMtx->lines; #pragma omp parallel private(j, aux) firstprivate(i, counter, incCounterVertical) { //vamos percorrer toda a 2ªlinha da matriz e, a partir daí, ir de diagonal em diagonal para completar a matriz for(j=1; j <= lcsMtx->cols; j++) { #pragma omp barrier //todas as threads têm de esperar que a ultima diagonal esteja completa antes de passarem para a proxima funct_parallel(lcsMtx, i, j, counter); counter++; //cada vez que nos deslocamos mais para a direita o numero de valores na diagonal aumenta. So nao pode exceder maxDiag if(counter > maxDiag) counter=maxDiag; } j=lcsMtx->cols; aux = j; #pragma omp barrier //antes de começar a percorrer a ultima coluna, é preciso assegurar que todas as threads anteriores acabaram // Percorrer toda a ultima coluna da matriz para ober os valores abaixo da diagonal principal da matriz for(i=2; i <= lcsMtx->lines; i++) { if (aux == maxAbs) { //calculo auxiliares que asseguram o valor correcto de counter caso a matriz tenha nºlinhas<nºcolunas ou ao contrario incCounterVertical = -1; } else { aux++; } counter += incCounterVertical; if (counter > maxDiag) counter = maxDiag; #pragma omp barrier funct_parallel(lcsMtx, i, j, counter); //tal como no ciclo anterior, ele percorre diagonal a diagonal e completa a matriz } } // printLcsMatrix(lcsMtx); return; } /*--------------------------------------------------------- Função: findLongestCommonSubsequence Objectivo: aplicar o algoritmo, escrito no enunciado, na matriz e obter a sequencia equivalente das duas strings Variaveis: i, j -> percorrem a matriz counter -> +1 sempre que existe igualdade. Guarda o numero de caracteres da string equivalente lcsStringInverted -> sabendo que a string equivalente nunca podera ser maior que o minimo do numero colunas/linhas, guarda a string invertida a medida que se percorre a matriz lcsString -> depois de obtido o tamanho e a matriz invertida, inverte esta ultima e guarda assim a resposta final do problema ----------------------------------------------------------*/ LcsResult findLongestCommonSubsequence(LcsMatrix *lcsMtx) { LcsResult result; // start at button right of the matrix int i = lcsMtx->lines; int j = lcsMtx->cols; char *lcsStringInverted = (char *)calloc(i<j ? i+1 : j+1, sizeof(char)); char *lcsString; int counter = 0; /*aplica o algoritmo tal como dito no enunciado. Começa no valor do canto inferior direito da matriz Caso exista equivalencia, desloca-se na diagonal e guarda o caracter. Caso contrário, desloca-se para o maior dos dois valores, acima ou a esquerda dele, na matriz*/ while (i!=0 && j!=0) { // check match if (lcsMtx->seqLine[i] == lcsMtx->seqColumn[j]) { lcsStringInverted[counter] = lcsMtx->seqLine[i]; counter = counter + 1; // move diagonally i--; j--; } else { // check which is larger if (lcsMtx->mtx[i][j-1] >= lcsMtx->mtx[i-1][j]) { // move to largest j--; } else { i--; } } } //encerra a sequencia final adicionando o \0 no fim lcsStringInverted[counter] = '\0'; //inverte a matriz lcsStringInverted e guarda a sequencia final lcsString = (char *)calloc(counter, sizeof(char)); for (i=counter-1; i>=0; i--) { lcsString[counter-1-i] = lcsStringInverted[i]; } free(lcsStringInverted); result.counter = counter; result.sequence = lcsString; return result; }
C
#ifndef BASE_CVECTOR_H_ #define BASE_CVECTOR_H_ #include <assert.h> /* for assert */ #include <stddef.h> /* for size_t */ #include <stdlib.h> /* for malloc/realloc/free */ /** * @brief cvector_vector_type - The vector type used in this library */ #define cvector_vector_type(type) type * /** * @brief cvector_create - Create a vector of zero size */ #define cvector_create_empty() \ (void *)(((size_t*)calloc(2, sizeof(size_t))) + 2) /** * @brief cvector_set_capacity - For internal use, sets the capacity variable of the vector * @param vec - the vector * @param size - the new capacity to set * @return void */ #define cvector_set_capacity(vec, size) \ do { \ if (vec) { \ ((size_t *)(vec))[-1] = (size); \ } \ } while (0) /** * @brief cvector_set_size - For internal use, sets the size variable of the vector * @param vec - the vector * @param size - the new capacity to set * @return void */ #define cvector_set_size(vec, size) \ do { \ if (vec) { \ ((size_t *)(vec))[-2] = (size); \ } \ } while (0) /** * @brief cvector_capacity - gets the current capacity of the vector * @param vec - the vector * @return the capacity as a size_t */ #define cvector_capacity(vec) \ ((vec) ? ((size_t *)(vec))[-1] : (size_t)0) /** * @brief cvector_size - gets the current size of the vector * @param vec - the vector * @return the size as a size_t */ #define cvector_size(vec) \ ((vec) ? ((size_t *)(vec))[-2] : (size_t)0) /** * @brief cvector_empty - returns non-zero if the vector is empty * @param vec - the vector * @return non-zero if empty, zero if non-empty */ #define cvector_empty(vec) \ (cvector_size(vec) == 0) /** * @brief cvector_grow - For internal use, ensures that the vector is at least <count> elements big * @param vec - the vector * @param size - the new capacity to set * @return void */ #define cvector_grow(vec, count) \ do { \ const size_t __sz = (count) * sizeof(*(vec)) + (sizeof(size_t) * 2); \ if (!(vec)) { \ size_t *__p = malloc(__sz); \ assert(__p); \ (vec) = (void *)(&__p[2]); \ cvector_set_capacity((vec), (count)); \ cvector_set_size((vec), 0); \ } else { \ size_t *__p1 = &((size_t *)(vec))[-2]; \ size_t *__p2 = realloc(__p1, (__sz)); \ assert(__p2); \ (vec) = (void *)(&__p2[2]); \ cvector_set_capacity((vec), (count)); \ } \ } while (0) /** * @brief cvector_pop_back - removes the last element from the vector * @param vec - the vector * @return void */ #define cvector_pop_back(vec) \ do { \ cvector_set_size((vec), cvector_size(vec) - 1); \ } while (0) /** * @brief cvector_erase - removes the element at index i from the vector * @param vec - the vector * @param i - index of element to remove * @return void */ #define cvector_erase(vec, i) \ do { \ if (vec) { \ const size_t __sz = cvector_size(vec); \ if ((i) < __sz) { \ cvector_set_size((vec), __sz - 1); \ size_t __x; \ for (__x = (i); __x < (__sz - 1); ++__x) { \ (vec)[__x] = (vec)[__x + 1]; \ } \ } \ } \ } while (0) /** * @brief cvector_free - frees all memory associated with the vector * @param vec - the vector * @return void */ #define cvector_free(vec) \ do { \ if (vec) { \ size_t *p1 = &((size_t *)(vec))[-2]; \ free(p1); \ } \ } while (0) /** * @brief cvector_begin - returns an iterator to first element of the vector * @param vec - the vector * @return a pointer to the first element (or NULL) */ #define cvector_begin(vec) \ (vec) /** * @brief cvector_end - returns an iterator to one past the last element of the vector * @param vec - the vector * @return a pointer to one past the last element (or NULL) */ #define cvector_end(vec) \ ((vec) ? &((vec)[cvector_size(vec)]) : NULL) /* user request to use logarithmic growth algorithm */ #ifdef CVECTOR_LOGARITHMIC_GROWTH /** * @brief cvector_push_back - adds an element to the end of the vector * @param vec - the vector * @param value - the value to add * @return void */ #define cvector_push_back(vec, value) \ do { \ size_t __cap = cvector_capacity(vec); \ if (__cap <= cvector_size(vec)) { \ cvector_grow((vec), !__cap ? __cap + 1 : __cap * 2); \ } \ vec[cvector_size(vec)] = (value); \ cvector_set_size((vec), cvector_size(vec) + 1); \ } while (0) #else /** * @brief cvector_push_back - adds an element to the end of the vector * @param vec - the vector * @param value - the value to add * @return void */ #define cvector_push_back(vec, value) \ do { \ size_t __cap = cvector_capacity(vec); \ if (__cap <= cvector_size(vec)) { \ cvector_grow((vec), __cap + 1); \ } \ vec[cvector_size(vec)] = (value); \ cvector_set_size((vec), cvector_size(vec) + 1); \ } while (0) #endif /* CVECTOR_LOGARITHMIC_GROWTH */ #endif /* BASE_CVECTOR_H_ */
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "include/list.h" #include "include/maths.h" #include "include/inout.h" //testing functions void printElement(struct point *node){ printf("next: %lf %lf before: %lf %lf beta: %lf theta: %lf\n relatives: %lf %lf absolutes: %lf %lf", node->nextDist, node->nextHz, node->beforeDist, node->beforeHz, node->beta, node->theta, node->relativeX, node->relativeY, node->absoluteX, node->absoluteY); } void echoList(struct point *node){ printElement(node); printf("%d\n", (node->next!=NULL)); if(node->next!=NULL){ echoList(node->next); }else{ printf("END"); } } //End of testing functions struct point *newPoint(double nextAngle, double nextDist, double beforeAngle, double beforeDist, double beta){ struct point *new = (struct point *)malloc(sizeof(struct point)); new->nextHz = nextAngle; new->nextDist = nextDist; new->beforeHz = beforeAngle; new->beforeDist = beforeDist; new->beta = beta; new->next = NULL; return new; } void addPoint(struct point *curr, struct point *pt){ if(curr->next == NULL){ curr->next = pt; }else{ addPoint(curr->next, pt); } } void applyFunc(struct point *node, void (*func)(struct point *pt)){ (*func)(node); if(node->next!=NULL){ applyFunc(node->next, func); } } void correctBeta(struct point *node, double val){ node->beta += val; if(node->next!=NULL){ correctBeta(node->next, val); } } void subtractAlpha(struct point *node, double alpha){ if(node->next!=NULL){ subtractAlpha(node->next, alpha); }else{ node->beta-=alpha; } } void computeThetas(struct point *node, struct point* curr){ curr->theta=roundFirstDecimal(node->theta+(200-curr->beta)); if(curr->next != NULL){ computeThetas(curr, curr->next); } } void computeRelatives(struct point *node, double *sumX, double *sumY){ node->relativeX=node->beforeDist*cos(graToRad(node->theta)); //okay, i have no //idea if this is //right node->relativeY=node->beforeDist*sin(graToRad(node->theta)); *sumX += node->relativeX; *sumY += node->relativeY; if(node->next!=NULL){ computeRelatives(node->next, sumX, sumY); } } void correctRelatives(struct point* node, double CTx, double CTy){ node->relativeX+=CTx*node->nextDist; node->relativeY+=CTy*node->nextDist; if(node->next!=NULL){ correctRelatives(node->next, CTx, CTy); } } void computeAbsolutes(struct point *node, double stationX, double stationY){ node->absoluteX = node->relativeX + stationX; node->absoluteY = node->relativeY + stationY; if(node->next!=NULL){ computeAbsolutes(node->next, stationX, stationY); } } void printList(FILE *outputFile, struct point *node){ printPoint(outputFile, node->point_id, node->absoluteX, node->absoluteY, -1); if(node->next!=NULL){ printList(outputFile, node->next); } } void freeList(struct point *node){ if(node->next!=NULL){ freeList(node->next); } free(node); }
C
/* ** EPITECH PROJECT, 2019 ** PSU_2018_nmobjdump ** File description: ** elf_header */ #include "my_objdump.h" char *get_format(int idt) { if (idt == ELFCLASS32) return ("elf32-x86-64"); else if (idt == ELFCLASS64) return ("elf64-x86-64"); return ("unknow"); } char *get_engine(int eng) { if (eng == EM_X86_64) return ("i386:x86-64"); return ("unknown"); } void print_header(Elf64_Shdr *shdr, Elf64_Ehdr *elf, char *file) { printf("\n%s: file format %s\n", file, get_format(elf->e_ident[EI_CLASS])); printf("architecture: %s, flags 0x%08x:\n", get_engine(elf->e_machine), flags(elf, shdr)); print_flags(flags(elf, shdr)); printf("start address 0x%016lx\n\n", elf->e_entry); }
C
//================================================================= //ļstudent.h //ߣ // V 1.0.0 //գ201825 // 飺ļԶݽṹ //================================================================= #ifndef H_STUDENT_HH //ֵֹܳظ궨 #define H_STUDENT_HH #include <stdio.h> #include <stdlib.h> //׼ͷļ #include <conio.h> //console input/output #include <string.h> //ַ #define LEN sizeof(struct student) #define FORMAT "%-5d%-10s%-10.2lf%-10.2lf%-10.2lf%-10.2lf\n" #define DATA info[i].num,info[i].name,info[i].language,info[i].math,info[i].english,info[i].sum //ṹ洢ÿѧϢ extern struct student { int num; //ѧ char name[20]; // double language; //ijɼ double math; // ѧɼ double english; //Ӣɼ double sum; //ɼܷ }; extern struct student info[50]; // void menu(void); //˵ void add(void); //¼ѧɼ void search(void); //ѯѧɼ void del(void); //ɾѧɼ void modify(void); //޸ѧɼ void total(void); //ʾѧ void show(void); //ʾѧϢ void order(void); //ܷ #endif //H_STUDENT_HH
C
/** sol08.8b.c ** ------------------------------------------------------------ A larger extension of waitdemo1.c that creates and waits for a number of processes specified on the command line is sol08.8b.c. This program raises an interesting question about computing random numbers with rand(). If the random delay is computed in the child, every child gets the same random number. The reason is that the rand() function generates random numbers be applying a mathematical operation to the last random number it generated. If the parent asks for the random number, then the copy of that last number is in the parent, available to be used the next time. If the child computes the random number, the copy of that new number is stored in the child, and the parent's copy is unaffected. ** ------------------------------------------------------------ ** ** * A version of waitdemo1.c that creates and waits for as many * children as you specify on the command line. * * usage: sol08.8b numchildren * * Interesting sidelight: if the delay is computed in the child, * then every child gets the same random number. That is, if the * code reads: * * child_code(1 + (rand()%MAXDELAY)); * * then every child gets the same value. Explain. * ** build: cc sol08.8b.c -o sol08.8b */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #define oops(s,x) { perror(s); exit(x); } #define MAXDELAY 10 main(int ac, char *av[]) { void child_code(int), parent_code(int); pid_t pid; int i,n; int delay; /* * setup */ if ( ac == 1 ){ fprintf(stderr,"usage: sol08.8b numberofchildren\n"); exit(1); } n = atoi(av[1]); srand(getpid()); printf("before: mypid is %d\n", getpid()); /* * main loop */ for(i=0; i<n ; i++){ delay = 1 + (rand() % MAXDELAY); pid = fork(); if ( pid == -1 ) oops("fork", 2); if ( pid == 0 ) child_code(delay); } parent_code(n); return 0; } /* * new process takes a nap and then exits */ void child_code(int delay) { printf("child %d here. will sleep for %d seconds\n", getpid(), delay); sleep(delay); printf("child done. about to exit\n"); exit(17); } /* * parent waits for children then prints a message */ void parent_code(int n) { int wait_rv; /* return value from wait() */ printf("waiting for %d children\n", n); while( ( wait_rv = wait(NULL) ) != -1 ) printf("Wait returned: %d. %d to go\n", wait_rv, --n); }
C
// MESSAGE PARTITION PACKING #define MAVLINK_MSG_ID_PARTITION 2 typedef struct __mavlink_partition_t { uint16_t index; ///< First register that was read out. char ID; ///< Partition ID - make this a general purpose message uint8_t size; ///< Holds how many bytes are of importance, begining from index. uint8_t togo; ///< Holds how many partitions are still to come. If togo = 0, the last message was received. uint8_t value[32]; ///< Values of the 32 fields, starting from the indicated register } mavlink_partition_t; #define MAVLINK_MSG_ID_PARTITION_LEN 37 #define MAVLINK_MSG_ID_2_LEN 37 #define MAVLINK_MSG_ID_PARTITION_CRC 248 #define MAVLINK_MSG_ID_2_CRC 248 #define MAVLINK_MSG_PARTITION_FIELD_VALUE_LEN 32 #define MAVLINK_MESSAGE_INFO_PARTITION { \ "PARTITION", \ 5, \ { { "index", NULL, MAVLINK_TYPE_UINT16_T, 0, 0, offsetof(mavlink_partition_t, index) }, \ { "ID", NULL, MAVLINK_TYPE_CHAR, 0, 2, offsetof(mavlink_partition_t, ID) }, \ { "size", NULL, MAVLINK_TYPE_UINT8_T, 0, 3, offsetof(mavlink_partition_t, size) }, \ { "togo", NULL, MAVLINK_TYPE_UINT8_T, 0, 4, offsetof(mavlink_partition_t, togo) }, \ { "value", NULL, MAVLINK_TYPE_UINT8_T, 32, 5, offsetof(mavlink_partition_t, value) }, \ } \ } /** * @brief Pack a partition message * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * * @param ID Partition ID - make this a general purpose message * @param index First register that was read out. * @param size Holds how many bytes are of importance, begining from index. * @param togo Holds how many partitions are still to come. If togo = 0, the last message was received. * @param value Values of the 32 fields, starting from the indicated register * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_partition_pack(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, char ID, uint16_t index, uint8_t size, uint8_t togo, const uint8_t *value) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_PARTITION_LEN]; _mav_put_uint16_t(buf, 0, index); _mav_put_char(buf, 2, ID); _mav_put_uint8_t(buf, 3, size); _mav_put_uint8_t(buf, 4, togo); _mav_put_uint8_t_array(buf, 5, value, 32); memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_PARTITION_LEN); #else mavlink_partition_t packet; packet.index = index; packet.ID = ID; packet.size = size; packet.togo = togo; mav_array_memcpy(packet.value, value, sizeof(uint8_t)*32); memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_PARTITION_LEN); #endif msg->msgid = MAVLINK_MSG_ID_PARTITION; #if MAVLINK_CRC_EXTRA return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_PARTITION_LEN, MAVLINK_MSG_ID_PARTITION_CRC); #else return mavlink_finalize_message(msg, system_id, component_id, MAVLINK_MSG_ID_PARTITION_LEN); #endif } /** * @brief Pack a partition message on a channel * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message will be sent over * @param msg The MAVLink message to compress the data into * @param ID Partition ID - make this a general purpose message * @param index First register that was read out. * @param size Holds how many bytes are of importance, begining from index. * @param togo Holds how many partitions are still to come. If togo = 0, the last message was received. * @param value Values of the 32 fields, starting from the indicated register * @return length of the message in bytes (excluding serial stream start sign) */ static inline uint16_t mavlink_msg_partition_pack_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, char ID,uint16_t index,uint8_t size,uint8_t togo,const uint8_t *value) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_PARTITION_LEN]; _mav_put_uint16_t(buf, 0, index); _mav_put_char(buf, 2, ID); _mav_put_uint8_t(buf, 3, size); _mav_put_uint8_t(buf, 4, togo); _mav_put_uint8_t_array(buf, 5, value, 32); memcpy(_MAV_PAYLOAD_NON_CONST(msg), buf, MAVLINK_MSG_ID_PARTITION_LEN); #else mavlink_partition_t packet; packet.index = index; packet.ID = ID; packet.size = size; packet.togo = togo; mav_array_memcpy(packet.value, value, sizeof(uint8_t)*32); memcpy(_MAV_PAYLOAD_NON_CONST(msg), &packet, MAVLINK_MSG_ID_PARTITION_LEN); #endif msg->msgid = MAVLINK_MSG_ID_PARTITION; #if MAVLINK_CRC_EXTRA return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_PARTITION_LEN, MAVLINK_MSG_ID_PARTITION_CRC); #else return mavlink_finalize_message_chan(msg, system_id, component_id, chan, MAVLINK_MSG_ID_PARTITION_LEN); #endif } /** * @brief Encode a partition struct * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param msg The MAVLink message to compress the data into * @param partition C-struct to read the message contents from */ static inline uint16_t mavlink_msg_partition_encode(uint8_t system_id, uint8_t component_id, mavlink_message_t* msg, const mavlink_partition_t* partition) { return mavlink_msg_partition_pack(system_id, component_id, msg, partition->ID, partition->index, partition->size, partition->togo, partition->value); } /** * @brief Encode a partition struct on a channel * * @param system_id ID of this system * @param component_id ID of this component (e.g. 200 for IMU) * @param chan The MAVLink channel this message will be sent over * @param msg The MAVLink message to compress the data into * @param partition C-struct to read the message contents from */ static inline uint16_t mavlink_msg_partition_encode_chan(uint8_t system_id, uint8_t component_id, uint8_t chan, mavlink_message_t* msg, const mavlink_partition_t* partition) { return mavlink_msg_partition_pack_chan(system_id, component_id, chan, msg, partition->ID, partition->index, partition->size, partition->togo, partition->value); } /** * @brief Send a partition message * @param chan MAVLink channel to send the message * * @param ID Partition ID - make this a general purpose message * @param index First register that was read out. * @param size Holds how many bytes are of importance, begining from index. * @param togo Holds how many partitions are still to come. If togo = 0, the last message was received. * @param value Values of the 32 fields, starting from the indicated register */ #ifdef MAVLINK_USE_CONVENIENCE_FUNCTIONS static inline void mavlink_msg_partition_send(mavlink_channel_t chan, char ID, uint16_t index, uint8_t size, uint8_t togo, const uint8_t *value) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char buf[MAVLINK_MSG_ID_PARTITION_LEN]; _mav_put_uint16_t(buf, 0, index); _mav_put_char(buf, 2, ID); _mav_put_uint8_t(buf, 3, size); _mav_put_uint8_t(buf, 4, togo); _mav_put_uint8_t_array(buf, 5, value, 32); #if MAVLINK_CRC_EXTRA _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, buf, MAVLINK_MSG_ID_PARTITION_LEN, MAVLINK_MSG_ID_PARTITION_CRC); #else _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, buf, MAVLINK_MSG_ID_PARTITION_LEN); #endif #else mavlink_partition_t packet; packet.index = index; packet.ID = ID; packet.size = size; packet.togo = togo; mav_array_memcpy(packet.value, value, sizeof(uint8_t)*32); #if MAVLINK_CRC_EXTRA _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, (const char *)&packet, MAVLINK_MSG_ID_PARTITION_LEN, MAVLINK_MSG_ID_PARTITION_CRC); #else _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, (const char *)&packet, MAVLINK_MSG_ID_PARTITION_LEN); #endif #endif } #if MAVLINK_MSG_ID_PARTITION_LEN <= MAVLINK_MAX_PAYLOAD_LEN /* This varient of _send() can be used to save stack space by re-using memory from the receive buffer. The caller provides a mavlink_message_t which is the size of a full mavlink message. This is usually the receive buffer for the channel, and allows a reply to an incoming message with minimum stack space usage. */ static inline void mavlink_msg_partition_send_buf(mavlink_message_t *msgbuf, mavlink_channel_t chan, char ID, uint16_t index, uint8_t size, uint8_t togo, const uint8_t *value) { #if MAVLINK_NEED_BYTE_SWAP || !MAVLINK_ALIGNED_FIELDS char *buf = (char *)msgbuf; _mav_put_uint16_t(buf, 0, index); _mav_put_char(buf, 2, ID); _mav_put_uint8_t(buf, 3, size); _mav_put_uint8_t(buf, 4, togo); _mav_put_uint8_t_array(buf, 5, value, 32); #if MAVLINK_CRC_EXTRA _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, buf, MAVLINK_MSG_ID_PARTITION_LEN, MAVLINK_MSG_ID_PARTITION_CRC); #else _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, buf, MAVLINK_MSG_ID_PARTITION_LEN); #endif #else mavlink_partition_t *packet = (mavlink_partition_t *)msgbuf; packet->index = index; packet->ID = ID; packet->size = size; packet->togo = togo; mav_array_memcpy(packet->value, value, sizeof(uint8_t)*32); #if MAVLINK_CRC_EXTRA _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, (const char *)packet, MAVLINK_MSG_ID_PARTITION_LEN, MAVLINK_MSG_ID_PARTITION_CRC); #else _mav_finalize_message_chan_send(chan, MAVLINK_MSG_ID_PARTITION, (const char *)packet, MAVLINK_MSG_ID_PARTITION_LEN); #endif #endif } #endif #endif // MESSAGE PARTITION UNPACKING /** * @brief Get field ID from partition message * * @return Partition ID - make this a general purpose message */ static inline char mavlink_msg_partition_get_ID(const mavlink_message_t* msg) { return _MAV_RETURN_char(msg, 2); } /** * @brief Get field index from partition message * * @return First register that was read out. */ static inline uint16_t mavlink_msg_partition_get_index(const mavlink_message_t* msg) { return _MAV_RETURN_uint16_t(msg, 0); } /** * @brief Get field size from partition message * * @return Holds how many bytes are of importance, begining from index. */ static inline uint8_t mavlink_msg_partition_get_size(const mavlink_message_t* msg) { return _MAV_RETURN_uint8_t(msg, 3); } /** * @brief Get field togo from partition message * * @return Holds how many partitions are still to come. If togo = 0, the last message was received. */ static inline uint8_t mavlink_msg_partition_get_togo(const mavlink_message_t* msg) { return _MAV_RETURN_uint8_t(msg, 4); } /** * @brief Get field value from partition message * * @return Values of the 32 fields, starting from the indicated register */ static inline uint16_t mavlink_msg_partition_get_value(const mavlink_message_t* msg, uint8_t *value) { return _MAV_RETURN_uint8_t_array(msg, value, 32, 5); } /** * @brief Decode a partition message into a struct * * @param msg The message to decode * @param partition C-struct to decode the message contents into */ static inline void mavlink_msg_partition_decode(const mavlink_message_t* msg, mavlink_partition_t* partition) { #if MAVLINK_NEED_BYTE_SWAP partition->index = mavlink_msg_partition_get_index(msg); partition->ID = mavlink_msg_partition_get_ID(msg); partition->size = mavlink_msg_partition_get_size(msg); partition->togo = mavlink_msg_partition_get_togo(msg); mavlink_msg_partition_get_value(msg, partition->value); #else memcpy(partition, _MAV_PAYLOAD(msg), MAVLINK_MSG_ID_PARTITION_LEN); #endif }
C
#include <stdio.h> #define sqr(x) x*x int main(){ printf("%i\n",sqr(3+2)); }
C
// Dwarven Newbie Area: Created By Mist Fall 1994 // Addition to the Dwarven Newbie Area: Mist Spring 1997 #include "path.h" inherit ROOM+"baseroom.c"; object caverat; void setup () { my_setup(); set_short("Realm of the Dwarf: Cave"); set_zone("CAVE"); set_light(40); set_long("\n Realm of the Dwarf: Behind Waterfall\n\n" " The thunderous sound of the waterfall drowns out all " "other noise and makes it difficult to even think. The " "water is soaking you as it falls into the lake and " "spills backwards into a small opening in the southern " "wall. The opening is allowing a small river of water to " "escape and move quickly south. " "The pathway continues to the northwest. " "\n\n"); add_item(({"lake"}),"The waterfall completely blocks your view " "of the lake. " "\n\n"); add_item(({"water","waterfall","spray","falls"}),"The waterfall is " "loudly spilling water into the lake and soaking you with " "its cold spray. Any movement towards the falls could " "be disasterous, as the force of the falling water would " "be sure to pull you in. " "\n\n"); add_item(({"opening","river"}),"Some of the water from the falls " "is running through the opening in the southern wall. " "\n\n"); add_exit("south",ROOM+"dwarf31","path"); add_exit("east",ROOM+"dwarf25","path"); add_exit("northwest",ROOM+"dwarf20","path"); }
C
//header.c #include "header.h" #include "header.h" void GotoXY(int x, int y) { COORD Pos; Pos.X = x; Pos.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), Pos); } void CursorView(char show) { CONSOLE_CURSOR_INFO ConsoleCursor; ConsoleCursor.bVisible = show; ConsoleCursor.dwSize = 1; SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &ConsoleCursor); } void move_cursor(int* row, int* col) // xy�� ���� Ŀ�� ��ġ { int key; if (_kbhit()) // Ű���带 ������ �� { key = _getch(); if (key = ARROW) // Ȯ�� �ƽ�Ű �ڵ忡�� ����Ű�� �ǹ��ϴ� ���� �Է¹޴´�. { key = _getch(); // ������ �ǹ��ϴ� �� �ޱ� switch(key) { case UP: if (!(IsBlock(*row - 1, *col))) { maze[*row][*col] = '0'; maze[*row - 1][*col] = 'x'; *row -= 1; if (IsFinish(*row, *col)) { Complete(); } } break; case DOWN: if (!(IsBlock(*row + 1, *col))) { maze[*row][*col] = '0'; maze[*row + 1][*col] = 'x'; *row += 1; if (IsFinish(*row , *col)) { Complete(); } } break; case LEFT: if (!(IsBlock(*row , *col-1))) { maze[*row][*col] = '0'; maze[*row ][*col-1] = 'x'; *col -= 1; if (IsFinish(*row, *col)) { Complete(); } } break; case RIGHT: if (!(IsBlock(*row, *col+1))) { maze[*row][*col] = '0'; maze[*row][*col+1] = 'x'; *col += 1; if (IsFinish(*row, *col)) { Complete(); } } break; } } } } void PrintMaze() { int i,j; for (i = 0; i < SIZE; i++) { GotoXY(XP, YP + i); for (j = 0; j < SIZE; j++) { if (maze[i][j] == '1') { printf("��"); } else if (maze[i][j] == 'y') { printf("��"); } else if (maze[i][j] == '0') { printf("��"); } else { printf("��"); } } puts(""); } } void LoadMaze() { char path[25] = "./Maze"; char level; int i,j; printf("���̵��� �����ϼ���. (1, 2, 3) "); scanf("%c", &level); printf("lvl : %c\n", level); strcat(path, &level); strcat(path, ".txt"); printf("path : %s\n", path); // ���ڿ��� �̾�ٿ��� ��� ���� FILE* f = fopen(&path, "r"); // �Է¹��� path�� ���Ͽ��� char str_tmp[50] = {0, }; //�Է� ���� f ���� ���� for(i =0; i<SIZE; i++) { fgets(str_tmp, 50, f); char *ptr =strtok(str_tmp, "\t"); // str_tmp �ȿ��� tab������ ������ ptr �ȿ� ���� for(j =0; j<SIZE; j++) { maze[i][j] = *ptr; //maze �ȿ� ���� ptr = strtok(NULL, "\t"); //���� ���� ������ SIZE ��ŭ �ݺ� } } fclose(f); } int IsBlock(int i, int j) { if (maze[i][j] == '1' || maze[i][j] == 'y') return 1; else return 0; } int IsFinish(int i, int j) { if (maze[i][j] == 'y') return 1; else return 0; } void Complete() { _end = clock(); res = (float)(_end - start) / CLOCKS_PER_SEC; GotoXY(XP, YP + SIZE); printf("Complete!\n"); GotoXY(XP, YP + SIZE + 1); printf("����ð� : %.2f��", res); exit(0); }
C
#include <stdio.h> int facotorial(int N); int main(){ int N,K; scanf("%d %d", &N, &K); int nFac = facotorial(N); int kFac = facotorial(K); int nMink = facotorial(N-K); printf("%d", nFac / (kFac*nMink)); } int facotorial(int N){ if(N==0) return 1; else return N *facotorial(N-1); }
C
// SCU COEN 146 // // This program implements the server side of stop & wait protocol // the server receives file contents from a client // // // For the stop and wait protocol, the assumestions are: // -- packet corruption, and packet loss #include "tfv1.h" // global variables int state = 0; // we only have two states: 0 and 1 int sock; struct sockaddr_in serverAddr; socklen_t addr_size; // list of functions int main (int, char *[]); int my_receive (PACKET *); int calc_checksum (char *, int); int main (int argc, char *argv[]) { FILE *fp; int n; PACKET buf; if (argc != 2) { printf ("Need port number\n"); return 1; } // STUDENT WORK serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); serverAddr.sin_port = htons(atoi(argv[1])); serverAddr.sin_family = PF_INET; printf("%d \n",atoi(argv[1])); // create socket if ((sock = socket (PF_INET, SOCK_DGRAM, 0)) < 0) { printf ("socket error\n"); return 1; } // bind if (bind (sock, (struct sockaddr *)&serverAddr, sizeof (serverAddr)) != 0) { printf ("bind error\n"); return 1; } memset(buf.data,'\0',sizeof(buf.data)); if ((n = my_receive (&buf)) <= 0) { printf ("could not get the name of the file\n"); return 1; } printf ("File name has been received!\n"); // Open file with received name if ((fp = fopen (buf.data, "wb")) == NULL) { printf ("error fopen\n"); return 1; } printf ("Receiving file %s ... \n", buf.data); while ((n = my_receive (&buf)) > 0) { printf ("writing to file... n = %d\n", n); // STUDENT WORK fwrite(&buf.data,sizeof(char),n,fp); } close (sock); fclose (fp); return 0; } // my_receive() function ensures the received data chunks are not corrupted int my_receive (PACKET *recv_pck) { int cs_in; int cs_calc; int d; int r; int nbytes; HEADER ack_packet; struct sockaddr ret_addr; socklen_t addr_size = sizeof (ret_addr); while (1) { // size_t recvfrom(int socket, void *restrict buffer, size_t length, // int flags, struct sockaddr *restrict address, socklen_t *restrict address_len); // buffer: Points to the buffer where the message should be stored. // address: A null pointer, or points to a sockaddr structure in which the sending address is to be stored. // The length and format of the address depend on the address family of the socket. // address_len: Specifies the length of the sockaddr structure pointed to by the address argument. printf("Trying to receive\n"); memset(recv_pck->data,'\0',sizeof(recv_pck->data)); if ((nbytes = recvfrom (sock, recv_pck, sizeof(PACKET), 0, &ret_addr, &addr_size)) < 0) { printf("Failed\n"); return 0; } memset(recv_pck->data + recv_pck->header.len,'\0',sizeof(recv_pck->data)-recv_pck->header.len); printf ("Received a UDP packet!\n"); printf("\tchecksum: %d\n", recv_pck->header.checksum); printf("\tdata: %s\n",recv_pck->data); cs_in = recv_pck->header.checksum; recv_pck->header.checksum = 0; // recalculate checksum // STUDENT WORK cs_calc = calc_checksum (recv_pck, sizeof (HEADER) + recv_pck->header.len); // Check good checksum and good ack if (cs_in == cs_calc && recv_pck->header.seq_ack == state) { printf ("Checksum passed! Sequence number matched!\n"); // good packet // STUDENT WORK ack_packet.checksum = 0; ack_packet.seq_ack = state; ack_packet.len = 0; ack_packet.checksum = calc_checksum ((char *)&ack_packet, sizeof (HEADER) + ack_packet.len); // simulating erroneous channel...corruption and loss // STUDENT WORK r = rand () % 10; if (r > 8) { ack_packet.checksum = 0; printf("\nPacket got corrupted on the way\n"); } printf("\tChecksum: %d\n", ack_packet.checksum); printf("\tSequence: %d\n", ack_packet.seq_ack); r = rand() % 10; if(r <= 8) sendto(sock,&ack_packet,sizeof(HEADER),0,(struct sockaddr *) &ret_addr,sizeof(ret_addr)); else printf("\n\n\n\nPacket got lost along the way\n\n\n\n"); // now we are expecting the next packet // STUDENT WORK state = !state; return recv_pck->header.len; } else { printf ("Checksum/sequence number check failed!\n"); // bad packet // STUDENT WORK ack_packet.checksum = 0; ack_packet.seq_ack = !state; ack_packet.len = 0; ack_packet.checksum = calc_checksum (&ack_packet, sizeof(HEADER) + ack_packet.len); printf ("Resending ack for sequence number: %d...\n", ack_packet.seq_ack ); // simulating erroneous channel...corruption and loss // STUDENT WORK r = rand () % 10; if (r > 8) { ack_packet.checksum = 0; printf("\n\n\n\nPacket got corrupted along the way\n\n\n\n"); } printf("\tChecksum: %d\n", ack_packet.checksum); printf("\tSequence: %d\n", ack_packet.seq_ack); r = rand() % 10; if(r <= 8) sendto(sock, &ack_packet, sizeof(HEADER), 0, &ret_addr, sizeof(ret_addr)); else printf("\n\n\n\nPacket got corrupted along the way\n\n\n\n"); } } return -1; } int calc_checksum (char *buf, int tbytes) { int i; char cs = 0; char *p; // STUDENT WORK for(i = 0; i < tbytes; i++) { cs ^= buf[i]; } return cs; }
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node* next; }; struct node*head; void ll_traversal(); void ll_insert_first(); void ll_insert_Atindex(); void ll_randominsert(); void ll_insertlast(); void ll_delete_first(); void ll_delete_atindex(); void ll_delete_atend(); void main(){ int c; while(c!=9){ printf("\nHere are the choice\n"); printf("1:Display\n"); printf("2:insert_first\n"); printf("3:insert_At index\n"); printf("4:By index adding\n"); printf("5:insert_last\n"); printf("6:delete_first\n"); printf("7:delete_atindex\n"); printf("8:delete_last\n"); printf("Enter Choice:-"); scanf("%d",&c); switch (c) { case 1: ll_traversal(); break; case 2: ll_insert_first(); break; case 3: ll_insert_Atindex(); break; case 4: ll_randominsert(); break; case 5: ll_insertlast(); break; case 6: ll_delete_first(); break; case 7: ll_delete_atindex(); break; case 8: ll_delete_atend(); break; } } } void ll_traversal(){ struct node *ptr; ptr=head; if(ptr==NULL) { printf("\nNothing to traverse..\n"); } else { while (ptr!=NULL) { printf("%d->",ptr->data); ptr=ptr->next; } } } void ll_insert_first(){ struct node*ptr; ptr=(struct node*)malloc(sizeof(struct node)); if(ptr==NULL) { printf("Can't Insert"); } else{ printf("Enter Value:-"); scanf("%d",&ptr->data); ptr->next=head; head=ptr; printf("Node inserted Successfully"); } } //this is inserting by value void ll_insert_Atindex(){ int value,key; printf("Enter number after which you want to add:-"); scanf("%d",&key); struct node* newnode,*ptr,*p; newnode=(struct node* )malloc(sizeof(struct node)); if(newnode==NULL) { printf("No node created"); } printf("Enter Value to be inserted:-"); scanf ("%d",&newnode->data); if(head== NULL) { printf("This is for adding at first"); newnode->next=NULL; newnode=head; } else { ptr=head; p=head; while(p->data!=key) { ptr=ptr->next; p=p->next; } newnode->next=p->next; p->next=newnode; printf("Node inserted successfully"); } } //this in inserting by index void ll_randominsert() { int i,loc,item; struct node *ptr, *temp; ptr = (struct node *) malloc (sizeof(struct node)); if(ptr == NULL) { printf("\nOVERFLOW"); } else { printf("\nEnter element value"); scanf("%d",&item); ptr->data = item; printf("\nEnter the location after which you want to insert "); scanf("\n%d",&loc); temp=head; for(i=0;i<loc;i++) { temp = temp->next; if(temp == NULL) { printf("\ncan't insert\n"); return; } } ptr ->next = temp ->next; temp ->next = ptr; printf("\nNode inserted"); } } void ll_insertlast() { struct node*ptr,*p; p=(struct node *)malloc(sizeof(struct node)); if(p == NULL) { printf("\nOVERFLOW"); } else { printf("Enter Value:-"); scanf("%d",&p->data); if(head == NULL) { p-> next = NULL; head = p; printf("\nNode inserted"); } else { ptr=head; while(ptr->next!=NULL) { ptr=ptr->next; } ptr->next=p; p->next=NULL; printf("\nNode Inserted"); } } } void ll_delete_first() { struct node*ptr; if(head==NULL) { printf("no node for deletion"); } else { ptr=head; head=ptr->next; free(ptr); printf("Node Deleted Successfully"); } } void ll_delete_atindex() { struct node* p=head;; struct node* q=head->next; int index,i; printf("\n Enter the location of the node after which you want to perform deletion \n"); scanf("%d",&index); for ( i = 0; i < index-1; i++) { p=p->next; q=q->next; if(q==NULL) { printf("Can't Delete"); return; } } p->next=q->next; free(q); printf("Node Deleted successfully"); } void ll_delete_atend() { struct node* p=head; struct node*q=head->next; if(head==NULL){ printf("List is empty"); } else if(head->next==NULL) { head=NULL; free(head); printf("No node left"); } else{ while(q->next!=NULL) { p=p->next; q=q->next; } p->next=NULL; free(q); printf("Node deleted Successfully"); } }
C
/******************************************************************************/ /** @file slstore.c @author Kris Wallperington @brief Unit tests for Skiplist data store */ /******************************************************************************/ #include "sltests.h" /** @brief Helper function that creates a skiplist based on the given parameters. @param skiplist Skiplist to initialize @param key_type Type of key used @param compare Function pointer to a comparison method used by the skiplist @param maxheight Maximum height of the skiplist @param key_size Size of key in bytes allowed @param value_size Size of value in bytes allowed @param pnum Probability numerator @param pden Probability denominator */ void initialize_skiplist( skiplist_t *skiplist, key_type_t key_type, char (*compare)(ion_key_t, ion_key_t, ion_key_size_t), int maxheight, int key_size, int value_size, int pnum, int pden ) { sl_initialize( skiplist, key_type, key_size, value_size, maxheight, pnum, pden ); skiplist->super.compare = compare; } /** @brief Secondary helper function that creates a skiplist using the standard conditions variable. Simplifies the creation of a skiplist. @param skiplist Skiplist to initialize */ void initialize_skiplist_std_conditions( skiplist_t *skiplist ) { int key_size, value_size, pden, pnum, maxheight; key_type_t key_type; char (*compare)(ion_key_t, ion_key_t, ion_key_size_t); key_type = key_type_numeric_signed; compare = dictionary_compare_signed_value; key_size = 4; value_size = 10; pnum = 1; pden = 4; maxheight = 7; initialize_skiplist( skiplist, key_type, compare, maxheight, key_size, value_size, pnum, pden ); } /** @brief Tests creation of the skiplist. @param tc CuTest dependency */ void test_skiplist_initialize( CuTest *tc ) { PRINT_HEADER(); int key_size, value_size, pden, pnum, maxheight; key_type_t key_type; char (*compare)(ion_key_t, ion_key_t, ion_key_size_t); skiplist_t skiplist; key_type = key_type_numeric_signed; compare = dictionary_compare_signed_value; key_size = 4; value_size = 10; pnum = 1; pden = 4; maxheight = 7; initialize_skiplist( &skiplist, key_type, compare, maxheight, key_size, value_size, pnum, pden ); #if DEBUG > 0 print_skiplist(&skiplist); #endif ion_key_size_t t_key_size = skiplist.super.record.key_size; ion_value_size_t t_value_size = skiplist.super.record.value_size; CuAssertTrue(tc, skiplist.super.key_type == key_type_numeric_signed); CuAssertTrue(tc, skiplist.super.compare == dictionary_compare_signed_value); CuAssertTrue(tc, t_key_size == key_size); CuAssertTrue(tc, t_value_size == value_size); CuAssertTrue(tc, skiplist.maxheight == maxheight); CuAssertTrue(tc, skiplist.pnum == pnum); CuAssertTrue(tc, skiplist.pden == pden); } /** @brief Tests if the Skiplist is properly destroyed. @param tc CuTest dependency */ void test_skiplist_free_all( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); sl_destroy(&skiplist); CuAssertTrue(tc, skiplist.head == NULL); } /** @brief Tests random height generation with a known seed against prior known values. Sample size is 100. @param tc CuTest dependency */ void test_skiplist_generate_levels_std_conditions( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); /* * This is 100 level generations with maxheight = 7, pnum = 1, pden = 4. * The seed used is 0xDEADBEEF. */ int prediction[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 3, 0, 0, 0, 0, 1, 0, 0, 1 }; srand(0xDEADBEEF); int i; for(i = 0; i < 99; i++) { CuAssertTrue(tc, sl_gen_level(&skiplist) == prediction[i]); } sl_destroy(&skiplist); } /** @brief Tests a single insert into the skiplist. @param tc CuTest dependency */ void test_skiplist_single_insert( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int key = 6; unsigned char value[10]; strcpy((char*) value, "single."); sl_insert(&skiplist, (ion_key_t) &key, value); #if DEBUG > 0 print_skiplist(&skiplist); #endif CuAssertTrue(tc, *((int*) skiplist.head->next[0]->key) == 6); CuAssertStrEquals(tc, (char*) skiplist.head->next[0]->value, "single."); sl_destroy(&skiplist); } /** @brief Tests several insertions into the skiplist. The skiplist structure is accessed directly in order to verify the insertion has properly occurred. @param tc CuTest dependency */ void test_skiplist_insert_multiple( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char strs[5][6] = { "one", "two", "three", "four", "five" }; int i; for(i = 1; i <= 5; i++) { sl_insert(&skiplist, (ion_key_t) &i, strs[i - 1]); } #if DEBUG > 0 print_skiplist(&skiplist); #endif sl_node_t *cursor; cursor = skiplist.head->next[0]; CuAssertTrue(tc, *((int*) cursor->key) == 1); CuAssertStrEquals(tc, (char*) cursor->value, "one"); cursor = skiplist.head->next[0]->next[0]; CuAssertTrue(tc, *((int*) cursor->key) == 2); CuAssertStrEquals(tc, (char*) cursor->value, "two"); cursor = skiplist.head->next[0]->next[0]->next[0]; CuAssertTrue(tc, *((int*) cursor->key) == 3); CuAssertStrEquals(tc, (char*) cursor->value, "three"); cursor = skiplist.head->next[0]->next[0]->next[0]->next[0]; CuAssertTrue(tc, *((int*) cursor->key) == 4); CuAssertStrEquals(tc, (char*) cursor->value, "four"); cursor = skiplist.head->next[0]->next[0]->next[0]->next[0]->next[0]; CuAssertTrue(tc, *((int*) cursor->key) == 5); CuAssertStrEquals(tc, (char*) cursor->value, "five"); sl_destroy(&skiplist); } /** @brief Tests a mixed order insert. The structure is traversed and tested to confirm that (p + 1) >= ( p ) in all cases, where p is the key of the current node. @param tc CuTest dependency */ void test_skiplist_randomized_insert( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char str[10]; strcpy((char*) str, "random"); int i; for(i = 0; i < 100; i++) { int key = rand() % 101; sl_insert(&skiplist, (ion_key_t) &key, str); } #if DEBUG > 0 print_skiplist(&skiplist); #endif sl_node_t *cursor = skiplist.head; while(cursor->next[0]->next[0] != NULL) { int now = *((int*)cursor->next[0]->key); int next = *((int*)cursor->next[0]->next[0]->key); CuAssertTrue(tc, next >= now); cursor = cursor->next[0]; } sl_destroy(&skiplist); } /** @brief Tests node search on a single node in a skiplist with only one node. @details Tests node search on a single node in a skiplist with only one node. The key searched for is exact. The test compares the given node key and value information with the information inserted into the skiplist. The test passes if they are the same. @param tc CuTest dependency */ void test_skiplist_get_node_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char str[10]; strcpy((char*) str, "find this"); int key = 3; sl_insert(&skiplist, (ion_key_t) &key, str); int search = 3; sl_node_t *node = sl_find_node(&skiplist, (ion_key_t) &search); CuAssertTrue(tc, node != NULL); CuAssertTrue(tc, *((int*)node->key) == key); CuAssertStrEquals(tc, (char*) str, (char*) node->value); sl_destroy(&skiplist); } /** @brief Tests node search on a single node in a skiplist with only one node. @details Tests node search on a single node in a skiplist with only one node. The key searched for is higher than the inserted key. The test compares the given node key and value information with the information inserted into the skiplist. The test passes if they are the same. @param tc CuTest dependency */ void test_skiplist_get_node_single_high( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char str[10]; strcpy((char*) str, "find this"); int key = 3; sl_insert(&skiplist, (ion_key_t) &key, str); #if DEBUG > 0 print_skiplist(&skiplist); #endif int search = 10; sl_node_t *node = sl_find_node(&skiplist, (ion_key_t) &search); CuAssertTrue(tc, *((int*)node->key) == key); CuAssertStrEquals(tc, (char*) str, (char*) node->value); sl_destroy(&skiplist); } /** @brief Tests node search on a single node in a skiplist with only one node. @details Tests node search on a single node in a skiplist with only one node. The key searched for is lower than the inserted key. The test compares the given node key and value information with the information inserted into the skiplist. The test passes if the node returned is the same as the head node. (Since there's only one node, the only node that can be smaller than the one insert is the head node.) @param tc CuTest dependency */ void test_skiplist_get_node_single_low( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char str[10]; strcpy((char*) str, "find this"); int key = 3; sl_insert(&skiplist, (ion_key_t) &key, str); #if DEBUG > 0 print_skiplist(&skiplist); #endif int search = 2; sl_node_t *node = sl_find_node(&skiplist, (ion_key_t) &search); CuAssertTrue(tc, node == skiplist.head); sl_destroy(&skiplist); } /** @brief Tests node search on a single node in a skiplist with several nodes. @details Tests node search on a single node in a skiplist with several nodes. The key searched for is exact. The test compares the given node key and value information with the information inserted into the skiplist. The test passes if they are the same. @param tc CuTest dependency */ void test_skiplist_get_node_single_many( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char str[10]; strcpy((char*) str, "find this"); int key = 25; sl_insert(&skiplist, (ion_key_t) &key, str); unsigned char junk[10]; strcpy( (char*) junk, "big junk"); int i; for(i = 0; i < 100; i++) { if(i >= 10 && i <= 35) { //Create a gap 10 from the target key continue; } sl_insert(&skiplist, (ion_key_t) &i, junk); } #if DEBUG > 0 print_skiplist(&skiplist); #endif int search = 25; sl_node_t *node = sl_find_node(&skiplist, (ion_key_t) &search); CuAssertTrue(tc, *((int*)node->key) == key); CuAssertStrEquals(tc, (char*) str, (char*) node->value); sl_destroy(&skiplist); } /** @brief Randomly generates 50 random key value pairs and inserts them into the skiplist. The nodes are then recalled and the key/value pairs are compared to the original inserted ones for accuracy. @param tc CuTest dependency */ void test_skiplist_get_node_several( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); #if DEBUG > 0 // If debugging, use a static seed srand(0xDEADBEEF); #endif int targets[50]; unsigned char buffer[10]; int i; for(i = 0; i < 50; i++) { int key = rand() % 1000; targets[i] = key; sprintf((char*) buffer, "TEST %d", key); sl_insert(&skiplist, (ion_key_t) &key, buffer); } #if DEBUG > 0 print_skiplist(&skiplist); #endif for(i = 0; i < 50; i++) { int key = targets[i]; sl_node_t *node = sl_find_node(&skiplist, (ion_key_t) &key); sprintf((char*) buffer, "TEST %d", key); CuAssertTrue(tc, *((int*)node->key) == key); CuAssertStrEquals(tc, (char*) node->value, (char*) buffer); } sl_destroy(&skiplist); } /** @brief Tests querying on an empty skiplist. assertion is that the status should return as "err_item_not_found", and that the value pointer should not be allocated and will be set to null. @param tc CuTest dependency */ void test_skiplist_query_nonexist_empty( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int key = 3; unsigned char value[10] = "NULL"; err_t status = sl_query(&skiplist, (ion_key_t) &key, value); #if DEBUG > 0 print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_item_not_found); CuAssertStrEquals(tc, (char*) value, "NULL"); sl_destroy(&skiplist); } /** @brief Tests querying on a skiplist with one element, but for a key that doesn't exist within the skiplist. assertion is that the status should return as "err_item_not_found", and that the value pointer be initialized to null. @param tc CuTest dependency */ void test_skiplist_query_nonexist_populated_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int test_key = 23; unsigned char test_value[10]; strcpy((char*) test_value, "I am test"); sl_insert(&skiplist, (ion_key_t) &test_key, test_value); #if DEBUG > 0 print_skiplist(&skiplist); #endif int key = 10; unsigned char value[10] = "NULL"; err_t status = sl_query(&skiplist, (ion_key_t) &key, value); CuAssertTrue(tc, status == err_item_not_found); CuAssertStrEquals(tc, (char*) value, "NULL"); sl_destroy(&skiplist); } /** @brief Tests querying on a skiplist with several elements, but for a key that doesn't exist within the skiplist. assertion is that the status should return as "err_item_not_found", and that the value pointer be initialized to null. @param tc CuTest dependency */ void test_skiplist_query_nonexist_populated_several( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int test_key = 46; unsigned char test_value[10]; int i; for(i = 0; i < 32; i++) { sprintf((char*) test_value, "I am: %d", test_key); sl_insert(&skiplist, (ion_key_t) &test_key, test_value); test_key--; } #if DEBUG > 0 print_skiplist(&skiplist); #endif int key = 10; unsigned char value[10] = "NULL"; err_t status = sl_query(&skiplist, (ion_key_t) &key, value); CuAssertTrue(tc, status == err_item_not_found); CuAssertStrEquals(tc, (char*) value, "NULL"); sl_destroy(&skiplist); } /** @brief Tests querying on a skiplist with a single element, for a key that does exist within the skiplist. assertion is that the status should return as "err_ok", and that the value be initialized to the same value as stored at the specified key. @param tc CuTest dependency */ void test_skiplist_query_exist_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int test_key = 11; unsigned char test_value[10]; strcpy((char*) test_value, "Find me!"); sl_insert(&skiplist, (ion_key_t) &test_key, test_value); #if DEBUG > 0 print_skiplist(&skiplist); #endif int key = 11; unsigned char value[10]; err_t status = sl_query(&skiplist, (ion_key_t) &key, value); CuAssertTrue(tc, status == err_ok); CuAssertStrEquals(tc, (char*) value, "Find me!"); sl_destroy(&skiplist); } /** @brief Tests querying on a skiplist with several elements, for a key that exists within the skiplist. assertion is that the status should return as "err_ok", and that the value be initialized to the same value stored at the specified key. @param tc CuTest dependency */ void test_skiplist_query_exist_populated_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char test_value[10]; int i; for(i = 0; i < 100; i += 2) { sprintf((char*) test_value, "Find %d", i); sl_insert(&skiplist, (ion_key_t) &i, test_value); } #if DEBUG > 0 print_skiplist(&skiplist); #endif int key = 24; unsigned char value[10]; err_t status = sl_query(&skiplist, (ion_key_t) &key, value); CuAssertTrue(tc, status == err_ok); CuAssertStrEquals(tc, (char*) value, "Find 24"); sl_destroy(&skiplist); } /** @brief Tests querying on a skiplist with several elements, for a key that exists within the skiplist. assertion is that the status should return as "err_ok", and that the value be initialized to the same value stored at the specified key. @param tc CuTest dependency */ void test_skiplist_query_exist_populated_several( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char test_value[10]; int i; for(i = 0; i < 100; i++) { sprintf((char*) test_value, "Find %d", i); sl_insert(&skiplist, (ion_key_t) &i, test_value); } #if DEBUG > 0 print_skiplist(&skiplist); #endif char find_value[10]; unsigned char value[10]; for(i = 0; i < 100; i++) { sprintf(find_value, "Find %d", i); err_t status = sl_query(&skiplist, (ion_key_t) &i, value); CuAssertTrue(tc, status == err_ok); CuAssertStrEquals(tc, (char*) value, find_value); } sl_destroy(&skiplist); } /** @brief Tests a deletion from a skiplist that's empty. The assertion is that the deletion will fail, and return "err_item_not_found". No modifications should be made to the structure. @param tc CuTest dependency */ void test_skiplist_delete_empty( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int key = 3; err_t status = sl_delete(&skiplist, (ion_key_t) &key); #if DEBUG > 0 print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_item_not_found); sl_destroy(&skiplist); } /** @brief Tests a deletion from a skiplist that has one element, and the deleted element is not the one within the skiplist. The assertion is that the returned status is "err_item_not_found", and that no modification is to be made to the data structure. @param tc CuTest dependency */ void test_skiplist_delete_nonexist_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int key = 16; unsigned char value[10]; strcpy((char*) value, "Delete me"); sl_insert(&skiplist, (ion_key_t) &key, value); int fake_key = 33; err_t status = sl_delete(&skiplist, (ion_key_t) &fake_key); #if DEBUG > 0 print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_item_not_found); sl_destroy(&skiplist); } /** @brief Tests a deletion from a skiplist that has many elements, and the deleted element is not the one within the skiplist. The assertion is that the returned status is "err_item_not_found", and that no modification is to be made to the data structure. @param tc CuTest dependency */ void test_skiplist_delete_nonexist_several( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int key = 16; unsigned char value[10]; strcpy((char*) value, "Delete me"); int i; for(i = 0; i < 10; i++) { sl_insert(&skiplist, (ion_key_t) &key, value); key += 3; } int fake_key = 20; err_t status = sl_delete(&skiplist, (ion_key_t) &fake_key); #if DEBUG > 0 print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_item_not_found); sl_destroy(&skiplist); } /** @brief Tests deletion in a single element skiplist, where the deleted element is the one that exists within the skiplist. The assertion is that the status returned will be "err_ok", and the key/value pair deleted is no longer within the skiplist. @param tc CuTest dependency */ void test_skiplist_delete_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int key = 97; unsigned char value[10]; strcpy((char*) value, "Special K"); sl_insert(&skiplist, (ion_key_t) &key, value); #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif err_t status = sl_delete(&skiplist, (ion_key_t) &key); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, skiplist.head->next[0] == NULL); sl_destroy(&skiplist); } /** @brief Tests deleting a single node in a skiplist of several nodes, where the element to delete exists in the skiplist. The assertion is that the status returned will be "err_ok", and the key/value pair deleted is no longer within the skiplist. @param tc CuTest dependency */ void test_skiplist_delete_single_several( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char value[10]; strcpy((char*) value, "Poof me!"); int i; for(i = 101; i < 120; i++) { sl_insert(&skiplist, (ion_key_t) &i, value); } #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif sl_node_t *onebefore = sl_find_node(&skiplist, (ion_key_t) &(int) {111}); sl_node_t *theone = sl_find_node(&skiplist, (ion_key_t) &(int) {112}); sl_level_t theone_h = theone->height + 1; sl_level_t onebefore_h = onebefore->height + 1; /* This copies all the pointers that the target linked to before for assert * testing. */ sl_node_t *oldnextarr[theone_h]; for(i = 0; i < theone_h; i++) { oldnextarr[i] = theone->next[i]; } /* After this block, "theone" is undefined, freed memory and should not * be accessed. */ int key = 112; err_t status = sl_delete(&skiplist, (ion_key_t) &key); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); for(i = 0; i < (theone_h >= onebefore_h ? onebefore_h : theone_h); i++) { CuAssertTrue(tc, onebefore->next[i] == oldnextarr[i]); } sl_destroy(&skiplist); } /** @brief Tests deleting a single node in a skiplist of several nodes, where the element to delete exists in the skiplist. This skiplist is non- contiguous in its elements. The assertion is that the status returned will be "err_ok", and the key/value pair deleted is no longer within the skiplist. @param tc CuTest dependency */ void test_skiplist_delete_single_several_noncont( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char value[10]; strcpy((char*) value, "Bop me!"); int i; for(i = 230; i < 300; i+= 5) { sl_insert(&skiplist, (ion_key_t) &i, value); } #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif sl_node_t *onebefore = sl_find_node(&skiplist, (ion_key_t) &(int) {235}); sl_node_t *theone = sl_find_node(&skiplist, (ion_key_t) &(int) {240}); sl_level_t theone_h = theone->height + 1; sl_level_t onebefore_h = onebefore->height + 1; /* This copies all the pointers that the target linked to before for assert * testing. */ sl_node_t *oldnextarr[theone_h]; for(i = 0; i < theone_h; i++) { oldnextarr[i] = theone->next[i]; } /* After this block, "theone" is undefined, freed memory and should not * be accessed. */ int key = 240; err_t status = sl_delete(&skiplist, (ion_key_t) &key); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); for(i = 0; i < (theone_h >= onebefore_h ? onebefore_h : theone_h); i++) { CuAssertTrue(tc, onebefore->next[i] == oldnextarr[i]); } sl_destroy(&skiplist); } /** @brief Tests the deletion of all elements from a skiplist that has several. The assertion is that every deletion will return an "err_ok" status, and that at the end of the operations the skiplist must be empty. @param tc CuTest dependency */ void test_skiplist_delete_several_all( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); unsigned char value[10]; strcpy((char*) value, "Wipe"); int i; for(i = 9; i < 99; i+= 3) { sl_insert(&skiplist, (ion_key_t) &i, value); } #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif for(i = 9; i < 99; i+= 3) { err_t status = sl_delete(&skiplist, (ion_key_t) &i); CuAssertTrue(tc, status == err_ok); } #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif sl_node_t *cursor = skiplist.head; sl_level_t h; for(h = cursor->height; h >= 0; h--) { CuAssertTrue(tc, cursor->next[h] == NULL); } sl_destroy(&skiplist); } /** @brief Tests the updating of a node in an empty skiplist. The assertion is that the update will instead insert the node. @param tc CuTest dependency */ void test_skiplist_update_single_nonexist( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {72}, (ion_value_t) (char*){"test val"}); #if DEBUG > 0 print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, *(int*)skiplist.head->next[0]->key == 72); CuAssertStrEquals(tc, (char*) skiplist.head->next[0]->value, "test val"); sl_destroy(&skiplist); } /** @brief Tests the updating of a node in a skiplist with one element, but not with the same key that is being inserted. The assertion is that the update will instead insert the node. @param tc CuTest dependency */ void test_skiplist_update_single_nonexist_nonempty( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {99}, (ion_value_t) (char*){"not val"}); #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {13}, (ion_value_t) (char*){"test val"}); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, *(int*)skiplist.head->next[0]->key == 13); CuAssertStrEquals(tc, (char*) skiplist.head->next[0]->value, "test val"); sl_destroy(&skiplist); } /** @brief Tests the updating of a node in a skiplist with many elements, but not with the same key that is being inserted. The assertion is that the update will instead insert the node. @param tc CuTest dependency */ void test_skiplist_update_many_nonexist_nonempty( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 30; i < 40; i+= 2) { sl_insert(&skiplist, (ion_key_t) &i, (ion_value_t) (char*){"not it!"}); } #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {45}, (ion_value_t) (char*){"test val"}); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif sl_node_t *cursor = sl_find_node(&skiplist, (ion_key_t) &(int) {38}); CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, *(int*)cursor->next[0]->key == 45); CuAssertStrEquals(tc, (char*) cursor->next[0]->value, "test val"); sl_destroy(&skiplist); } /** @brief Tests the updating of a node in a skiplist with one element, where the one element is the node we attempt to update. The assertion is that the update will return the status of "err_ok", and the changes will be reflected within the node. @param tc CuTest dependency */ void test_skiplist_update_single_exist( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {45}, (ion_value_t) (char*){"old val"}); #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {45}, (ion_value_t) (char*){"new val"}); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, *(int*)skiplist.head->next[0]->key == 45); CuAssertStrEquals(tc, (char*) skiplist.head->next[0]->value, "new val"); sl_destroy(&skiplist); } /** @brief Tests the updating of a node in a skiplist with many elements, where the one to be updated exists in the skiplist. The assertion is that the update will return the status of "err_ok", and the changes will be reflected within the targeted node. @param tc CuTest dependency */ void test_skiplist_update_single_many_exist( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 20; i < 46; i += 2) { sl_insert(&skiplist, (ion_key_t) &i, (ion_value_t) (char*){"MATH"}); } #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {30}, (ion_value_t) (char*){"COSC"}); #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif sl_node_t *cursor = sl_find_node(&skiplist, (ion_key_t) &(int) {30}); CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, *(int*)cursor->key == 30); CuAssertStrEquals(tc, (char*) cursor->value, "COSC"); sl_destroy(&skiplist); } /** @brief Tests the updating of nodes in a skiplist with many elements, where all the nodes are to be updated. The assertion is that the update will return the status of "err_ok", and the changes will be reflected within all nodes. @param tc CuTest dependency */ void test_skiplist_update_several_many_exist( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 60; i < 99; i += 3) { sl_insert(&skiplist, (ion_key_t) &i, (ion_value_t) (char*){"TEST"}); } #if DEBUG > 0 printf("%s\n", "** BEFORE **"); print_skiplist(&skiplist); #endif for(i = 60; i < 99; i += 3) { /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &i, (ion_value_t) (char*){"VALUE"}); sl_node_t *cursor = sl_find_node(&skiplist, (ion_key_t) &i); CuAssertTrue(tc, status == err_ok); CuAssertTrue(tc, *(int*)cursor->key == i); CuAssertStrEquals(tc, (char*) cursor->value, "VALUE"); } #if DEBUG > 0 printf("%s\n", "** AFTER **"); print_skiplist(&skiplist); #endif sl_destroy(&skiplist); } /** @brief Tests an update in a skiplist containing several elements, all of the same key. The assertion is that all elements should be updated, with none of the original values remaining in the skiplist. @param tc CuTest dependency */ void test_skiplist_update_several_same_key( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 0; i < 100; i++) { /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {64}, (ion_value_t) (char*) {"samez U"}); } #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {64}, (ion_value_t) (char*) {"new same"}); #if DEBUG > 0 printf("%s\n", "** UPDATE **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); sl_node_t *cursor = skiplist.head; for(i = 0; i < 100; i++) { cursor = cursor->next[0]; CuAssertStrEquals(tc, "new same", (char*) cursor->value); } sl_destroy(&skiplist); } /** @brief Tests an update in a skiplist containing several elements, some of which with the same key. The assertion is that all elements of that specific key be updated, with none of the original values remaining. @param tc CuTest dependency */ void test_skiplist_update_several_same_key_in_mix( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); sl_insert(&skiplist, (ion_key_t) &(int) {32}, (ion_value_t) (char*) {"samez U"}); sl_insert(&skiplist, (ion_key_t) &(int) {33}, (ion_value_t) (char*) {"samez U"}); sl_insert(&skiplist, (ion_key_t) &(int) {35}, (ion_value_t) (char*) {"samez U"}); int i; for(i = 0; i < 100; i++) { /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {55}, (ion_value_t) (char*) {"samez U"}); } sl_insert(&skiplist, (ion_key_t) &(int) {100}, (ion_value_t) (char*) {"samez U"}); sl_insert(&skiplist, (ion_key_t) &(int) {101}, (ion_value_t) (char*) {"samez U"}); #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ err_t status = sl_update(&skiplist, (ion_key_t) &(int) {55}, (ion_value_t) (char*){"new same"}); #if DEBUG > 0 printf("%s\n", "** UPDATE **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); /* TODO collapse these into macros, so that this fits 80 cols */ sl_node_t *find = sl_find_node(&skiplist, (ion_key_t) &(int) {55}); for(i = 0; i < 100; i++) { /* TODO collapse these into macros, so that this fits 80 cols */ CuAssertStrEquals(tc, (char*) find->value, (char*){"new same"}); find = find->next[0]; } sl_destroy(&skiplist); } /** @brief Tests a deletion of a skiplist with one element, and then tests a reinsertion of a different key/value pair into the same skiplist. The assertion is that the insertion should work OK with no errors. @param tc CuTest dependency */ void test_skiplist_delete_then_insert_single( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {66}, (ion_value_t) (char*) {"toaster"}); #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif err_t status = sl_delete(&skiplist, (ion_key_t) &(int) {66}); CuAssertTrue(tc, status == err_ok); #if DEBUG > 0 printf("%s\n", "** DELETE **"); print_skiplist(&skiplist); #endif /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {365}, (ion_value_t) (char*) {"potato"}); #if DEBUG > 0 printf("%s\n", "** REINSERT **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, skiplist.head->next[0] != NULL); CuAssertTrue(tc, *(int*) skiplist.head->next[0]->key == 365); CuAssertStrEquals(tc, (char*) skiplist.head->next[0]->value, "potato"); sl_destroy(&skiplist); } /** @brief Tests a deletion of a skiplist with several elements, and then tests a reinsertion of several different key/value pairs into the same skiplist. The assertion is that the insertion should work OK with no errors. @param tc CuTest dependency */ void test_skiplist_delete_then_insert_several( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 0; i < 50; i++) { sl_insert(&skiplist, (ion_key_t) &i, (ion_value_t) (char*) {"cake"}); } #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif for(i = 0; i < 50; i++) { err_t status = sl_delete(&skiplist, (ion_key_t) &i); CuAssertTrue(tc, status == err_ok); } #if DEBUG > 0 printf("%s\n", "** DELETE **"); print_skiplist(&skiplist); #endif for(i = 50; i < 100; i++) { sl_insert(&skiplist, (ion_key_t) &i, (ion_value_t) (char*) {"pie"}); } #if DEBUG > 0 printf("%s\n", "** REINSERT **"); print_skiplist(&skiplist); #endif sl_node_t *cursor = skiplist.head; for(i = 50; i < 100; i++) { CuAssertStrEquals(tc, (char*) cursor->next[0]->value, "pie"); cursor = cursor->next[0]; } sl_destroy(&skiplist); } /** @brief Tests a deletion in a skiplist containing several elements, all of the same key. The assertion is that all elements should be deleted, with nothing remaining in the skiplist. @param tc CuTest dependency */ void test_skiplist_delete_several_same_key( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 0; i < 100; i++) { /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {64}, (ion_value_t) (char*) {"samez"}); } #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif err_t status = sl_delete(&skiplist, (ion_key_t) &(int) {64}); #if DEBUG > 0 printf("%s\n", "** DELETE **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); int h; for(h = skiplist.head->height; h >= 0; h--) { CuAssertTrue(tc, skiplist.head->next[h] == NULL); } sl_destroy(&skiplist); } /** @brief Tests a deletion in a skiplist containing several elements, some of which with the same key. The assertion is that all elements of the specific key be deleted, with only the other elements remaining. @param tc CuTest dependency */ void test_skiplist_delete_several_same_key_in_mix( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); sl_insert(&skiplist, (ion_key_t) &(int) {32}, (ion_value_t) (char*) {"samez"}); sl_insert(&skiplist, (ion_key_t) &(int) {33}, (ion_value_t) (char*) {"samez"}); sl_insert(&skiplist, (ion_key_t) &(int) {35}, (ion_value_t) (char*) {"samez"}); int i; for(i = 0; i < 100; i++) { /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(int) {55}, (ion_value_t) (char*) {"samez"}); } sl_insert(&skiplist, (ion_key_t) &(int) {100}, (ion_value_t) (char*) {"samez"}); sl_insert(&skiplist, (ion_key_t) &(int) {101}, (ion_value_t) (char*) {"samez"}); #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif err_t status = sl_delete(&skiplist, (ion_key_t) &(int) {55}); #if DEBUG > 0 printf("%s\n", "** DELETE **"); print_skiplist(&skiplist); #endif CuAssertTrue(tc, status == err_ok); /* TODO collapse these into macros, so that this fits 80 cols */ sl_node_t *find = sl_find_node(&skiplist, (ion_key_t) &(int) {55}); CuAssertTrue(tc, skiplist.super.compare(find->key, (ion_key_t) &(int) {55}, skiplist.super.record.key_size) != 0); sl_destroy(&skiplist); } /** @brief Tests a skiplist with different initialization parameters than usual. Each basic operation of insert, query, and delete are tested on the non-standard structure. @param tc CuTest dependency */ void test_skiplist_different_size( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; int key_size, value_size, pden, pnum, maxheight; key_type_t key_type; char (*compare)(ion_key_t, ion_key_t, ion_key_size_t); key_type = key_type_numeric_unsigned; compare = dictionary_compare_unsigned_value; key_size = 8; value_size = 4; pnum = 1; pden = 1; maxheight = 10; initialize_skiplist( &skiplist, key_type, compare, maxheight, key_size, value_size, pnum, pden ); /* TODO collapse these into macros, so that this fits 80 cols */ sl_insert(&skiplist, (ion_key_t) &(long long){64}, (ion_value_t) (char*){"pop"}); sl_insert(&skiplist, (ion_key_t) &(long long){32}, (ion_value_t) (char*){"bep"}); sl_insert(&skiplist, (ion_key_t) &(long long){16}, (ion_value_t) (char*){"tot"}); #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif sl_node_t *cursor; cursor = skiplist.head->next[0]; CuAssertTrue(tc, *(long long*) cursor->key == 16); CuAssertStrEquals(tc, (char*) cursor->value, "tot"); cursor = skiplist.head->next[0]->next[0]; CuAssertTrue(tc, *(long long*) cursor->key == 32); CuAssertStrEquals(tc, (char*) cursor->value, "bep"); cursor = skiplist.head->next[0]->next[0]->next[0]; CuAssertTrue(tc, *(long long*) cursor->key == 64); CuAssertStrEquals(tc, (char*) cursor->value, "pop"); unsigned char value[10]; err_t status; status = sl_query(&skiplist, (ion_key_t) &(long long){64}, value); CuAssertTrue(tc, status == err_ok); CuAssertStrEquals(tc, (char*) value, "pop"); status = sl_query(&skiplist, (ion_key_t) &(long long){32}, value); CuAssertTrue(tc, status == err_ok); CuAssertStrEquals(tc, (char*) value, "bep"); status = sl_query(&skiplist, (ion_key_t) &(long long){16}, value); CuAssertTrue(tc, status == err_ok); CuAssertStrEquals(tc, (char*) value, "tot"); status = sl_delete(&skiplist, (ion_key_t) &(long long){64}); CuAssertTrue(tc, status == err_ok); status = sl_delete(&skiplist, (ion_key_t) &(long long){32}); CuAssertTrue(tc, status == err_ok); status = sl_delete(&skiplist, (ion_key_t) &(long long){16}); CuAssertTrue(tc, status == err_ok); #if DEBUG > 0 printf("%s\n", "** DELETE **"); print_skiplist(&skiplist); #endif sl_destroy(&skiplist); } /** @brief Tests a skiplist under standard conditions with large keys. This is intended to test the comparison function, which used to break when keys were greater than 256. @param tc Cutest dependency */ void test_skiplist_big_keys( CuTest *tc ) { PRINT_HEADER(); skiplist_t skiplist; initialize_skiplist_std_conditions(&skiplist); int i; for(i = 230; i < 999; i++) { sl_insert(&skiplist, (ion_key_t) &i, (ion_value_t) (char*){"BIG!"}); } for(i = 230; i < 999; i++) { sl_node_t *cursor = sl_find_node(&skiplist, (ion_key_t) &i); CuAssertTrue(tc, *(int*)cursor->key == i); CuAssertStrEquals(tc, (char*) cursor->value, "BIG!"); } #if DEBUG > 0 printf("%s\n", "** INSERT **"); print_skiplist(&skiplist); #endif for(i = 230; i < 999; i++) { sl_delete(&skiplist, (ion_key_t) &i); } #if DEBUG > 0 printf("%s\n", "** DELETE **"); print_skiplist(&skiplist); #endif int h; for(h = skiplist.head->height; h >= 0; h--) { CuAssertTrue(tc, skiplist.head->next[h] == NULL); } sl_destroy(&skiplist); } /** @brief Creates the suite to test using CuTest. @return Pointer to a CuTest suite. */ CuSuite* skiplist_getsuite() { CuSuite *suite = CuSuiteNew(); /* Initialization Tests */ SUITE_ADD_TEST(suite, test_skiplist_initialize); SUITE_ADD_TEST(suite, test_skiplist_free_all); /* Level Tests */ SUITE_ADD_TEST(suite, test_skiplist_generate_levels_std_conditions); /* Insertion Tests */ SUITE_ADD_TEST(suite, test_skiplist_single_insert); SUITE_ADD_TEST(suite, test_skiplist_insert_multiple); SUITE_ADD_TEST(suite, test_skiplist_randomized_insert); /* Get Node Tests */ SUITE_ADD_TEST(suite, test_skiplist_get_node_single); SUITE_ADD_TEST(suite, test_skiplist_get_node_single_high); SUITE_ADD_TEST(suite, test_skiplist_get_node_single_low); SUITE_ADD_TEST(suite, test_skiplist_get_node_single_many); SUITE_ADD_TEST(suite, test_skiplist_get_node_several); /* Query Tests */ SUITE_ADD_TEST(suite, test_skiplist_query_nonexist_empty); SUITE_ADD_TEST(suite, test_skiplist_query_nonexist_populated_single); SUITE_ADD_TEST(suite, test_skiplist_query_nonexist_populated_several); SUITE_ADD_TEST(suite, test_skiplist_query_exist_single); SUITE_ADD_TEST(suite, test_skiplist_query_exist_populated_single); SUITE_ADD_TEST(suite, test_skiplist_query_exist_populated_several); /* Delete Tests */ SUITE_ADD_TEST(suite, test_skiplist_delete_empty); SUITE_ADD_TEST(suite, test_skiplist_delete_nonexist_single); SUITE_ADD_TEST(suite, test_skiplist_delete_nonexist_several); SUITE_ADD_TEST(suite, test_skiplist_delete_single); SUITE_ADD_TEST(suite, test_skiplist_delete_single_several); SUITE_ADD_TEST(suite, test_skiplist_delete_single_several_noncont); SUITE_ADD_TEST(suite, test_skiplist_delete_several_all); SUITE_ADD_TEST(suite, test_skiplist_delete_several_same_key); SUITE_ADD_TEST(suite, test_skiplist_delete_several_same_key_in_mix); /* Update Tests */ SUITE_ADD_TEST(suite, test_skiplist_update_single_nonexist); SUITE_ADD_TEST(suite, test_skiplist_update_single_nonexist_nonempty); SUITE_ADD_TEST(suite, test_skiplist_update_many_nonexist_nonempty); SUITE_ADD_TEST(suite, test_skiplist_update_single_exist); SUITE_ADD_TEST(suite, test_skiplist_update_single_many_exist); SUITE_ADD_TEST(suite, test_skiplist_update_several_many_exist); SUITE_ADD_TEST(suite, test_skiplist_update_several_same_key); SUITE_ADD_TEST(suite, test_skiplist_update_several_same_key_in_mix); /* Hybrid Tests */ SUITE_ADD_TEST(suite, test_skiplist_delete_then_insert_single); SUITE_ADD_TEST(suite, test_skiplist_delete_then_insert_several); /* Variation Tests */ SUITE_ADD_TEST(suite, test_skiplist_different_size); SUITE_ADD_TEST(suite, test_skiplist_big_keys); return suite; } /** @brief Runs all skiplist related tests and outputs the result. */ void runalltests_skiplist() { CuString *output = CuStringNew(); CuSuite *suite = skiplist_getsuite(); CuSuiteRun(suite); CuSuiteSummary(suite, output); CuSuiteDetails(suite, output); printf("----\nSkiplist Tests:\n%s\n", output->buffer); CuSuiteDelete(suite); CuStringDelete(output); }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int i, b[100], a[100]; for(i=1; i<=100; i=i+1) { b[i]=i; } a[0]=0; for(i=1; i<=100; i=i+1) { a[i]=b[i]+a[i-1]; } printf("%d\n" ,a[29]); printf("%d\n" ,a[30]); printf("%d\n" ,a[49]); printf("%d\n" ,a[50]); printf("%d\n" ,a[50]-a[30]); printf("\n\n"); system("PAUSE"); return 0; }
C
//B+ݽṹ #ifndef __BTREE_H_ #define __BTREE_H_ #include "vector.h" #pragma pack() #define BTREE_KEY_NUM 10 #define BTREE_KEY_FULL 2 #define BTREE_KEY_EXIST 0 #define BTREE_KEY_SUC 1 #define BTREE_FAIL -1 #define BTREE_OK 0 #define BT_KEY unsigned long typedef enum { BT_LVL_LEAF = 1, BT_LVL_INT, BT_LVL_ROOT }btlvl_t; typedef enum { TYPE_LEAF = 1, TYPE_INT }btype_t; typedef struct btree_key_s { BT_KEY bn_key; //ؼ }btk_t; typedef struct btree_pointer_s { void * bn_ptr; //ָ }btp_t; typedef struct btree_leaf_s { struct list_head lnode; //Ҷӽڵ int bn_num; //ڵЧkey btk_t bn_data[]; //Ҷӽڵ }btleaf_t; typedef struct btree_index_s { btk_t bn_key; btp_t bn_ptr; }bti_t; typedef struct btree_inter_s { int bn_num; //ڵЧkey bti_t bn_entry[]; //мڵҶϢ }btinter_t; typedef struct bptree_node_s { btlvl_t bn_level; //ڵlevel btype_t bn_type; //ڵ union{ btleaf_t bn_leaf; //Ҷӽڵ btinter_t bn_inter; //мڵ }; }btnode_t; #define BT_PTR (btnode_t *) typedef struct bplus_tree_s { btnode_t * bpt_root; //ĸڵָ int bpt_level; //ܲ㼶 int bpt_branch_nums; //Ҷ int bpt_leaf_nums; //Ҷӽڵ }bptree_t; #define NODE_SIZE 128 #define INTER_KEY_NUM ((NODE_SIZE-sizeof(btlvl_t)-sizeof(btype_t)-sizeof(int))/sizeof(bti_t)) #define LEAF_KEY_NUM ((NODE_SIZE-sizeof(btlvl_t)-sizeof(btype_t)-sizeof(int)-sizeof(struct list_head))/sizeof(btk_t)) typedef enum { MOD_OK = 0, MOD_NOK, MOD_FAIL }modv_t; //delete return value typedef enum { ROT_DEL = 1, ROT_ADD }rot_t; //rotate mode typedef enum { LEFT = 0, MID, RIGHT, ORDNUM }ndflag_t; //node flag for rotate/merge typedef struct { int leftkey; int midkey; int rightkey; ndflag_t invalidnode; bti_t newnode; }modinfo_t; typedef struct { btk_t updkey; //update key bti_t newidx; //split new entry }spt_info_t; typedef struct { btnode_t * pleft; //ڵ btnode_t * plfather; //ӽڵĸڵ int leftidx; //ӽڵ btnode_t * pmid; //ӽڵ int mididx; //ӽڵ btnode_t * pright; //ҽڵ btnode_t * prfather; //ӽڵĸڵ int rightidx; //ӽڵ }btpath_t; #endif
C
#include <stdio.h> #include <stdlib.h> int main() { /* DICHIARAZIONE */ int A; int B; /* start */ /* IN A, B */ scanf("%i %i", &A, &B); /* condizione A > B */ if( A>B ) { /* blocco di istruzioni ramo Vero */ /* OUT A */ printf("%i", A); } else { /* blocco di istruzioni ramo Falso */ /* OUT B */ printf("%i", B); } /* stop */ return 0; }
C
#include <stdio.h> #include <string.h> int isPalin(char *inp); int isMirror(char *inp); int compare(char a, char b); int main() { char inp[10000]; register int p,m; while(scanf(" %[^\n]",inp)!=EOF) { p=isPalin(inp); m=isMirror(inp); if(p && m) printf("%s -- is a mirrored palindrome.",inp); else if(!p && m) printf("%s -- is a mirrored string.",inp); else if(p && !m) printf("%s -- is a regular palindrome.",inp); else printf("%s -- is not a palindrome.",inp); printf("\n\n"); } return 0; } int isPalin(char *inp) { register int i,j,l; l=strlen(inp); for(i=0,j=l-1; i<=l/2; i++,j--) { if(inp[i]=='0') inp[i]='O'; if(inp[j]=='0') inp[j]='O'; if(inp[i]!=inp[j]) return 0; } return 1; } int isMirror(char *inp) { register int i,j,l,p; l=strlen(inp); for(i=0,j=l-1; i<=l/2; i++,j--) if(!compare(inp[i],inp[j])) return 0; return 1; } int compare(char a, char b) { if(a=='0') a='O'; if(b=='0') b='O'; char num[]="1SE Z 8 "; char let[]="A 3 HIL JM O 2TUVWXY5"; if(a>='1' && a<='9') return (b==num[a-'1']); if(a>='A' && a<='Z') return (b==let[a-'A']); return 0; }
C
#include <stdio.h> /* Escrever um algoritmo que gere e escreva os números múltiplos de 11 entre 100 e 200. */ int main (void){ int i = 0; while (i*11 <= 200){ if (11*i >= 100 && 11*i <=200){ printf("%i\n", 11*i); } else if (11*i > 200){ break; } i++; } }
C
/* Name: Jyotishka Bhattacharjee Scholar ID: 2012025 */ #include <stdio.h> int main() { char number[1000]; printf("Enter the value\n"); scanf("%s", number); int i = 0; int condition1 = 0, condition2 = 0; while (number[i] != '\0') { if (number[i] == '.') { condition1++; if (number[i + 1] != '\0') condition2 = 1; } i++; } if (condition1 == 1 && condition2 == 1) printf("Valid floating point number\n"); else printf("Invalid floating point number\n"); return 0; }
C
#include<stdio.h> #include<conf.h> #include<kernel.h> #include<proc.h> static unsigned long *esp; void printprocstks(int prior) { kprintf("\n#4 printprocstk------------------------\n"); struct pentry *proc; int i; kprintf("pname\tpid\tpriority\tstack base\tstack size\tstack limit\tstack pointer\n"); for(i = 0; i < NPROC; i++) { proc = &proctab[i]; if(proc->pstate != PRFREE && proc->pprio < prior) { if(proc->pstate == PRCURR) { asm("movl %esp, esp"); kprintf("%s\t%d\t%d\t%08x\t%d\t%08x\t%08x <---- current proc\n", proc->pname, i, proc->pprio, proc->pbase, proc->pstklen, proc->plimit, esp); } else { esp = (unsigned long *)proc->pesp; kprintf("%s\t%d\t%d\t%08x\t%d\t%08x\t%08x\n", proc->pname, i, proc->pprio, proc->pbase, proc->pstklen, proc->plimit, esp); } } } }
C
#include "header.h" /*---------------------------------------------------------funcs for input data base (per line)-----------------------------------*/ /*database_get_pointer_to_*/ input_data* get_data_base() { static input_data data; return &data; } int data_set_line(FILE* file) { input_data* data; data = get_data_base(); if (fgets(data->line, MAX_LINE_LEN, file) == NULL) return EOF; return OK; } char* data_get_line() { input_data* data; data = get_data_base(); return data->line; } char** data_get_lable() { input_data* data; data = get_data_base(); return &(data->lable); } char** data_get_command() { input_data* data; data = get_data_base(); return &(data->command); } char* data_get_command_type() { input_data* data; data = get_data_base(); return &(data->command_type); } char** data_get_value() { input_data* data; data = get_data_base(); return &(data->str_value); } int* data_get_num_value() { input_data* data; data = get_data_base(); return &(data->num_of_values); } value_and_mode** data_get_value_arr() /*geting a pinter to a array of structs that store the values */ { input_data* data; data = get_data_base(); return &(data->values_arr); }
C
#ifndef DESCOMPACTADOR_H_ #define DESCOMPACTADOR_H_ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "../include/tree.h" #include "../include/list.h" #include "../include/bitmap.h" #include "../include/huffman.h" #endif /* DESCOMPACTADOR_H_ */ /** * @brief Realiza a leitura do arquivo compactado. * @param fRComp Ponteiro para o arquivo compactado. * @return Ponteiro para o bitmap no qual foi setado o conteúdo que estava no arquivo compactado. **/ bitmap* leArquivoCompactado(FILE *fRComp); /** * @brief Lê o cabeçalho do arquivo .comp e gera a árvore de codificação de huffman. * @param bm Bitmap que contém o cabeçalho a ser lido. * @param tree Árvore que será gerada após decodificação do cabeçalho. * Obs: Deve estar inicializada. * @param i Ponteiro para i-ésima posição do bitmap. É ponteiro para * que seu valor atual seja acessado em qualquer nível de recursão. * @param folhas Ponteiro para o contador de folhas que já foram lidas no cabeçalho. * É ponteiro para que seu valor atual seja acessado em qualquer nível de recursão. * @param lixo Ponteiro para lixo do cabeçalho. Ao longo da função, vai calculando * o tamanho do lixo, ou seja, a quantidade de bits que devem ser ignorados no bitmap após * decodificar o cabeçalho. **/ void recriaTree(bitmap* bm, Tree* tree, int* i, int* folhas, int* lixo); /** * @brief Decodifica o trecho de texto compactado de um bitmap. * @param bm Bitmap que contém a codificação do arquivo .comp. * @param i Ponteiro para i-ésima posição do bitmap. É ponteiro para * que seu valor atual seja acessado em qualquer nível de recursão. * @param tree Árvore de codificação de huffman. * @param lixoTexto Tamanho do lixo em bits do trecho de texto compactado. * Em outras palavras, é a quantidade de bits que devem ser ignorados no final do bitmap. * @param nomeArquivoCompactado Nome do arquivo .comp. **/ void decodificaTexto(bitmap* bm, int* i, Tree* tree, int lixoTexto, unsigned char* nomeArquivoCompactado); /** * @brief Decodifica um bitmap que contém a codificação do arquivo .comp. * @param bm Bitmap que contém a codificação do arquivo .comp. * @param nomeArquivoCompactado Nome do arquivo .comp. **/ void decodifica(bitmap* bm, unsigned char* nomeArquivoCompactado); /** * @brief Pega a parte do cabeçalho que representa o tamanho do lixo do texto e o calcula. * @param bm Bitmap que contém a codificação do arquivo. * @return Tamanho do lixo do texto. **/ int getLixoTexto(bitmap* bm); /** * @brief Gera um bitmap codificado a partir de uma string com o conteúdo a ser setado nele. * @param str String com o conteúdo que será setado no bitmap. * @param tam tamanho da string. * @return Bitmap criado e inicializado. **/ bitmap* recuperaBitmap(unsigned char* str, int tam); /** * @brief Descompacta um arquivo que foi compactado com a codificação de huffman. * @param nomeArquivoCompactado Nome do arquivo compactado com a codificação de huffman. **/ void descompacta(unsigned char* nomeArquivoCompactado);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_selection_state.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mel-idri <mel-idri@student.1337.ma> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/05 18:11:08 by mel-idri #+# #+# */ /* Updated: 2021/02/11 19:29:00 by mel-idri ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_select.h" t_selection_state *init_selection_state(char **argv) { t_selection_state *selection_state; t_selection_element selection_element; if (argv[0] == NULL || argv[1] == NULL) return (NULL); selection_state = safe_malloc(sizeof(t_selection_state)); selection_state->cursor_pos = 0; selection_state->vector = (t_selection_element_vec *) vector_init(sizeof(t_selection_element), NULL); selection_element.is_selected = 0; argv++; while (*argv) { selection_element.value = *argv; vector_push((t_vector *)selection_state->vector, &selection_element); argv++; } return (selection_state); }
C
#include <stdbool.h> #include <stdio.h> int main(int argc, char const* argv[]) { char A[] = "madam"; int size = sizeof(A) / sizeof(char); bool isPalin; for(int i = 0; i < size; ++i) { if(A[i] == A[size - i]) { isPalin = true; } } if(isPalin) { printf("Palindrome \n"); } else { printf("Not palindrome\n"); } return 0; }
C
//******************************************************************************************************* // xfersong.c // // DESCRIPTION // // AUTHORS // Jace Hensley (jehensle@asu.edu) // Computer Systems Engineering // Arizona State University //******************************************************************************************************** #include "xfersong.h" #include "uc_pushb.h" uint8 g_rx_buf[531]; int g_bytes_in_packet; int g_rx_cnt; xfer_state_t xfer_state; static song_t l_song; // Create local song variable to fill and return xfer_led_t led1 = led_off; // When UART receives a byte void xfersong_callback(){ g_rx_buf[g_rx_cnt] = get_char(); // Store the byte in the buffer if(led1 == led_off) { uc_led_on(uc_led_1); led1 = led_on; } else { uc_led_off(uc_led_1); led1 = led_off; } //uc_led_toggle(uc_led_1); // Toggle the LED g_rx_cnt++; // Increment the counter } static void pit0_xfer_callback(){ if(led1 == led_off) { uc_led_on(uc_led_1); led1 = led_on; } else { uc_led_off(uc_led_1); led1 = led_off; } // uc_led_toggle(uc_led_1); } static void xfersong_pb2_callback() { if (xfer_state == xfer_idle_state) { xfer_state = xfer_exit_state; } } static void xfersong_pb1_callback() { //nothing } // Will return a song_t object to main.c song_t transfer_song(){ int secondByte; // Second byte holds the most significant 8 bits of total number of bytes int thirdByte; // Third byte holds the least significant 8 bits of total number of bytes int ninthByte; // Ninth byte holds the most significant 8 bits of the tempo int tenthByte; // Tenth byte holds the least signifcant 8 bits of the tempo int eleventhByte; // 11th byte holds the most significant 8 bits of the tempo int twelthByte; // 12th byte holds the least signifcant 8 bits of the tempo int i; // Counter int noteCount; uc_pushb_set_callback(uc_pushb_2, xfersong_pb2_callback); // Configure push button 2 for different functionality uc_pushb_set_callback(uc_pushb_1, xfersong_pb1_callback); xfer_state = xfer_start_state; // Start state //uart_channel_enable(1, xfersong_callback); // Turn on UART pit_init(pit_timer_0, (uint8) 0x7, (uint16) 78124, pit0_xfer_callback); pit_enable(pit_timer_0); // Enable the PIT to toggle LED at 2Hz while(xfer_state != xfer_exit_state){ switch(xfer_state){ case xfer_start_state: g_rx_cnt = 0; // Initialize the counter to 0 g_bytes_in_packet = 0; // Reset number of bytes to 0 xfer_state = xfer_idle_state; // Go to next state break; case xfer_idle_state: uart_channel_enable(1, xfersong_callback); // Enable the UART module to start receiving bytes at 300baud while(g_rx_cnt == 0){ // Wait in an infinite while loop until the first byte is received if(xfer_state == xfer_exit_state){ // While waiting, check to see if PB2 is pressed. If pressed, // break out of switch and transfer_song function return l_song; } } xfer_state = xfer_begin_state; // After first character received, go to the next state break; case xfer_begin_state: pit_disable(pit_timer_0); // Disable PIT0 to stop toggling LED1 uc_led_on(uc_led_1); // Turn LED1 on xfer_state = xfer_wait_state; // Go to next state break; case xfer_wait_state: while(g_rx_cnt <= 3) { if(g_rx_cnt == 2) secondByte = 256 * (int)g_rx_buf[1]; // Retrieve the most significant 8 bits and turn into int else if(g_rx_cnt == 3) thirdByte = (int)g_rx_buf[2]; // Retrieve the least significant 8 bits and turn into int } g_bytes_in_packet = secondByte + thirdByte; // Add the least and most significant bytes together to get total bytes as integer xfer_state = xfer_xfering_state; // Go to next state break; case xfer_xfering_state: while (g_rx_cnt < g_bytes_in_packet) { // Retrieve all the bytes in the packet } xfer_state = xfer_end_state; // Go to next state break; case xfer_end_state: uc_led_on(uc_led_1); // Turn LED1 on pit_enable(pit_timer_0); // Enable Pit0 again to flash LED1 at 2Hz (toggle every .25s) // Extract info from buffer and store into a song_t ninthByte = 256 * (int)g_rx_buf[8]; // Retrieve the most significant 8 bits and turn into int tenthByte = (int)g_rx_buf[9]; // Retrieve the least significant 8 bits and turn into int l_song.tempo = ninthByte + tenthByte; // Get the tempo from the sum of the ninth and tenth byte eleventhByte = 256 * (int)g_rx_buf[10]; // Retrieve the most significant 8 bits and turn into int twelthByte = (int)g_rx_buf[11]; // Retrieve the least significant 8 bits and turn into int l_song.num_notes = eleventhByte + twelthByte + 1; // Get the number of notes from the sum of the 11th and 12th byte // Parse each note into a song_t structure noteCount = 0; for(i = 19; i < g_bytes_in_packet; i++) { if((i % 2) == 1) l_song.notes[(i-19-noteCount)].pitch = (pitch_t)g_rx_buf[i]; else { l_song.notes[(i-20-noteCount)].duration = (duration_t)g_rx_buf[i]; noteCount++; } } xfer_state = xfer_start_state; // Go back to start state l_song.success = true; break; } } uart_channel_disable(1); // Turn off UART uc_led_off(uc_led_1); // Turn off LED1 uc_led_off(uc_led_3); // Turn off LED3 uc_led_off(uc_led_4); // Turn off LED4 return l_song; }
C
#include "lifegame.h" void life(char namein[] , char nameout[] , int hei , int wit , int n , int f , char core[]) { int i,j; int image_counter=1; char buf[256]; mat_t mat=mat_alloc(hei,wit); mat_t mat_tmp=mat_alloc(hei , wit); population_t pop=pop_alloc(); population_t pop_dead=pop_alloc(); population_t pop_tmp=pop_alloc(); population_t ptmp; mat_t mtmp; read_file(namein , pop); // wczytanie z pliku komorek do populacji for(i=0;i<pop->size;i++) // uzupelnienie planszy { if(is_edge( pop->c[i].x , pop->c[i].y , mat->n , mat->m)) { printf("\nPLANSZA JEST ZA MALA NA TE DANE\nPOWIEKSZ PLANSZE ZWIEKSZAJAC -n I -m W PARAMATRACH\n"); exit ( EXIT_FAILURE); } mat->board[pop->c[i].x][pop->c[i].y]=1; } for(i=0;i<n;i++) { if(i%f==0) { sprintf(buf , "images/%s%d.bmp" , core , image_counter); make_image(pop , mat->n , mat->m , buf); image_counter++; } for(j=0;j<pop->size;j++) dead_neighbor(pop->c[j].x , pop->c[j].y , pop_dead , mat->board , mat->n , mat->m ); for(j=0;j<pop_dead->size;j++) { if(is_alive(pop_dead->c[j].x , pop_dead->c[j].y , mat->board , mat->n , mat->m)) { mat_tmp->board[pop_dead->c[j].x][pop_dead->c[j].y]=1; pop_add(pop_tmp , pop_dead->c[j].x , pop_dead->c[j].y); } mat->board[pop_dead->c[j].x][pop_dead->c[j].y]=0; } pop_clear(pop_dead); for(j=0;j<pop->size;j++) { if(is_alive(pop->c[j].x , pop->c[j].y , mat->board , mat->n , mat->m)) { mat_tmp->board[pop->c[j].x][pop->c[j].y]=1; pop_add(pop_tmp , pop->c[j].x , pop->c[j].y); } } for(j=0;j<pop->size;j++) mat->board[pop->c[j].x][pop->c[j].y]=0; pop_clear(pop); ptmp=pop;//zamienic na funkcje? pop=pop_tmp; pop_tmp=ptmp; mtmp=mat; mat=mat_tmp; mat_tmp=mtmp; } write_file( nameout , pop ); pop_free(pop); pop_free(pop_tmp); pop_free(pop_dead); mat_free(mat); mat_free(mat_tmp); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* operation_r.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: youncho <youncho@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/20 05:58:11 by youncho #+# #+# */ /* Updated: 2021/06/24 12:40:38 by youncho ### ########.fr */ /* */ /* ************************************************************************** */ #include "../push_swap.h" void rx(t_stack *x) { if (x->size < 2) return ; x->head = x->head->next; if (x->name) ft_printf("r%c\n", x->name); } void rr(t_ps *ps) { if (ps->a->size >= 2) ps->a->head = ps->a->head->next; if (ps->b->size >= 2) ps->b->head = ps->b->head->next; if (!ps->is_chk && (ps->a->size >= 2 || ps->b->size >= 2)) ft_printf("rr\n"); } void rrx(t_stack *x) { if (x->size < 2) return ; x->head = x->head->prev; if (x->name) ft_printf("rr%c\n", x->name); } void rrr(t_ps *ps) { if (ps->a->size >= 2) ps->a->head = ps->a->head->prev; if (ps->b->size >= 2) ps->b->head = ps->b->head->prev; if (!ps->is_chk && (ps->a->size >= 2 || ps->b->size >= 2)) ft_printf("rrr\n"); }