language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#ifndef TCP_H #define TCP_H #include "includes/packet.h" enum{ TRANSPORT_MAX_SIZE = PACKET_MAX_PAYLOAD_SIZE, TRANSPORT_HEADER_SIZE = 8, TRANSPORT_MAX_PAYLOAD_SIZE = TRANSPORT_MAX_SIZE - TRANSPORT_HEADER_SIZE, TRANSPORT_MAX_PORT = 255 }; //Types of Packets enum{ TRANSPORT_SYN = 0, TRANSPORT_ACK = 1, TRANSPORT_SYNACK = 2, TRANSPORT_FIN = 3, TRANSPORT_FINACK = 4, TRANSPORT_DATA = 5, TRANSPORT_TYPE_SIZE = 6 }; enum{ NULL_TRANSPORT_PAYLOAD = 0, NULL_TRANSPORT_VALUE = 0, NULL_TRANSPORT_HEX_VALUE = 0x0000 }; typedef nx_struct TCP{ nx_uint8_t srcPort; nx_uint8_t destPort; nx_uint8_t type; nx_uint16_t window; nx_uint16_t seq; nx_uint8_t len; nx_uint8_t payload[TRANSPORT_MAX_PAYLOAD_SIZE]; }TCP; void createTransport(transport *output, uint8_t srcPort, uint8_t destPort, uint8_t type, uint16_t window, int16_t seq, uint8_t *payload, uint8_t packetLength); void printTransport(transport *input); #endif /* TCP_H */
C
#include<stdio.h> #include<stdlib.h> struct node { int data; struct node *next; }; void create(struct node **head,int d) { struct node *new; new=(struct node *)malloc(sizeof(struct node)); new->data=d; new->next=NULL; if(*head==NULL) { *head=new; } else { struct node *t=*head; while(t->next!=NULL) { t=t->next; } t->next=new; } } void display(struct node *head) { struct node *ptr=head; while(ptr!=NULL) { printf("%d\t",ptr->data); ptr=ptr->next; } } void traverse_M_leaving_N(struct node *head,int m,int n) { struct node *t=head; struct node *t1; int i,j; while(t) { for(i=1;i<m,t!=NULL;++i) { t=t->next; } if(t==NULL) { return; } t1=t->next; for(j=1;j<=n,t1!=NULL;++j) { struct node *temp=t1; t1=t1->next; free(temp); } t->next=t1; t=t1; } } int main() { int n,e; printf("enter the no. of nodes\n"); scanf("%d",&n); struct node *head=NULL; for(int i=0;i<n;++i) { printf("enter the data\n"); scanf("%d",&e); create(&head,e); } display(head); int m,n1; printf("enter the value of m,n\n"); scanf("%d%d",&m,&n1); traverse_M_leaving_N(head,m,n1); printf("\n New List\n"); display(head); return 0; }
C
#include <stdio.h> int main() {void avsco(float *,float *); void avcour1(char (*)[10],float *); void fali2(char course[5][10],int num[],float *pscore,float aver[4]); void good(char course[5][10],int num[4],float *pscore,float aver[4]); int i,j,*pnum,num[4]; float score[4][5],aver[4],*pscore,*paver; char course[5][10],(*pcourse)[10]; printf("input course:\n"); pcourse=course; for (i=0;i<5;i++) scanf("%s",course[i]); printf("input NO. and scores:\n"); printf("NO."); for (i=0;i<5;i++) printf(",%s",course[i]); printf("\n"); pscore=&score[0][0]; pnum=&num[0]; for (i=0;i<4;i++) {scanf("%d",pnum+i); for (j=0;j<5;j++) scanf("%f",pscore+5*i+j); } paver=&aver[0]; printf("\n\n"); avsco(pscore,paver); // ÿѧƽɼ avcour1(pcourse,pscore); // һſεƽɼ printf("\n\n"); fali2(pcourse,pnum,pscore,paver); // ҳ2ſβѧ printf("\n\n"); good(pcourse,pnum,pscore,paver); // ҳɼõѧ return 0; } void avsco(float *pscore,float *paver) // ÿѧƽɼĺ {int i,j; float sum,average; for (i=0;i<4;i++) {sum=0.0; for (j=0;j<5;j++) sum=sum+(*(pscore+5*i+j)); //ۼÿѧĸƳɼ average=sum/5; //ƽɼ *(paver+i)=average; } } void avcour1(char (*pcourse)[10],float *pscore) // һγ̵ƽɼĺ {int i; float sum,average1; sum=0.0; for (i=0;i<4;i++) sum=sum+(*(pscore+5*i)); //ۼÿѧĵ÷ average1=sum/4; //ƽɼ printf("course 1:%s average score:%7.2f\n",*pcourse,average1); } void fali2(char course[5][10],int num[],float *pscore,float aver[4]) // Ͽγ̲ѧĺ {int i,j,k,labe1; printf(" ==========Student who is fail in two courses======= \n"); printf("NO. "); for (i=0;i<5;i++) printf("%11s",course[i]); printf(" average\n"); for (i=0;i<4;i++) {labe1=0; for (j=0;j<5;j++) if (*(pscore+5*i+j)<60.0) labe1++; if (labe1>=2) {printf("%d",num[i]); for (k=0;k<5;k++) printf("%11.2f",*(pscore+5*i+k)); printf("%11.2f\n",aver[i]); } } } void good(char course[5][10],int num[4],float *pscore,float aver[4]) // ҳɼѧ(85ϻƽ90)ĺ {int i,j,k,n; printf(" ======Students whose score is good======\n"); printf("NO. "); for (i=0;i<5;i++) printf("%11s",course[i]); printf(" average\n"); for (i=0;i<4;i++) {n=0; for (j=0;j<5;j++) if (*(pscore+5*i+j)>85.0) n++; if ((n==5)||(aver[i]>=90)) {printf("%d",num[i]); for (k=0;k<5;k++) printf("%11.2f",*(pscore+5*i+k)); printf("%11.2f\n",aver[i]); } } }
C
typedef struct { int top; int limit; int* list; } Stack; Stack create_stack(int limit); void print_stack(Stack stack); int stack_push(Stack *stack, int num); int stack_pop(Stack *stack); Stack create_stack(int limit) { Stack stack; stack.top = 0; stack.limit = limit; stack.list = (int *)malloc(limit * sizeof(int)); return stack; } void print_stack(Stack stack) { printf("["); while(stack.top > 0) printf(" %d,", stack_pop(&stack)); puts(" ]"); } int stack_push(Stack *stack, int num) { if (stack->top == stack->limit) { puts("Stack overflow"); return -1; } stack->list[stack->top++] = num; return 0; } int stack_pop(Stack *stack) { if (stack->top == 0) { puts("Stack underflow"); return - 1; } int num = stack->list[stack->top]; stack->list[stack->top--] = 0; return num; }
C
double ft_db_fibonacci(int index) { double pred; double pre_floor; if (index < 0) return (-1); else if (index == 0) return (0); else if (index == 1) return (1); else if (index == 2) return (1); else if (index == 3) return (2); else if (index == 4) return (3.5); else { pred = ft_db_fibonacci(index - 1); pre_floor =(double)(int)pred; return (pre_floor + (int)((1/(pred - pre_floor))+.5)+1/pre_floor); } } int ft_fibonacci(int index) { return ((int)ft_db_fibonacci(index)); }
C
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> long int buyMaximumProducts(int n, long int k, int* a) { // Complete this function long int sum = 0; long int counter = 0; int i = 0; while (i < n) { int j = 0; while (j <= i && sum < k) { sum += a[i]; // printf("%d:%ld::counter = %ld ", i, sum, counter); // if (sum > k) { // return counter; // } else if (sum == k) { // return ++counter; // } j++; counter++; } i++; } return counter; } int main() { int n = 3; // int n = 1; // int arr[5] = {10, 10, 10, 10, 10}; // int arr[2] = {100, 100}; int arr[3] = {10, 7, 19}; // long int arr[1] = {10}; // long int k = 20; // long int k = 100; long int k = 45; long int result = buyMaximumProducts(n, k, arr); printf("%ld\n", result); return 0; }
C
#include<stdio.h> int main() { int n,i; float a[n],avg,sum; printf("enter the no:"); scanf("%d",&n); if(n<=10) { for(i=0;i<n;i++) { scanf("%f",&a[i]); sum=sum+a[i]; } avg=sum/n; printf("%f",avg); } else printf("error"); }
C
#include <stdio.h> int main(){ int l,c,i,j,k,menor; printf("Inf QT de Linhas: "); scanf("%d",&l); printf("Inf QT de Colunas: "); scanf("%d",&c); int m[l][c]; // Coloco os valores na matriz for(i=0;i<l;i++){ for(j=0;j<c;j++){ printf("Inf Valor P/ L:%d C:%d : ",i,j); scanf("%d",&m[i][j]); } } // Printa a Matriz printf("\nMatriz\n"); for(i=0;i<l;i++){ printf("|"); for(j=0;j<c;j++){ printf("%d|",m[i][j]); } printf("\n"); } // encontra o menor elemento da linha for(i=0;i<l;i++){ menor=m[i][0]; for(j=0;j<c;j++){ // printf("oi11\n"); if(menor > m[i][j]){ menor = m[i][j]; printf("Menor: %d\n",menor); } } printf("1=Menor: %d\n",menor); // Divide aqui pelo menor elemento da linha toda a linha for(k=0;k<c;k++){ m[i][k]= (m[i][k])/menor; //printf("\nAqui\n"); } //printf("\nAqui2\n"); } // Printa Matriz printf("\nMatriz Dividida! ! !\n"); for(i=0;i<l;i++){ printf("|"); for(j=0;j<c;j++){ printf("%d|",m[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> // Method 1 struct Location { int x; int y; }; // <- ALWAYS remember to put a semicolon here. int main(){ struct Location A; // also notice, when declaring, i'm writing 'struct Location', instead of just Location. if you do normal struct declaration, this is how you will be declaring variables. A.x = 10; A.y = 20; printf("%d %d\n", A.x, A.y); return 0; }
C
#include <assert.h> #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #define ARRAY_LEN(ARR) (sizeof(ARR) / sizeof(*(ARR))) /** * Possible symbols that can be rolled. */ const char *const symbols[] = {"bell", "orange", "cherry", "horseshoe"}; #define NUM_SYMBOLS ARRAY_LEN(symbols) const uint8_t longest_symbol = 9; struct roll_result { enum { ROLL_LOSE, ROLL_WIN, ROLL_JACKPOT } result; uint matching_symbols; }; // NOTE: this [<idx>] = <expr>, syntax is a GNU C extension, supported by GCC // and CLang: https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html /** * Map of result values to the text to print. */ const char *const result_text[] = {[ROLL_LOSE] = "You lose", [ROLL_WIN] = "You win!", [ROLL_JACKPOT] = "Jackpot!!"}; static void sleep_ms(uint num_ms) { struct timespec ts; ts.tv_sec = num_ms / 1000; ts.tv_nsec = (num_ms % 1000) * 1000000; nanosleep(&ts, NULL); } /** * Random function that seeds the first time called * * @returns a random number in the range (min, max] */ static int get_random(int min, int max) { assert(min < max); static bool is_seeded = 0; if (!is_seeded) { srand(time(NULL)); is_seeded = true; } return (rand() % (max - min)) + min; } /** * Roll the wheel once. */ static int roll_wheel(void) { return get_random(0, NUM_SYMBOLS); } /** * Check the symbols that were rolled. * * If all match: jackpot. * If any match: win. * If none match: lose. */ static struct roll_result check_rolls(const int *const rolls, size_t num_rolls) { // since we ensure we select the strings from the array // we can compare them as pointers // start assuming a jackpot bool is_jackpot = true; uint matching_symbols = 0; for (size_t i = 0; i < num_rolls; i++) { // start j at i+1, we check all the rolls to the right of i for (size_t j = i + 1; j < num_rolls; j++) { if (rolls[i] == rolls[j]) { matching_symbols++; // once we know a symbol has a match, we can skip to the next one break; } // any non matching symbols means the jackpot wasn't hit is_jackpot = false; } } return (struct roll_result){ .matching_symbols = matching_symbols, .result = is_jackpot ? ROLL_JACKPOT : (matching_symbols ? ROLL_WIN : ROLL_LOSE)}; } static void print_rolls(const int *const rolls, size_t num_rolls) { assert(num_rolls > 0); printf("%*s", longest_symbol, symbols[rolls[0]]); for (int i = 1; i < num_rolls; i++) { printf(" - %*s", longest_symbol, symbols[rolls[i]]); } } /** * Render the rolls made in a rotating fashion. */ static void render_rotating_rolls(int *const rolls, size_t num_rolls) { struct rotation_pos { int idx; int steps_left; }; struct rotation_pos *positions = malloc(sizeof(struct rotation_pos) * num_rolls); int max_steps = 0; for (int i = 0; i < num_rolls; i++) { // random position this roll will start at int init_pos = roll_wheel(); // how many rotations we need to make to get to the destination symbol int num_steps_to_dest = (rolls[i] - init_pos + 1) % NUM_SYMBOLS; // cycle the roll some extra times. // // NOTE: we need to do at least 1 cyclehere, since num_steps_to_dest // will be negative half the time. int extra_cycles_to_do = get_random(1, 5); int num_steps = num_steps_to_dest + extra_cycles_to_do * NUM_SYMBOLS; if (num_steps > max_steps) { max_steps = num_steps; } positions[i] = (struct rotation_pos){.idx = init_pos, .steps_left = num_steps}; } // print a single newline to put the animation on printf("\n"); while (max_steps--) { for (int i = 0; i < num_rolls; i++) { // if this roll has finished it's animation if (!positions[i].steps_left) { continue; } rolls[i] = positions[i].idx; positions[i].idx = (positions[i].idx + 1) % NUM_SYMBOLS; positions[i].steps_left--; } // clear the line and return the cursor to the start of the line printf("\33[2K\r"); print_rolls(rolls, num_rolls); // have to flush manually since we don't print newlines fflush(stdout); sleep_ms(100); } printf("\n"); free(positions); } static void roll_wheels(int *const rolls, size_t num_rolls) { for (int i = 0; i < num_rolls; i++) { rolls[i] = roll_wheel(); } } static bool poll_question(const char *const q) { printf("%s? y/n\n", q); char inp[5]; fgets(inp, sizeof(inp), stdin); return inp[0] == 'y'; } static struct roll_result run_once(int *const rolls, size_t num_rolls) { roll_wheels(rolls, num_rolls); render_rotating_rolls(rolls, num_rolls); // poll the user if they want to nudge a wheel if (poll_question("Nudge wheel")) { printf("select roll (0,%lu]:\n", num_rolls); char inp[30]; fgets(inp, sizeof(inp), stdin); int roll = atoi(inp); if (roll < 0 || roll >= num_rolls) { puts("Invalid roll"); } else { rolls[roll] = (rolls[roll] + 1) % NUM_SYMBOLS; puts("new result:"); print_rolls(rolls, num_rolls); putchar('\n'); } } struct roll_result result = check_rolls(rolls, num_rolls); printf("matching symbols: %d, %s\n", result.matching_symbols, result_text[result.result]); return result; } static void print_stats(int *const stats, size_t num_rolls) { for (int i = 0; i < num_rolls; i++) { printf("%d: %d\n", i, stats[i]); } } int main(int argc, char **argv) { if (argc != 2) { fprintf(stderr, "usage: %s <rolls>\n", *argv); return 1; } size_t num_rolls = atoi(argv[1]); if (num_rolls <= 0) { fprintf(stderr, "At least 1 roll must be used.\n"); } int *rolls = malloc(sizeof(int) * num_rolls); int *stats = calloc(num_rolls, sizeof(int)); do { struct roll_result res = run_once(rolls, num_rolls); stats[res.matching_symbols]++; } while (poll_question("Play again")); puts("Game stats:"); print_stats(stats, num_rolls); free(rolls); free(stats); }
C
#include <stdio.h> #include <stdarg.h> struct bogus { int x; char *y; int z; }; void foo(char *dummy, ...) { va_list va; struct bogus b; va_start(va, dummy); b = va_arg(va, struct bogus); printf("%d, %s, %d\n", b.x, b.y, b.z); } int main() { struct bogus b; b.x = 123; b.y = "hello"; b.z = 456; foo(NULL, b); }
C
#include "config.h" #include <bitcoin/varint.h> size_t varint_size(varint_t v) { if (v < 0xfd) return 1; if (v <= 0xffff) return 3; if (v <= 0xffffffff) return 5; return 9; } size_t varint_put(u8 buf[VARINT_MAX_LEN], varint_t v) { u8 *p = buf; if (v < 0xfd) { *(p++) = v; } else if (v <= 0xffff) { (*p++) = 0xfd; (*p++) = v; (*p++) = v >> 8; } else if (v <= 0xffffffff) { (*p++) = 0xfe; (*p++) = v; (*p++) = v >> 8; (*p++) = v >> 16; (*p++) = v >> 24; } else { (*p++) = 0xff; (*p++) = v; (*p++) = v >> 8; (*p++) = v >> 16; (*p++) = v >> 24; (*p++) = v >> 32; (*p++) = v >> 40; (*p++) = v >> 48; (*p++) = v >> 56; } return p - buf; } size_t varint_get(const u8 *p, size_t max, varint_t *val) { if (max < 1) return 0; switch (*p) { case 0xfd: if (max < 3) return 0; *val = ((u64)p[2] << 8) + p[1]; return 3; case 0xfe: if (max < 5) return 0; *val = ((u64)p[4] << 24) + ((u64)p[3] << 16) + ((u64)p[2] << 8) + p[1]; return 5; case 0xff: if (max < 9) return 0; *val = ((u64)p[8] << 56) + ((u64)p[7] << 48) + ((u64)p[6] << 40) + ((u64)p[5] << 32) + ((u64)p[4] << 24) + ((u64)p[3] << 16) + ((u64)p[2] << 8) + p[1]; return 9; default: *val = *p; return 1; } }
C
#include "stm32f10x.h" #include "stm32f10x_gpio.h" #include "stm32f10x_usart.h" #include "motor.h" #include "sg90.h" #include "hcsr04.h" #include "red.h" #include "blue.h" #include "delay.h" int main(void) { NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); Motor_Init(); //motorʼ Bluetooth_Config();//óʼ SystemInit(); //ϵͳʱΪ72M delay_init(); //ʱʼ Red_Config(); //ʼ TIM4_PWM_Init(); //pwm TIM4 SG90_pwm_init(); //SG-90ʼ pwmʵת TIM3 HC_SR04_Init(); //HC-SR04ʼʱTIM2 char blue_flag=0;//һʱڽݵı while(1){ SG90_Front;//ת //ú⴫򵥱 if(R==0&&L==0){CarBack(800);delay_ms(50);DelayCheck(100);} //Ҷϰһ£ͣж if(R==0){CarBackLeft(100);delay_ms(50);DelayCheck(100);} //ұϰ󵹳һ£ͣж if(L==0){CarBackRight(100);delay_ms(50);DelayCheck(100);} //ϰҵһ£ͣж //Сֻ͵ݣ blue_flag = USART_ReceiveData(USART1); //նַ0־ͣ //һֱУ൱while(1)ѭ switch(blue_flag){ case 'A': // delay_ms(10); Ultrasonic_Avoidance();break; case 'B': // delay_ms(10); Red_Avoidance();break; case 'C': //¹ CarTest();delay_ms(500);break; case '0': //ֹͣ delay_ms(10); CarStop(); delay_ms(10); break; case '1'://ת delay_ms(10); CarLeft(999); break; case '2': //ת delay_ms(10); CarRight(999); break; case '3': // delay_ms(10); CarBack(999); break; case '4': //ǰ delay_ms(10); CarGo(999); break; case '5': //ǰת delay_ms(10); CarForwardLeft(100); break; case '6': //ǰת delay_ms(10); CarForwardRight(100); break; case '7': //󵹳 delay_ms(10); CarBackLeft(999); break; case '8': //ҵ delay_ms(10); CarBackRight(999); break; default: //Ĭֹͣ delay_ms(10); CarStop(); delay_ms(10); break; } } }
C
/* Write a program in C to find the sum of the series 1!/1+2!/2+3!/3+4!/4+5!/5 using the function.*/ #include<stdio.h> int fact(int x); int main() { int sum; sum=fact(1)/1+fact(2)/2+fact(3)/3+fact(4)/4+fact(5)/5; printf("\nThe sum of the series is : %d\n\n",sum); } int fact(int n){ int num=0,f=1; while(num<=n-1){ f =f+f*num; num++; } return f; }
C
//Program menghitung rata2 nilai dg Iterasi #include <stdio.h> //main function int main(void) { //declare variables int counter, grade, total, average; //inisialisasi var total & counter total = 0; counter = 1; while (counter <= 10){ //loop 10x --> counter sbg nilai penjaga/sentinel value printf("Masukkan nilai ke-%d: ", counter); //perintah untuk input scanf("%d", &grade); //input grade total = total + grade; //add grade ke total //counter = counter + 1; counter++; } average = total/10; //hitung grade rata2 printf("Nilai rata2 adalah: %d\n", average); //print grade rata2 }
C
#include<stdio.h> /*ͷļ*/ int main() { printf("What a nice day!\n"); /*ַ*/ return 0; /**/ }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> int l=0; int m,n,strt; int dist[1000]; struct edge { int src,des,w; }; struct edge *list[10000]; struct edge* createlist(int src,int des,int w) { struct edge*e=(struct edge*)malloc(sizeof(struct edge)); e->src=src; e->des=des; e->w=w; list[l++]=e; } void bellmanford(int strt) { for(int i=0; i<n; i++) { dist[i]=INT_MAX; } dist[strt]=0; for(int i=1; i<=n-1; i++) { for(int j=0; j<m; j++) { int u=list[j]->src; int v=list[j]->des; int w=list[j]->w; if(dist[u]!=INT_MAX && dist[u]+list[j]->w<dist[v]) { dist[v]=dist[u]+list[j]->w; } } } for(int i=0; i<m; i++) { int u=list[i]->src; int v=list[i]->des; int w=list[i]->w; if(dist[u]!=INT_MAX && dist[u]+list[i]->w<dist[v]) printf("graph contains a negative cycle"); } } void scanfile() { int u,v,w; scanf("%d%d",&n,&m); for(int i=0; i<m; i++) { scanf("%d%d%d",&u,&v,&w); createlist(u,v,w); //createlist(v,u,w); } scanf("%d",&strt); } int main() { scanfile(); bellmanford(strt); printf("%d%d%d\n",n,m,l); printf("shotest distance from the source vertex\n"); for(int i=0; i<n; i++) { printf("%d--->%d\n",i,dist[i]); } return 0; }
C
#include "lpg_ecmascript_value.h" ecmascript_value ecmascript_value_create_integer(uint64_t value) { ecmascript_value result; result.type = ecmascript_value_integer; result.integer = value; return result; } ecmascript_value ecmascript_value_create_boolean(bool value) { ecmascript_value result; result.type = ecmascript_value_boolean; result.boolean = value; return result; } ecmascript_value ecmascript_value_create_undefined(void) { ecmascript_value result; result.type = ecmascript_value_undefined; return result; } success_indicator generate_ecmascript_value(ecmascript_value const value, stream_writer const ecmascript_output) { switch (value.type) { case ecmascript_value_boolean: if (value.boolean) { LPG_TRY(stream_writer_write_string(ecmascript_output, "true")); } else { LPG_TRY(stream_writer_write_string(ecmascript_output, "false")); } break; case ecmascript_value_integer: LPG_TRY(stream_writer_write_string(ecmascript_output, "/*enum*/ ")); LPG_TRY(stream_writer_write_integer(ecmascript_output, integer_create(0, value.integer))); break; case ecmascript_value_null: LPG_TRY(stream_writer_write_string(ecmascript_output, "null")); break; case ecmascript_value_undefined: LPG_TRY(stream_writer_write_string(ecmascript_output, "undefined")); break; } return success_yes; } bool ecmascript_value_equals(ecmascript_value const left, ecmascript_value const right) { if (left.type != right.type) { return false; } switch (left.type) { case ecmascript_value_integer: return (left.integer == right.integer); case ecmascript_value_boolean: return (left.boolean == right.boolean); case ecmascript_value_null: case ecmascript_value_undefined: return true; } LPG_UNREACHABLE(); }
C
#include<stdio.h> int main(){ int a, n, p;//定义变量a,n,p int ret = 1;//定义变量ret并将其初始化为1 scanf("%d %d %d", &a, &n, &p);//输入a,n,p三个数的值 while (n) { if (n % 2 == 1) { ret = ret * a % p; } n = n / 2; a = a * a % p; } printf("ret : %d\n", ret); return 0; }
C
//Programa que impmie 10 numeros de forema descendente: DO-WHILE #include <stdio.h> #include <stdlib.h> int main() { int contador=10; do{ printf("%d\n",contador); contador--; } while(contador>=0); return 0; } /* //Programa que impmie 10 numeros de forema descendente: WHILE #include <stdio.h> #include <stdlib.h> int main() { int contador=10; while(contador>=0){ printf("%d\n",contador); contador--; } return 0; } Programa que impmie 10 numeros de forema descendente: FOR #include <stdio.h> #include <stdlib.h> int main() { int contador = 0; for(contador=10; contador >= 0; contador--){ printf("%d\n",contador); } return 0; } */
C
#include <stdio.h> int tak(int x, int y, int z){ if (x <= y){ return y; }else{ return tak(tak((x - 1),y,z), tak((y - 1),z,x), tak((z - 1),x,y)); } } int main(void){ printf("%d\n",tak(16,15,0)); }
C
#include <stdlib.h> #include <string.h> #include <errno.h> #include <sepol/policydb/policydb.h> #include <sepol/policydb/services.h> #include "context_internal.h" #include "debug.h" #include "context.h" #include "handle.h" #include "mls.h" /* ----- Compatibility ---- */ int policydb_context_isvalid(const policydb_t * p, const context_struct_t * c) { return context_is_valid(p, c); } int sepol_check_context(const char *context) { return sepol_context_to_sid((const sepol_security_context_t)context, strlen(context) + 1, NULL); } /* ---- End compatibility --- */ /* * Return 1 if the fields in the security context * structure `c' are valid. Return 0 otherwise. */ int context_is_valid(const policydb_t * p, const context_struct_t * c) { role_datum_t *role; user_datum_t *usrdatum; ebitmap_t types, roles; int ret = 1; ebitmap_init(&types); ebitmap_init(&roles); if (!c->role || c->role > p->p_roles.nprim) return 0; if (!c->user || c->user > p->p_users.nprim) return 0; if (!c->type || c->type > p->p_types.nprim) return 0; if (c->role != OBJECT_R_VAL) { /* * Role must be authorized for the type. */ role = p->role_val_to_struct[c->role - 1]; if (!ebitmap_get_bit(&role->cache, c->type - 1)) /* role may not be associated with type */ return 0; /* * User must be authorized for the role. */ usrdatum = p->user_val_to_struct[c->user - 1]; if (!usrdatum) return 0; if (!ebitmap_get_bit(&usrdatum->cache, c->role - 1)) /* user may not be associated with role */ return 0; } if (!mls_context_isvalid(p, c)) return 0; return ret; } /* * Write the security context string representation of * the context structure `context' into a dynamically * allocated string of the correct size. Set `*scontext' * to point to this string and set `*scontext_len' to * the length of the string. */ int context_to_string(sepol_handle_t * handle, const policydb_t * policydb, const context_struct_t * context, char **result, size_t * result_len) { char *scontext = NULL; size_t scontext_len = 0; char *ptr; /* Compute the size of the context. */ scontext_len += strlen(policydb->p_user_val_to_name[context->user - 1]) + 1; scontext_len += strlen(policydb->p_role_val_to_name[context->role - 1]) + 1; scontext_len += strlen(policydb->p_type_val_to_name[context->type - 1]); scontext_len += mls_compute_context_len(policydb, context); /* We must null terminate the string */ scontext_len += 1; /* Allocate space for the context; caller must free this space. */ scontext = malloc(scontext_len); if (!scontext) goto omem; scontext[scontext_len - 1] = '\0'; /* * Copy the user name, role name and type name into the context. */ ptr = scontext; sprintf(ptr, "%s:%s:%s", policydb->p_user_val_to_name[context->user - 1], policydb->p_role_val_to_name[context->role - 1], policydb->p_type_val_to_name[context->type - 1]); ptr += strlen(policydb->p_user_val_to_name[context->user - 1]) + 1 + strlen(policydb->p_role_val_to_name[context->role - 1]) + 1 + strlen(policydb->p_type_val_to_name[context->type - 1]); mls_sid_to_context(policydb, context, &ptr); *result = scontext; *result_len = scontext_len; return STATUS_SUCCESS; omem: ERR(handle, "out of memory, could not convert " "context to string"); free(scontext); return STATUS_ERR; } /* * Create a context structure from the given record */ int context_from_record(sepol_handle_t * handle, const policydb_t * policydb, context_struct_t ** cptr, const sepol_context_t * record) { context_struct_t *scontext = NULL; user_datum_t *usrdatum; role_datum_t *roldatum; type_datum_t *typdatum; /* Hashtab keys are not constant - suppress warnings */ char *user = strdup(sepol_context_get_user(record)); char *role = strdup(sepol_context_get_role(record)); char *type = strdup(sepol_context_get_type(record)); const char *mls = sepol_context_get_mls(record); scontext = (context_struct_t *) malloc(sizeof(context_struct_t)); if (!user || !role || !type || !scontext) { ERR(handle, "out of memory"); goto err; } context_init(scontext); /* User */ usrdatum = (user_datum_t *) hashtab_search(policydb->p_users.table, (hashtab_key_t) user); if (!usrdatum) { ERR(handle, "user %s is not defined", user); goto err_destroy; } scontext->user = usrdatum->s.value; /* Role */ roldatum = (role_datum_t *) hashtab_search(policydb->p_roles.table, (hashtab_key_t) role); if (!roldatum) { ERR(handle, "role %s is not defined", role); goto err_destroy; } scontext->role = roldatum->s.value; /* Type */ typdatum = (type_datum_t *) hashtab_search(policydb->p_types.table, (hashtab_key_t) type); if (!typdatum || typdatum->flavor == TYPE_ATTRIB) { ERR(handle, "type %s is not defined", type); goto err_destroy; } scontext->type = typdatum->s.value; /* MLS */ if (mls && !policydb->mls) { ERR(handle, "MLS is disabled, but MLS context \"%s\" found", mls); goto err_destroy; } else if (!mls && policydb->mls) { ERR(handle, "MLS is enabled, but no MLS context found"); goto err_destroy; } if (mls && (mls_from_string(handle, policydb, mls, scontext) < 0)) goto err_destroy; /* Validity check */ if (!context_is_valid(policydb, scontext)) { if (mls) { ERR(handle, "invalid security context: \"%s:%s:%s:%s\"", user, role, type, mls); } else { ERR(handle, "invalid security context: \"%s:%s:%s\"", user, role, type); } goto err_destroy; } *cptr = scontext; free(user); free(type); free(role); return STATUS_SUCCESS; err_destroy: errno = EINVAL; context_destroy(scontext); err: free(scontext); free(user); free(type); free(role); ERR(handle, "could not create context structure"); return STATUS_ERR; } /* * Create a record from the given context structure */ int context_to_record(sepol_handle_t * handle, const policydb_t * policydb, const context_struct_t * context, sepol_context_t ** record) { sepol_context_t *tmp_record = NULL; char *mls = NULL; if (sepol_context_create(handle, &tmp_record) < 0) goto err; if (sepol_context_set_user(handle, tmp_record, policydb->p_user_val_to_name[context->user - 1]) < 0) goto err; if (sepol_context_set_role(handle, tmp_record, policydb->p_role_val_to_name[context->role - 1]) < 0) goto err; if (sepol_context_set_type(handle, tmp_record, policydb->p_type_val_to_name[context->type - 1]) < 0) goto err; if (policydb->mls) { if (mls_to_string(handle, policydb, context, &mls) < 0) goto err; if (sepol_context_set_mls(handle, tmp_record, mls) < 0) goto err; } free(mls); *record = tmp_record; return STATUS_SUCCESS; err: ERR(handle, "could not create context record"); sepol_context_free(tmp_record); free(mls); return STATUS_ERR; } /* * Create a context structure from the provided string. */ int context_from_string(sepol_handle_t * handle, const policydb_t * policydb, context_struct_t ** cptr, const char *con_str, size_t con_str_len) { char *con_cpy = NULL; sepol_context_t *ctx_record = NULL; /* sepol_context_from_string expects a NULL-terminated string */ con_cpy = malloc(con_str_len + 1); if (!con_cpy) goto omem; memcpy(con_cpy, con_str, con_str_len); con_cpy[con_str_len] = '\0'; if (sepol_context_from_string(handle, con_cpy, &ctx_record) < 0) goto err; /* Now create from the data structure */ if (context_from_record(handle, policydb, cptr, ctx_record) < 0) goto err; free(con_cpy); sepol_context_free(ctx_record); return STATUS_SUCCESS; omem: ERR(handle, "out of memory"); err: ERR(handle, "could not create context structure"); free(con_cpy); sepol_context_free(ctx_record); return STATUS_ERR; } int sepol_context_check(sepol_handle_t * handle, const sepol_policydb_t * policydb, const sepol_context_t * context) { context_struct_t *con = NULL; int ret = context_from_record(handle, &policydb->p, &con, context); context_destroy(con); free(con); return ret; }
C
#include<stdio.h> int main(void) { int choice,i; double price; for(i=1;i<=5;i++) printf("[1] select apples\n"); printf("[2] select pears\n"); printf("[3] select oranges\n"); printf("[4] select grapes\n"); printf("[0] exit\n"); printf("Enter choice:"); scanf("%d",&choice); if(choice==0) break; switch(choice){ case 1:price=3.00; break; case 2:price=2.50; break; case 3:price=4.10; break; case 4:price=10.20; break; default:price=0.0; break; } printf("price=%0.1f\n",price); } printf("Thanks\n"); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main(){ int n,i,j; int *a; int sum=0; scanf("%d",&n); a=(int*)malloc(sizeof(int)*n); for(i=0;i<n;i++){ scanf("%d",&a[i]); } for(i=0;i<n;i++){ for(j=0;j<n;j++){ if(j!=i){ sum+=a[i]*10+a[j]; } } } printf("%d",sum); return 0; }
C
/* * uart.h * * Created: 12/27/2016 5:12:49 PM * Author: ROHIT */ /* * uart.h * * UART example for ATMega328P clocked at 16 MHz * * TODO :- * - Implement string read function * - Optimize for size * - Add helper routines and compile to .a file * * Created on: 22-Jan-2014 * Author: Shrikant Giridhar */ #ifndef UART_H_ #define UART_H_ #include <avr/io.h> #include <stdint.h> /* Probably already defined somewhere else. Define here, if isn't. */ #ifndef FOSC #define FOSC 16000000UL #endif /* Settings */ #define _BAUD 9600 // Baud rate (9600 is default) #define _DATA 0x03 // Number of data bits in frame = byte tranmission #define _UBRR (FOSC/16)/_BAUD - 1 // Used for UBRRL and UBRRH #define RX_BUFF 10 /* Useful macros */ #define TX_START() UCSR0B |= _BV(TXEN0) // Enable TX #define TX_STOP() UCSR0B &= ~_BV(TXEN0) // Disable TX #define RX_START() UCSR0B |= _BV(RXEN0) // Enable RX #define RX_STOP() UCSR0B &= ~_BV(RXEN0) // Disable RX #define COMM_START() TX_START(); RX_START() // Enable communications /* Interrupt macros; Remember to set the GIE bit in SREG before using (see datasheet) */ #define RX_INTEN() UCSR0B |= _BV(RXCIE0) // Enable interrupt on RX complete #define RX_INTDIS() UCSR0B &= ~_BV(RXCIE0) // Disable RX interrupt #define TX_INTEN() UCSR0B |= _BV(TXCIE0) // Enable interrupt on TX complete #define TX_INTDIS() UCSR0B &= ~_BV(TXCIE0) // Disable TX interrupt /* Prototypes */ void initUART(void); uint8_t getByte(void); void putByte(unsigned char data); void writeString(char *str); const char* readString(void); #endif /* UART_H_ */
C
#ifndef NODE_H #define NODE_H #define MAX_STR 64 // This makes the header file work for both C and C++ #ifdef __cplusplus extern "C" { #endif #include <stdbool.h> #include <pthread.h> typedef struct list_node { struct graph_node* graph_node; struct list_node* next; } list_node_t; typedef struct graph_node { char type; // S or C const char* val; list_node_t* neighbors; int flag; // generally useful to include :) pthread_mutex_t m; } graph_node_t; graph_node_t* graph_add(char type, const char* val); void add_node_neighbor(graph_node_t* node1, graph_node_t* node2); void graph_delete(graph_node_t* sad_node); // helper functions bool _compare_node(graph_node_t* node1, graph_node_t* node2); // list functions list_node_t* list_node_append(list_node_t* list, graph_node_t* node); bool list_node_contains(list_node_t* list, char type, const char* val); // This makes the header file work for both C and C++ #ifdef __cplusplus } #endif #endif
C
/********************************************* * * Proyecto: Practica 1 de SSOO2 * * Programa: pb.c * * Descripcion: Copiar el modelo de examen en el directorio de un estudiante * * Fecha de Creacion: 27-02-2020 * * Nombre: Paulino de la Fuente Lizcano * * Seguimiento: En github se puede ver el cronograma del proyecto, aunque tuve problemas y no * esta todo reflejado **********************************************/ #define _POSIX_SOURCE #include <stdlib.h> #include <string.h> #include <stdio.h> #include <dirent.h> #include <errno.h> #include <signal.h> #include "libreria.h" /*Lectura del txt donde estan almacenados los recursos necesarios de los estudiantes*/ void lecturaEstudiantes(); void instalarManejadorSignal(); void manejadorSignal(int sig); /*Comparamos el modelo con los tipos de examenes Una vez asignado el examen, copiamos dicho examen en su directorio*/ void copiarExamen(char *modelo, char *dni); char *asginarExamen(char *modelo); /*********PROGRAMA MAIN*********/ int main(int argc, char **argv){ instalarManejadorSignal(); lecturaEstudiantes(); return EXIT_SUCCESS; } /******FUNCIONES AUXILIARES*******/ void instalarManejadorSignal(){ if(signal(SIGINT,manejadorSignal)==SIG_ERR){ fprintf(stderr,"[PB] Error al instalar el manejador: %s\n",strerror(errno)); exit(EXIT_FAILURE); } } void manejadorSignal(int sig){ printf("[PB] Programa terminado(Ctrl+C)\n"); exit(EXIT_FAILURE); } /**********FUNCIONES PROGRAMAS*********/ void lecturaEstudiantes(){ FILE *archivo; char buffer[1024]; char *modelo; char *dni; if((archivo=fopen(ESTUDIANTES,"r"))==NULL){ fprintf(stderr,"[PB] Error leyendo el archivo estudiantes.txt, %s\n",strerror(errno)); exit(EXIT_FAILURE); } while(fgets(buffer,1024,archivo)!=NULL){ dni = strtok(buffer," "); modelo = strtok(NULL," "); /*Descomentar linea de abajo para ver si la lectura es correcta*/ /*printf("DNI: %s\t Modelo:%s\n",dni,modelo);*/ copiarExamen(asginarExamen(modelo),dni); } } char *asginarExamen(char *modelo){ char *Examen; if(strcmp("A",modelo)==0){ Examen = A; }else if(strcmp("B",modelo)==0){ Examen = B; }else if(strcmp("C",modelo)==0){ Examen = C; } return Examen; } void copiarExamen(char *modelo, char *dni){ FILE *nuevo, *mi_examen; int data = 0; /*Variable para almacenar el path enterod e un examen*/ char fullPathEx[1024]; /*Variable para guardar el directorio donde guardar el examen de cada alumno*/ char fullPathEs[1024]; sprintf(fullPathEx,"%s/%s",PATH_EXAMENES,modelo); sprintf(fullPathEs,"%s/%s/%s",PATH_ESTUDIANTES,dni,modelo); if((mi_examen = fopen(fullPathEx,"r"))==NULL){ fprintf(stderr,"[PB] Error abriendo el examen %s\n",fullPathEx); exit(EXIT_FAILURE); } if((nuevo = fopen(fullPathEs,"w"))==NULL){ fprintf(stderr,"[PB] Error creando el nuevo fichero %s\n",fullPathEs); exit(EXIT_FAILURE); } while((data = fgetc(mi_examen))!=EOF){ fputc(data,nuevo); } fclose(nuevo); fclose(mi_examen); }
C
#include<stdio.h> #include "genericll.h" struct node *merge(struct node *left, struct node *right) { if(left == NULL) return right; if(right == NULL) return left; struct node *head=NULL; if(left->data <= right->data) { head = left; head->next = merge(left->next, right); } else { head = right; head->next = merge(left, right->next); } return head; } struct node *merge_cnt(struct node *left, int lc, struct node *right, int rc) { struct node *head= NULL, *curr=NULL; if(lc > 0 && rc > 0) { if(left->data <= right->data) { head = left; left= left->next; lc--; } else { head = right; right = right->next; rc++; } } else if(rc == 0) { return left; } else if(lc == 0) { return right; } curr = head; while(1) { if(lc > 0 && rc > 0) { if(left->data <= right->data) { curr->next = left; left = left->next; lc--; } else { curr->next = right; right = right->next; rc--; } } else if (rc == 0) { curr->next = left; } else if(lc ==0) { curr->next = right; } } return head; } struct node* mergesort_util(struct node **head, int len) { printf("len = %d\n",len); if(len == 1) return *head; struct node *left = mergesort_util(head, len/2); *head = (*head)->next; if(*head != NULL) { printf("head : %d\n",(*head)->data); } struct node *right = mergesort_util(head, len - len/2); printf("merging %d , %d.\n",left->data,right->data); return merge_cnt(left, len/2, right, len - len/2); } void mergesort(struct node **head){ int len = length(*head); if(len > 1) { struct node *tmp = mergesort_util(head, len); *head = tmp; } } main() { struct node *ll = NULL; push(&ll,1); push(&ll,5); push(&ll,3); print(ll); struct node *list2 = NULL; push(&list2,2); push(&list2,6); push(&list2,4); printf("pushed all the elements.\n"); print(list2); printf("printed all the elements.\n"); struct node *tmp = merge(ll,list2); print(tmp); mergesort(&tmp); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define N 4 #define M 5 // N行M列の行列を出力する関数 void print_matrix(char *s, int n, int m, double r[n][m]); // 行列式の値を求める(戻り値は成功したかどうか,行列式の値はグローバル変数へ) double det; int cal(double p[M][N]); // 転置(転置後の行列はグローバル変数へ) void transposition(double p[M][N]); double A_t[N][M]; // 掛け算 void multiplication(int Na1, int Na2, int Nb2, double a[Na1][Na2], double b[Na2][Nb2], double ans[Na1][Nb2]); // 逆行列(計算結果の行列はグローバル変数へ) void inverse(int n, double a[n][n]); double A_inverse[N][N]; int main(void) { double A[M][N]; double A_square[N][N]; double A_pseudo_inverse[N][M]; double b[M][1]; double ans[N][1]; int i, j; srand((unsigned)time(NULL)); for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { A[i][j] = (double)rand() / RAND_MAX * 2.0 - 1.0; } b[i][0] = (double)rand() / RAND_MAX * 2.0 - 1.0; } print_matrix("*行列Aの初期値", M, N, A); print_matrix("\r\n*ベクトルbの初期値", M, 1, b); transposition(A); multiplication(N, M, N, A_t, A, A_square); inverse(N, A_square); multiplication(N, N, M, A_inverse, A_t, A_pseudo_inverse); multiplication(N, M, 1, A_pseudo_inverse, b, ans); print_matrix("\r\n-ans-", N, 1, ans); return 0; } void print_matrix(char *s, int n, int m, double r[n][m]) { int i, j; printf("%s\n", s); for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%9.5f ", r[i][j]); } printf("\n"); } } // 転置 void transposition(double A[M][N]) { int i, j; for (i = 0; i < M; ++i) { for (j = 0; j < N; ++j) { A_t[j][i] = A[i][j]; } } } void multiplication(int Na1, int Na2, int Nb2, double a[Na1][Na2], double b[Na2][Nb2], double ans[Na1][Nb2]) { int i, j, k; for (i = 0; i < Na1; i++) { for (j = 0; j < Na2; j++) { for (k = 0; k < Nb2; k++) { ans[i][k] += a[i][j] * b[j][k]; } } } } void inverse(int n, double a[n][n]) { double buf; //一時的なデータを蓄える int i, j, k; //カウンタ //単位行列を作る for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { A_inverse[i][j] = (i == j) ? 1.0 : 0.0; } } //掃き出し法 for (i = 0; i < n; i++) { buf = 1 / a[i][i]; for (j = 0; j < n; j++) { a[i][j] *= buf; A_inverse[i][j] *= buf; } for (j = 0; j < n; j++) { if (i != j) { buf = a[j][i]; for (k = 0; k < n; k++) { a[j][k] -= a[i][k] * buf; A_inverse[j][k] -= A_inverse[i][k] * buf; } } } } }
C
/* *********TMN3053/TMN4133-System Programming********** * * * ******************* * * * Group Project * * * ******************* * * * * Abu Sayed 59395 * * Nur Addina binti Baslan 50738 * * Mohamad Faridzuan bin Roslan 42107 * * Izham Wahidan bin Kamal 41491 * ***************************************************** */ //Preprocessor Directives #include <unistd.h> #include <sys/types.h> #include <errno.h> #include <wait.h> #include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { int pid, childpid, status, exec; //Display the Current Working Directory char cwd[1024]; if (getcwd(cwd, sizeof(cwd)) == NULL) perror("getcwd() error()"); else printf("\nDirectory: %s\n", cwd); //Original or Parent Process printf("\n%s I'm a process\n", argv[0]); printf("\n%s My PID is %d and My parent's PID is %d. \n", argv[0], getpid(), getppid() ); printf("\n%s Forking a child off.\n", argv[0]); //Create Child Process with fork() system call pid = fork(); //Error handling for fork() system call if(pid < 0) { perror("Fork Failed"); exit(1); return -1; } //This is The child process if(pid == 0) { printf("\nChild: I have been created!\n"); printf("\nChild: My PID is %d and my parent's PID is %d. \n\n", getpid(), getppid() ); sleep(5); //sleep for 5 seconds /*----------- Child Exec now with program2b----------*/ char* args[] ={"./program2b", "Arg1", "Arg2", (char *)0}; exec = execvp("./program2b", args); //Error handling for execvp() system call if(exec < 0) { perror("Exec Failed"); exit(1); return -2; } } sleep(1); //sleep for 1 seconds //Display the system process chart printf("\n%s Printing System Process chart using \"ps -al\"\n\n\n", argv[0]); system ("ps -al"); printf("\n%s Waiting for my child to die\n\n\n", argv[0]); //Declare the wait() system call childpid = wait(&status); //Child terminate and display the status code printf("\n%s Child exited with status code %d\n", argv[0], status >> 8); //Process terminate printf("%s I am going to die.\n\n", argv[0]); return 0; } /******************************************** The End of Project ***********************************************/
C
#include<stdio.h> #include<stdlib.h> int size,s[20],top=-1; void push(); void pop(); void peek(); void traverse(); int main() { int n; printf("++++STACK IMPLEMENTATION++++"); printf("\n\n Enter size of stack : "); scanf("%d",&size); do { printf("\n1. Push \n2. Pop \n3. Peek \n4. Traverse \n5. Exit \nEnter a choice : "); scanf("%d",&n); switch(n) { case 1: push(); //fn call break; case 2: pop(); break; case 3: peek(); break; case 4: traverse(); break; case 5: break; default: printf("\n\n INVALID"); break; }} while(n!=5); return 0; } //PUSH void push() { int item; if(top==size-1) { printf("\n\n ***Stack Overflow***"); } else { top=top+1; printf("\n Enter the element : "); scanf("%d",&item); s[top]=item; // printf("%d",s[top]); } } //POP void pop() { if(top<0) { printf("\n\n ***Stack Underflow***"); } else { printf("\nDeleted the element : %d",s[top]); top=top-1; } } //PEEK void peek() { if(top==-1) printf("\n\n***No Element***"); else printf("Top element is : %d",s[top]); } //TRAVERSE void traverse() { int i; if(top==-1) { printf("\n***Stack Empty***"); } else { printf("\n\nSTACK : "); for(i=0;i<=top;i++) { printf("%d\t",s[i]); } } }
C
/*Errors*/ #include <stdio.h> #include <math.h> int main() { float sum=0,n,term; int count; printf("Enter Value of N\n->"); scanf("%f",&n); term = (1.0)/n; while (count <= n) { sum = sum + term; count = count + 1; } printf("Sum = %f\n", sum); }
C
/* Description 计算两个整数a,b的和,整数范围为-1000<a,b<1000。 */ #include<stdio.h> int main(){ int a,b; scanf("%d", &a); scanf("%d", &b); printf("%d\n",a^a^a^a^a^a^a^a^a-a-a-a-a+a+a+a+a+b^b^b^b^b-b-b-b-b+b+b+b+b); return 0; }
C
/* runG.c a program that runs other programs! * Alexandre Castro */ #include <unistd.h> int main(int argc, char** args){ write(1, "Get ready!\n\n",12); execvp(args[1], args + 1); //library wrapper for execve system call write (1, "Ghosts\n", 17); return 0; }
C
#include "Header.h" void sig_handler(int signo) { if(signo == SIGUSR1) { puts("--------------------------------------------"); puts("부모 프로세스가 공유메모리를 모두 채웠습니다"); } } int main() { void *shared_Mem = (void*)0; int shmid; int *shmaddr; pid_t my_pid, your_pid, fork_result; int i; FILE *fwp; // Shared Memory의 내용을 저장할 txt파일에 대한 포인터 // 정상적으로 열리지 않았다면, 에러메시지 출력 fwp = fopen("Backup.txt", "w+"); if(fwp == NULL) { puts("File Open ERROR"); exit(EXIT_FAILURE); } // 시그널 핸들러 등록 signal(SIGUSR1, sig_handler); // 자신의 pid와 부모의 pid를 계산하고, 출력한다. my_pid = getpid(); your_pid = getppid(); puts("[자식 프로세스]"); printf("My_pid=%d Your_pid=%d\n",my_pid,your_pid); // 부모프로세스가 // 자식 프로세스에서의 정상적인 pid 출력이 완료될 때 까지 대기중이므로 // 부모프로세스에게 완료되었다는 signal을 보내준다. kill(your_pid, SIGUSR2); // 부모프로세스와 같은 Shared Memory를 get, 실패시 에러메시지 출력 shmid = shmget((key_t)9134, sizeof(int) * SHMSIZE, 0666|IPC_CREAT); if(shmid == -1) { fprintf(stderr, "shmget failed\n"); exit(EXIT_FAILURE); } // Shared Memory attach, 실패한다면 에러메시지 출력 shared_Mem = shmat(shmid, (void*)0, 0); if(shared_Mem == (void*)-1) { fprintf(stderr, "shmat failed\n"); exit(EXIT_FAILURE); } // shmaddr에 Shared Memory 시작주소값 저장, // shared_Mem이 void형이므로 int형 데이터의 주소값 계산을 위해 // int형으로 강제 형변환 shmaddr = (int *)shared_Mem; // 부모프로세스에서 Shared Memory에 Write마칠때까지 대기한다. pause(); // Shared Memory의 내용을 Backup.txt파일에 저장한다. for(i=1; i<=1024;i++) { fprintf(fwp,"%d\n", *(shmaddr + (i-1))); } // 부모프로세스에게 저장이 끝났음을 알린다. kill(your_pid,SIGUSR1); // Shared Memory detach, 실패시 에러메시지 출력 if(shmdt(shared_Mem)==-1) { fprintf(stderr, "shmdt failed\n"); exit(EXIT_FAILURE); } // 파일 포인터 삭제. fclose(fwp); exit(EXIT_SUCCESS); }
C
#include "ArrayList.h" struct arrayListStruct { int length; void * array; size_t defaultSize; }; static Boolean validateIndex(ArrayList * list, int index); ArrayList * ArrayList_create(int initialSize, size_t objectSize) { if(initialSize < 1) return NULL; ArrayList * list = malloc(sizeof(struct arrayListStruct)); if(list == NULL) return NULL; list->length = initialSize; list->defaultSize = objectSize; list->array = calloc(objectSize, initialSize); return list; } Boolean ArrayList_destroy(ArrayList * list) { if(list == NULL) return false; free(list->array); free(list); return true; } Boolean ArrayList_set(ArrayList * list, int index, void * value) { if(!validateIndex(list, index)) return false; void * destPoint = list->array + (index * list->defaultSize); memcpy(destPoint, value, list->defaultSize); return true; } Boolean ArrayList_get(ArrayList * list, int index, void * result) { if(index >= list->length) return false; void * srcPoint = list->array + (index * list->defaultSize); memcpy(result, srcPoint, list->defaultSize); return true; } static Boolean validateIndex(ArrayList * list, int index) { if(index < list->length) { return true; } int newLength = list->length * 2; while(index >= newLength) newLength *= 2; void * newArray = calloc(list->defaultSize, newLength); if(newArray == NULL) return false; memcpy(newArray, list->array, list->defaultSize * newLength); free(list->array); list->length = newLength; list->array = newArray; return true; }
C
/* * NumberOf1Bits2.c * * Created on: Sep 16, 2016 * Author: xinsu * * Binary count: 24 arithmetic operations (bitwise shit, bitwise and, add) */ /* Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also known as the Hamming weight). For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011, so the function should return 3. Credits: Special thanks to @ts for adding this problem and creating all test cases. */ #include <stdio.h> #include <stdint.h> int hammingWeight(uint32_t n) { uint32_t m1 = 0x55555555; // 0101 0101 0101 0101 0101 0101 0101 0101 uint32_t m2 = 0x33333333; // 0011 0011 0011 0011 0011 0011 0011 0011 uint32_t m4 = 0x0f0f0f0f; // 0000 1111 0000 1111 0000 1111 0000 1111 uint32_t m8 = 0x00ff00ff; // 0000 0000 1111 1111 0000 0000 1111 1111 uint32_t m16 = 0x0000ffff; // 0000 0000 0000 0000 1111 1111 1111 1111 n = (n & m1) + ((n >> 1) & m1); // put count of each 2 bits into those 2 bits n = (n & m2) + ((n >> 2) & m2); // put count of each 4 bits into those 4 bits n = (n & m4) + ((n >> 4) & m4); // put count of each 8 bits into those 8 bits n = (n & m8) + ((n >> 8) & m8); // put count of each 16 bits into those 16 bits n = (n & m16) + ((n >> 16) & m16); // put count of each 32 bits into those 32 bits return (int) n; }
C
#include <stdio.h> #include <string.h> #define SIZE 32 int main(void) { /* char str1[10] = { 'a', 'b', 'c' }; char str2[10] = "abc"; char str3[] = "abc"; char str4[10] = "very long string"; int size = sizeof(str1) / sizeof(str1[0]); int i; printf("str = "); for ( i = 0; i < size; i++) { printf("%c", str1[i]); } printf("\n"); printf("str2 = %s\n", str2); printf("str3 = "); printf(str3); printf("\n"); printf("str4 = %s\n", str4); */ /* char s1[] = "hello"; char s2[] = ""; int len = 0; printf("s1 : %d\n", strlen(s1)); printf("s2 : %d\n", strlen(s2)); printf("-- : %d\n", strlen("bye bye")); printf("s1 ũ: %d\n", sizeof(s1)); len = strlen(s1); if (len > 0) { s1[len - 1] = '\0'; } printf("s1 = %s\n", s1); */ char str1[SIZE] = ""; char str2[SIZE] = ""; //char temp[SIZE]; printf("ڿ? "); scanf_s("%s %s", &str1, &str2); printf("str1 = %s, str2 = %s\n", str1, str2); }
C
/* ** A rudimentary implementation of ping-pong timing for message passing. */ #include<stdio.h> #include<stdlib.h> #include<mpi.h> #define proc_A 0 #define proc_B 1 #define ping 101 #define pong 101 float buffer[10001]; int processor_A (void); int processor_B (void); int main ( int argc, char *argv[] ) { int ierror; int rank; int size; /* Initialize MPI */ MPI_Init(&argc, &argv); /* Get rank */ MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD,&size); /* keep the example to a simple pairwise exchange */ if (size != 2) { fprintf(stderr,"Error: wrong number of processes (use 2 processes)\n"); MPI_Abort(MPI_COMM_WORLD,1); } /* Call ping-pong functions */ if (rank == proc_A) { processor_A(); } else if (rank == proc_B) { processor_B(); } /* Finalize MPI */ MPI_Finalize(); return EXIT_SUCCESS; } int processor_A( void ) { int ii; int ierror; int sfloat; MPI_Status status; double tic, toc, elapsed_time; extern float buffer[10001]; int length; sfloat = sizeof(float); printf("length time/message (usec) transfer rate (Gbyte/sec)\n"); /* Process A sets the message size */ for (length=1; length<=10001; length+=1000) { /* Get the start time for the pingpong message passing */ tic = MPI_Wtime(); /* Process A sends and then receives the message back 1000 times */ for (ii=0; ii<1000; ii++){ MPI_Ssend(buffer, length, MPI_FLOAT, proc_B, ping, MPI_COMM_WORLD); MPI_Recv(buffer, length, MPI_FLOAT, proc_B, pong, MPI_COMM_WORLD, &status); } /* Get the finish time for the pingpong message passing */ toc = MPI_Wtime(); elapsed_time = toc - tic; printf("%d\t %f %f\n", length, (elapsed_time/2000.0)*1000000.0, (float)(2*sfloat*1000*length)/(elapsed_time*1000000000)); } return EXIT_SUCCESS; } int processor_B( void ) { int ii; int ierror; MPI_Status status; extern float buffer[10001]; int length; /* Process B sets the message size */ for (length=1; length<=10001; length+=1000) { /* Process B receives and then sends the message back 1000 times */ for (ii=0; ii<1000; ii++) { MPI_Recv(buffer, length, MPI_FLOAT, proc_A, ping, MPI_COMM_WORLD, &status); MPI_Ssend(buffer, length, MPI_FLOAT, proc_A, pong, MPI_COMM_WORLD); } } return EXIT_SUCCESS; }
C
#include <stdio.h> int main(int argc, char ** argv) { printf("int bytes: %lu\n", (sizeof (int))); printf("float bytes: %lu\n", (sizeof (float))); printf("doublebytes: %lu\n", (sizeof (double))); printf("long int bytes: %lu\n", (sizeof (long int))); printf("char bytes: %lu\n", (sizeof (char))); printf("long bytes: %lu\n", (sizeof (long))); printf("long long bytes: %lu\n", (sizeof (long long))); printf("long double bytes: %lu\n", (sizeof (long double))); printf("char* bytes: %lu\n", (sizeof (char*))); printf("int* bytes: %lu\n", (sizeof (int*))); printf("void* bytes: %lu\n", (sizeof (void*))); return 0; }
C
/* * Copyright (C) 2018 Brian Kubisiak <[email protected]> */ #ifndef FSVM_OPS_H_ #define FSVM_OPS_H_ enum { FSVM_DEX, /* ensure directory existence */ FSVM_DMK, /* make a new directory */ FSVM_FMK, /* make a new file */ FSVM_FMV, /* move a file */ FSVM_FRM, /* delete a file */ FSVM_LNK, /* create a symbolic link */ FSVM_DLNK, /* delete a symbolic link */ FSVM_RCAT, /* concatenate from a register */ FSVM_ACAT, /* concatenate from an argument */ FSVM_LD, /* load a directory as an index */ FSVM_GLOB, /* glob from the current index */ FSVM_RD, /* read a single entry from the current index */ FSVM_GMAP, /* map relative to the glob */ FSVM_GRDLNK, /* read a link relative to the glob */ FSVM_RRDLNK, /* read a link into a register */ FSVM_ABORT, /* abort execution */ FSVM_NOP, /* do nothing */ FSVM_NUM_OPS }; #define OP_DEX(path) { .type = FSVM_DEX, .x = path, } #define OP_DMK(path) { .type = FSVM_DMK, .x = path, } #define OP_FMK(path, contents) { .type = FSVM_FMK, .x = path, .y = contents, } #define OP_FMV(old, new) { .type = FSVM_FMV, .x = old, .y = new, } #define OP_FRM(file) { .type = FSVM_FRM, .x = file, } #define OP_LNK(target, link) { .type = FSVM_LNK, .x = target, .y = link, } #define OP_DLNK(target, link) { .type = FSVM_DLNK, .x = target, .y = link, } #define OP_RCAT(dst, src) { .type = FSVM_RCAT, .x = dst, .y = src, } #define OP_ACAT(dst, src) { .type = FSVM_ACAT, .x = dst, .y = src, } #define OP_LD(path) { .type = FSVM_LD, .x = path, } #define OP_GLOB { .type = FSVM_GLOB, } #define OP_RD(name) { .type = FSVM_RD, .x = name, } #define OP_GMAP(dst, name) { .type = FSVM_GMAP, .x = dst, .y = name, } #define OP_GRDLNK(dst, name) { .type = FSVM_GRDLNK, .x = dst, .y = name, } #define OP_RRDLNK(dst, name) { .type = FSVM_RRDLNK, .x = dst, .y = name, } #define OP_ABORT { .type = FSVM_ABORT, } #define OP_NOP { .type = FSVM_NOP, } #endif /* end of include guard: FSVM_OPS_H_ */
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <errno.h> #include <netinet/in.h> #include "data.h" #include "entry.h" #include "tree.h" #include "tree-private.h" #include "serialization.h" int data_to_buffer(struct data_t *data, char **data_buf){ if(!data || !data_buf){ return -1; } int size = data->data ? strlen(data->data)+1 : 0; int totalSize = sizeof(int) + size; *data_buf = calloc(1, totalSize); if(*data_buf){ int htons_size = htons(size); memcpy(*data_buf, &htons_size, sizeof(htons_size)); memcpy(*data_buf + sizeof(htons_size), data->data, size); } return totalSize; } struct data_t *buffer_to_data(char *data_buf, int data_buf_size){ int maxSize = sizeof(int);//tamanho buffer + data vazio if(data_buf_size < maxSize){ return NULL; } struct data_t *data; data = calloc(1,sizeof(struct data_t)); int v = 0; memcpy(&v, data_buf, sizeof(v)); v = ntohs(v); memcpy(&data->datasize, &v, sizeof(v)); data->data = calloc(1,data->datasize); memcpy(data->data, data_buf + sizeof(v) , data->datasize); return data; } int entry_to_buffer(struct entry_t *data, char **entry_buf){ if(!data || !entry_buf) { return -1;} int totalSize = sizeof(int) + strlen(data->key)+1 + sizeof(int) + data->value->datasize; *entry_buf = calloc(1,totalSize); int offset = 0; int v = htons(strlen(data->key)+1); memcpy(*entry_buf, &v, sizeof(v)); offset += sizeof(v); memcpy(*entry_buf + offset, data->key, strlen(data->key)+1); offset += strlen(data->key)+1; v = htons(data->value->datasize); memcpy(*entry_buf + offset, &v, sizeof(v)); offset += sizeof(v); memcpy(*entry_buf + offset, data->value->data, data->value->datasize); return totalSize; } struct entry_t *buffer_to_entry(char *entry_buf, int entry_buf_size){ int minSize = 2 * sizeof(int); if(entry_buf_size<minSize){ return NULL; } struct entry_t *data; data = calloc(1,sizeof(entry_buf_size)); int offset = 0; int v = 0; memcpy(&v, entry_buf, sizeof(v)); offset += sizeof(v); v = ntohs(v); if (v > 0){ data->key = calloc(1,v + 1); memcpy(data->key, entry_buf + offset, v); offset += v; } memcpy(&v, entry_buf + offset, sizeof(v)); v = ntohs(v); data->value = calloc(1, sizeof(int) + v); memcpy(&data->value->datasize, &v, sizeof(v)); offset += sizeof(data->value->datasize); if (data->value->datasize > 0){ data->value->data = calloc(1,v + 1); memcpy(data->value->data, entry_buf + offset, data->value->datasize); } return data; } int tree_to_buffer(struct tree_t *tree, char **tree_buf){ if(tree == NULL || tree_buf == NULL){ return -1; } int datasize = tree->entry->value->datasize; int strl = strlen(tree->entry->key)+1; int treeSize = tree_size(tree); char *aux_buff = malloc(sizeof(int) + strl + sizeof(int) + datasize + sizeof(int) + treeSize); int offset = 0; //tamanho de key memcpy(aux_buff, &strl, sizeof(int)); offset += sizeof(int); //passar a key memcpy(aux_buff + offset, tree->entry->key, strl); offset += strl; //tamanho datasize memcpy(aux_buff + offset, &datasize, sizeof(int)); offset += sizeof(int); //passa a entry memcpy(aux_buff + offset, tree->entry->value, datasize); offset += datasize; //tamanho da tree memcpy(aux_buff + offset, &treeSize, sizeof(int)); offset += sizeof(int); //passa a tree memcpy(aux_buff+offset, tree_get_keys(tree), treeSize); *tree_buf = aux_buff; return offset; } struct entry_t *buffer_to_tree(char *tree_buf, int tree_buf_size){ if (tree_buf == NULL || tree_buf_size <= 0){ return NULL; } int offset = 0; int strl = 0; //tamanho da key memcpy(&strl,tree_buf,sizeof(int)); offset += sizeof(int); //descobre key char* key = malloc(0); memcpy(key,tree_buf + offset, strl); offset += strl; //datasize int datasize = 0; memcpy(&datasize,tree_buf + offset, sizeof(int)); offset += sizeof(int); //descobre a data void* data_data = malloc(datasize); memcpy(data_data,tree_buf + offset, datasize); offset += datasize; //tree_size int tree_size = 0; memcpy(&tree_size,tree_buf,sizeof(int)); offset += sizeof(int); struct data_t *data = data_create2(datasize,data_data); struct entry_t *entry = entry_create(key,data); return entry; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define BUFFER_SIZE 128 void bufferFill(FILE *, char *); void inputBuffering(char *); void identifiers(char *, char *); int main(int argc, char const *argv[]){ char buffer[BUFFER_SIZE], filename[64] = "input.txt"; FILE *filePtr; int i; memset(buffer, 0, sizeof(buffer)); // initializing the buffer (emptying) filePtr = fopen(filename, "rb"); if (filePtr == NULL){ printf("Cannot open file \n"); exit(0); } bufferFill(filePtr, buffer); // if an EOF is encountered insert <EOF> for (i = 0; i < strlen(buffer) && i < BUFFER_SIZE; ++i) printf(buffer[i] == EOF ? "<EOF>" : "%c", buffer[i]); printf("\nTotal Number of Characters read: %d\n", i); fclose(filePtr); inputBuffering(buffer); return 0; } // Fills the Buffer void bufferFill(FILE *filePtr, char *buffer){ int buffer_i=0, ch; while ((ch = fgetc(filePtr)) != EOF && buffer_i <= BUFFER_SIZE) buffer[buffer_i++] = ch; buffer[buffer_i] = EOF; } void inputBuffering(char *buffer){ char *lexemeBegin=&buffer[0], *fp=&buffer[0]; char specialCharacters[BUFFER_SIZE]; int str_i=0; memset(specialCharacters, 0, sizeof(specialCharacters)); // initializing the specialCharacters (emptying) for (int i = 0; i < strlen(buffer) && i < BUFFER_SIZE; ++i){ fp=&buffer[i]; if (*fp == '+' || *fp == '*' || *fp == '-' || *fp == '/' || *fp == '%' || *fp == '=' || *fp == ',' || *fp==';'){ specialCharacters[str_i++] = buffer[i]; identifiers(lexemeBegin, fp); lexemeBegin=&buffer[i+1]; fp=&buffer[i+1]; } else if (*fp == ' ' || *fp == '\t' || *fp == '\n'){ identifiers(lexemeBegin, fp); lexemeBegin=&buffer[i+1]; fp=&buffer[i+1]; } } printf("Operators: %s\n", specialCharacters); } // iter moves through lexemeBegin and fp printing the identifier void identifiers(char *lexemeBegin, char *fp){ char *iter = lexemeBegin; printf(lexemeBegin != fp ? "Identifier: " : ""); while(iter != fp){ printf("%c", *iter); iter++; } printf(lexemeBegin != fp ? "\n" : ""); }
C
#include <ctype.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include <string.h> #ifndef FRANK_TRIE_H_ #define FRANK_TRIE_H_ #ifdef __cplusplus extern "C" { #endif typedef void (*fFRANK_TRIE_DUMP_DATA)(const char *keyword, void *data, char *dump_buff, int dump_max); typedef struct FRANK_TRIE { int (*add)(struct FRANK_TRIE *const trie, const char *keyword, void *data); int (*del)(struct FRANK_TRIE *const trie, const char *keyword); void (*empty)(struct FRANK_TRIE *const trie); void * (*find)(struct FRANK_TRIE *const trie, const char *keyword); void (*dump)(struct FRANK_TRIE *const trie, const char *title); void (*dump2)(struct FRANK_TRIE *const trie, const char *title, fFRANK_TRIE_DUMP_DATA dump_data); }ST_FRANK_TRIE, *LP_FRANK_TRIE; extern LP_FRANK_TRIE FTRIE_create(int data_size); extern void FTRIE_release(LP_FRANK_TRIE trie); #if 0 typedef struct STUDENT_SCORE { int maths, physics, biology, chemistry; }ST_STUDENT_SCORE; static void student_score_dump(const char *student_name, void *data) { struct STUDENT_SCORE *score = (struct STUDENT_SCORE *)(data); printf("%s score: Maths=%d Physics=%d Biology=%d Chemistry=%d", student_name, score->maths, score->physics, score->biology, score->chemistry); } int main(int argc, char *argv[]) { ST_STUDENT_SCORE mike = { 80, 66, 70, 50, }; ST_STUDENT_SCORE mary = { 92, 55, 91, 72, }; ST_STUDENT_SCORE lucy = { 71, 78, 88, 84, }; LP_FRANK_TRIE trie = NULL; while(NULL != (trie = FTRIE_create(sizeof(ST_STUDENT_SCORE)))){ // add the score trie->add(trie, "Mike", &mike); trie->add(trie, "Mary", &mary); trie->add(trie, "Lucy", &lucy); trie->dump2(trie, student_score_dump); // delete a student trie->del(trie, "Mary"); trie->dump2(trie, student_score_dump); // adjust data ST_STUDENT_SCORE *score = trie->find(trie, "Mike"); if(score){ score->maths = 99; // duplicate score trie->add(trie, "Macro", score); } trie->dump2(trie, student_score_dump); trie->empty(trie); FTRIE_release(trie); // loop to check the possibly memory leak //break; } return 0; } #endif #ifdef __cplusplus }; #endif #endif //FRANK_TREE_H_
C
#include "libcgc.h" #include "cgc_cgc_libc.h" #include "cgc_cgc_malloc.h" int read_fd = 8; int write_fd = 8; //char *pattern; char pattern[1024]; char * cgc_read_buf(int fd) { unsigned int recv_size; unsigned int buf_size; char *buf = NULL; recv_size = cgc_receive_all(read_fd, (char *) &buf_size, sizeof(buf_size)); if (recv_size != sizeof(buf_size)) cgc__terminate(1); if (recv_size == 0) cgc__terminate(2); buf_size = recv_size; buf = cgc_malloc(recv_size); if (!buf) cgc__terminate(3); recv_size = cgc_receive_all(read_fd, buf, buf_size); if (recv_size != buf_size) cgc__terminate(4); return buf; } void cgc_setup(void) { unsigned int size; size = cgc_receive_all(read_fd, (char *) &write_fd, sizeof(write_fd)); if (size != sizeof(write_fd)) cgc__terminate(0); size = cgc_receive_all(read_fd, (char *) &read_fd, sizeof(read_fd)); if (size != sizeof(read_fd)) cgc__terminate(0); if (write_fd == 0xFFFF) cgc__terminate(0); } void cgc_do_config(void) { cgc_read_until(read_fd, pattern, sizeof(pattern), '\n'); } int cgc_search(char *buffer, int buffer_size) { cgc_size_t size = cgc_strlen(pattern); cgc_size_t offset = 0; while (size + offset <= buffer_size) { if (cgc_memcmp(buffer + offset, pattern, size) == 0) { return 1; } offset++; } return 0; } void cgc_exit(int i) { cgc_transmit_all(write_fd, "\x00\n", 2); cgc__terminate(i); } int main(int cgc_argc, char *cgc_argv[]) { char buf[1024]; int ret; cgc_do_config(); cgc_setup(); cgc_sleep(2); while (1) { cgc_memset(buf, 0, sizeof(buf)); ret = cgc_read_until(read_fd, buf, sizeof(buf), '\n'); if (ret == -1) cgc_exit(4); if (ret > 0) { if (buf[0] == 0) { cgc_exit(0); } ret = cgc_search(buf, cgc_strlen(buf)); if (ret != 1) { cgc_printf(write_fd, "%s\n", buf); } } } cgc_exit(1); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* koch.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hdezier <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/19 20:48:15 by hdezier #+# #+# */ /* Updated: 2015/01/19 20:48:16 by hdezier ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" #include "libft.h" #include <math.h> void koch_line(t_map *m, t_point origin, t_point dest, int depth) { t_point tier_1; t_point tier_2; t_point pic; if (depth <= 0) draw_line(m, origin, dest); else { tier_1 = (t_point){(2.0 * origin.x + dest.x) / 3.0 , (2.0 * origin.y + dest.y) / 3.0, C_WHITE}; tier_2 = (t_point){(origin.x + 2.0 * dest.x) / 3.0 , (origin.y + 2.0 * dest.y) / 3.0, C_WHITE}; pic = (t_point){(origin.x + dest.x) / 2.0 - sqrt(3.0) * (dest.y - origin.y) / 6.0 , (origin.y + dest.y) / 2.0 + sqrt(3.0) * (dest.x - origin.x) / 6.0, C_WHITE}; koch_line(m, origin, tier_1, depth - 1); koch_line(m, tier_1, pic, depth - 1); koch_line(m, pic, tier_2, depth - 1); koch_line(m, tier_2, dest, depth - 1); } } void koch(t_map *m) { t_point a; t_point b; t_point c; a = (t_point){WIN_W / 3, WIN_H / 3, C_WHITE}; b = (t_point){2 * WIN_W / 3, WIN_H / 3, C_WHITE}; c = (t_point){WIN_W / 2, 2 * WIN_H / 3, C_WHITE}; koch_line(m, b, a, m->kd.depth); koch_line(m, a, c, m->kd.depth); koch_line(m, c, b, m->kd.depth); }
C
/** \file hexfile.h \author G. Icking-Konert \date 2018-12-14 \version 0.2 \brief declaration of routines for HEX, S19 and table files declaration of routines for importing and exporting Motorola S19 and Intel HEX files, as well as plain ASCII tables. (format descriptions under http://en.wikipedia.org/wiki/SREC_(file_format) or http://www.keil.com/support/docs/1584.htm). */ // for including file only once #ifndef _HEXFILE_H_ #define _HEXFILE_H_ /// buffer size [B] for files #define LENFILEBUF 10*1024*1024 /// buffer size [B] for memory image #define LENIMAGEBUF 10*1024*1024 // read next line from RAM buffer char *get_line(char **buf, char *line); // read file into memory buffer void load_file(const char *filename, char *fileBuf, uint32_t *lenFileBuf, uint8_t verbose); // convert Motorola s19 format in memory buffer to memory image void convert_s19(char *fileBuf, uint32_t lenFileBuf, uint16_t *imageBuf, uint32_t *addrStart, uint32_t *addrStop, uint8_t verbose); // convert Intel hex format in memory buffer to memory image void convert_ihx(char *fileBuf, uint32_t lenFileBuf, uint16_t *imageBuf, uint32_t *addrStart, uint32_t *addrStop, uint8_t verbose); // convert plain text table (hex addr / data) in memory buffer to memory image void convert_txt(char *fileBuf, uint32_t lenFileBuf, uint16_t *imageBuf, uint32_t *addrStart, uint32_t *addrStop, uint8_t verbose); // convert binary data in memory buffer to memory image void convert_bin(char *fileBuf, uint32_t lenFileBuf, uint16_t *imageBuf, uint32_t addrStart, uint32_t *addrStop, uint8_t verbose); // export RAM image to file in Motorola s19 format void export_s19(char *filename, uint16_t *imageBuf, uint32_t addrStart, uint32_t addrStop, uint8_t verbose); // export RAM image to file with plain text table (hex addr / data) void export_txt(char *filename, uint16_t *imageBuf, uint32_t addrStart, uint32_t addrStop, uint8_t verbose); // export RAM image to binary file (w/o address) void export_bin(char *filename, uint16_t *imageBuf, uint32_t addrStart, uint32_t addrStop, uint8_t verbose); // print RAM image to console void print_console(uint16_t *imageBuf, uint32_t addrStart, uint32_t addrStop, uint8_t verbose); #endif // _HEXFILE_H_
C
#include <stdio.h> #include <string.h> #include "bx_numbers.h" #include "bx_usart.h" // For debugging #include <avr/pgmspace.h> // For strings in flash /* stdlib.h Provides atoi for ascii to integer conversions. */ #include <stdlib.h> /* asc2num() Converts an ascii character representing a hexadecimal number into its integer equivalent. Accepts both upper and lower case characters. Returns 0 for non-numeric arguments. */ uint8_t asc2num(char n_asc) { uint8_t n_int = 0; n_int = n_asc - 0x30; // Subtract off non-numeric beginning of table if ( n_int > 0x09 ) { // Input number is 0xa or larger. Need to subtract off the // non-numeric interval between 9 and A in the table. n_int -= 0x07; } if ( n_int > 0x0f ) { // Input number is lower case. Need to subtract off the difference // between lower and upper cases. n_int -= 0x20; } if ( n_int > 0xf ) { // If the integer is still too big, this is an invalid entry. n_int = 0x00; } return n_int; } /* hex2num() Converts a string of ascii characters into a decimal by repeatedly calling asc2num() */ uint16_t hex2num(char *hexstr) { uint8_t digits = 0; // Number of digits in the string uint16_t totval = 0; // Returned value of the string digits = strlen(hexstr); while (digits != 0) { totval += asc2num(hexstr[0]) << (4 * (digits - 1)); hexstr++; digits--; } return totval; } /* uint2num( string representing unsigned integer ) Converts a string of ascii characters into an integer. Doesn't do any size checking. If the number is larger than 65535, output will be undefined. */ uint16_t uint2num(char *uintstr) { uint16_t retval = atoi(uintstr); return retval; } /* sint2num( string representing signed integer ) Converts a string of ascii characters into a signed integer. Doesn't do any size checking. If the number is larger than 65535, output will be undefined. */ uint16_t sint2num(char *sintstr) { uint16_t retval = atoi(sintstr); return retval; } /* bitshifts_max8 ( 8-bit number ) Returns the maximum power of bitshifts that will fit in the number. */ uint8_t bitshifts_max8 (uint8_t number) { uint8_t powtwo = 1; uint8_t shift = 0; while (powtwo < number) { powtwo <<= 1; shift++; } return shift; }
C
#include <stdio.h> #include "snake.h" int main() { printf("Enter the number of items: "); scanf_s("%d", &obj.szCount); int ekey = 0; init(); int win = 0; while (1) { if (_kbhit()) { ekey = _getch(); _flushall(); switch (ekey) { case L: if (kb_direction != RIGHT) kb_direction = LEFT; break; case R: if (kb_direction != LEFT) kb_direction = RIGHT; break; case U: if (kb_direction != DOWN) kb_direction = UP; break; case D: if (kb_direction != UP) kb_direction = DOWN; break; default: break; } } update(); win = game_is_going(); if (win != 0) { break; } draw(); Sleep(100); } release(); if (win == 1) { printf("YOU WIN!\n"); } else { printf("YOU LOSE!\n"); } system("PAUSE"); }
C
#include <sys/types.h> // for open #include <err.h> // for err.. duh #include <fcntl.h> // for open flags #include <unistd.h> // for read #include <string.h> // for strcpy #include "parameter.h" #include "segment.h" int openFile(char * filename, int flags) { int fd = open(filename, flags); if ( fd == -1) { freeSegmentParameters(); err(3, "Can't open configuration file %s", filename); } return fd; } int createFile(char * filename) { int fd = open(filename, O_CREAT | O_WRONLY, 0666); if ( fd == -1) { freeSegmentParameters(); err(4, "Can't create configuration file %s", filename); } return fd; } void writeFile(int count, int fd) { for (int i = 0; i < count; i++) { if (write(fd, &segments[i], sizeof(segments[i])) <= 0) { close(fd); freeSegmentParameters(); err(7, "Couldn't rewrite the file"); } } } int readFile(int fd) { int count = 0; ssize_t readSize; while((readSize = read(fd, &segments[count], sizeof(segments[count]))) != 0 ) { if (readSize < 0) { close(fd); freeSegmentParameters(); err(7, "An error occured while reading from a file"); } count++; } return count; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sqatim <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/31 18:58:00 by sqatim #+# #+# */ /* Updated: 2019/11/08 22:40:49 by sqatim ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int words(char *str, char c) { int i; int j; i = 0; j = 0; while (str[i]) { while (str[i] == c && str[i]) i++; if (str[i] && str[i] != c) { i++; j++; } while (str[i] && str[i] != c) i++; } return (j); } static void *leak(char **spl, int j) { j = j - 1; while (spl[j]) { free(spl[j]); j--; } free(spl); return (NULL); } static int carcts(char *str, char c) { int i; i = 0; while (str[i] && str[i] != c) { i++; } return (i); } static char *alloc(char **tab, char *src, char c) { int i; int j; int o; j = 0; o = 0; while (src[o] == c) o++; while (j < words(src, c)) { i = 0; if (!(tab[j] = malloc(sizeof(char) * (carcts(&src[o], c) + 1)))) return (leak(tab, j)); while (src[o] != c && src[o]) tab[j][i++] = src[o++]; tab[j][i] = '\0'; while (src[o] == c && src[o]) o++; j++; } tab[j] = NULL; return (*tab); } char **ft_split(char const *s, char c) { int i; int j; int o; char **tab; char *str; o = 0; i = 0; j = 0; if (!s) return (NULL); str = (char *)s; tab = malloc(sizeof(char *) * (words(str, c) + 1)); if (!tab) return (NULL); tab[j] = alloc(tab, str, c); return (tab); }
C
/** * @file ooc_template.h * @brief Template header file * * Includes macros for templates * Credits to: * https://github.com/pfultz2/Cloak/wiki/C-Preprocessor-tricks,-tips,-and-idioms * for preprocesser tricks * * @warning * @date 8/7/2017 */ #pragma once #include "ooc_object.h" #include "ooc_string.h" #include <math.h> #include <stdbool.h> /**********************************************************************************************//** * @def EXPAND(x) * * @brief expands a token * * @param x Variable to expand * * @def CAT(a, b) * * @brief appends two token * * @param a Variable to append * @param b Variable to append * * @def STRINGIFY(x) * * @brief makes a token a string * * @param x Variable to become a string * * @def GET_FIRST_ARG(arg, ...) * * @brief Gets the first argument of a macro * * @param arg The first argument * @param args The arguments * * @note bug in VS... https://stackoverflow.com/questions/4750688/how-to-single-out-the-first-parameter-sent-to-a-macro-taking-only-a-variadic-par * * @def PP_NARG(...) * * @brief Returns the number of arguments * * @param args The arguments * * @def New(type) * * @brief A macro that calls new for a class and returns an object * @param type The class * @return An object * * @def Delete(type, object) * * @brief A macro that calls new for a class and returns an object * * @param type The class * @param object the object to be deleted * * @def Call(type, function, ...) * * @brief A macro that calls a function in an object * * @param type The class * @param function The object's member method * @param ... Variable arguments providing additional information. * @note The first parameter in the variable arguments must be the <b>object</b> because every member * function passes <b>this</b> as the first argument * * @def SafeCall(type, function, ...) * * @brief A macro that calls a function in an object and checks the type at runtime * * @param type The class * @param function The object's member method * @param ... Variable arguments providing additional information. * @note The first parameter in the variable arguments must be the <b>object</b> because every member * function passes <b>this</b> as the first argument * * @def Initializer_List(type, ...) * * @brief A macro that initializes an object * * @param type The class's type * @param ... List of arguements * * @def Upcast(new_type, object) * * @brief Casts an object to a new_object, returns vftable, NULL if failure * * @param new_type The new upcast type * @param object The object * * **************************************************************************************************/ #define EMPTY(...) #define DEFER(...) __VA_ARGS__ EMPTY() #define EXPAND(...) __VA_ARGS__ #define PRIMITIVE_CAT(a, b) a##b #define CAT(a, b) PRIMITIVE_CAT(a, b) #define STRINGIFY_EXPANSION(x) #x #define STRINGIFY(x) STRINGIFY_EXPANSION(x) #define ADD_PARERENTHSIS_EXPANSION(x) (x) #define ADD_PARERENTHSIS(x) ADD_PARERENTHSIS_EXPANSION(x) #define GET_FIRST_ARG_(arg, ...) arg #define GET_FIRST_ARG(args) GET_FIRST_ARG_ args #define GET_SECOND_ARG_(arg, arg2, ...) arg2 #define GET_SECOND_ARG(args) GET_SECOND_ARG_ args //https ://stackoverflow.com/questions/2124339/c-preprocessor-va-args-number-of-arguments //doesn't work with empty #define PP_NARG(...) \ PP_NARG_(__VA_ARGS__,PP_RSEQ_N()) #define PP_NARG_(...) \ EXPAND(PP_ARG_N(__VA_ARGS__)) #define PP_ARG_N( \ _1, _2, _3, _4, _5, _6, _7, _8, _9,_10, \ _11,_12,_13,_14,_15,_16,_17,_18,_19,_20, \ _21,_22,_23,_24,_25,_26,_27,_28,_29,_30, \ _31,_32,_33,_34,_35,_36,_37,_38,_39,_40, \ _41,_42,_43,_44,_45,_46,_47,_48,_49,_50, \ _51,_52,_53,_54,_55,_56,_57,_58,_59,_60, \ _61,_62,_63,N,...) N #define PP_RSEQ_N() \ 63,62,61,60, \ 59,58,57,56,55,54,53,52,51,50, \ 49,48,47,46,45,44,43,42,41,40, \ 39,38,37,36,35,34,33,32,31,30, \ 29,28,27,26,25,24,23,22,21,20, \ 19,18,17,16,15,14,13,12,11,10, \ 9,8,7,6,5,4,3,2,1,0 //Macros for calling #define Initializer_List(type, ...) (const type[]) {__VA_ARGS__, 0}, PP_NARG(__VA_ARGS__) //TEMPLATES #define VectorExpansion(type) CAT(Vector, type) #define Vector(type) VectorExpansion(type) #define SetExpansion(type) CAT(Set, type) #define Set(type) SetExpansion(type) #define EntryExpansion(key_type, value_type) CAT(Entry, CAT(key_type, value_type)) #define Entry(key_type, value_type) EntryExpansion(key_type, value_type) #define MapExpansion(key_type, value_type) CAT(Map, CAT(key_type, value_type)) #define Map(key_type, value_type) MapExpansion(key_type, value_type) #define IteratorExpansion(type) CAT(type, Iterator) #define Iterator(type) IteratorExpansion(type) //CASTS void* SetVFTable(void* object, void* new_vftable); void* UpcastVFTableRecurse(const char* new_type, void* _pVFTable, void* _basepVFTable); void* UpcastVFTable(const char* new_type, void* object); //only casts table #define UpcastTableExpansion(new_type, object) \ UpcastVFTable(STRINGIFY(new_type), object) \ #define UpcastTable(new_type, object) UpcastTableExpansion(new_type, object) //casts object (changes vftable) #define Upcast(new_type, object) ((UpcastTable(new_type, object)) ? (SetVFTable(object, UpcastTable(new_type, object))) : (NULL)) void* DowncastVFTable(void* _newTypeVFTable, void* object); //only casts table #define DowncastTableExpansion(new_type, object) \ DowncastVFTable(&CAT(new_type, vfTable), object) \ #define DowncastTable(new_type, object) DowncastTableExpansion(new_type, object) #define Downcast(new_type, object) ((DowncastTable(new_type, object)) ? (SetVFTable(object, DowncastTable(new_type, object))) : (NULL)) //used for SafeCall -- we don't want to change the vftable, only checks if cast is allowed #define CheckDynamicCast(new_type, object) ((UpcastTable(new_type, object)) ? (true) : ((DowncastTable(new_type, object)) ? (true) : (false))) //converts actual object's vftable //#define DynamicCast(new_type, object) ((UpcastTable(new_type, object)) ? (Upcast(new_type, object)) : ((DowncastTable(new_type, object)) ? (Downcast(new_type, object)) : (NULL))) //attempts upcast and downcast vftable (doesn't change vftable) #define DynamicCast(new_type, object) ((UpcastTable(new_type, object)) ? (object) : ((DowncastTable(new_type, object)) ? (object) : (NULL))) //Important expansions #define NewExpansion(type) New ## type() #define New(type) NewExpansion(type) //TOTAL UNSAFE... :( //MOVE SEMANTICS // =/ in C LUL? //ugh not perfect, we convert the macro to a string and check if it is a move //const char* CheckForMove(const char* macro); /* #define Moo(type, function, ...) CheckForMove(GET_FIRST_ARG((#__VA_ARGS__))) #define CheckMove(...) CheckForMove(GET_FIRST_ARG((#__VA_ARGS__))) #define MoveCall(type, function, ...) \ (CheckForMove(GET_FIRST_ARG((#__VA_ARGS__))) \ ? \ (Call(type, CAT(move_, function), __VA_ARGS__)) \ : \ (Call(type, function, __VA_ARGS__)) \ ) \ #define MoveCall(type, function, ...) MoveCallExpansion(type, function, __VA_ARGS__) */ bool MoveSetPointerToNull(bool result, void** object); /* #define MoveCallExpansion(type, function, ...) ((type ## VFTable*)((Object)GET_FIRST_ARG((__VA_ARGS__)))->pVFTable)->CAT(move_, function)(__VA_ARGS__) #define MoveCall(type, function, ...) MoveCallExpansion(type, function, __VA_ARGS__) */ //default to V2 if V1 is not defined #define OOC_V2 #if defined(OOC_V1) #define Delete(type, object) DeleteExpansion(type, object) #define CallExpansion(type, function, ...) ((type ## VFTable*)((Object)GET_FIRST_ARG((__VA_ARGS__)))->pVFTable)->function(__VA_ARGS__) #define Call(type, function, ...) CallExpansion(type, function, __VA_ARGS__) #define MoveCallExpansion(type, function, ...) MoveSetPointerToNull(((type ## VFTable*)((Object)GET_FIRST_ARG((__VA_ARGS__)))->pVFTable)->CAT(move_, function)(__VA_ARGS__), (void**)&GET_SECOND_ARG((__VA_ARGS__))) #define MoveCall(type, function, ...) MoveCallExpansion(type, function, __VA_ARGS__) #define SafeCallExpansion(type, function, ...) (CheckDynamicCast(type, GET_FIRST_ARG((__VA_ARGS__))) ? (((type ## VFTable*)((Object)GET_FIRST_ARG((__VA_ARGS__)))->pVFTable)->function(__VA_ARGS__)) : 0) #define SafeCall(type, function, ...) SafeCallExpansion(type, function, __VA_ARGS__) #define DeleteExpansion(type, object) \ Delete ## type(object); \ object = NULL \ //Iterators #define ForEach(element, container_type, container, ...) \ for( \ Iterator(container_type) CAT(container, Iterator) = Call(container_type, begin, container); \ Call(container_type, end, container, CAT(container, Iterator)) != NULL; \ Call(container_type, next, container, CAT(container, Iterator)) \ ) \ { \ element = CAT(container, Iterator)->data; \ __VA_ARGS__ \ } \ #elif defined(OOC_V2) //Iterators #define ForEach(element, container_type, container, ...) \ for( \ Iterator(container_type) CAT(container, Iterator) = Call(container, begin); \ Call(container, end, CAT(container, Iterator)) != NULL; \ Call(container, next, CAT(container, Iterator)) \ ) \ { \ element = CAT(container, Iterator)->data; \ __VA_ARGS__ \ } \ #define MoveCallExpansion(object, function, ...) MoveSetPointerToNull((object)->pVFTable->CAT(move_, function)(object, __VA_ARGS__), (void**)&GET_FIRST_ARG((__VA_ARGS__))) #define MoveCall(object, function, ...) MoveCallExpansion(object, function, __VA_ARGS__) #ifdef _MSC_VER //microsoft (nonstandard) zero arguments erases comma #define CallExpansion(object, function, ...) ((object)->pVFTable->function(object, __VA_ARGS__)) #define Call(object, function, ...) CallExpansion(object, function, __VA_ARGS__) #define SafeCallExpansion(type, object, function, ...) ((CheckDynamicCast(type, object)) ? (Call(type, object, function, __VA_ARGS__)) : (0)) #define SafeCall(type, object, function, ...) do { SafeCallExpansion(type, object, function, __VA_ARGS__) } while(0); #else //assume gcc/clang (nonstandard) zero arguments passed to __VA_ARGS__ doesn't erase the comma #define CallExpansion(object, function, ...) ((object)->pVFTable->function(object, ##__VA_ARGS__)) #define Call(object, function, ...) CallExpansion(object, function, ##__VA_ARGS__) #define SafeCallExpansion(type, object, function, ...) ((CheckDynamicCast(type, object)) ? (Call(type, object, function, ##__VA_ARGS__)) : (0)) #define SafeCall(type, object, function, ...) do { SafeCallExpansion(type, object, function, ##__VA_ARGS__) } while(0); #endif #define DeleteExpansion(object) \ Call(object, delete); \ object = NULL; \ #define Delete(object) do { DeleteExpansion(object) } while(0) #endif #ifdef OOC_V1 #undef OOC_V1 #endif #ifdef OOC_V2 #undef OOC_V2 #endif //GLOBAL DEFINES #define NPOS -1 #define OOC_CLASS(type, ...) \ typedef struct CAT(type, VFTable_) CAT(type, VFTable); \ typedef struct CAT(type, _) \ { \ CAT(type, VFTable)* pVFTable; \ CAT(type, VFTable)* objectpVFTable; \ struct \ GET_FIRST_ARG((__VA_ARGS__)) \ ; \ } *type; \ \ typedef struct CAT(type, VFTable_) \ { \ CompleteObjectLocator* pCompleteObjectLocator; \ void (*delete)(type this); \ type (*copy)(type this); \ bool (*equals)(type this, type other); \ int (*compareTo)(type this, type other); \ char* (*toString)(type this); \ struct \ GET_SECOND_ARG((__VA_ARGS__)) \ ; \ } CAT(type, VFTable); \ \ type CAT(New, type)(); \ void Delete##type(type this); \ type CAT(type, copy)(type this); \ bool CAT(type, equals)(type this, type other); \ int CAT(type, compareTo)(type this, type other); \ char* CAT(type, toString)(type this); \ \ TypeDescriptor CAT(type, TypeDescriptor); \ BaseClassDescriptor CAT(type, BaseClassArray)[2]; \ ClassHierarchyDescriptor CAT(type, ClassHierarchyDescriptor); \ CompleteObjectLocator CAT(type, CompleteObjectLocator); \ \ #define OOC_DEFAULT_CLASS_IMPL(type) \ CAT(type, VFTable) CAT(type, vfTable) = { 0 }; \ type CAT(New, type)() \ { \ type this = check_calloc(sizeof(struct CAT(type, _))); \ this->pVFTable = check_calloc(sizeof(CAT(type, VFTable))); \ ObjectConstruct(this); \ \ CAT(type, vfTable).pCompleteObjectLocator = &CAT(type, CompleteObjectLocator); \ CAT(type, vfTable).delete = &Delete##type; \ CAT(type, vfTable).copy = &CAT(type, copy); \ CAT(type, vfTable).equals = &CAT(type, equals); \ CAT(type, vfTable).compareTo = &CAT(type, compareTo); \ CAT(type, vfTable).toString = &CAT(type, toString); \ \ memcpy(this->pVFTable, &CAT(type, vfTable), sizeof(struct CAT(type, _))); \ \ return this; \ } \ \ void Delete##type(type this) \ { \ ObjectDestruct(this); \ this->pVFTable = NULL; \ free(this->objectpVFTable); \ free(this); \ } \ \ type CAT(type, copy)(type this) \ { \ type copy_object = CAT(New, type)(this); \ memcpy((char*)copy_object + 2 * sizeof(CAT(type, VFTable)*), (char*)this + 2 * sizeof(CAT(type, VFTable)*), sizeof(struct CAT(type, _)) - 2 * sizeof(CAT(type, VFTable)*)); \ return copy_object; \ } \ \ bool CAT(type, equals)(type this, type other) \ { \ return !memcmp((char*)this + 2 * sizeof(CAT(type, VFTable)*), (char*)other + 2 * sizeof(CAT(type, VFTable)*), sizeof(struct CAT(type, _)) - 2 * sizeof(CAT(type, VFTable)*)); \ } \ \ int CAT(type, compareTo)(type this, type other) \ { \ return memcmp((char*)this + 2 * sizeof(CAT(type, VFTable)*), (char*)other + 2 * sizeof(CAT(type, VFTable)*), sizeof(struct CAT(type, _)) - 2 * sizeof(CAT(type, VFTable)*)); \ } \ \ char* CAT(type, toString)(type this) \ { \ return ObjectToString(this); \ } \ \ TypeDescriptor CAT(type, TypeDescriptor) = \ { \ .pVFTable = &CAT(type, vfTable), \ .name = STRINGIFY(type) \ }; \ \ BaseClassDescriptor CAT(type, BaseClassArray)[] = \ { \ ObjectBaseClassDescriptor, \ { \ .numContainedClasses = 2, \ .pTypeDescriptor = &CAT(type, TypeDescriptor) \ } \ }; \ \ ClassHierarchyDescriptor CAT(type, ClassHierarchyDescriptor) = \ { \ .attributes = CLASS_HIERARCHY_VIRTUAL_INHERITENCE, \ .numBaseClasses = 2, \ .pBaseClassArray = CAT(type, BaseClassArray) \ }; \ \ CompleteObjectLocator CAT(type, CompleteObjectLocator) = \ { \ .signature = 0x48454845, \ .pTypeDescriptor = &CAT(type, TypeDescriptor), \ .pClassHierarchyDescriptor = &CAT(type, ClassHierarchyDescriptor) \ }; \ \ //GCC #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) /* Test for GCC > 4.9.0 */ #if GCC_VERSION > 40900 //implement _Generic #define GCC_New() void free_object(void* obj); //https://snai.pe/c/c-smart-pointers/ #define unique __attribute__((cleanup(free_object))) #endif
C
#include "test.h" #include "algorithm.h" #include "encoder.h" void enterTest(SmartCar * smartCar, uint8_t); void segmentTest(SmartCar * smartCar); void servoTest(SmartCar * smartCar); void motorTest(SmartCar * smartCar); void cameraTest(SmartCar * smartCar); LEDData getLine(Camera * camera); void test(SmartCar * smartCar) { uint8_t menu = 0; board.led.off(1); board.led.off(2); board.led.off(3); board.led.off(4); while (1) { Segment_print(&smartCar->segment[0], (uint16_t)1111); Segment_print(&smartCar->segment[1], menu); Segment_print(&smartCar->segment[2], (uint16_t)1111); switch (board.button.read()) { case 1: menu++; break; case 2: menu--; break; case 3: if (menu > 4 || menu < 1) { menu = 1; continue; } enterTest(smartCar, menu); Segment_print(&smartCar->segment[0], 0); break; case 4: Segment_print(&smartCar->segment[0], (uint16_t)0123); Segment_print(&smartCar->segment[1], (uint16_t)3456); Segment_print(&smartCar->segment[2], (uint16_t)6789); return; } } } void enterTest(SmartCar * smartCar, uint8_t menu) { switch (menu) { case 1: // segment & barLED segmentTest(smartCar); break; case 2: // servo servoTest(smartCar); break; case 3: // motor & encoder motorTest(smartCar); break; case 4: // camera cameraTest(smartCar); break; } } void segmentTest(SmartCar * smartCar) { int16_t segmentInput[3] = { (uint16_t) 1234, (uint16_t) 4567, (uint16_t) 7890 }; uint8_t tempOfcalc[4] = { 0, 0, 0, 0 }; uint8_t i, j; while (1) { for (i = 0; i < 2; i++) { BarLED_print(&smartCar->barLED[i], smartCar->barLED[i].data); } for (i = 0; i < 3; i++) { Segment_print(&smartCar->segment[i], segmentInput[i]); } //button4 is clicked, and segment test end switch (board.button.check()) { //BarLED ON case 1: for (i = 0; i < 16; i++) { LEDData_add(&smartCar->barLED[0].data, i); LEDData_add(&smartCar->barLED[1].data, i); } break; //BarLED OFF case 2: for (i = 0; i < 2; i++) { smartCar->barLED[i].data.len = 0; } break; //add each segment value case 3: for (i = 0; i < 4; i++) { tempOfcalc[i] = 0; } for (i = 0; i < 3; i++) { tempOfcalc[0] = (uint8_t) ((segmentInput[i] / 1000) % 10); tempOfcalc[1] = (uint8_t) ((segmentInput[i] / 100) % 10); tempOfcalc[2] = (uint8_t) ((segmentInput[i] / 10) % 10); tempOfcalc[3] = (uint8_t) (segmentInput[i] % 10); for (j = 0; j < 4; j++) { if (tempOfcalc[j] > 9) { tempOfcalc[j] = 0; } else { tempOfcalc[j]++; } } segmentInput[i] = (uint16_t) tempOfcalc[0] * 1000; segmentInput[i] = segmentInput[i] + (uint16_t) tempOfcalc[1] * 100; segmentInput[i] = segmentInput[i] + (uint16_t) tempOfcalc[2] * 10; segmentInput[i] = segmentInput[i] + (uint16_t) tempOfcalc[3]; } break; //segment Test end case 4: for (i = 0; i < 3; i++) { segmentInput[i] = 0; Segment_print(&smartCar->segment[i], segmentInput[i]); } for (i = 0; i < 2; i++) { smartCar->barLED[i].data.len = 0; } return; } } } void servoTest(SmartCar * smartCar) { smartCar->servo.steer = 0; while (1) { Servo_runAs(&smartCar->servo, smartCar->servo.steer); Segment_print(&smartCar->segment[1], smartCar->servo.steer); switch (board.button.read()) { case 1: if (smartCar->servo.steer < 100) { smartCar->servo.steer = smartCar->servo.steer + 10; } else { smartCar->servo.steer = 100; } break; case 2: if (smartCar->servo.steer > -100) { smartCar->servo.steer = smartCar->servo.steer - 10; } else { smartCar->servo.steer = -100; } break; case 3: smartCar->servo.steer = -smartCar->servo.steer; break; case 4: smartCar->servo.steer = 0; Servo_runAs(&smartCar->servo, smartCar->servo.steer); Segment_print(&smartCar->segment[1], smartCar->servo.steer); return; } } } void motorTest(SmartCar * smartCar) { int16_t speed = 300; Motor_Enable(&smartCar->motor); Servo_init(&smartCar->servo); Servo_runAs(&smartCar->servo,0); while (1) { Servo_runAs(&smartCar->servo,0); smartCar->motor.sendPID = 1;//for bluetooth send start Motor_runAs(&smartCar->motor, speed); Segment_print(&smartCar->segment[0], smartCar->motor.targetSpeed); Segment_print(&smartCar->segment[1], Encoder_get(&smartCar->encoder)); Segment_print(&smartCar->segment[2], smartCar->motor.currentSpeed); switch (board.button.check()) { case 1: // fast if (speed < 2000) { speed = speed + 50; } else { speed = 2000; } break; case 2: // slow if (speed > -2000) { speed = speed - 50; } else { speed = -2000; } break; case 3: // reverse speed = -speed; break; case 4: //motor test end smartCar->motor.sendPID = 0;//for bluetooth send stop speed = 0; Motor_Disable(&smartCar->motor); Segment_print(&smartCar->segment[0], speed); Segment_print(&smartCar->segment[1], speed); return; } } } void cameraTest(SmartCar * smartCar) { AIData data[2]; int16_t pos[2]; while (1) { AIData_init(&data[0], &smartCar->camera[0]); AIData_init(&data[1], &smartCar->camera[1]); binarization(&data[0]); binarization(&data[1]); dumpData(data[0].arr, &smartCar->barLED[0]); dumpData(data[1].arr, &smartCar->barLED[1]); pos[0] = findIndexRL(&data[0]); pos[1] = findIndexLR(&data[1]); Segment_print(&smartCar->segment[0], (smartCar->camera[1].average + smartCar->camera[0].average)/2); Segment_print(&smartCar->segment[1], handling(pos[0], pos[1],smartCar->motor.targetSpeed)); Segment_print(&smartCar->segment[2], Camera_getInterval() / 100); switch (board.button.check()) { case 4: Segment_print(&smartCar->segment[0], 0); Segment_print(&smartCar->segment[1], 0); Segment_print(&smartCar->segment[2], 0); return; } } }
C
#include<stdio.h> int i; int** createMatrix(int r, int c){ //rows and columns int ** m; **m = malloc(r*sizeof(int)); for(i=0; ; i++){ *(m+1) = malloc(c*sizeof(int)); } return m; } int main(){ int **matrix; matrix = createMatrix(5,5); for(){ } free(matrix); }
C
/* SAUVAGE Tao 19/10/11 Utils */ #ifndef DEF_UTILS #define DEF_UTILS #include <stdlib.h> #include <stdio.h> /* Boolean datatype */ #define TRUE 1 #define FALSE 0 typedef unsigned int Boolean; /* Result: boolean Data: data to test Process: test if the data is empty (i.e NULL) */ int power(int, int); void clean_stdin(void); #endif
C
#include <stdio.h> #include <stdlib.h> size_t maxSeq(int *array, size_t n); size_t grader(int *array, size_t n, size_t correctSequence) { int funcAns = maxSeq(array, n); if (correctSequence != funcAns) { return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } int main() { int test[7] = {1, 2, 2, 3, 4, 5, 0}; int testResult = grader(test, 7, 4); if (testResult == EXIT_FAILURE) { return EXIT_FAILURE; } int test2[6] = {10, 9, 8, 7, 6, 7}; int test2Result = grader(test2, 6, 2); if (test2Result == EXIT_FAILURE) { return EXIT_FAILURE; } int test3[0]; int test3Result = grader(test3, 0, 0); if (test3Result == EXIT_FAILURE) { return EXIT_FAILURE; } int test4[7] = {1, 1, 1, 1, 1, 1, 1}; int test4Result = grader(test4, 7, 0); if (test4Result == EXIT_FAILURE) { return EXIT_FAILURE; } int test5[5] = {10, 9, 8, 7, 7}; int test5Result = grader(test5, 5, 0); if (test5Result == EXIT_FAILURE) { return EXIT_FAILURE; } int test6[3] = {1, 2, 3}; int test6Result = grader(test6, 3, 3); if (test6Result == EXIT_FAILURE) { return EXIT_FAILURE; } int test7[3] = {3, 2, 1}; int test7Result = grader(test7, 3, 0); if (test7Result == EXIT_FAILURE) { return EXIT_FAILURE; } int test8[3] = {3, -2, 1}; int test8Result = grader(test8, 3, 2); if (test8Result == EXIT_FAILURE) { return EXIT_FAILURE; } return EXIT_SUCCESS; }
C
#include <fcntl.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include <time.h> #include <stdio.h> #define MAX_BUF 1024 int main() { int fd; char * myfifo = "/tmp/myfifo"; char buf[MAX_BUF]; /* open, read, and display the message from the FIFO */ while(1){ time_t timeBase = time(NULL); char *currTimeHere = ctime(&timeBase); // Find the current time for this program fd = open(myfifo, O_RDONLY); if (fd > -1){ read(fd, buf, MAX_BUF); // Read from the FIFO // Output recieved time (that at the sending program) and the local time (that here) printf("%s\n", buf); close(fd); } else { return 0; } } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <unistd.h> int read_line(char *line, char terminator, int maxlen) { int c, i = 0; while((c = getchar()) != terminator) { if (i < maxlen) *line++ = c, i++; } *line = '\0'; return i; } struct vstring { int len; char *str[]; }; int compar(const void *a, const void *b) { return strcmp(*(char **)a, *(char **)b); } int main() { char word[20]; char **words = malloc(sizeof(char *) * 20); int word_count = 0; int read = 0; for(;;) { if (isatty(fileno(stdin))) printf("Enter a word: "); if(!(read = read_line(word, '\n', 20))) break; if (word_count == 20) { words = realloc(words, sizeof(char *) * word_count * 2); if (!words) exit(1); } words[word_count] = malloc(strlen(word) + 1); strcpy(words[word_count++], word); } qsort(words, word_count, sizeof(char *), compar); printf("\n\n\nSorted words: "); for(int i = 0; i < word_count; i++) { printf("%s", words[i]); printf("%s", i == word_count - 1 ? "": ", "); printf("%s", !(i % 5) ? "\n" : ""); } return 0; }
C
/* * Copyright (C) 1998, 1999, 2002, 2003, 2005 Hewlett-Packard Co * David Mosberger-Tang <[email protected]> * * Register stack engine related helper functions. This file may be * used in applications, so be careful about the name-space and give * some consideration to non-GNU C compilers (though __inline__ is * fine). */ #ifndef RSE_H #define RSE_H #include <libunwind.h> static inline uint64_t rse_slot_num (uint64_t addr) { return (addr >> 3) & 0x3f; } /* * Return TRUE if ADDR is the address of an RNAT slot. */ static inline uint64_t rse_is_rnat_slot (uint64_t addr) { return rse_slot_num (addr) == 0x3f; } /* * Returns the address of the RNAT slot that covers the slot at * address SLOT_ADDR. */ static inline uint64_t rse_rnat_addr (uint64_t slot_addr) { return slot_addr | (0x3f << 3); } /* * Calculate the number of registers in the dirty partition starting at * BSPSTORE and ending at BSP. This isn't simply (BSP-BSPSTORE)/8 * because every 64th slot stores ar.rnat. */ static inline uint64_t rse_num_regs (uint64_t bspstore, uint64_t bsp) { uint64_t slots = (bsp - bspstore) >> 3; return slots - (rse_slot_num(bspstore) + slots)/0x40; } /* * The inverse of the above: given bspstore and the number of * registers, calculate ar.bsp. */ static inline uint64_t rse_skip_regs (uint64_t addr, long num_regs) { long delta = rse_slot_num(addr) + num_regs; if (num_regs < 0) delta -= 0x3e; return addr + ((num_regs + delta/0x3f) << 3); } #endif /* RSE_H */
C
#include "SSSDT.h" extern ULONG_PTR SSSDTDescriptor; extern PDRIVER_OBJECT CurrentDriverObject; extern PVOID SysModuleBsse; extern ULONG_PTR ulSysModuleSize; //SSSDTַ*4+SSSDT һ4λúƫơSSSDTõ Ӧַ PVOID GetSSSDTFunctionAddress64(ULONG ulIndex) { LONG v1 = 0; ULONG_PTR v2 = 0; ULONG_PTR ServiceTableBase= 0 ; PSYSTEM_SERVICE_TABLE64 SSSDT = (PSYSTEM_SERVICE_TABLE64)SSSDTDescriptor; ServiceTableBase=(ULONG_PTR)(SSSDT ->ServiceTableBase); v2 = ServiceTableBase + 4 * ulIndex; v1 = *(PLONG)v2; v1 = v1>>4; return (PVOID)(ServiceTableBase + (ULONG_PTR)v1); } //SSSDTַ+4*IndexSSSDTӦĺַ PVOID GetSSSDTFunctionAddress32(ULONG ulIndex) { ULONG_PTR ServiceTableBase= 0 ; PSYSTEM_SERVICE_TABLE32 SSSDT = (PSYSTEM_SERVICE_TABLE32)SSSDTDescriptor; ServiceTableBase = (ULONG_PTR)(SSSDT->ServiceTableBase); return (PVOID)(*(PULONG_PTR)((ULONG_PTR)ServiceTableBase + 4 * ulIndex)); } //Ring3ģDriverObject->DriverSectionṹ Ƚϣ һ򷵻ַ BOOLEAN GetSysModuleByLdrDataTable(WCHAR* wzModuleName) { BOOLEAN bRet = FALSE; if (CurrentDriverObject) { PKLDR_DATA_TABLE_ENTRY ListHead = NULL, ListNext = NULL; ListHead = ListNext = (PKLDR_DATA_TABLE_ENTRY)CurrentDriverObject->DriverSection; //dt _DriverObject while((PKLDR_DATA_TABLE_ENTRY)ListNext->InLoadOrderLinks.Flink != ListHead) { //DbgPrint("%wZ\r\n",&ListNext->BaseDllName); if (ListNext->BaseDllName.Buffer&& wcsstr((WCHAR*)(ListNext->BaseDllName.Buffer),wzModuleName)!=NULL) { SysModuleBsse = (PVOID)(ListNext->DllBase); ulSysModuleSize = ListNext->SizeOfImage; //DbgPrint("%x %x\r\n",ListNext->DllBase,ListNext->EntryPoint); // DbgPrint("ModuleNameSecondGet:%wZ\r\n",&(ListNext->FullDllName)); bRet = TRUE; break; } ListNext = (PKLDR_DATA_TABLE_ENTRY)ListNext->InLoadOrderLinks.Flink; } } return bRet; } //DriverObject->DriverSectionṹвҺģ BOOLEAN GetSysModuleByLdrDataTable1(PVOID Address,WCHAR* wzModuleName) { BOOLEAN bRet = FALSE; ULONG_PTR ulBase; ULONG ulSize; if (CurrentDriverObject) { PKLDR_DATA_TABLE_ENTRY ListHead = NULL, ListNext = NULL; ListHead = ListNext = (PKLDR_DATA_TABLE_ENTRY)CurrentDriverObject->DriverSection; //dt _DriverObject while((PKLDR_DATA_TABLE_ENTRY)ListNext->InLoadOrderLinks.Flink != ListHead) { ulBase = (ListNext)->DllBase; ulSize = (ListNext)->SizeOfImage; if((ULONG_PTR)Address > ulBase && (ULONG_PTR)Address < ulSize+ulBase) { memcpy(wzModuleName,(WCHAR*)(((ListNext)->FullDllName).Buffer),sizeof(WCHAR)*60); bRet = TRUE; break; } ListNext = (PKLDR_DATA_TABLE_ENTRY)ListNext->InLoadOrderLinks.Flink; } } return bRet; } VOID UnHookSSSDTWin7(ULONG ulIndex, ULONG_PTR OriginalFunctionAddress) { ULONG_PTR v2 = 0; ULONG_PTR ServiceTableBase = 0 ; ULONG CurrentFunctionOffsetOfSSSDT = 0; PSYSTEM_SERVICE_TABLE64 SSSDT = (PSYSTEM_SERVICE_TABLE64)SSSDTDescriptor; ServiceTableBase=(ULONG_PTR)(SSSDT ->ServiceTableBase); CurrentFunctionOffsetOfSSSDT = (ULONG)((ULONG_PTR)OriginalFunctionAddress - (ULONG_PTR)(SSSDT->ServiceTableBase)); CurrentFunctionOffsetOfSSSDT = CurrentFunctionOffsetOfSSSDT<<4; v2 = ServiceTableBase + 4 * ulIndex; WPOFF(); *(PLONG)v2 = CurrentFunctionOffsetOfSSSDT; WPON(); } VOID UnHookSSSDTWinXP(ULONG ulIndex, ULONG_PTR OriginalFunctionAddress) { ULONG_PTR ServiceTableBase = 0 ; ULONG_PTR v2 = 0; PSYSTEM_SERVICE_TABLE32 SSSDT = (PSYSTEM_SERVICE_TABLE32)SSSDTDescriptor; ServiceTableBase=(ULONG_PTR)(SSSDT->ServiceTableBase); v2 = ServiceTableBase + 4 * ulIndex; WPOFF(); *(PLONG)v2 = (ULONG)OriginalFunctionAddress; WPON(); } BOOLEAN ResumeSSSDTInlineHook(ULONG ulIndex,UCHAR* szOriginalFunctionCode) { PVOID CurrentFunctionAddress = NULL; #ifdef _WIN64 CurrentFunctionAddress = GetSSSDTFunctionAddress64(ulIndex); #else CurrentFunctionAddress = GetSSSDTFunctionAddress32(ulIndex); #endif WPOFF(); SafeCopyMemory(CurrentFunctionAddress,szOriginalFunctionCode,CODE_LENGTH); //memcpy(CurrentFunctionAddress,szOriginalFunctionCode,CODE_LENGTH); WPON(); return TRUE; }
C
#include <stdio.h> void ft_swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; } int main() { int num1 = 7; int num2 = 5; int *pnum1 = &num1; int *pnum2 = &num2; printf("pnum1= %d\n",*pnum1); printf("num1= %d\n", num1); printf("pnum2= %d\n",*pnum2); printf("num2= %d\n", num2); ft_swap(pnum1, pnum2); printf("num1= %d\n", num1); printf("pnum1 = %d\n",*pnum1); printf("num2= %d\n", num2); printf("pnum2 = %d\n",*pnum2); return(0); }
C
#include <stdio.h> #include <stdlib.h> static int binary_search_first(const int *A, const int n, const int key) { int l = 0, r = n - 1, m = (n - 1) / 2; while (l <= r){ if (A[m] < key) l = m + 1; else r = m - 1; m = (l + r) / 2; } return l; } static int binary_search_last(const int *A, const int n, const int key) { int l = 0, r = n - 1, m = (n - 1) / 2; while (l <= r){ if (A[m] > key) r = m - 1; else l = m + 1; m = (l + r) / 2; } return r; } int main(int argc, char **argv) { const int A[] = {0, 0, 0, 2, 3, 3, 3, 3, 3, 4, 5, 5}; int l, r, key, n; if (argc != 2){ printf("Usage: %s key\n", argv[0]); return 1; } key = atoi(argv[1]); n = sizeof(A) / sizeof(int); /*0 <= l <= n*/ l = binary_search_first(A, n, key); if (l >= n || key != A[l]){ printf("%d not found\n", key); return 0; } /*-1 <= r <= n -1*/ r = binary_search_last(A, n, key); if (l > r){ printf("%d not found\n", key); }else{ printf("%d occurs %d times\n", key, r - l + 1); } return 0; }
C
#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node *next; }; //struct Node *indertOrdered(struct Node, int); //struct Node *deleteNode(struct Node, int); struct Node *insertOrdered(struct Node* head, int data){ struct Node *ptr, *ptr2; if(head== NULL){ // list is empty head= malloc(sizeof(struct Node)); //create new node (*head).data=data; //make new node head of LL (*head).next=NULL; //head node points to NULL }else if (data < (*start).data){ //value of new node is less than head node struct Node *nextNode =malloc(sizeof(struct Node)); //create new node (*nextNode).data=data; // new node data is set to incoming data (*nextNode).next=head; // new node link points to head, head link still points to NULL return nextNode; //returns LL with new head }else{ ptr = head; //set pointer to beginning of LL while(ptr != NULL){ //iterates pointer through LL if(data < (*ptr).data){//finds where greater value node then insert before struct Node *newNode =malloc(sizeof(struct Node)); //create node (*newNode).data = data; //newNode data is set to incoming data (*newNode).next = (*ptr).next; (*ptr).next = newNode; return head; }else if(data == (*ptr).data){ // node with data already in LL return head; //silently ignore and return LL } ptr2 = ptr; ptr = (*ptr).next; } struct Node *santoshNode = malloc(sizeof(struct Node)); (*santoshNode).data=data; (*santoshNode).next=NULL; (*ptr2).next=santoshNode; return head; } } struct Node *deleteNode(struct Node *head, int data){ struct Node *ptr = head; struct Node *ptr2 = head; if(data == (*head).data){//node has same value as head return (*head).next;//deletes link to first node } if(head == NULL){ //case where list is empty return head; //return empty list } while(ptr != NULL){ if(data == (*ptr).data){ (*ptr2).next = (*ptr).next; return head; } ptr2 = ptr; ptr2 = (*ptr2).next; return head; } } int main(int argc, char** argv){ struct Node *head; /*If no file was inputed*/ if (argc != 2){ return 0; } FILE *inputFile = fopen(argv[1], "r"); char action; int num; // File doesn't exist if (inputFile == NULL){ printf("error\n"); return 0; } while(fscanf(inputFile, "%c %d\n", &action, &num) == 2 ){ if(action == 'i'){ head = insertOrdered(head, num); } else if(action == 'd'){ head = deleteNode(head, num); } else { printf("error"); return 0; } } if(!feof(inputFile)){ printf("error"); return 0; } while (head != NULL){ printf("%d\t", head->data); head = head->next; } fclose(inputFile); free(head); return 0; }
C
#include <stdio.h> #include "bitboard.h" bitboard PDIAGS[15] = {0x0100000000000000ull, 0x0201000000000000ull, 0x0402010000000000ull, 0x0804020100000000ull, 0x1008040201000000ull, 0x2010080402010000ull, 0x4020100804020100ull, 0x8040201008040201ull, 0x0080402010080402ull, 0x0000804020100804ull, 0x0000008040201008ull, 0x0000000080402010ull, 0x0000000000804020ull, 0x0000000000008040ull, 0x0000000000000080ull }; bitboard NDIAGS[15] = {0x0000000000000001ull, 0x0000000000000102ull, 0x0000000000010204ull, 0x0000000001020408ull, 0x0000000102040810ull, 0x0000010204081020ull, 0x001020408102040ull, 0x0102040810204080ull, 0x0204081020408000ull, 0x0408102040800000ull, 0x0810204080000000ull, 0x1020408000000000ull, 0x2040800000000000ull, 0x4080000000000000ull, 0x8000000000000000ull }; inline int countBits(bitboard b) { unsigned long long int c; asm ( "popcntq %1, %0" : "=r" (c) : "r" (b) ); return (int) c; } /* given a bitboard, returns the first occupied position */ inline int bsf(bitboard b){ unsigned long long int v; asm ( "bsfq %1, %0\n\t" "jnz 1f\n\t" "movq $64, %0\n\t" "1:" : "=r" (v) : "r" (b) ); return (int) v; } inline int bsr(bitboard b){ unsigned long long int v; asm ( "bsrq %1, %0\n\t" "jnz 1f\n\t" "movq $64, %0\n\t" "1:" : "=r" (v) : "r" (b) ); return (int) v; } //like bsf, but returns 63 if a 1 is not found. inline int sf(bitboard b){ unsigned long long int v = 63; asm ( "bsfq %1, %0\n\t" "jnz 1f\n\t" "movq $63, %0\n\t" "1:" : "=r" (v) : "r" (b) ); return v; } //like bsr, but returns 0 if a 1 is not found inline int sr(bitboard b){ unsigned long long int v = 0; asm ( "bsrq %1, %0\n\t" "jnz 1f\n\t" "movq $0, %0\n\t" "1:" : "=r" (v) : "r" (b) ); return v; } inline int popBit(bitboard* b){ int p = bsf(*b); *b &= *b - 1; return p; } void printBitboard(bitboard bits){ int r, c; for (r = 7; r >= 0; r--){ for (c = 0; c < 8; c++){ int i = r*8 + c; char c = ((bits >> i) & 1) ? 'x': '.'; printf("%c", c); } printf("\n"); } }
C
// // Created by Mario on 21.11.2020. // #define pageSize 4096 #define fenceSize 16 #define fenceVal 17 #define utilitySize (sizeof(struct control)+(2*fenceSize)) #define PAGES_AVAILABLE 16384 //#define hehe 1 #include "heap.h" #include "custom_unistd.h" #include <stdio.h> #include <string.h> #include <stdlib.h> #include <errno.h> #include <stdint.h> void fenceset(char* ptr) { for(int i = 0 ; i < fenceSize ; i++) { ptr[i] = (char)fenceVal; } } uint64_t controlCalc(struct control *ptr) { uint64_t sum = 0; for(int i = 0; i < 5; i++) { sum += *((uint64_t *)ptr+i); } return sum; } char fence[17] = {fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal, fenceVal}; struct mein_heap myHeap = {0,0,0}; struct control *getLost() { struct control *temp = myHeap.head; for (; temp->next != NULL; temp = temp->next) { ; } return temp; } void *findAlignment(struct control *node) { void *temp = node->usersMem; for(unsigned int i = 0 ; i <= node->size ; i++) { if((((intptr_t)((char *)temp+i) & (intptr_t)(pageSize - 1)) == 0)) { return (char *)temp+i; } } return NULL; } int heap_setup(void) //1 { errno = 0; myHeap.heapStart= custom_sbrk(2*pageSize); if(errno) { return -1; } myHeap.size = 2*pageSize; // calkowita dostepna pamiec myHeap.head = (struct control *)((char*)myHeap.heapStart+fenceSize); //ustawiam control block na poczatku sterty, za plotkami memset(myHeap.heapStart,fenceVal,fenceSize); // plotek na poczatku memset((char*)(myHeap.heapStart)-fenceSize+2*pageSize,fenceVal, fenceSize); // plotek na koncu (myHeap.head)->next = NULL; // pierwszy wezel (myHeap.head)->prev = NULL; // (myHeap.head)->size = myHeap.size - 3*fenceSize - sizeof(struct control); // rozmiar wolnego bloku (myHeap.head)->isFree = 1; // wolny, memset((char *)myHeap.head+sizeof(struct control), fenceVal, fenceSize); // plotek za control blockiem (myHeap.head)->usersMem = (char*)myHeap.head+fenceSize+sizeof(struct control); //wskaznik na pierwszy adres wolnej przestrzeni (za blokiem i plotkiem) myHeap.head->control = controlCalc(myHeap.head); return 0; } void heap_clean(void) //2 { myHeap.heapStart = custom_sbrk((int)-myHeap.size); myHeap.heapStart = NULL; myHeap.size = 0; myHeap.head = NULL; } void* heap_malloc(size_t size) //4 { if(size<=0) { return NULL; // no troche maly size imo } struct control *temp = myHeap.head; for(;temp!=NULL; temp = temp->next) { if(temp->next == NULL) { break; // BO MI TEMP ZNIKNIE } if(temp->isFree == 1) { if(temp->size >= size || (char*)temp->usersMem+size == (char*)temp->next-fenceSize) // czy kiedys byl recyklingowy { temp->size = size; // nowy size memset((char*)temp->usersMem+size,fenceVal,fenceSize); // fill temp->isFree = 0; temp->control = controlCalc(temp); return temp->usersMem; // zwracam stary wskaznik }else { continue; } } } // Nie ma free blockow w liscie -> jestem na koncu listy// jesli koniec listy, to raczej ten blok nie bedzie fillowany // ten if sie aktywuje przy 1. mallocu ZAWSZE if(temp->next == NULL) { //if(temp->trueSize == temp->size) { if(temp->size > utilitySize + size) // czy zmieszcze nowy malloc { memset((char *)temp->usersMem+size, fenceVal, fenceSize); struct control *node = (struct control *)((char *)temp->usersMem + size + fenceSize); memset(((char *)node + sizeof(struct control)), fenceVal, fenceSize); unsigned int nowySize = temp->size - size - utilitySize; temp->size = size; temp->next = node; temp->isFree = 0; temp->control = controlCalc(temp); node->next = NULL; node->prev = temp; node->usersMem = (char *)node + fenceSize+sizeof(struct control); if((int)nowySize - fenceSize < 0) { errno = 0; custom_sbrk(pageSize); if(errno) { return NULL; } myHeap.size += pageSize; memset((char*)myHeap.heapStart+myHeap.size-fenceSize, fenceVal, fenceSize); nowySize += pageSize; node->size = nowySize; node->control = controlCalc(node); }else { node->size = nowySize; node->control = controlCalc(node); } node->isFree = 1; node->control = controlCalc(node); return temp->usersMem; }else // koncowka strony, nie ma miejsca na nowy malloc { //plswork: errno = 0; unsigned int ileStron = ((size/pageSize)+1); // ile potrzebuje stron /// if(ileStron > PAGES_AVAILABLE) { return NULL; } unsigned int ileDoszlo = pageSize * ileStron; custom_sbrk(ileDoszlo); if(errno) { return NULL; } //printf(" size before dociagnieciu %d\n", myHeap.size); myHeap.size += ileDoszlo; //printf(" size after dociagnieciu %d\n\n", myHeap.size); memset(((char*)myHeap.heapStart+myHeap.size-fenceSize),fenceVal,fenceSize); // nowe plotki na koncu heapa temp->size += (ileDoszlo); // malloc + nowy control block // struct control *lastNode = (struct control *)((char* )temp->usersMem+size+fenceSize); temp->next = lastNode; temp->isFree = 0; memset((char *)lastNode+sizeof(struct control),fenceVal, fenceSize); memset((char *)lastNode - fenceSize, fenceVal, fenceSize); lastNode->next = NULL; lastNode->prev = temp; lastNode->isFree = 1; lastNode->size = temp->size-size-utilitySize; temp->size = size; lastNode->usersMem = (char*)lastNode + sizeof(struct control) + fenceSize; lastNode->control = controlCalc(lastNode); temp->control = controlCalc(temp); return temp->usersMem; } } } return NULL; } void* heap_calloc(size_t number, size_t size) { if(number <= 0 || size <= 0) { return NULL; } void *temp = heap_malloc(number*size); if(temp != NULL) memset(temp,0,number*size); return temp; } void* heap_realloc(void* memblock, size_t count) { if(heap_validate() != 0) { return NULL; } if(get_pointer_type(memblock) != pointer_valid && get_pointer_type(memblock) != pointer_null) { return NULL; } if(memblock == NULL) { return heap_malloc(count); } if(count == 0) { heap_free(memblock); return NULL; } struct control *last = getLost(); struct control *temp = (struct control*)((char*)memblock-(fenceSize+sizeof(struct control))); if(count==temp->size) { return memblock; } if(temp->size>count){ //przestaw plotek, rozmiar i zwroc block temp->size=count; memset((char *)memblock + temp->size, fenceVal, fenceSize); temp->control=controlCalc(temp); return memblock; } plswork:; //zwiekszamy size bloku if(count>temp->size){//to liczy ile wolnej pamieci pomiedzy poczatkiem usermema ktory powiekszasz a koncem nastepnego z ktorym merge if(temp->next && temp->next->isFree && (((uint64_t)((char*)temp->next+temp->next->size+sizeof(struct control)+fenceSize)-(uint64_t)temp->usersMem)>=count && temp->next->next != NULL)){ //merge w prawo //dla potomnych wskazniki struct control placeholder = *temp->next; placeholder.next=temp->next; placeholder.prev=temp->prev; //setting new size temp->size = count; //relinking list temp->next=placeholder.next->next; if(placeholder.next->next){ placeholder.next->next->prev=temp; placeholder.next->next->control=controlCalc(placeholder.next->next); } temp->control=controlCalc(temp); memset((char *)memblock + temp->size, fenceVal, fenceSize); return temp->usersMem; }else if(temp->next && temp->next->isFree && (((uint64_t)((char*)temp->next+temp->next->size+sizeof(struct control)+fenceSize)-(uint64_t)temp->usersMem) >= count + utilitySize && temp->next->next == NULL)){ //merge w prawo //dla potomnych wkazniki struct control placeholder = *temp->next; placeholder.next=temp->next; placeholder.prev=temp->prev; //nowy size temp->size = count; //przepinka temp->next=placeholder.next->next; if(placeholder.next->next){ placeholder.next->next->prev=temp; placeholder.next->next->control=controlCalc(placeholder.next->next); }else { struct control *newNode = (struct control *)((char *)temp->usersMem + temp->size + fenceSize); memset((char *)newNode+sizeof(struct control),fenceVal, fenceSize); newNode->usersMem = (char *)newNode + sizeof(struct control) + fenceSize; newNode->isFree = 1; newNode->next = NULL; newNode->prev = temp; temp->next = newNode; newNode->size = (uint64_t)((char *)myHeap.heapStart + myHeap.size - fenceSize) - (uint64_t)(newNode->usersMem); newNode->control = controlCalc(newNode); } temp->control=controlCalc(temp); memset((char *)memblock + temp->size, fenceVal, fenceSize); return temp->usersMem; }else if(count + utilitySize >= last->size) { errno = 0; custom_sbrk((((count + utilitySize)/pageSize)+1)*pageSize); if(errno) { return NULL; } myHeap.size += (((count + utilitySize)/pageSize)+1)*pageSize; memset((char*)myHeap.heapStart+myHeap.size-fenceSize, fenceVal, fenceSize); last->size += (((count + utilitySize)/pageSize)+1)*pageSize; last->control = controlCalc(last); //printf("1"); goto plswork; } // nie mozna uzyc starego wiec malloc -> memcpy ->free ->nowy blok else{ void* newBlock=heap_malloc(count); memcpy(newBlock,memblock,temp->size); heap_free(memblock); return newBlock; } } return NULL; } void heap_free(void* memblock) { //printf("samo freee\n"); if(custom_sbrk_check_fences_integrity()) { printf(" free check \n"); } if(memblock != NULL) { if(heap_validate() == 0 && get_pointer_type(memblock) == pointer_valid) { struct control *temp = (struct control *)((char *)memblock - sizeof(struct control) - fenceSize); temp->size = (char *)temp->next - (char *)temp->usersMem - fenceSize; memset((char *)temp->usersMem + temp->size, fenceVal, fenceSize); //temp->isFree = 1; if(temp->next->isFree == 1 && temp->next != NULL) // merge lewo { struct control *temp2 = temp->next; temp->next = temp2->next; temp->size += temp2->size+utilitySize; temp2->isFree = 1; temp->isFree = 1; temp->control = controlCalc(temp); if(temp->next){ temp->next->prev=temp; temp->next->control=controlCalc(temp->next); } memset((char*)temp->usersMem+temp->size, fenceVal, fenceSize); } if(temp->prev != NULL && temp->prev->isFree == 1 && !(((intptr_t)memblock & (intptr_t)(pageSize - 1)) == 0)) { struct control *temp2 = temp->prev; temp2->next = temp->next; temp2->size += temp->size + utilitySize; if(temp2->next){ temp2->next->prev=temp2; temp2->next->control=controlCalc(temp2->next); } temp2->control = controlCalc(temp2); memset((char*)temp2->usersMem+temp2->size, fenceVal, fenceSize); } temp->isFree = 1; temp->control = controlCalc(temp); } } } size_t heap_get_largest_used_block_size(void) { struct control *temp = myHeap.head; if(temp == NULL) { return 0; } if(heap_validate()) { return 0; } unsigned int max = 0; unsigned int cnt = 0; for(;temp!=NULL; temp = temp->next) { if(cnt != 0 && temp->next == NULL && temp->isFree == 0) { return 0; } cnt++; if(temp->size > max && temp->isFree == 0 && temp->next != NULL) { max = temp->size; } } return max; } enum pointer_type_t get_pointer_type(const void* const pointer) { if(pointer == NULL) return pointer_null; if(heap_validate()) { return pointer_heap_corrupted; } struct control *temp = myHeap.head; for(;temp!=NULL; temp = temp->next) { void *begin = temp; //AAAABBBBB //void *end = temp->next; void *end = (void *)((char *)temp->usersMem + temp->size + fenceSize); if(pointer >= begin && pointer < end) { if(temp->isFree == 1) { return pointer_unallocated; }else { //control block// if(pointer >= begin && (char *)pointer < (char *)begin+sizeof(struct control)) { return pointer_control_block; } //plotek za CB// if((char*)pointer >= (char *)begin+sizeof(struct control) && (char *)pointer < (char *)temp->usersMem) { return pointer_inside_fences; } //poczatek user blocka// if(pointer == temp->usersMem) { return pointer_valid; } if(pointer > temp->usersMem && (char *)pointer < (char *)temp->usersMem + temp->size) { return pointer_inside_data_block; } //za user blockem (czyli plotek + retarded plotek)// if((char *)pointer >= (char *)temp->usersMem + temp->size &&(char *)pointer < (char *)temp->usersMem + temp->size +fenceSize) { return pointer_inside_fences; } } } } return pointer_unallocated; } int heap_validate(void) //3 validate as true { // printf("validate called\n"); if(!myHeap.heapStart) { return 2; } //fenceset(fence); //printf("%d\n", __LINE__); struct control *temp = myHeap.head; //plotki heapa // printf("%d\n", __LINE__); if(memcmp(myHeap.heapStart, fence, fenceSize)==0) { //printf("%d\n", __LINE__); if(memcmp((char*)myHeap.heapStart+myHeap.size-fenceSize,fence,fenceSize) != 0) { //printf("%d\n", __LINE__); //printf("umar plotek heapa :( \n"); return 1; } } //plotki na stercie// // printf("%d\n", __LINE__); uint64_t chck = 0; for(;temp!=NULL; temp = temp->next) { // suma kontrolna //printf("%d\n", __LINE__); chck = controlCalc(temp); if(temp->control != chck) { // printf("%d\n", __LINE__); return 3; } //plotki dookola user blocka// //printf("%d\n", __LINE__); if(memcmp((char*)temp->usersMem-fenceSize,(char*)fence,fenceSize) != 0) { //printf("%d\n", __LINE__); //printf("umar plotek user blocku :( no.1 wywolanie %d\n", i); return 1; }else { //printf("%d\n", __LINE__); if(memcmp((char*)temp->usersMem+temp->size,(char*)fence,fenceSize) != 0) { // printf("%d\n", __LINE__); //printf("umar plotek user blocku :( no.2 wywolanie %d\n", i); return 1; } } } //printf("%d\n", __LINE__); // printf("validate done\n"); return 0; } void* heap_malloc_aligned(size_t size) { // printf("malloc called \n"); if(size<=0) { return NULL; // no troche maly size imo } struct control *temp = myHeap.head; for(;temp!=NULL; temp = temp->next) { if(temp->next == NULL) { if((((intptr_t)temp->usersMem & (intptr_t)(pageSize - 1)) == 0)) // TEGO NIE PRZEWIDZIELISMY { if(temp->size > size + utilitySize) { struct control *newLastNode = (struct control* )((char *)temp->usersMem + size + fenceSize); newLastNode->usersMem = (char *)newLastNode + sizeof(struct control) + fenceSize; newLastNode->size = temp->size - size - utilitySize; memset((char *)newLastNode->usersMem - fenceSize, fenceVal, fenceSize); memset((char *)newLastNode->usersMem + newLastNode->size, fenceVal, fenceSize); memset((char *)temp->usersMem + size, fenceVal, fenceSize); temp->size = size; temp->isFree = 0; newLastNode->isFree = 1; newLastNode->next = NULL; newLastNode->prev = temp; temp->next = newLastNode; temp->control = controlCalc(temp); newLastNode->control = controlCalc(newLastNode); return temp->usersMem; } }else break; // BO MI TEMP ZNIKNIE } if(temp->isFree == 1 && (((intptr_t)temp->usersMem & (intptr_t)(pageSize - 1)) == 0)) //recykling alignowanego bloku { if(temp->size >= size || (char*)temp->usersMem+size == (char*)temp->next-fenceSize) // czy kiedys byl recyklingowy { temp->size = size; // nowy size memset((char*)temp->usersMem+size,fenceVal,fenceSize); // fill temp->isFree = 0; temp->control = controlCalc(temp); return temp->usersMem; // zwracam stary wskaznik }else { continue; } } } // Nie ma free blockow w liscie -> jestem na koncu listy// jesli koniec listy, to raczej ten blok nie bedzie fillowany // ten if sie aktywuje przy 1. mallocu ZAWSZE void *alignedPtr = NULL; if(temp->next == NULL) { //if(temp->trueSize == temp->size) { plswork2:; if((alignedPtr = findAlignment(temp)) != NULL) { if((size_t)(((char *)myHeap.heapStart + myHeap.size - fenceSize) -((char *)alignedPtr)) > size + utilitySize) // koniec heapa - poczatek userblocka >= malloc + utility { //printf("%d\n", __LINE__); struct control backup; // bo sie zgubia linki oO backup.next = temp->next; backup.prev = temp->prev; backup.usersMem = temp->usersMem; backup.size = temp->size; backup.isFree = temp->isFree; struct control *nodeAlign = (struct control *)((char *)alignedPtr - fenceSize - sizeof(struct control)); memset((char *)alignedPtr - fenceSize, fenceVal, fenceSize); memset((char *)alignedPtr + size, fenceVal, fenceSize); struct control *newLast = (struct control *)((char *)alignedPtr + size + fenceSize); newLast->size = ((char *)myHeap.heapStart + myHeap.size - fenceSize) - ((char *)newLast + sizeof(struct control) + fenceSize); newLast->usersMem = (char *)newLast + sizeof(struct control) + fenceSize; memset((char *)newLast->usersMem - fenceSize, fenceVal, fenceSize); memset((char *)newLast->usersMem + newLast->size, fenceVal, fenceSize); newLast->next = backup.next; newLast->prev = nodeAlign; newLast->isFree = 1; newLast->control = controlCalc(newLast); nodeAlign->next = newLast; nodeAlign->prev = backup.prev; if(nodeAlign->prev != NULL) { nodeAlign->prev->next = nodeAlign; nodeAlign->prev->control = controlCalc(nodeAlign->prev); }else { temp->next = nodeAlign; temp->size = (char *)nodeAlign - (char *)temp->usersMem - fenceSize; memset((char *)temp->usersMem+temp->size,fenceVal,fenceSize); temp->control = controlCalc(temp); } nodeAlign->size = size; nodeAlign->isFree = 0; nodeAlign->usersMem = alignedPtr; nodeAlign->control = controlCalc(nodeAlign); //printf("returned \n"); return nodeAlign->usersMem; }else alignedPtr = NULL; } if(alignedPtr == NULL) { errno = 0; unsigned int ileStron = (((size+utilitySize + fenceSize)/pageSize)+1); // ile potrzebuje stron /// tu sie cos sypie if(ileStron > PAGES_AVAILABLE) { return NULL; } unsigned int ileDoszlo = pageSize * ileStron; custom_sbrk(ileDoszlo); if(errno) { return NULL; } myHeap.size += ileDoszlo; memset(((char*)myHeap.heapStart+myHeap.size-fenceSize),fenceVal,fenceSize); // nowe plotki na koncu heapa temp->size += (ileDoszlo); temp->control = controlCalc(temp); //printf("2"); goto plswork2; } } } printf("Cos poszlo bardzo nie tak z kodem"); return NULL; } void* heap_calloc_aligned(size_t number, size_t size) { if(number <= 0 || size <= 0) { return NULL; } void *temp = heap_malloc_aligned(number*size); if(temp != NULL) memset(temp,0,number*size); return temp; } void* heap_realloc_aligned(void* memblock, size_t count) { //printf("realloc\n"); if(heap_validate() != 0) { return NULL; } if(get_pointer_type(memblock) != pointer_valid && get_pointer_type(memblock) != pointer_null) { return NULL; } if(memblock == NULL) { //printf("realloc to malloc memblock null\n"); return heap_malloc_aligned(count); } if(count == 0) { //printf("realloc to free\n"); heap_free(memblock); return NULL; } struct control *last = getLost(); struct control *temp = (struct control*)((char*)memblock-(fenceSize+sizeof(struct control))); if(count==temp->size) { return memblock; } if(temp->size>count){ //przestaw plotek, rozmiar i zwroc block temp->size=count; memset((char *)memblock + temp->size, fenceVal, fenceSize); temp->control=controlCalc(temp); return memblock; } plswork:; //zwiekszamy blok if(count>temp->size){//to liczy ile masz wolnej pamieci pomiedzy poczatkiem usermema ktory powiekszasz a koncem nastepnego z ktorym mergujesz if(temp->next && temp->next->isFree && (((uint64_t)((char*)temp->next+temp->next->size+sizeof(struct control)+fenceSize)-(uint64_t)temp->usersMem)>=count && temp->next->next != NULL)){ //printf("%d\n", __LINE__); //merge w prawo //dla potomnych wskazniki struct control placeholder = *temp->next; placeholder.next=temp->next; placeholder.prev=temp->prev; //nowy size temp->size = count; //przepinka temp->next=placeholder.next->next; if(placeholder.next->next){ placeholder.next->next->prev=temp; placeholder.next->next->control=controlCalc(placeholder.next->next); } temp->control=controlCalc(temp); memset((char *)memblock + temp->size, fenceVal, fenceSize); return temp->usersMem; }else if(temp->next && temp->next->isFree && (((uint64_t)((char*)temp->next+temp->next->size+sizeof(struct control)+fenceSize)-(uint64_t)temp->usersMem) >= count + utilitySize && temp->next->next == NULL)){ //printf("%d\n", __LINE__); //merge w prawo //dla potomnych wskazniki struct control placeholder = *temp->next; placeholder.next=temp->next; placeholder.prev=temp->prev; //nowy size temp->size = count; //przepinka temp->next=placeholder.next->next; if(placeholder.next->next){ placeholder.next->next->prev=temp; placeholder.next->next->control=controlCalc(placeholder.next->next); }else { //printf("%d\n", __LINE__); struct control *newNode = (struct control *)((char *)temp->usersMem + temp->size + fenceSize); memset((char *)newNode+sizeof(struct control),fenceVal, fenceSize); newNode->usersMem = (char *)newNode + sizeof(struct control) + fenceSize; newNode->isFree = 1; newNode->next = NULL; newNode->prev = temp; temp->next = newNode; newNode->size = (uint64_t)((char *)myHeap.heapStart + myHeap.size - fenceSize) - (uint64_t)(newNode->usersMem); newNode->control = controlCalc(newNode); } temp->control=controlCalc(temp); memset((char *)memblock + temp->size, fenceVal, fenceSize); return temp->usersMem; }else if((size_t)((char *)temp->next - (char *)temp->usersMem - fenceSize) > count) { //printf("%d\n", __LINE__); temp->size = count; memset((char *)temp->usersMem + temp->size,fenceVal, fenceSize); temp->control = controlCalc(temp); return temp->usersMem; } else if(count + utilitySize >= last->size) { //printf("%d\n", __LINE__); errno = 0; custom_sbrk((((count + utilitySize)/pageSize)+1)*pageSize); if(errno) { return NULL; } myHeap.size += (((count + utilitySize)/pageSize)+1)*pageSize; memset((char*)myHeap.heapStart+myHeap.size-fenceSize, fenceVal, fenceSize); last->size += (((count + utilitySize)/pageSize)+1)*pageSize; last->control = controlCalc(last); // printf("3"); // return 3 pls goto plswork; } // nie mozna uzyc starego wiec malloc -> memcpy ->free ->nowy blok else{ // printf("realloc to malloc\n"); //printf("%d\n", __LINE__); void* newBlock=heap_malloc_aligned(count); memcpy(newBlock,memblock,temp->size); heap_free(memblock); return newBlock; } } return NULL; }
C
// // looks like you don't have to go #ifndef #define #end with functions (but you have to import the .h file in mx2) // //int Factorial(int M); int Factorial_send_var(int M) { int factorial=1; // Calculate the factorial with a FOR loop for(int i=1; i<=M; i++) { factorial = factorial*i; } return factorial; // This value is returned to caller } int Factorial_send_ptr(int* M) { int factorial=1; // Calculate the factorial with a FOR loop for(int i=1; i<=*M; i++) { factorial = factorial*i; } return factorial; // This value is returned to caller } int Factorial_send_ref(int& M) { int factorial=1; // Calculate the factorial with a FOR loop for(int i=1; i<=M; i++) { factorial = factorial*i; } return factorial; // This value is returned to caller }
C
/* * header.c * * Created on: 2 kwi 2019 * Author: X */ #include <stdio.h> #include <stdlib.h> #include "header.h" struct element *wsk_str = NULL; //wskaźnik na strukture void dodawanie_elementu(int i) { struct element *aktualny; struct element *first; aktualny = (struct element*)malloc(sizeof(struct element)); //rezerwacja pamięci i przypisanie do wskaznika if (wsk_str == NULL) { wsk_str = aktualny; } else { struct element *temp = wsk_str; while (temp->nastepny !=NULL) { temp = temp->nastepny; } temp->nastepny = aktualny; aktualny->poprzedni = temp; } aktualny->calk = i; aktualny->rzecz = i+0.6; aktualny->pozycja = i; aktualny->pierwszy=wsk_str; } void usuwanie_elementu(int i) { struct element *temp = wsk_str; struct element *aktualny = NULL; if(i==1){ //podmiana danych z elemntu nr 2 do elementu nr 1 temp=temp->nastepny; aktualny=temp->pierwszy; aktualny->poprzedni=NULL; aktualny->calk=temp->calk; aktualny->rzecz=temp->rzecz; aktualny->nastepny=temp->nastepny; } else if(i==10) { for(int k=0; k<i-1; k++) { temp=temp->nastepny; } aktualny=temp->poprzedni; aktualny->nastepny=NULL; } else { for(int k=0; k<i-1; k++) { temp=temp->nastepny; } aktualny=temp->poprzedni; aktualny->nastepny=temp->nastepny; aktualny=temp->nastepny; aktualny->poprzedni=temp->poprzedni; aktualny=temp; temp=temp->nastepny; free(aktualny); } } void wyswietlanie_elementu() { struct element *temp = wsk_str; while (temp != NULL) { printf("Integer: %d ", temp->calk); printf("Float: %.1f \n", temp->rzecz); temp = temp->nastepny; //przejście do następnego } }
C
/* * HEAP-SIFT.C --Fundamental operations for implicit (array) heaps. * * Contents: * heap_sift_up() --Sift a value from the bottom of the heap to the top. * heap_sift_down() --Sift a value from the top to its "correct" position. * heap_ok() --Check the heap condition. * * Remarks: * The heap data structure is a semi-ordered tree that maintains the * property that a parent is greater/equal than ALL its descendents, * with no ordering specified between siblings. It is commonly * modelled as an "implicit" binary tree, implemented as a simple * array. An array implementation is possible because binary-tree * heaps are inherently "balanced" (maybe "full-ish" is a better term * here), so there are no "holes" in the tree. */ #include <string.h> #include <xtd/heap.h> #include <xtd/estring.h> /* for memswap() */ /* * heap_sift_up() --Sift a value from the bottom of the heap to the top. * * Parameters: * heap --specifies the heap array * n_items --No. items in the heap * item_size --size of each item * cmp --comparison function * * Remarks: * A heap "sift-up" is usually used after an insertion: the item is * appended to the end of the list, creating a heap that is valid * *except* for this last leaf item. sift-up re-creates the heap * condition by "floating" the value up the heap towards root. */ void heap_sift_up(void *heap, int n_items, int item_size, CompareProc cmp) { for (int i = n_items - 1; i > 0; i = (i - 1) / 2) { char *node = (char *) heap + i * item_size; char *parent = (char *) heap + (i - 1) / 2 * item_size; if (cmp(node, parent) < 0) { memswap(parent, node, (size_t) item_size); } } } /* * heap_sift_down() --Sift a value from the top to its "correct" position. * * Parameters: * heap --specifies the heap array * n_items --No. items in the heap * item_size --size of each item * cmp --comparison function * * Remarks: * A heap "sift-down" is usually used after a deletion: the first item * is removed, and the last item is swapped into its place, reducing * the heap by 1. The sift-down re-creates the heap condition by * pushing the root down to the child slots. */ void heap_sift_down(void *heap, int n_items, int item_size, CompareProc cmp) { int level; char *node, *child, *end; end = (char *) heap + n_items * item_size; for (level = 1, node = heap; node < end; node = child, level *= 2) { child = (char *) node + level * item_size; /* left child */ if (child >= end) { break; } char *alt_child = child + item_size; /* right child */ if (alt_child < end && cmp(child, alt_child) > 0) { /* choose smallest child */ child = alt_child; } if (cmp(child, node) > 0) { break; } memswap(node, child, (size_t) item_size); } } /* * heap_ok() --Check the heap condition. * * Parameters: * heap --specifies the heap array * n_items --No. items in the heap * item_size --size of each item * cmp --comparison function * * Remarks: * This function is used for unit testing. */ int heap_ok(void *heap, int n_items, int item_size, CompareProc cmp) { char *node, *parent; for (int i = n_items - 1; i > 0; --i) { node = (char *) heap + i * item_size; parent = (char *) heap + (i - 1) / 2 * item_size; if (cmp(node, parent) < 0) { return 0; } } return 1; }
C
/***************************** * 11875 * Brick Game * Accepted ******************************/ #include <stdio.h> int main() { int a[11],i,j,N,T; scanf("%d",&T); for(i=1;i<=T;i++){ scanf("%d",&N); for(j=0;j<N;j++){ scanf("%d",&a[j]); } printf("Case %d: %d\n",i,a[j/2]); } return 0; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* get_commands.c :+: :+: */ /* +:+ */ /* By: bbremer <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/07/22 14:52:39 by bbremer #+# #+# */ /* Updated: 2019/07/24 11:21:04 by bbremer ######## odam.nl */ /* */ /* ************************************************************************** */ #include "../checker_src/checker.h" void print_commands(t_commands *commands) { while (commands->next != NULL) { ft_printf("command is %i\n", commands->command); commands = commands->next; } ft_printf("command is %i\n", commands->command); } void add_commands(t_commands **commands, char *str) { t_commands *new; t_commands *temp; new = new_command(str); temp = *commands; while (temp->next != NULL) temp = temp->next; temp->next = new; } int get_command_id(char *str) { if (ft_strcmp(str, "sa") == 0) return (1); else if (ft_strcmp(str, "sb") == 0) return (2); else if (ft_strcmp(str, "ss") == 0) return (3); else if (ft_strcmp(str, "pa") == 0) return (4); else if (ft_strcmp(str, "pb") == 0) return (5); else if (ft_strcmp(str, "ra") == 0) return (6); else if (ft_strcmp(str, "rb") == 0) return (7); else if (ft_strcmp(str, "rr") == 0) return (8); else if (ft_strcmp(str, "rra") == 0) return (9); else if (ft_strcmp(str, "rrb") == 0) return (10); else if (ft_strcmp(str, "rrr") == 0) return (11); else return (0); } t_commands *new_command(char *str) { t_commands *new; new = (t_commands*)malloc(sizeof(t_commands)); new->command = get_command_id(str); new->next = NULL; if (new->command == 0) { ft_printf("Error: command %s not valid\n", str); free(new); new = NULL; exit(1); } return (new); } void get_commands(t_commands **commands) { int ret; char *line; ret = get_next_line(0, &line); while (ret > 0) { if (!line || ft_strcmp(line, "\n") == 0) break ; if (!*commands) *commands = new_command(line); else add_commands(commands, line); free(line); ret = get_next_line(0, &line); } }
C
#include<stdio.h> #define nil 1<<30 int path[101][101],n,flag[101]; int dis[101]; int sum; int dij(int i,int num) { int min=nil,t,j; for(j=1;j<=n;j++) { if(dis[j]>dis[i]+path[i][j]&&i!=j&&path[i][j]>0) dis[j]=dis[i]+path[i][j]; } for(j=1;j<=n;j++) { if(flag[j]==0&&min>dis[j]) { t=j; min=dis[j]; } } if(min==nil) { if(num==n) return dis[i]; else return nil; } flag[t]=1; dij(t,num+1); } int main() { int m,i,j,a,b,min,t; while(scanf("%d",&n)&&n) { memset(path,-1,sizeof(path)); for(i=1;i<=n;i++) { scanf("%d",&m); while(m--) { scanf("%d%d",&a,&b); path[i][a]=b; } }min=nil; for(i=1;i<=n;i++) { memset(flag,0,sizeof(flag)); for(j=1;j<=n;j++) dis[j]=nil; // printf("%d\n",dis[4]); dis[i]=0; flag[i]=1; sum=dij(i,1); // printf("%d\n",sum); if(sum<min) { min=sum; t=i; } } if(min==nil) { printf("disjoint\n"); } else printf("%d %d\n",t,min); } return 0; }
C
#include <stdio.h> #include <time.h> int main() { struct timespec ts; clock_getres(CLOCK_REALTIME, &ts); printf("clock precision = %ld.%09ld\n", ts.tv_sec, ts.tv_nsec); return 0; }
C
/* * token.c Read the next token from a string. * Yes it's pretty primitive but effective. * * Version: $Id$ * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA * * Copyright 2000,2006 The FreeRADIUS server project */ #include "ident.h" #include "libradius.h" #include "token.h" #include <ctype.h> static const FR_NAME_NUMBER tokens[] = { { "=~", T_OP_REG_EQ, }, /* order is important! */ { "!~", T_OP_REG_NE, }, { "{", T_LCBRACE, }, { "}", T_RCBRACE, }, { "(", T_LBRACE, }, { ")", T_RBRACE, }, { ",", T_COMMA, }, { "+=", T_OP_ADD, }, { "-=", T_OP_SUB, }, { ":=", T_OP_SET, }, { "=*", T_OP_CMP_TRUE, }, { "!*", T_OP_CMP_FALSE, }, { "==", T_OP_CMP_EQ, }, { "=", T_OP_EQ, }, { "!=", T_OP_NE, }, { ">=", T_OP_GE, }, { ">", T_OP_GT, }, { "<=", T_OP_LE, }, { "<", T_OP_LT, }, { "#", T_HASH, }, { ";", T_SEMICOLON, }, { NULL, 0, }, }; /* * This works only as long as special tokens * are max. 2 characters, but it's fast. */ #define TOKEN_MATCH(bptr, tptr) \ ( (tptr)[0] == (bptr)[0] && \ ((tptr)[1] == (bptr)[1] || (tptr)[1] == 0)) /* * Read a word from a buffer and advance pointer. * This function knows about escapes and quotes. * * At end-of-line, buf[0] is set to '\0'. * Returns 0 or special token value. */ static FR_TOKEN getthing(const char **ptr, char *buf, int buflen, int tok, const FR_NAME_NUMBER *tokenlist) { char *s; const char *p; int quote, end = 0; unsigned int x; const FR_NAME_NUMBER*t; FR_TOKEN rcode; buf[0] = 0; /* Skip whitespace */ p = *ptr; while (*p && isspace((int) *p)) p++; if (*p == 0) { *ptr = p; return T_EOL; } /* * Might be a 1 or 2 character token. */ if (tok) for (t = tokenlist; t->name; t++) { if (TOKEN_MATCH(p, t->name)) { strcpy(buf, t->name); p += strlen(t->name); while (isspace((int) *p)) p++; *ptr = p; return (FR_TOKEN) t->number; } } /* Read word. */ quote = 0; if ((*p == '"') || (*p == '\'') || (*p == '`')) { quote = *p; end = 0; p++; } s = buf; while (*p && buflen-- > 1) { if (quote && (*p == '\\')) { p++; switch(*p) { case 'r': *s++ = '\r'; break; case 'n': *s++ = '\n'; break; case 't': *s++ = '\t'; break; case '\0': *s++ = '\\'; p--; /* force EOS */ break; default: if (*p >= '0' && *p <= '9' && sscanf(p, "%3o", &x) == 1) { *s++ = x; p += 2; } else *s++ = *p; break; } p++; continue; } if (quote && (*p == quote)) { end = 1; p++; break; } if (!quote) { if (isspace((int) *p)) break; if (tok) { for (t = tokenlist; t->name; t++) if (TOKEN_MATCH(p, t->name)) break; if (t->name != NULL) break; } } *s++ = *p++; } *s++ = 0; if (quote && !end) { fr_strerror_printf("Unterminated string"); return T_OP_INVALID; } /* Skip whitespace again. */ while (*p && isspace((int) *p)) p++; *ptr = p; /* we got SOME form of output string, even if it is empty */ switch (quote) { default: rcode = T_BARE_WORD; break; case '\'': rcode = T_SINGLE_QUOTED_STRING; break; case '"': rcode = T_DOUBLE_QUOTED_STRING; break; case '`': rcode = T_BACK_QUOTED_STRING; break; } return rcode; } /* * Read a "word" - this means we don't honor * tokens as delimiters. */ int getword(const char **ptr, char *buf, int buflen) { return getthing(ptr, buf, buflen, 0, tokens) == T_EOL ? 0 : 1; } /* * Read a bare "word" - this means we don't honor * tokens as delimiters. */ int getbareword(const char **ptr, char *buf, int buflen) { FR_TOKEN token; token = getthing(ptr, buf, buflen, 0, NULL); if (token != T_BARE_WORD) { return 0; } return 1; } /* * Read the next word, use tokens as delimiters. */ FR_TOKEN gettoken(const char **ptr, char *buf, int buflen) { return getthing(ptr, buf, buflen, 1, tokens); } /* * Expect a string. */ FR_TOKEN getstring(const char **ptr, char *buf, int buflen) { const char *p = *ptr; while (*p && (isspace((int)*p))) p++; *ptr = p; if ((*p == '"') || (*p == '\'') || (*p == '`')) { return gettoken(ptr, buf, buflen); } return getthing(ptr, buf, buflen, 0, tokens); } /* * Convert a string to an integer */ int fr_str2int(const FR_NAME_NUMBER *table, const char *name, int def) { const FR_NAME_NUMBER *this; for (this = table; this->name != NULL; this++) { if (strcasecmp(this->name, name) == 0) { return this->number; } } return def; } /* * Convert an integer to a string. */ const char *fr_int2str(const FR_NAME_NUMBER *table, int number, const char *def) { const FR_NAME_NUMBER *this; for (this = table; this->name != NULL; this++) { if (this->number == number) { return this->name; } } return def; } const char *fr_token_name(int token) { return fr_int2str(tokens, token, "???"); }
C
#include "holberton.h" /** * print_binary - print binary representation of number * @n: number, unsigned * Do not use array, malloc, % and / * * Return: void */ void print_binary(unsigned long int n) { char c; /*base case n == 0*/ if (n == 0) { _putchar('0'); return; } /*base case n at beginning > 0 I have reached most significant bit*/ if ((n ^ 1) == 0) { _putchar('1'); return; } /*recursion*/ print_binary(n >> 1); c = ((n & 1) == 0) ? '0' : '1'; _putchar(c); } /* due to constraints, use recursion * there are 2 base cases: if we want print_binary(0), we have * to return 0, however in any other case we do not want to start * with a 0 so we stop at the leftmost digit that is = 1, ie * the most significant digit, we know it exists since the number * is > 0 */
C
#include "main.h" #include <stdio.h> /** * _strstr - a function that locates a substring. * @haystack: an input string to search in * @needle: an input string to locate into string haystack * Return: a pointer to the beginning of the located substring, * or NULL if the substring is not found. */ char *_strstr(char *haystack, char *needle) { char *startn = needle, *starth = haystack; while (*haystack) { starth = haystack; needle = startn; while (*haystack == *needle) { haystack++; needle++; } if (*needle == '\0') return (haystack); haystack = starth + 1; } return (NULL); }
C
#include "SoundEffects.h" #include <stdio.h> SoundEffect_Queue* create_SoundEffect_Queue(int cap){ SoundEffect_Queue* ptr = (SoundEffect_Queue*) malloc(sizeof(SoundEffect_Queue)); return ptr; } // void EnqueueSoundEffect(SoundEffect_Queue* queue , int soundEffectSelector){ // // if(!isQueueFull(queue) && soundEffectSelector < 6 && soundEffectSelector >= 0){ // queue->size += 1; // queue->back = (queue->back + 1) % queue->capacity; // // queue->effects[queue->back] = soundEffectSelector; // } // } // void PlaySoundEffectThenDequeue(SoundEffect_Queue* queue){ // if(!isQueueEmpty(queue)){} // } int isQueueEmpty(SoundEffect_Queue* queue){ return (queue->size == 0); } int isQueueFull(SoundEffect_Queue* queue){ return (queue->size == queue->capacity); } void SoundEffect_Player_Tick(){}
C
#include <stdio.h> /* construction of a function that returns the arithmetic mean of two numbers */ float media(float n1, float n2); int main() { float r; r = media(10, 20); printf("%f\n", r); return 0; } float media(float n1, float n2) { float result = (n1 + n2) / 2; return result; }
C
#include<stdio.h> int length; int partition(int arr[],int p, int r) { int j, i, temp, x; i= p-1; x= arr[r]; for(j=p;j<r;j++) { if(arr[j]<=x) { i+=1; temp = arr[i]; arr[i] = arr[j]; arr[j]=temp; } } temp = arr[i+1]; arr[i+1] = arr[r]; arr[r] = temp; return i+1; } void quickSort(int arr[], int p, int r) { int q,j ; if(p<r) { q = partition(arr,p,r); for(j=0;j<length;j++) printf("%d ",arr[j]); printf("\n"); quickSort(arr, p, q-1); quickSort(arr, q+1, r); } } int main() { int size; scanf("%d",&size); length = size ; int arr[size]; int i; for(i=0;i<size;i++) scanf("%d",&arr[i]); quickSort(arr,0,size-1); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define SIZE 64 int main() { char *string; string = malloc(sizeof(char)*SIZE); if( string == NULL ) { puts("Unable to allocate memory"); return(1); } printf("Your name: "); fgets(string,SIZE,stdin); printf("Welcome %s\n", string); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(int argc, char const *argv[]) { char line[1044][255], c; int i, j = 0, month[1044], day[1044], hour[1044], minute[1044], counter = 0; FILE * fp = fopen("input1.txt", "r"); if(!fp) { printf("Error: File not opened\n"); return 0; } for(j = 0; j < 1044; j++) { for(i = 0; i < 255; i++) { line[j][i] = '\0'; } } j = 0; while(c != EOF) { i = 0; while(c != '\n' && c != EOF) //GET LINE INTO buff[] { c = fgetc(fp); line[j][i] = c; i++; } j++; if(c != EOF) { c = '\0'; } } for(j = 0; j < 1044; j++) { month[j] = (((int) line[j][6] - 48) * 10) + ((int) line[j][7] - 48); day[j] = (((int) line[j][9] - 48) * 10) + ((int) line[j][10] - 48); hour[j] = (((int) line[j][12] - 48) * 10) + ((int) line[j][13] - 48); minute[j] = (((int) line[j][15] - 48) * 10) + ((int) line[j][16] - 48); //printf("%d-%d %d:%d\n", month[j], day[j], hour[j], minute[j]); } for(int x = 0; x < 1044; x++) { i = 0; for(j = 1; j < 1044; j++) { if(month[j] == month[i]) { //GO UP A LEVEL if(day[j] == day[i]) { //GO UP A LEVEL if(hour[j] == hour[i]) { if(minute[j] < minute[i]) { i = j; } } else { if(hour[j] < hour[i]) { i = j; } } } else { if(day[j] < day[i]) { i = j; } } } else { if(month[j] < month[i]) { i = j; } } } printf("%s", line[i]); month[i] = 13; day[i] = 32; hour[i] = 24; minute[i] = 60; counter++; } //printf("%d lines output\n", counter); fclose(fp); return 0; }
C
#define TYPE_FLOAT 0 #define TYPE_INTEGER 1 #define TYPE_STRING 2 #define COMMAND_SIZE 8 byte COMMAND_BUFFER[COMMAND_SIZE]; //Compare to bytes, ignoring casing. bool equalsIgnoreCasing(byte a, byte b) { if (a == b) return true; if (a - ( 'a' - 'A' ) == b) return true; if (a + ( 'a' - 'A' ) == b) return true; return false; } //Check if a command is located at a given index. bool isCommand(byte command_index) { for (byte i = 0; i < COMMAND_SIZE; i++) { byte b = COMMAND_BUFFER[i]; byte c = readROM(command_index * COMMAND_SIZE + i); if (c == 0) { if (b == ' ' || b == '\n' || b == 0) return true; else return false; } if (!equalsIgnoreCasing(b, c)) { return false; } } return false; } //Extracts a command from a position in RAM. // Returns the command's index. //Gets argument count. bool exec(ibword pos) { //Variables used... byte i = 0; byte valid = false; byte command = -1; byte c = 0; //Skip over white space. c = readPRG(pos); while ( (c == ' ' || c == '\t') && c != 0) { c = readPRG(++pos); } if (c == 0) return true; //Copy command ibwordo the command buffer. for (byte i = 0; i < 8; i++) { COMMAND_BUFFER[i] = 8; } //Look for command while (readROM(COMMAND_SIZE * i) != 255) { if (isCommand(i)) { command = i; break; } i++; } if (command == -1) return false; //Skip over command. for (i = 0; i < COMMAND_SIZE; i++) { if (readROM(COMMAND_SIZE * command) == 0) { break; } pos++; } //Skip over white space. c = readPRG(pos); while ( (c == ' ' || c == '\t') && c != 0 ) { c = readPRG(++pos); } //Parse arguments. return true; }
C
#ifndef LINKEDLIST_H #define LINKEDLIST_H #include <stdio.h> #include <stdlib.h> #include "Graph.h" typedef struct tagNode { Vertex* Data; struct tagNode* NextNode; } Node; /* Single Linked List (SLL) */ Node* SLL_CreateNode(Vertex* NewData); void SLL_DestroyNode(Node* Node); void SLL_DestroyAllNodes(Node** List); void SLL_AppendNode(Node** Head, Node* NewNode); void SLL_InsertAfter(Node* Current, Node* NewNode); void SLL_InsertBefore(Node** Head, Node* Current, Node* NewNode); void SLL_InsertNewHead(Node** Head, Node* NewHead); Node* SLL_GetNodeAt(Node* Head, int Location); int SLL_GetNodeCount(Node* Head); #endif
C
/* Author: Danchen Huang Date Created: 09/15/2015 This file is dedicated to resemble a small graphics library for project 1 of CS1550 */ #include <time.h> #include <termios.h> #include <fcntl.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <linux/fb.h> #include <sys/ioctl.h> #include <sys/mman.h> #include "iso_font.h" #include <stdio.h> typedef unsigned short color_t; unsigned short *frameBuffer; unsigned long virtualResolutionX; unsigned long virtualResolutionY; unsigned long lineLength; int fileDescriptor; void init_graphics(); void exit_graphics(); void clear_screen(); char getkey(); void sleep_ms(long ms); void draw_pixel(int x, int y, color_t color); void draw_rect(int x1, int y1, int width, int height, color_t color); void fill_rect(int x1, int y1, int width, int height, color_t color); void fill_circle(int x, int y, int radius, color_t color); void draw_text(int x, int y, const char *text, color_t color); void draw_line(int x1, int y1, int x2, int y2, color_t color); void draw_char(int x, int y, unsigned char *ch, color_t color); void init_graphics() { struct fb_var_screeninfo sInfo; struct fb_fix_screeninfo bitDepth; struct termios terminalSetting; int fDesc = open("/dev/fb0", O_RDWR); ioctl(fDesc, FBIOGET_VSCREENINFO, &sInfo); ioctl(fDesc, FBIOGET_FSCREENINFO, &bitDepth); fileDescriptor = fDesc; virtualResolutionX = sInfo.xres_virtual; virtualResolutionY = sInfo.yres_virtual; lineLength = bitDepth.line_length; frameBuffer = (unsigned short *)mmap( NULL, virtualResolutionY * lineLength, PROT_WRITE, MAP_SHARED, fDesc, 0); ioctl(STDIN_FILENO, TCGETS, &terminalSetting); terminalSetting.c_lflag &= ~ICANON; terminalSetting.c_lflag &= ~ECHO; ioctl(STDIN_FILENO, TCSETS, &terminalSetting); clear_screen(); } void exit_graphics() { struct termios terminalSetting; ioctl(STDIN_FILENO, TCGETS, &terminalSetting); terminalSetting.c_lflag |= ICANON; terminalSetting.c_lflag |= ECHO; ioctl(STDIN_FILENO, TCSETS, &terminalSetting); munmap(frameBuffer, lineLength * virtualResolutionY); close(fileDescriptor); clear_screen(); } void clear_screen() { int clearScreen; clearScreen = write(1, "\033[2J", 7); } char getkey() { char key; fd_set fileDescVar; FD_ZERO(&fileDescVar); FD_SET(STDIN_FILENO, &fileDescVar); struct timeval timeout; timeout.tv_sec = 2; timeout.tv_usec = 0; int result; result = select( STDIN_FILENO+1, &fileDescVar, NULL, NULL, &timeout ); if( result > 0 ) { read(0, &key, sizeof(key)); } return key; } void sleep_ms(long ms) { struct timespec timeSetting; timeSetting.tv_sec = 0; timeSetting.tv_nsec = ms * 1000000; nanosleep(&timeSetting, NULL); } void draw_pixel(int x, int y, color_t color) { if(x < 0 || x >= virtualResolutionX) { return; } else { if(y < 0 || y >= virtualResolutionY) { return; } } unsigned long x1 = x; unsigned long y1 = y * (lineLength / 2); unsigned short *pixel_ptr = (frameBuffer + x1 + y1); *pixel_ptr = color; } void draw_rect(int x1, int y1, int width, int height, color_t color) { int lowerLeftX = x1; int lowerLeftY = y1; int upperRightX = x1 + width; int upperRightY = y1 + height; int upperLeftX = x1; int upperLeftY = y1 + height; int lowerRightX = x1 + width; int lowerRightY = y1; draw_line(lowerLeftX, lowerLeftY, lowerRightX, lowerRightY, color); draw_line(lowerLeftX, lowerLeftY, upperLeftX, upperLeftY, color); draw_line(upperLeftX, upperLeftY, upperRightX, upperRightY, color); draw_line(lowerRightX, lowerRightY, upperRightX, upperRightY, color); } void fill_rect(int x1, int y1, int width, int height, color_t color) { int x; int y; for(x = x1; x <= x1 + width; x++) { for(y = y1; y <= y1 + height; y++) { draw_pixel(x, y, color); } } } //Midpoint Circle Algorithm similar to wikipedia implementation void fill_circle(int x, int y, int radius, color_t color) { int x1 = radius; int y1 = 0; int decisionOver2 = 1 - x1; while( y1 <= x1) { // setPixel(x0 + x, y0 + y), setPixel(x0 - x, y0 + y) // is equivalent of drawLine(x0 - x, y0 + y, x0 + x, y0 + y) draw_line(x - x1, y + y1, x + x1, y + y1, color); draw_line(x - x1, y - y1, x + x1, y - y1, color); draw_line(x - y1, y + x1, x + y1, y + x1, color); draw_line(x - y1, y - x1, x + y1, y - x1, color); y1++; if(decisionOver2 <= 0) { decisionOver2 += 2 * y1 + 1; } else { x1--; decisionOver2 += 2 * (y1 - x1) + 1; } } } void draw_text(int x, int y, const char *text, color_t color) { const char lineEscape = '\0'; unsigned char ch; int i = 0; while(*(text + i) != lineEscape) { ch = *(text + i); x = x + 8; draw_char(x, y, iso_font + ch * 16, color); i++; } } void draw_char(int x, int y, unsigned char *ch, color_t color) { int i; int j; unsigned char c; for(i = 0;i < 16; i++) { y++; for(j = 0, c = *(ch + i); j < 8; j++) { c = c >> 1; if(c & 0x01) { draw_pixel(x + j, y, color); } } } } void draw_line(int x1, int y1, int x2, int y2, color_t color) { int dx = x2 - x1; int dy = y2 - y1; if( dx < 0 ) { dx = -dx; } if( dy < 0 ) { dy = -dy; } int sx = x1 < x2 ? 1 : -1; int sy = y1 < y2 ? 1 : -1; int err = ( dx > dy ? dx : -dy) / 2; int e2; for(;;) { draw_pixel(x1, y1, color); if(x1 == x2 && y1 == y2) break; e2 = err; if (e2 >-dx) { err -= dy; x1 += sx; } if (e2 < dy) { err += dx; y1 += sy; } } }
C
/* @Author: Raghav Maheshwari. @Date: 26th May, 2019 @Topic: Prims Algorithm for MST */ #include<stdio.h> int cost[20][20]; int visited[20] = {0}; int min_cost = 0; void prims(int n){ int ne = 1; //This is to keep track of the number of edges in MST, should be n-1; int a; //this is the source of the edge. int b; //this is the destination of the edge. while(ne<n){ int min = 999; for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ if(cost[i][j] < min){ //ALl following is valid only i is visited. if(visited[i] != 0){ min = cost[i][j]; a = i; //source b = j; //destination } } } } if(visited[a] == 0 || visited[b] == 0){ printf("\nEdge %d: from %d to %d, cost: %d",ne,a,b,min); min_cost += min; ne++; visited[b] = 1; //marking the destination as visited. } //Before the loop restarts marking cost[a][b] and cost[b][a] as 999 cost[a][b] = cost[b][a] = 999; } printf("\n----------------------------------------------------\n"); printf("\nThe minimum spanning tree cost is %d\n",min_cost); printf("\n----------------------------------------------------\n"); } void main(){ int n; printf("\nEnter the number of vertices in the graph."); scanf("%d",&n); printf("\nEnter the cost of each edge of tree"); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ scanf("%d",&cost[i][j]); if(cost[i][j] == 0){ cost[i][j] = 999; } } } int source; printf("\nEnter the source node:\t"); scanf("%d",&source); visited[source] = 1; prims(n); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* text.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: blee <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/11/30 18:34:20 by blee #+# #+# */ /* Updated: 2018/12/04 15:49:58 by blee ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void angle_display(t_data *data) { char *tmp; tmp = ft_itoa(data->x_deg); mlx_string_put(data->mlx, data->win, (data->wd / 3) - 15, 5, 0xFFFFFF, "X:"); mlx_string_put(data->mlx, data->win, (data->wd / 3) + 5, 5, 0xFFFFFF, tmp); free(tmp); tmp = ft_itoa(data->y_deg); mlx_string_put(data->mlx, data->win, (data->wd / 2) - 15, 5, 0xFFFFFF, "Y:"); mlx_string_put(data->mlx, data->win, (data->wd / 2) + 5, 5, 0xFFFFFF, tmp); free(tmp); tmp = ft_itoa(data->z_deg); mlx_string_put(data->mlx, data->win, ((data->wd * 2) / 3) - 15, 5, 0xFFFFFF, "Z:"); mlx_string_put(data->mlx, data->win, ((data->wd * 2) / 3) + 5, 5, 0xFFFFFF, tmp); free(tmp); }
C
#ifndef GET_CH #define GET_CH #include <stdio.h> #include "getint.h" char buf[BUFFSIZE]; int bufp=0; int getch(void) { return (bufp>0) ? buf[--bufp]:getchar(); } void ungetch(int c) { if(bufp>=BUFFSIZE) printf("Can't ungetch: too many\n"); else buf[bufp++] = c; } #endif
C
#include "basic.h" void selection_sort(Array array, int n) { int i, j, min; for (i = 0; i <= n - 2; i++) { min = i; for (j = i + 1; j <= n - 1; j++) { if (cmp(array[j], array[min]) < 0) { min = j; } } if (cmp(array[min], array[i]) < 0) { swap(array, i, min); } } }
C
/* Um funcionario recebe um salario fixo mais 4% de comissao sobre as vendas. Faca um programa que receba o salario fixo de um funcionario e o valor de suas vendas, calcule e mostre a comissao e o salario final do funcionario. */ #include <stdio.h> #define TAXA_COMISSAO 0.04 int main() { double salario_fixo = 0.00, valor_vendas = 0.00; double comissao = 0.00, salario_final = 0.00; printf("Informe o salario fixo do funcionario: "); scanf("%lf", &salario_fixo); printf("Informe o valor total das vendas do funcionario: "); scanf("%lf", &valor_vendas); comissao = valor_vendas * TAXA_COMISSAO; salario_final = salario_fixo + comissao; printf("Comissao: %.2lf\n", comissao); printf("Salario final: %.2lf\n", salario_final); return 0; }
C
#include <stdio.h> #define XMAX 200 #define YMAX 150 struct point makepoint(int, int, int, int, int); struct point { int x; int y; int z; int a; int b; }; struct rect { struct point pt1; struct point pt2; }; int main() { struct rect screen; struct point middle; screen.pt1 = makepoint(1, 2, 3, 4, 5); screen.pt2 = makepoint(XMAX, YMAX, 4, 5, 6); middle = makepoint((screen.pt1.x + screen.pt2.x)/2, (screen.pt1.y + screen.pt2.y)/2, 0, 0, 0); printf("midpoint: (%d,%d)\n", middle.x, middle.y); struct point origin, *pp; pp = &origin; int a = (*pp).x; a = pp->x; return 0; } /* makepoint: make a point from x and y components */ struct point makepoint(int x, int y, int z, int a, int b) { struct point temp; temp.x = x; temp.y = y; temp.z = z; temp.a = a; temp.b = b; return temp; }
C
/** \file caudales.c * \author Abel N. Dammiani * * \brief Contiene la maquina de estados correspondiente al la medicion de caudales. * */ #include "caudales.h" #include "macros.h" #include "inicio.h" #include <stdio.h> #include <stdlib.h> #include <avr/io.h> #include <avr/pgmspace.h> /***************************************************************************** * Variables Máquina de estados *****************************************************************************/ unsigned char uchEstadoCaudales; /**< \brief variable de la maquina de estados de caudales */ volatile unsigned char uchEtapaMedicionCaudal; /**< \brief variable que indica la etapa de medicion en la que se encuentra la captura */ volatile unsigned int uContStandbyCaudal; /**< \brief contador de espera entre mediciones de caudal para dar tiempo al recorrido de las maquinas de estado */ volatile unsigned int uPrimerCaptura; /**< \brief valores de captura para la medicion de caudal */ volatile unsigned int uSegundaCaptura; /**< \brief valores de captura para la medicion de caudal */ float flCaudalMedido; /**< \brief valor medio de caudal en l/min */ /***************************************************************************** * Variables externas *****************************************************************************/ /***************************************************************************** * Maquina de estados *****************************************************************************/ void Medicion_Caudales (void) { switch (uchEstadoCaudales) { case MEDICION_CAUDAL_STANDBY: if (uContStandbyCaudal == 0){ // si hay voy a medir uchEstadoCaudales = MEDICION_CAUDAL; } break; case MEDICION_CAUDAL: if (uchEtapaMedicionCaudal == ETAPA_MEDICION_STANDBY){ Iniciar_Medicion_Caudal(); } else if (uchEtapaMedicionCaudal == ETAPA_MEDICION_CALCULO){ float flCuentas = uSegundaCaptura-uPrimerCaptura; float flCaudal = 15000000/(flCuentas*PULSOS_X_LITRO_CAUDAL); // en l/min int muestrasPromedio = 65535 / flCuentas; //32767.5@1L 1000@30L if (muestrasPromedio<1){ muestrasPromedio=1; } else if (muestrasPromedio>MAXIMO_MUESTRAS_CAUDAL){ muestrasPromedio=MAXIMO_MUESTRAS_CAUDAL; } flCaudalMedido = flCaudalMedido + (flCaudal - flCaudalMedido) / muestrasPromedio; // hago una media movil // cargo el valor medido uContStandbyCaudal = TIEMPO_MEDICION_CAUDAL_STANDBY; uchEtapaMedicionCaudal = ETAPA_MEDICION_STANDBY; uchEstadoCaudales = MEDICION_CAUDAL_STANDBY; } else if (uchEtapaMedicionCaudal == ETAPA_MEDICION_OVERFLOW){ flCaudalMedido = 0;//lValorCaudal - flValorCaudal / MUESTRAS_CAUDAL; // hago una media movil // cargo el valor medido uContStandbyCaudal = TIEMPO_MEDICION_CAUDAL_STANDBY; uchEtapaMedicionCaudal = ETAPA_MEDICION_STANDBY; uchEstadoCaudales = MEDICION_CAUDAL_STANDBY; } break; default: Configuracion_Timer_Medicion_Caudales(); break; } } /***************************************************************************** * Inicio de Maquina de estados *****************************************************************************/ void Configuracion_Timer_Medicion_Caudales (void) { TCCR1A = (OFF<<COM1A1)|(OFF<<COM1A0)|(OFF<<COM1B1)|(OFF<<COM1B0)|(OFF<<WGM11)|(OFF<<WGM10); /* el timer opera en modo normal */ TCCR1B = (ON<<ICNC1)|(ON<<ICES1)|(OFF<<WGM13)|(OFF<<WGM12)|(OFF<<CS12)|(OFF<<CS11)|(OFF<<CS10); /* con filtro activado, flanco positivo y sin prescaler */ TCCR1C = (OFF<<FOC1A)|(OFF<<FOC1B); /* aseguro que no hay ninguna salida por comparación activada mas alla del modo de operacion */ CLEAR_BIT (TIMSK1, OCIE1A); /* deshabilito la interrupción del comparador A */ CLEAR_BIT (TIMSK1, OCIE1B); /* deshabilito la interrupción del comparador B */ CLEAR_BIT (TIMSK1, TOIE1); /* deshabilito la interrupción por overflow */ CLEAR_BIT (TIMSK1, ICIE1); /* deshabilito la interrupción por captura */ SET_BIT (TIFR1, ICF1); /* reaseguro que no haya ninguna interrupción activa */ SET_BIT (TIFR1, OCF1A); /* reaseguro que no haya ninguna interrupción activa */ SET_BIT (TIFR1, OCF1B); /* reaseguro que no haya ninguna interrupción activa */ SET_BIT (TIFR1, TOV1); /* reaseguro que no haya ninguna interrupción activa */ flCaudalMedido=0.0; uContStandbyCaudal = TIEMPO_MEDICION_CAUDAL_STANDBY; uchEtapaMedicionCaudal = ETAPA_MEDICION_STANDBY; uchEstadoCaudales = MEDICION_CAUDAL_STANDBY; } /************************************************************************ * Inicio medicion ************************************************************************/ void Iniciar_Medicion_Caudal (void) { uchEtapaMedicionCaudal = ETAPA_MEDICION_CAPTURA_1; TCNT1 = 0; /* pongo en cero el timer */ SET_BIT (TIFR1, ICF1); /* reaseguro que no haya ninguna interrupción activa */ SET_BIT (TIFR1, OCF1A); /* reaseguro que no haya ninguna interrupción activa */ SET_BIT (TIFR1, OCF1B); /* reaseguro que no haya ninguna interrupción activa */ SET_BIT (TIFR1, TOV1); /* reaseguro que no haya ninguna interrupción activa */ TCCR1B |= (ON<<CS11)|(ON<<CS10); /* pongo a correr el timer con preescaler en 64 */ SET_BIT (TIMSK1, ICIE1); /* habilito la interrupción por captura */ SET_BIT (TIMSK1, TOIE1); /* habilito la interrupción por overflow */ }
C
#include<avr/io.h> #include <util/delay.h> #define LCD_port PORTA #define LCD_ctrl PORTB #define LCD_port_ddr DDRA #define LCD_ctrl_ddr DDRB #define LCD_RS 0 #define LCD_RW 1 #define LCD_E 2 #define SETB(x,y) x |= (1<<y) #define CLRB(x,y) x &= ~(1<<y) #define COMB(x,y) x ^= (1<<y) void lcd_cmd(char cmd){ LCD_port = cmd; CLRB(LCD_ctrl,LCD_RS); CLRB(LCD_ctrl,LCD_RW); SETB(LCD_ctrl,LCD_E); _delay_ms(100); CLRB(LCD_ctrl,LCD_E); } void lcd_data(char data){ LCD_port = data; SETB(LCD_ctrl,LCD_RS); CLRB(LCD_ctrl,LCD_RW); SETB(LCD_ctrl,LCD_E); _delay_ms(1); CLRB(LCD_ctrl,LCD_E); } void lcd_init(){ LCD_port_ddr = 0xFF; LCD_ctrl_ddr = 0xFF; lcd_cmd(0x38); lcd_cmd(0x0E); lcd_cmd(0x01); lcd_cmd(0x06); } void gotoxy(unsigned char x, unsigned char y){ unsigned char f[] = {0x80,0xC0,0x94,0xD4}; lcd_cmd(f[y-1]+x-1); _delay_ms(1); } void lcd_string(unsigned char str[]){ unsigned int i =0,count = 0; while(str[i]!='\0'){ lcd_data(str[i++]); } }
C
#include <stdio.h> #include <string.h> char nm[3][20], aux[20]; int main(){ for (int i = 0; i < 3; i++) { printf("\nNome %i: ", i+1); scanf("%s", nm[i]); } for (int i = 1; i < 3; i++) { /* 3 = qtde de palavras */ for (int j = 1; j < 3; j++) { // verifica se tem que ser depois, se for troca de posio if (strcmp(nm[j - 1], nm[j]) > 0) { strcpy(aux, nm[j - 1]); strcpy(nm[j - 1], nm[j]); strcpy(nm[j], aux); } } } // s mostrar a matriz for (int i = 0; i < 3; i++) printf("\n%s", nm[i]); return 0; }
C
#include <stdio.h> void *test(char target[]) { printf("%s\n", target); } void run(void *func(), char args[]) { func(args); } int main() { run(test, "will it"); printf("%p\n", test); return 0; }
C
#include <string.h> // for memset #include <avr/io.h> #include "macro.h" #include "switch.h" #define GEN_PORT_GET_FUNC( PORTID ) \ char _port##PORTID##_get(char bitnum) \ { \ if( ( PIN##PORTID & _BV(bitnum) ) == 0 ) \ return SW_ON; \ else \ return SW_OFF; \ } \ typedef struct _sw_map{ char (* port_get)(char); char bitnum; } SW_MAP; /**** ***************************************************** * * XCb`̗p󋵂ɂ * GEN_PORT_GET_FUNC, NUM_SW, SW_MAP, sw_port_init * K؂ɏC邱 * ********************************************************************/ /* XCb`ƂĎg|[g錾B1 ‚łgĂ|[g̖O΂Đ錾邱ƁB */ GEN_PORT_GET_FUNC( B ); /* XCb`̐ƃXCb`̒` SW_MAP ̓YvOł̃XCb`̔ԍƂȂ */ #define NUM_SW 1 static char sw_prev_status[NUM_SW]; // 0: OFF, 1:ON const SW_MAP sw_map[] = { {_portB_get, 0} }; /* |[g̏Agp|[g͂ɂāAvAbvLɂĂ */ void sw_port_init( void ){ // pull up all ports DDRB = 0x00; PORTB = 0xFF; DDRC = 0x00; PORTC = 0xFF; } /**** ܂ *****************************************************/ void sw_init(void) { sw_port_init(); memset(sw_prev_status, 0, NUM_SW); } int sw_get_status( char swno, char *out ){ char (* port_get)(char bitnum) = sw_map[(int)swno].port_get; char bitnum = sw_map[(int)swno].bitnum; char now = port_get(bitnum); *out = now; if( sw_prev_status[ (int)swno ] != now ){ sw_prev_status[ (int)swno ] = now; return 1; } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> const char in[63]={48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,\ 81,82,83,84,85,86,87,88,89,90,95,97,98,99,100,101,102,103,104,105,106,107,108,109,110,\ 111,112,113,114,115,116,117,118,119,120,121,122}; const char inscram[63]={113,51,98,105,72,57,121,88,109,73,56,114,100,115,55,49,81,104,50,71,107,99,122,102,\ 67,103,119,69,75,97,111,48,53,89,77,106,90,101,110,68,80,112,108,52,70,116,83,74,84,120,86,\ 54,87,66,79,85,76,117,65,78,118,82,95}; char word[64]; char out[64]; int punchinelloDecrypt() { int ii=0,jj=0,len2=strlen(word),len=len2-2,idx1=0,idx2=0; if(len2==0 || len<=0) return 1; char word2[64]; memset(word2,0,64); for (ii=0;ii<63;ii++) { jj=ii+len; if (jj>62) jj-=63; out[ii]=inscram[jj]; } ii=jj=0; if (len<5) { idx1=len2-2; idx2=len2-1; } else { idx1=len/2; idx2=len-2; } for (ii=0;ii<len2;ii++) { if (ii==idx1 || ii==idx2) continue; word2[jj++]=word[ii]; } word2[jj]='\0'; if (strlen(word2)!=len) return 1; for (ii=0;ii<len;ii++) { for (jj=0;jj<63;jj++) { if (word2[ii]==out[jj]) { word2[ii]=in[jj]; break; } } } printf ("word=%s\n",word2); return 0; } int punchinelloCrypt() { int ii=0,jj=0,len=strlen(word),idx1=0,idx2=0; if(len==0) return 1; for (ii=0;ii<63;ii++) { jj=ii+len; if (jj>62) jj-=63; out[ii]=inscram[jj]; } for (ii=0;ii<len;ii++) { for (jj=0;jj<63;jj++) { if (word[ii]==in[jj]) { word[ii]=out[jj]; break; } } } if (len<5) { word[len]=40+len; word[len+1]=127-len; } else { idx1=len/2; idx2=len-2; memmove(&word[idx1+1],&word[idx1],len-idx1); word[idx1]=40+len; memmove(&word[idx2+1],&word[idx2],len+1-idx2); word[idx2]=127-len; } word[len+2]='\0'; printf ("word=%s\n",word); return 0; } int main(int argc,char **argv) { memset(word,0,64); memset(out,0,64); if (argc<3) { printf ("usage: pun\n -c word\n -d word\n"); return 1; } strncpy(word,argv[2],60); int res=1; if (strcmp(argv[1],"-c")==0) res=punchinelloCrypt(); else if (strcmp(argv[1],"-d")==0) res=punchinelloDecrypt(); if (res!=0) printf ("usage: pun\n -c word\n -d word\n"); return res; }
C
#include<stdio.h> #include<stdlib.h> #define MAX_SIZE 10 int sorted[MAX_SIZE]; // i ĵ Ʈ ε // j ĵ Ʈ ε // k ĵ Ʈ ε void merge(int list[], int left, int mid, int right) { int i, j, k, l; i = left; j = mid + 1; k = left; // ĵ list պ while (i<=mid && j <= right){ if (list[i] <= list[j]) sorted[k++] = list[i++]; else sorted[k++] = list[j++]; } if (i > mid) // ִ ڵ ϰ for (l = j; l <= right; l++) sorted[k++] = list[l]; else for (l = i; l <= mid; l++) sorted[k++] = list[l]; //迭 sorted[] Ʈ 迭 list[] for (l = left; l <= right; l++) list[l] = sorted[l]; } void merge_sort(int list[], int left, int right) { int mid; if (left < right) { mid = (left + right) / 2; // Ʈ յ merge_sort(list, left, mid); // κ Ʈ merge_sort(list, mid + 1, right); // κ Ʈ merge(list, left, mid, right); // պ } } /* պ ⵵ м */ // Ƚ: ũ n Ʈ Ȯ յйϹǷ log(n) н // н Ʈ ڵ n ϹǷ n /* ̵ Ƚ */ // ڵ ̵ н 2n ߻ϹǷ ü ڵ ̵ 2n*log(n) ߻ // ڵ ũⰡ ū 쿡 ſ ū ð ʷ // ڵ带 Ʈ Ͽ պ , ſ ȿ // , , ־ ū O(n*log(n)) ⵵ // ̸ ʱ л ޴´ // 1. Ʈ յ ũ ϰ ҵ Ʈ // 2. ĵ κ Ʈ Ͽ ü Ʈ Ѵ // , , ˰ Ѵ. // 1. (divide): 迭 ũ 2 κ 迭 // 2. (conquer): κ 迭 ϴµ, κ 迭 ũⰡ ȣ ̿Ͽ ٽ Ѵ // 3. (Combine): ĵ κй迭 ϳ 迭 Ѵ /* պ ˰ */ /* if left<right mid = (left+right)/2; merge_sort(list, left, mid); merge_sort(list, mid+1, right); merge(list, left, mid, right); */ /* պ ˰ */ /* i <- left; j <- mid+1 k <- left; while i < mid and j <right do if(list[i] < mid[j]) then sorted[k] <- list[i]; k++; i++; else sorted[k] <- mid[j]; k++; j++; Ұ κ 迭 sorted Ѵ; sorted list Ѵ */
C
// Program to convert celsius to Farenheit and vice-versa #include <stdio.h> #include <stdlib.h> float degree(float); float degrees(float); int main() { float cel,farenheit=100; cel=degree(farenheit); printf("%f farenheit is %f celsius\n",farenheit,cel); farenheit=degrees(cel); printf("%f celsius is %f farenheit\n",cel,farenheit); return 0; } float degree(float farenheit) { float a; a=(farenheit-32)/1.8;// formula to covert farenheit to celsius return a; } float degrees(float cel) { float b; b=(cel*1.8)+32;// to convert from celsius to Farenheit return b; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <assert.h> #include "linkedList.h" #include "mainAux.h" node* current = NULL; node* head = NULL; node* last = NULL; /* This method prints the undo-redo nodes from the beginning to the end */ void displayForward() { /*start from the beginning*/ struct node *ptr = head; /*navigate till the end of the list*/ printf("\n[ "); while(ptr != NULL) { printf("(%d,%d,%d) ",ptr->x,ptr->y,ptr->value); ptr = ptr->next; } printf(" ]\n"); if (current == NULL) { printf("current=NULL "); } else { printf("current = (%d,%d,%d)\n ",current->x,current->y,current->value); } if (head == NULL) { printf("Head=NULL "); } else { printf("Head = (%d,%d,%d)\n ",head->x,head->y,head->value); } if (last == NULL) { printf("Last=NULL "); } else { printf("Last = (%d,%d,%d)\n ",last->x,last->y,last->value); } } /*insert a node at the very last location*/ void insertLast(int x, int y, int value, int ** matrixBeforeAutofill) { struct node *link = (struct node*) malloc(sizeof(struct node)); link->x = x; link->y = y; link->value = value; link->next = NULL; link->prev = NULL; link->matrixBeforeAutofill = matrixBeforeAutofill; if(last != NULL) { last->next = link; link->prev = last; } else { head = link; /* that means that this is the first node to be on the linked list.*/ current = link; } last = link; current = last; } /* Delete the tail in the redo-undo list after an insert operation was done */ int deleteAllTail(int currentFirstNullFlag) { struct node *ptrToDelete; struct node *ptr; struct node *toBeLast; if (head == NULL) { return currentFirstNullFlag; } if (current == NULL && currentFirstNullFlag == 1) { head = NULL; last = NULL; return currentFirstNullFlag; } if (current == NULL && currentFirstNullFlag == 0) { current = last; currentFirstNullFlag = -1; return currentFirstNullFlag; } ptr = current->next; toBeLast = current; while(ptr != NULL) { ptrToDelete = ptr->next; free(ptr); ptr = ptrToDelete; } last = toBeLast; current = last; return -1; } /* Delete the whole redo-undo list */ void deleteLast() { /*if only one link*/ if(head->next == NULL) { if (head->matrixBeforeAutofill != NULL) { freeMatrix(head->matrixBeforeAutofill, N); head->matrixBeforeAutofill = NULL; } free(head); head = NULL; } else { if (last->prev->next != NULL) { if (last->prev->next->matrixBeforeAutofill != NULL) { freeMatrix(last->prev->next->matrixBeforeAutofill, N); last->prev->next->matrixBeforeAutofill = NULL; } free(last->prev->next); last->prev->next = NULL; } } last = last->prev; }
C
/** * \file ctslab.c * \author wzj * \brief a simple slab just like the nginx * \version * \note * \date: 2012年11月02日星期五23:45:03 * * discript your detail info. */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <Jlog.h> #include "ctslab.h" /** * \brief init the alloced buffer as a slab * \note input a valid buffer! */ ct_slab_head_st *ct_slab_init(char *buffer, unsigned int buffer_size) { if(buffer == NULL || buffer_size <= SYSTEM_PAGE_SIZE ) { dblog("invalid input! the buffer must be valid!"); return NULL; } ct_slab_head_st *phead = NULL; unsigned int tmplen = buffer_size; char *pbuffer = NULL; int i = 0; memset(buffer, 0, sizeof(char)*buffer_size); phead = (ct_slab_head_st *)buffer; pbuffer = buffer + sizeof(*phead); tmplen -= sizeof(*phead); phead->nslots = MAX_SLAB_OFFSET - MIN_SLAB_OFFSET + 1; phead->slots = (ct_slot_head_st*)pbuffer; for( i = 0; i < phead->nslots; i++) { ct_slot_head_st *pslot = phead->slots + sizeof(*pslot)*i; pslot->slab_offset = MIN_SLAB_OFFSET + i; } pbuffer = pbuffer + sizeof(*(phead->slots))*phead->nslots; tmplen -= sizeof(*(phead->slots))*phead->nslots; phead->pages = (ct_page_mgr_st* )pbuffer; phead->npages = tmplen/(sizeof(ct_page_mgr_st) + SYSTEM_PAGE_SIZE); phead->free_page_list = phead->pages; for(i = 0; i < phead->npages - 1; i++) phead->pages[i].next = &phead->pages[i+1]; pbuffer += sizeof(ct_page_mgr_st) * phead->npages; //pbuffer = (char*)(((unsigned int)pbuffer + (1 << SYSTEM_PAGE_OFFSET) - 1) & // ~((1 << SYSTEM_PAGE_OFFSET)-1)); /* do alaign */ pbuffer = MEM_ALAIGN(pbuffer); phead->used_pages = 0; phead->begin = pbuffer; phead->end = buffer + buffer_size; phead->total_size = buffer_size; return phead; } /* int ct_slab_alloc_slab(ct_slab_head_st *phead, uint offset) { ASSERT(phead != NULL && offset > 0, -1); } */ void *ct_slab_alloc(ct_slab_head_st *phead, unsigned int nsize) { ASSERT(phead != NULL, NULL); ct_slot_head_st *pslots = NULL; ct_page_mgr_st *ppagemgr = NULL; unsigned int offset = 1; char *ppage = NULL; char *alloced = NULL; char *mask = NULL; int blockpos = -1; int nblocks = 0; int nbytes = 0; int nbits = 0; int i = 0, j = 0; /* get the offset, the min is 3, alaign to the 8byte */ uint tmpsize = nsize; for(; tmpsize >>= 1; offset++){;} if(offset < MIN_SLAB_OFFSET) offset = MIN_SLAB_OFFSET; if(offset > MAX_SLAB_OFFSET) { dblog("malloc [%d] failed, over rage!", nsize); return NULL; } /* small piece */ if(offset < MID_SLAB_OFFSET) { pslots = &phead->slots[offset - MIN_SLAB_OFFSET]; if(pslots->free_slab_list == NULL) { if(phead->used_pages == phead->npages) return NULL; ppagemgr = &phead->pages[phead->used_pages++]; ppagemgr->prv = pslots; ppagemgr->slab_offset = offset; ppagemgr->next = pslots->free_slab_list; pslots->free_slab_list = ppagemgr; ppage = phead->begin + (ppagemgr - phead->pages)*SYSTEM_PAGE_SIZE; /* 初始化位图*/ mask = ppage; nblocks = 1 << (SYSTEM_PAGE_OFFSET - offset); nbytes = nblocks/8; for(i = 0; i < nbytes/8; i++) mask[i] = BIT_MASK; nbits = nbytes%8; for(j = 0; j < nbits; j++) mask[i] |= (1 << j); dblog("ppage:[%08X] nblocks[%d], mask[%d]", (uint)ppage, nblocks, (uint)mask); } ppagemgr = pslots->free_slab_list; ppage = phead->begin + (ppagemgr - phead->pages)*SYSTEM_PAGE_SIZE; /* 遍历位图 */ nblocks = 1 << (SYSTEM_PAGE_OFFSET - offset); nbytes = (nblocks + sizeof(char)-1)/sizeof(char); /* got 8 bits, reach the upline. */ mask = ppage; dblog("nblocks[%d], nbytes[%d], mask[%08x]", nblocks, nbytes, (uint)mask); for(i = 0; i < nbytes; i++) { if(mask[i] == BIT_MASK) continue; for(j=0; j < sizeof(char); j++) { if(mask[i] & (1 << j)) continue; blockpos = i * sizeof(char) + j; mask[i] |= 1 << j; break; } if(blockpos >= 0) break; } if(i >= nbytes) { dblog("move the slab outof the queue."); pslots->free_slab_list = ppagemgr->next; ppagemgr->next = NULL; } dblog("alloc ppage[%08x] slab[%d] blockpos[%d]", (uint)ppage, offset, blockpos); if(blockpos >= 0) { alloced = ppage + blockpos * (1 << offset); } } /* middle piece */ if(offset == MID_SLAB_OFFSET) { pslots = &phead->slots[offset - MIN_SLAB_OFFSET]; if(pslots->free_slab_list == NULL) { if(phead->used_pages == phead->npages) return NULL; ppagemgr = &phead->pages[phead->used_pages++]; ppagemgr->prv = pslots; ppagemgr->slab_offset = offset; ppagemgr->next = pslots->free_slab_list; ppagemgr->prv = (ct_slot_head_st* )((uint)ppagemgr->prv | SLAB_TYPE_MIDDLE); pslots->free_slab_list = ppagemgr; } ppagemgr = pslots->free_slab_list; ppage = phead->begin + (ppagemgr - phead->pages)*SYSTEM_PAGE_SIZE; for(i = 0; i < SIZEOFBITS(ppagemgr->slab_offset); i++) { if(!(ppagemgr->slab_offset & (1 << i))) { blockpos = i; ppagemgr->slab_offset |= (1 << i); break; } } if(i >= SIZEOFBITS(ppagemgr->slab_offset)) { dblog("alloc middle page failed!"); return NULL; } if(ppagemgr->slab_offset == 0XFFFFFFFF) { pslots->free_slab_list = ppagemgr->next; ppagemgr->next = NULL; } alloced = ppage + blockpos * (1 << offset); } /* large piece */ if(offset > MID_SLAB_OFFSET) { pslots = &phead->slots[offset - MIN_SLAB_OFFSET]; if(pslots->free_slab_list == NULL) { if(phead->used_pages == phead->npages) return NULL; ppagemgr = &phead->pages[phead->used_pages++]; ppagemgr->prv = pslots; ppagemgr->slab_offset = offset; ppagemgr->next = pslots->free_slab_list; ppagemgr->prv = (ct_slot_head_st*)((uint)ppagemgr->prv | SLAB_TYPE_LARGE); pslots->free_slab_list = ppagemgr; } ppagemgr = pslots->free_slab_list; ppage = phead->begin + (ppagemgr - phead->pages)*SYSTEM_PAGE_SIZE; uint offset_mask = ppagemgr->slab_offset >> 16; /* the high store the offset */ for(i = 0; i < SIZEOFBITS(short); i++) { if(!(offset_mask & (1 << i))) { blockpos = i; offset_mask |= (1 << i); ppagemgr->slab_offset |= offset_mask << SIZEOFBITS(short); break; } } if(i >= SIZEOFBITS(short)) { dblog("alloc large type slab failed!"); return NULL; } if(offset_mask == 0xFFFF) { pslots->free_slab_list = ppagemgr->next; ppagemgr->next = NULL; } alloced = ppage + blockpos * (1 << offset); } return alloced; } int ct_slab_free(ct_slab_head_st *phead, char *slab) { ASSERT(phead != NULL && slab != NULL, -1); ct_page_mgr_st *ppagemgr = NULL; unsigned int offset = 0; unsigned int slab_type = 0; int npage = 0; int nslab = 0; npage = (((uint)slab & (~((1 << SYSTEM_PAGE_OFFSET) - 1))) - (uint)phead->begin)/(SYSTEM_PAGE_SIZE); ppagemgr = phead->pages + npage; if(ppagemgr == NULL) { dblog("get curpage failed!"); return -1; } slab_type = (uint)ppagemgr->prv & 0x11; switch(slab_type) { case SLAB_TYPE_SMALL: { char *mask = phead->begin; int i = 0, j = 0; offset = ppagemgr->slab_offset; nslab = ((uint)slab & ((1 << SYSTEM_PAGE_OFFSET)-1))/(1 << offset); i = nslab / 8; j = nslab % 8; mask[i] &= ~(1 << j); /* add to the free list */ ppagemgr->next = ppagemgr->prv->free_slab_list; ppagemgr->prv->free_slab_list = ppagemgr; break; } case SLAB_TYPE_MIDDLE: { ct_slot_head_st *pslots = (ct_slot_head_st*)((uint)ppagemgr->prv & 0x100); offset = MID_SLAB_OFFSET; nslab = ((uint)slab & ((1 << SYSTEM_PAGE_OFFSET)-1))/(1 << offset); ppagemgr->slab_offset &= ~(1 << nslab); ppagemgr->next = ppagemgr->prv->free_slab_list; pslots->free_slab_list = ppagemgr; break; } case SLAB_TYPE_LARGE: { ct_slot_head_st *pslots = (ct_slot_head_st*)((uint)ppagemgr->prv & 0x100); offset = ppagemgr->slab_offset & 0xFFFF; nslab = ((uint)slab & ((1 << SYSTEM_PAGE_OFFSET)-1))/(1 << offset); ppagemgr->slab_offset &= ~((1 << nslab) << 16); ppagemgr->next = ppagemgr->prv->free_slab_list; pslots->free_slab_list = ppagemgr; break; } default: break; } memset(slab, 0, 1<<offset); return 0; } int main(int argc, char *argv[]) { ct_slab_head_st *slab = NULL; char *buffer = malloc(1024 * 1024); char *allocated = NULL; int i = 0; slab = ct_slab_init(buffer, 1024*1024); dblog("phead: [%08x]", (uint)slab); dblog("nslots:[%08x]", (uint)&slab->nslots); dblog("slots: [%08x]", (uint)slab->slots); dblog("pages: [%08x]", (uint)slab->pages); dblog("npages:[%08x]", (uint)&slab->npages); dblog("npages:[%d]", (uint)slab->npages); dblog("begin: [%08x]", (uint)slab->begin); dblog("end: [%08x]", (uint)slab->end); for(i = 0; i < 10; i++) { allocated = ct_slab_alloc(slab, i + 1000); if(allocated == NULL) dblog("alloc failed!"); else dblog("alloc [%08x]", (uint)allocated); // ct_slab_free(slab, allocated); } return 0; }
C
// one zero two zeros c soln for code eval by steven a dunn #include <stdlib.h> #include <stdio.h> #include <string.h> int find_start(char*); int count_zeros(char*, int); int main (int argc, char* const argv[]) { FILE *fp = fopen(argv[1], "r"); if (fp) { char line[1024]; while(fgets(line, sizeof(line), fp)) { char *token; int num_zeros, max_num, num_count, one_idx, zeros; int i; token = strtok(line, " "); num_zeros = atoi(token); token = strtok(NULL, " "); max_num = atoi(token); num_count = 0; for (i = 1; i < max_num + 1; ++i) { unsigned int j, idx; char binary[33]; binary[32] = '\0'; idx = 0; for (j = 1 << 31; j > 0; j = j / 2) { if (i & j) binary[idx] = '1'; else binary[idx] = '0'; ++idx; } one_idx = find_start(binary); zeros = count_zeros(binary, one_idx); if (zeros == num_zeros) ++num_count; } printf("%d\n", num_count); } fclose(fp); } return 0; } int find_start(char* string) { int i; for (i = 0; i < strlen(string); ++i) { if (string[i] == '1') return i; } return -1; } int count_zeros(char* string, int start_idx) { int sum; sum = 0; string += start_idx; while (*string != '\0') { if (*string == '0') ++sum; ++string; } return sum; }