language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> void main() { int i,n,flag=0,pass,temp; int num[50]; printf("no of elements?"); scanf("%d",&n); printf("Enter the elements"); for(i=1;i<=n;i++) { scanf("%d",&num[i]); } for(pass=1;pass<=n-1;pass++) { for(i=1;i<=n-1;i++) { if(num[i]>num[i+1]) { temp=num[i]; num[i]=num[i+1]; num[i+1]=temp; flag=1; } } if(flag=0)break; else flag=0; } printf("\nthe sorted element:\n"); for(i=1;i<=n;i++) { printf("%d\t",num[i]); } }
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include <time.h> #include <stdarg.h> #include "Error.h" #include "../Commons.h" /* Represents error occurence while compiling .as file */ typedef struct { ErrorCode code; /* Error code of the error */ int line_num; /* Line number where the error occured */ const char *asm_name; /* The name of file where the error occured */ const char *line_str; /* The line string which caused the error */ const char *info; /* Additional information about the error */ } Error; static void error_log_filename(char *dest, size_t dest_size); static void error_write(Error *e, FILE *first_stream, ...); static const char *error_msg(ErrorCode code); /* DEPRECATED DUE TO */ void error_print_old(ErrorCode code, int line_num, const char *asm_name, const char *line_str, const char *info) { static char log_filename[MAX_STRING_LEN] = {'\0'}; /* Store the error log file name */ FILE *error_log; /* Error log file stream pointer */ Error e; /* Error struct that contains error information */ e.code = code; e.line_num = line_num; e.asm_name = asm_name; e.line_str = line_str; e.info = info; /* If log_filename does not exists, create new log filename */ if(!(*log_filename)) { error_log_filename(log_filename, MAX_STRING_LEN); } /* Open log file and print error to that file */ if(!(error_log = fopen(log_filename, "a"))) { exit(EXIT_FAILURE); } error_write(&e, stderr, error_log, NULL); fclose(error_log); } /* Creates new error struct and prints it to errors files streams. */ void error_print(ErrorCode code, int line_num, const char *asm_name, const char *line_str, const char *info) { Error e; /* Error struct that contains error information */ e.code = code; e.line_num = line_num; e.asm_name = asm_name; e.line_str = line_str; e.info = info; error_write(&e, stderr, NULL); } /* Generate error log file by the current date and time */ void error_log_filename(char *dest, size_t dest_size) { time_t datetime; /* If could not get the current time use default error log filename */ if(time(&datetime) == -1) { strcpy(dest, "errors.log"); } else { strftime(dest, dest_size, "errors_%Y%m%d%H%M%S.log", localtime(&datetime));\ } } /* Print error message to stream based on the data exists in e */ void error_write(Error *e, FILE *first_stream, ...) { const char *type; FILE *stream; va_list ap; va_start(ap, first_stream); /* Find if the ErrorCode is warning or error */ if(e->code == BUF_LEN_EXCEEDED) { type = "fatal error"; } else if(IS_WRN(e->code)) { type = "warning"; } else { type = "error"; } /* Print to all streams found in unnamed argument */ for(stream = first_stream; stream; stream = va_arg(ap, FILE *)) { /* Print error message */ fprintf(stream, "%s:%d: \n\t%s: %s (error code: %d)", e->asm_name, e->line_num, type, error_msg(e->code), e->code); /* If any addition info exists, print it */ if(e->info) { fprintf(stream, "\n\tadditional information: \"%s\"", e->info); } /* Print the line which created the error */ if(e->code != BUF_LEN_EXCEEDED) { fprintf(stream, "\n\tline: \"%s\"", e->line_str); } fprintf(stream, "\n\n"); } va_end(ap); } /* Get the error message string by ErrorCode */ const char *error_msg(ErrorCode code) { switch (code) { case NOT_WORD_NUM: return "Expected integer number"; case RESERVED_WORD: return "Reserved word"; case UNDEFINED_COMMAND: return "Undefined command"; case AFTER_TEXT: return "Extraneous text after end of statment"; case MISSING_PARAM: return "Missing parameter"; case ILLEGAL_COMMA: return "Illegal comma"; case MISSING_COMMA: return "Missing comma"; case CONSECUTIVE_COMMA: return "Consecutive commas"; case INVALID_TAG: return "Invalid tag name"; case EMPTY_VAL: return "Empty value"; case ARGS_EXPECTED: return "Arguments expected"; case BUF_LEN_EXCEEDED: return "Line exceeded max length"; case TOK_LEN_EXCEEDED: return "Token exceeded max length"; case FILE_ERROR: return "Error while trying to open a file"; case INVALID_CL: return "Invalid command line arguments"; case INVALID_ADDRESS: return "Invalid address"; case INVALID_STRING: return "Invalid string"; case INVALID_COMB_LABEL_MACRO: return "Macro statement cannot be labaled"; case INVALID_MACRO_STATEMENT: return "Invalid macro statement"; case SYMBOL_ALREADY_EXIST: return "Symbol already declared"; case TOO_MANY_OPERANDS: return "Too many operands"; case NOT_DECLARED: return "Not declared"; case MISSING_ARRAY_BRACE: return "Missing array brace"; case NOT_ARRAY_INDEX: return "Invalid array index"; case ENTRY_ALREADY_EXISTS: return "Entry already declared"; case INVALID_ARGUMENT: return "Expected different argument type"; case UNUSED_SYMBOL: return "Symbol declared but never used"; case OUT_OF_RANGE_REGISTER: return "Unknown register"; case DATA_OVERFLOW: return "Data overflow"; case ENT_EXT_TAG: return "Invalid tag and reference declaration combination"; default: return NULL; } }
C
/*程序填空,不要改变与输入输出有关的语句。 输入一个正整数repeat (0<repeat<10),做repeat次下列运算: 给定平面任意两点坐标 (x1, y1) 和 (x2, y2),求这两点之间的距离(保留2位小数)。 要求定义和调用函数 dist(x1, y1, x2, y2)计算两点间的距离,函数形参x1、y1、x2和y2的类型都是double,函数类型是double。 输入输出示例:括号内是说明 输入 1 (repeat=1) 10 10 (x1=10, y1=10) 200 100 (x2=200, y2=100) 输出 Distance = 210.24*/ #include <stdio.h> #include <math.h> double dist(double x1, double y1, double x2, double y2); int main(void) { int repeat, ri; double distance, x1, y1, x2, y2; scanf("%d", &repeat); for(ri = 1; ri <= repeat; ri++) { scanf("%lf%lf%lf%lf", &x1, &y1, &x2, &y2); distance = dist(x1,y1,x2,y2); printf("Distance = %.2f\n", distance); } } double dist(double x1, double y1, double x2, double y2) { double distance,temp; if ( x1 < x2) { temp = x1; x1 = x2; x2 = temp; } if (y1 < y2) { temp = y1; y1 = y2; y2 = temp; } distance = sqrt(pow(x1-x2,2)+pow(y1-y2,2)); return distance; }
C
#include<stdio.h> int res = -1; long int res1 = -1; float res2; int main() { int a, b; printf("enter values of a,b\n"); scanf_s("%d %d", &a, &b); res = add(a, b); printf("addition result is %d\n", res); res = sub(a, b); printf("subtraction result is %d\n", res); res1 = mul(a, b); printf("multiplication result is %ld\n", res1); res2 = div(a, b); printf("division result is %f\n", res2); //scanf_s("%d", &a); system("pause"); return 0; }
C
#include <stdlib.h> #include <CUnit/CUnit.h> #include "main.h" #include "test.h" char **targv; char **arglim; char *progName; unsigned int verbose; void test_myinput_000(void) { char *temp[] = {"-d", "parse.y"}; char buf[512]; int max = 512; int ret; targv = temp; arglim = temp+2; ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 3); CU_ASSERT_NSTRING_EQUAL(buf, "-d ", 3); ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 8); CU_ASSERT_NSTRING_EQUAL(buf, "parse.y ", 8); ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 0); } void test_myinput_001(void) { char *temp[] = {"pa", "-"}; char buf[1]; int max = 1; int ret; targv = temp; arglim = temp+2; ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 0); } void test_myinput_002(void) { char *temp[] = {"pa", "-"}; char buf[2]; int max = 2; int ret; targv = temp; arglim = temp+2; ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 1); CU_ASSERT_NSTRING_EQUAL(buf, "p", 1); ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 2); CU_ASSERT_NSTRING_EQUAL(buf, "a ", 2); ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 2); CU_ASSERT_NSTRING_EQUAL(buf, "- ", 2); ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 0); } void test_myinput_003(void){ char *temp[] = {"parse.y"}; char buf[0]; int max = 0; int ret; targv = temp; arglim = temp+2; ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 0); } void test_myinput_004(void) { char *temp[] = {"", "parse.y"}; char buf[512]; int max = 512; int ret; targv = temp; arglim = temp+2; ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 1); CU_ASSERT_NSTRING_EQUAL(buf, " ", 1); ret = myinput(buf, max); CU_ASSERT_EQUAL(ret, 8); CU_ASSERT_NSTRING_EQUAL(buf, "parse.y ", 8); }
C
#include <stdio.h> int main() { printf("The datatype int is %ld bytes\n",sizeof(int)); printf("The datatype float is %ld bytes\n",sizeof(int)); printf("The datatype double is %ld bytes\n",sizeof(double)); printf("The datatype char is %ld bytes\n",sizeof(char)); }
C
//// //// Created by shuncs on 19-2-28. //// // //#include <stdio.h> // //int main(void) //{ // //每一个元素指向一个常量字符串 // //实质上是一个指针数组 // char *ch[3] = {"123", "ssdddd", "adsdfdfsdsd"}; // //字符串数组直接指向字符常量区的内容 // for(int i=0;i<3;i++) // { // printf("%s\n", ch[i]); // } // // //常量字符串指针可以更改指向,但是不能修改字符串的内容 // ch[1] = "zhushuai"; // // for(int i=0;i<3;i++) // { // printf("%s\n", ch[i]); // } // printf("=================\n"); // // //二维字符数组 // char str[2][4] = {"zhu", "123"}; // //将字符常量去的常量字符串复制到栈区 // //后续通过数组操作的是栈区的内容 // for(int i=0;i<2;i++) // { // printf("%s\n", str[i]); // } // // // return 0; //}
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <string.h> int main() { int } /* //7.12 6 int main() { int i=0; char ch; while((ch=getchar())!='#') { if(ch=='e') { i++; } if(ch=='i') { i++; } } printf("%d",i); } */ /* //7.12 4 int main() { int i=0; char ch; while((ch=getchar())!='#') { switch(ch) { case '.': putchar(ch-13); printf("\n"); i++; break; case '!': putchar(ch); putchar(ch); printf("\n"); i++; break; } } printf("%d",i); } */ /* //7.12 4 int main() { char ch; int i=0; while((ch=getchar())!='#') { if(ch=='.') { ch-=13; //'.'滻! putchar(ch); //ӡ printf("\n");//ӡ fflush(stdin);//ջ i++;//滻 } else if(ch=='!') { putchar(ch);//ַ'!'ӡ2̾ putchar(ch); printf("\n"); fflush(stdin); i++;//滻 } } printf("%d",i);//¼ӡ } */ /* //7.12 3 int main() { int num; int i=0; int j=0; double sum1; double sum2; while(scanf("%d",&num)==1) { if(num==0) { break; } if(num%2==0) { sum1+=num; i++; } else { sum2+=num; j++; } } printf("żƽΪ%.2lf\tƽΪ%.2lf\n",sum1/i,sum2/j); } */ /* //7.12 2 int main() { int i; char ch; while((ch=getchar())!='#') { if(ch=='\n') { continue; } printf("%c:%d ",ch,ch); i++; if ((0 == (i % 8)) && (i > 8)) printf("\n"); } } */ /* //7.12 1 int main() { int i=0; int j=0; int k=0; char ch; while((ch=getchar())!='#') { if(ch==' ') { i++; } else if(ch=='\n') { j++; } else { k++; } } printf("%dո%dس%d\n",i,j,k); } */ /* //7.7 int main() { char ch; printf("Give me aletter of the alphabet, and I will gove "); printf("an animal name\nbeginning with that letter.\n"); printf("Please type in a letter; type # to end my act.\n"); while((ch=getchar())!='#') { if('\n'==ch) { continue; } if(islower(ch)) switch(ch) { case 'a': printf("argali,a wild sheep of Asia\n"); break; case 'b': printf("babirusa, a wild pig of Malay\n"); break; case 'c': printf("coati, racoonlike mammal\n"); break; case 'd': printf("desman, aquatic, molelike critter\n"); break; case 'e': printf("echidna,the spiny anteater\n"); break; case 'f': printf("fisher, brownish marten\n"); break; default: printf("That's a stumper.\n"); } else { printf("I recoqnize only lowercase letters.\n"); } while(getchar()!='\n')//ջ! { continue; } printf("Please type another letter or a #.\n"); } printf("Bye!\n"); return 0; } */ /* //7.10 int main() { float length,width; printf("Enter the length of the rectangle:\n"); while((scanf("%f",&length)==1)) { printf("length=%0.2f:\n",length); printf("Enter its width:\n"); if((scanf("%f",&width))!=1) { break; } printf("Width=%0.2f:\n",width); printf("Area=%0.2f:\n",length*width); printf("Enter the length of the rectangle:\n"); } } */ /* //7.9 int main() { const float MIN=0.0f; const float MAX=100.0f; float score; float total=0.0f; int n=0; float min=MAX; float max=MIN; printf("enter the first score (q to quit): "); while(scanf("%f",&score)==1) { if(score<MIN||score>MAX) { printf("%0.1f is an invalid value. Try again:",score); continue; } printf("Accepting %0.1f:\n",score); min=(score<min)?score:min; max=(score>max)?score:max; total+=score; n++; printf("enter next score (q to quit): "); } if(n>0) { printf("Average of %d score is %0.1f.\n",n,total/n); printf("Low=%0.1f,high=%0.1f\n",min,max); } else { printf("No valid score were entered.\n"); } } */
C
#include <linux/init.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/workqueue.h> MODULE_AUTHOR("Mike Feng"); /*测试数据结构*/ struct my_data { struct work_struct my_work; int value; }; struct workqueue_struct *wq=NULL; struct work_struct work_queue; /*初始化我们的测试数据*/ struct my_data* init_data(struct my_data *md) { md=(struct my_data*)kmalloc(sizeof(struct my_data),GFP_KERNEL); md->value=1; md->my_work=work_queue; return md; } /*工作队列函数*/ static void work_func(struct work_struct *work) { struct my_data *md=container_of(work,struct my_data,my_work); printk("<2>""Thevalue of my data is:%d\n",md->value); } static __init int work_init(void) { struct my_data *md=NULL; struct my_data *md2=NULL; md2=init_data(md2); md=init_data(md); md2->value=20; md->value=10; /*第一种方式:使用统默认的workqueue队列——keventd_wq,直接调度*/ INIT_WORK(&md->my_work,work_func); schedule_work(&md->my_work); /*第二种方式:创建自己的工作队列,加入工作到工作队列(加入内核就对其调度执行)*/ wq=create_workqueue("test"); INIT_WORK(&md2->my_work,work_func); queue_work(wq,&md2->my_work); return 0; } static void work_exit(void) { /*工作队列销毁*/ //flush_workqueue(wq); //destroy_workqueue(wq); printk(KERN_ALERT "demo_exit.\n"); } module_init(work_init); module_exit(work_exit);
C
/** @file log.h */ #ifndef __LOG_H_ #define __LOG_H_ typedef struct _log_t { struct _log_t *prev; struct _log_t *next; char *item; } log_t; void log_init(log_t *l); void log_destroy(log_t* l); void log_push(log_t* l, const char *item); char *log_search(log_t* l, const char *prefix); #endif
C
#include<stdio.h> #include<math.h> /* creating a function so that in the future a function with different arguments but same signature can be used */ double function(double x){ return pow(x,10)-1; } /* the method takes a standard in_out function which has both input as well as output to be double*/ double bisection(double (*p)(double),double lower,double upper){ for(int i=0;i<10;i++){ double mid = (upper+lower)/2.0; printf("f(x) - %f x - %f\n",p(mid),mid); if((p(mid)*p(lower))<0){ upper =mid; } else{ lower = mid; } } } double regula_falsi(double (*p)(double),double lower,double upper){ } int main(int argc, char const *argv[]) { double t = bisection(function,0,1.3); printf("%f\n", t); return 0; }
C
/* This program finds the minimum number in an array */ #include <stdio.h> #define SIZE 8 int Minimum(int A[], int n) { int i; int min = A[0]; // let the 1st element be the initial min // inspect the remaining array elements for (i = 0; i < n; i++) if (A[i] < min) min = A[i]; return min; } int main() { int nums[SIZE] = {10, 23, 11, 63, -55, 99, -20, -88}; printf("Minimum is %d", Minimum(nums, SIZE)); return 0; }
C
int main() { int x = 1; int* y = &x; int* z = &*y; assert(*z == 1); *&x = 3; assert(*z == 3); }
C
#include "queue.h" #include <stdio.h> #include <stdlib.h> #include <assert.h> int main(void) { queueHead* queue; int i1 = 1; int i2 = 2; int i3 = 3; int i4 = 4; /* * Test 1 */ /* Create queue */ assert(NULL != (queue = queueCreate())); /* Fill the queue */ assert(1 == (queueAdd(queue, &i1))); /* Insert 1 */ assert(1 == (queueAdd(queue, &i2))); /* Insert 2 */ assert(1 == (queueAdd(queue, &i3))); /* Insert 3 */ assert(1 == (queueAdd(queue, &i4))); /* Insert 4 */ /* Check the queue */ assert(1 == (*(int*)queueFirst(queue))); /* Check 1 */ assert(1 == (*(int*)queueRemove(queue))); /* Remove 1 */ assert(2 == (*(int*)queueFirst(queue))); /* Check 2 */ assert(2 == (*(int*)queueRemove(queue))); /* Remove 2 */ assert(3 == (*(int*)queueFirst(queue))); /* Check 3 */ assert(3 == (*(int*)queueRemove(queue))); /* Remove 3 */ assert(4 == (*(int*)queueFirst(queue))); /* Check 4 */ assert(4 == (*(int*)queueRemove(queue))); /* Remove 4 */ assert(NULL == (queueFirst(queue))); /* Check empty */ assert(NULL == (queueRemove(queue))); /* Queue is empty */ /* Clear the queue */ queueFree(queue); printf("Queue: Test1 success!\n"); /* * Test 2 */ /* Create queue */ assert(NULL != (queue = queueCreate())); /* Fill the queue */ assert(1 == (queueAdd(queue, &i1))); /* Insert 1 */ assert(1 == (*(int*)queueRemove(queue))); /* Remove 1 */ assert(1 == (queueAdd(queue, &i1))); /* Insert 1 */ assert(1 == (queueAdd(queue, &i2))); /* Insert 2 */ assert(1 == (*(int*)queueRemove(queue))); /* Remove 1 */ assert(2 == (*(int*)queueRemove(queue))); /* Remove 2 */ assert(1 == (queueAdd(queue, &i1))); /* Insert 1 */ assert(1 == (*(int*)queueFirst(queue))); /* Check 1 */ assert(1 == (queueAdd(queue, &i2))); /* Insert 2 */ assert(1 == (*(int*)queueRemove(queue))); /* Remove 1 */ assert(1 == (queueAdd(queue, &i3))); /* Insert 3 */ assert(2 == (*(int*)queueRemove(queue))); /* Remove 2 */ assert(1 == (queueAdd(queue, &i4))); /* Insert 4 */ assert(3 == (*(int*)queueRemove(queue))); /* Remove 3 */ assert(4 == (*(int*)queueRemove(queue))); /* Remove 4 */ /* Fill the queue */ assert(1 == (queueAdd(queue, &i1))); /* Insert 1 */ assert(1 == (queueAdd(queue, &i2))); /* Insert 2 */ assert(1 == (queueAdd(queue, &i3))); /* Insert 3 */ assert(1 == (queueAdd(queue, &i4))); /* Insert 4 */ /* Check the queue */ assert(1 == (*(int*)queueRemove(queue))); /* Remove 1 */ assert(2 == (*(int*)queueFirst(queue))); /* Check 2 */ assert(2 == (*(int*)queueRemove(queue))); /* Remove 2 */ assert(3 == (*(int*)queueRemove(queue))); /* Remove 3 */ assert(4 == (*(int*)queueRemove(queue))); /* Remove 4 */ assert(NULL == (queueFirst(queue))); /* Check empty */ assert(NULL == (queueRemove(queue))); /* Queue is empty */ /* Clear the queue */ queueFree(queue); printf("Queue: Test2 success!\n"); return 0; }
C
#include <list.h> linklist* CreateListInHead() { linklist *L = NULL; linklist *tmp = NULL; int data = 0; int i = 0; int NodeCount = 0; if(NULL != L) { free(L); } printf("Please input the count that you want:\n"); scanf("%d",&NodeCount); if(NodeCount <= 0) { printf("Create fail!\n"); return L; } printf("Please input the last Data:\n"); scanf("%d",&data); L = (linklist *)malloc(sizeof(linklist)); if(NULL != L) { memset(L,0,sizeof(linklist)); } else { printf("Create List malloc fail!\n"); return (L = NULL); } L->data = data; L->next = NULL; //head = L; while(-- NodeCount) { printf("input the data %d:\n",NodeCount); data = 0; scanf("%d",&data); tmp = (linklist *)malloc(sizeof(linklist)); if(NULL != tmp) { memset(tmp,0,sizeof(linklist)); } else { printf("Create List malloc fail!\n"); return (tmp = NULL); } tmp->data = data; tmp->next = L; L = tmp; } return L; } void display(linklist * head) { linklist * p = head; while( p!= NULL) { printf("%d ",p->data); p = p->next; } printf("\n"); } void destory( linklist *head) { while(head != NULL) { linklist * p = head; head = head->next; free(p); } }
C
#include "keys.h" #include <GL/freeglut.h> void setSpecialKeyState(int key, bool state){ //Arrow keys if ((key >= GLUT_KEY_LEFT) && (key <= GLUT_KEY_DOWN)){ int myKey = (key-GLUT_KEY_LEFT) + KEY_A_LEFT; //if the key is an arrow key then set the state in the arrow key array keyData.arrowKeysPressed[myKey] = state; } //Function keys if ((key >= GLUT_KEY_F1) && (key <= GLUT_KEY_F12)){ int myKey = (key-GLUT_KEY_F1) + KEY_F_1; //if the key is an F key then set the state in the FKeys array keyData.FKeysPressed[myKey] = state; } } //set the correct state void onGLUTSpecialDown(int key){ setSpecialKeyState(key, true); } void onGLUTSpecialUp(int key){ setSpecialKeyState(key, false); } //these ones are easy void onGLUTKeyDown(unsigned char key){ keyData.keyPressed[key] = true; } void onGLUTKeyUp(unsigned char key){ keyData.keyPressed[key] = false; } void initKeyPressed(){ int i; for (i = 0; i<= 3; i++){ //initialise the first four keys for each array keyData.keyPressed[i] = false; keyData.FKeysPressed[i] = false; keyData.arrowKeysPressed[i] = false; } for (i = 4; i<= 11; i++){ //initialise the next 8 keys for the larger arrays keyData.keyPressed[i] = false; keyData.FKeysPressed[i] = false; } for (i = 12; i<= 255; i++){ //init the rest for the really big one keyData.keyPressed[i] = false; } }
C
#include "KeyBoard.h" void init_KeyBoard() { GPIO_InitTypeDef GPIO_InitStructure; /*************************键盘初始化*****************************/ RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOE | RCC_AHB1Periph_GPIOD, ENABLE); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_OUT; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOE, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0 | GPIO_Pin_1; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOE, &GPIO_InitStructure); GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOD, &GPIO_InitStructure); } /*****************************读取键盘返回button值*********************************************/ u8 Keyboard_Scan() { u8 button = 255; //设定一个初值 /****************************拉低KEY5*****************************************/ GPIO_ResetBits(GPIOE, GPIO_Pin_2); GPIO_SetBits(GPIOE, GPIO_Pin_3 | GPIO_Pin_4 | GPIO_Pin_5); if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_1) == 0) { button = 15; } if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_0) == 0) { button = 14; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_6) == 0) { button = 13; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_3) == 0) { button = 12; } /****************************拉低KEY6*****************************************/ GPIO_ResetBits(GPIOE, GPIO_Pin_3); GPIO_SetBits(GPIOE, GPIO_Pin_2 | GPIO_Pin_4 | GPIO_Pin_5); if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_1) == 0) { button = 11; } if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_0) == 0) { button = 10; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_6) == 0) { button = 9; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_3) == 0) { button = 8; } /****************************拉低KEY7*****************************************/ GPIO_ResetBits(GPIOE, GPIO_Pin_4); GPIO_SetBits(GPIOE, GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_5); if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_1) == 0) { button = 7; } if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_0) == 0) { button = 6; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_6) == 0) { button = 5; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_3) == 0) { button = 4; } /****************************拉低KEY8*****************************************/ GPIO_ResetBits(GPIOE, GPIO_Pin_5); GPIO_SetBits(GPIOE, GPIO_Pin_2 | GPIO_Pin_3 | GPIO_Pin_4); if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_1) == 0) { button = 3; } if (GPIO_ReadInputDataBit(GPIOE, GPIO_Pin_0) == 0) { button = 2; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_6) == 0) { button = 1; } if (GPIO_ReadInputDataBit(GPIOD, GPIO_Pin_3) == 0) { button = 0; } return button; } /*******************启动滴答计时器**********************************/ void Init_systick() { SysTick->LOAD |= 0x00004650;//18000,相当于2ms定时 SysTick->CTRL &= 0xfffffffb;//systick定时器配置时钟源 HCLK/8 SysTick->CTRL |= 0x00000003;//启动滴答计时器,(以产生SysTick中断的方式) } /************************************中断处理函数******************************************************/ void SysTick_Handler(void) { keyvalue_tmp = Keyboard_Scan();//接收扫描得到的键值 /*******************************键盘消抖**********************************************************/ if (Counter==0) { keyvalue = keyvalue_tmp; } else { if (keyvalue == keyvalue_tmp) { ++Counter; } else { Counter = 0; } } if (Counter==10) { KeyValue = keyvalue; } } /* 返回值为255时表示未读取到键盘输入*/
C
#include <stdio.h> #include <assert.h> #include <math.h> #include <stdlib.h> #include <stdbool.h> #include <gsl/gsl_matrix.h> #include <gsl/gsl_vector.h> #include <gsl/gsl_blas.h> #define RND (double)rand()/RAND_MAX #define FMT "%7.3f" //format of print "7 width, 3 digits after comma" // inspired by Dmitri Fedorovs print implementation void printm(gsl_matrix *A){ // iterating over all rows and columns for(int i=0;i<A->size1;i++){ for(int j=0;j<A->size2;j++) { printf(FMT,gsl_matrix_get(A,i,j)); } printf("\n");} } void printv(gsl_vector *A){ for(int i=0;i<A->size;i++){ printf(FMT,gsl_vector_get(A,i)); printf("\n"); } } void qr_gs_decomp(gsl_matrix* A, gsl_matrix* R) { int m = A->size2; int n = A->size1; gsl_vector_view a_i; gsl_vector_view a_j; int status; double R_ij, R_ii; for(int i=0; i<m; i++){ a_i= gsl_matrix_column(A, i); R_ii=gsl_blas_dnrm2(&a_i.vector); gsl_matrix_set(R, i, i, R_ii); gsl_vector_scale(&a_i.vector, 1.0/R_ii); for(int j=i+1; j<m; j++){ a_j = gsl_matrix_column(A, j); gsl_blas_ddot(&a_i.vector, &a_j.vector, &R_ij); gsl_matrix_set(R, i, j, R_ij); gsl_matrix_set(R,j,i,0); gsl_blas_daxpy(-R_ij,&a_i.vector,&a_j.vector); } } } void qr_gs_solve(gsl_matrix *Q, gsl_matrix* R, \ gsl_vector *b,gsl_vector *x){ //gsl_blas_dgemv(CblasNoTrans, 1.0, Q, b, 0.0, x); gsl_blas_dgemv(CblasTrans,1.0,Q,b,0.0,x); /* backsubstitution from Dmitri Fedorovs following (2.4) first time skipping the first for loop for starting point. then iterating down through yi each time first getting ci then subtracting the sum of Uik yik and dividing by Uii. */ for(int i=x->size-1; i>=0; i--){ double s = gsl_vector_get(x,i); for(int k=i+1; k<x->size; k++){ s -= gsl_matrix_get(R,i,k)*gsl_vector_get(x,k); } gsl_vector_set(x,i,s/gsl_matrix_get(R,i,i)); } } void qr_gs_inverse(const gsl_matrix* Q, const gsl_matrix* R, gsl_matrix* B){ int n = Q->size1; gsl_vector* x = gsl_vector_alloc(n); gsl_vector* e = gsl_vector_alloc(n); for(int i=0; i<n; i++) { gsl_vector_set(e, i, 1.0); qr_gs_solve(Q,R,e,x); gsl_matrix_set_col(B, i, x); gsl_vector_set(e, i, 0.0); } gsl_vector_free(x); gsl_vector_free(e); } void qr_gs_decomp_giddens(gsl_matrix* A, gsl_matrix* R) { int m = A->size2; int n = A->size1; gsl_vector_view a_i; gsl_vector_view a_j; int status; double R_ij, R_ii; for(int i=0; i<m; i++){ a_i= gsl_matrix_column(A, i); R_ii=gsl_blas_dnrm2(&a_i.vector); gsl_matrix_set(R, i, i, R_ii); gsl_vector_scale(&a_i.vector, 1.0/R_ii); for(int j=i+1; j<m; j++){ a_j = gsl_matrix_column(A, j); gsl_blas_ddot(&a_i.vector, &a_j.vector, &R_ij); gsl_matrix_set(R, i, j, R_ij); gsl_matrix_set(R,j,i,0); gsl_blas_daxpy(-R_ij,&a_i.vector,&a_j.vector); } } } /* taken from Dmitri Fedorovs implementation. */ void givens_qr(gsl_matrix* A){ /*A<-Q,R*/ // Iterating through the bottom part of matrix A first columns then rows for(int q=0;q<A->size2;q++)for(int p=q+1;p<A->size1;p++){ // Finding out the angle that will zero out xq double theta=atan2(gsl_matrix_get(A,p,q),gsl_matrix_get(A,q,q)); // iterating over above diagonal part of A for(int k=q;k<A->size2;k++){ // getting the current value of xq, xp double xq=gsl_matrix_get(A,q,k),xp=gsl_matrix_get(A,p,k); // changing xq, xp according to the transformation and saving theta at A_pq gsl_matrix_set(A,q,k,xq*cos(theta)+xp*sin(theta)); gsl_matrix_set(A,p,k,-xq*sin(theta)+xp*cos(theta));} gsl_matrix_set(A,p,q,theta);}} // successively applying the givens transformation by using the found theta angles void givens_qr_QTvec(gsl_matrix* QR,gsl_vector *v){/*v<-QˆTv*/ // iterating columns of recently found QR for(int q=0;q<QR->size2;q++)for(int p=q+1;p<QR->size1;p++){ // saving the found theta value double theta=gsl_matrix_get(QR,p,q); //changing the appropriate entrance of v according to the giddens transformation double vq=gsl_vector_get(v,q),vp=gsl_vector_get(v,p); gsl_vector_set(v,q,vq*cos(theta)+vp*sin(theta)); gsl_vector_set(v,p,-vq*sin(theta)+vp*cos(theta));}} void givens_qr_solve(gsl_matrix* QR,gsl_vector* b){ givens_qr_QTvec(QR,b); /* backsubstitution from Dmitri Fedorovs following (2.4) first time skipping the first for loop for starting point. then iterating down through yi each time first getting ci then subtracting the sum of Uik yik and dividing by Uii. */ for(int i=b->size-1; i>=0; i--){ double s = gsl_vector_get(b,i); for(int k=i+1; k<b->size; k++){ s -= gsl_matrix_get(QR,i,k)*gsl_vector_get(b,k); } gsl_vector_set(b,i,s/gsl_matrix_get(QR,i,i)); } } /* Also taken from Dmitri Fedorov. Basically using the same logic as my own Gram Schmidt implementation except now the system of equations is solved using givens */ void givens_qr_inverse(gsl_matrix* QR,gsl_matrix* B){ gsl_matrix_set_identity(B); for(int i=0;i<QR->size2;i++){ gsl_vector_view v=gsl_matrix_column(B,i); givens_qr_solve(QR,&v.vector);}} int main() { const int n = 5; const int m = 4; gsl_matrix* A = gsl_matrix_alloc(n, m); gsl_matrix* A_clone = gsl_matrix_alloc(n, m); gsl_matrix* R = gsl_matrix_alloc(m, m); for(int i=0; i<n; i++){ for(int j=0; j<m; j++){ gsl_matrix_set(A, i, j, RND); } } gsl_matrix_memcpy(A_clone, A); qr_gs_decomp(A, R); printf("This is A:\n"); printm(A_clone); printf("This is Q:\n"); printm(A); printf("This is R:\n"); printm(R); printf("Checking that R is upper triangular\n"); printf("By checking wether left-down is zero \n"); double R_ij; bool status=true; for(int i=1; i<m; i++){ for(int j=0; j<i; j++){ R_ij = gsl_matrix_get(R, i, j); if(R_ij!=0) status=false; } } printf(status ? "True\n": "False\n"); printf("checking Q^TQ=I by using gsl_BLAS:\n:"); gsl_matrix* A_T = gsl_matrix_alloc(m,n); gsl_matrix_transpose_memcpy(A_T, A); gsl_matrix* C = gsl_matrix_alloc(m, m); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A_T, A, 0.0, C); gsl_matrix* I = gsl_matrix_alloc(m, m); gsl_matrix_set_identity(I); printf("This is Q^TQ:\n"); printm(C); gsl_matrix* leftside = gsl_matrix_alloc(n, m); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A, R, 0.0, leftside); printf("checking QR=A by using gsl_BLAS:\n:"); printf("This is QR:\n"); printm(leftside); printf("2. new matrix B:\n"); int n_new = 4; gsl_matrix* B = gsl_matrix_alloc(n_new, n_new); gsl_matrix* B_clone = gsl_matrix_alloc(n_new, n_new); gsl_matrix* R2 = gsl_matrix_alloc(n_new, n_new); for(int i=0; i<n_new; i++){ for(int j=0; j<n_new; j++){ double a = RND; gsl_matrix_set(B, i, j, a); gsl_matrix_set(B_clone, i, j, a); } } qr_gs_decomp(B, R2); printm(B_clone); printf("This is Q:\n"); printm(B); printf("This is R:\n"); printm(R2); gsl_vector* x = gsl_vector_alloc(n_new); gsl_vector* b = gsl_vector_alloc(n_new); gsl_vector* b_leftside = gsl_vector_alloc(n_new); printf("The vector b is:\n"); for(int j=0; j<n_new; j++){ gsl_vector_set(b, j, RND); } printv(b); qr_gs_solve(B, R2, b, x); printf("This is the solution x:\n"); printv(x); gsl_blas_dgemv(CblasNoTrans, 1.0, B_clone, x, 0.0, b_leftside); printf("The vector Ax is:\n"); printv(b_leftside); // part two printf("We'll use the same matrix for the inverse\n"); printf("so A^-1:\n"); gsl_matrix* D = gsl_matrix_alloc(n_new, n_new); gsl_matrix* D_inverse = gsl_matrix_alloc(n_new, n_new); gsl_matrix* D_test = gsl_matrix_alloc(n_new, n_new); gsl_matrix_memcpy(D, B_clone); // remember B=Q, R2 is R qr_gs_inverse(B, R2, D_inverse); printm(D_inverse); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, D, D_inverse, 0.0, D_test); printf("AA^-1:\n"); printm(D_test); //part three gsl_matrix* A_g = gsl_matrix_alloc(n_new, n_new); gsl_matrix_memcpy(A_g, B_clone); gsl_matrix* A_g_clone= gsl_matrix_alloc(n_new, n_new); gsl_matrix_memcpy(A_g_clone, B_clone); givens_qr(A_g); printf("3. givens stuff\n"); printf("This is A_g:\n"); printm(A_g_clone); printf("This is QR:\n"); printm(A_g); printf("This is a new b:\n"); gsl_vector* b_g = gsl_vector_alloc(n_new); gsl_vector* b_g_clone = gsl_vector_alloc(n_new); gsl_vector* A_gx = gsl_vector_alloc(n_new); for(int i=0; i<n_new; i++) { double a = RND; gsl_vector_set(b_g, i,a); gsl_vector_set(b_g_clone, i,a); } printv(b_g); givens_qr_solve(A_g, b_g); printf("this is the solution Ax=b using givens:\n"); printv(b_g); printf("checking that this is correct by Ax:\n"); gsl_blas_dgemv(CblasNoTrans, 1.0, A_g_clone, b_g, 0.0, A_gx); printv(A_gx); // part two printf("We'll use the same matrix for the inverse\n"); printf("so A_G^-1:\n"); gsl_matrix* D_g = gsl_matrix_alloc(n_new, n_new); gsl_matrix* D_g_test = gsl_matrix_alloc(n_new, n_new); // remember B=Q, R2 is R givens_qr_inverse(A_g,D_g); printm(D_g); gsl_blas_dgemm(CblasNoTrans, CblasNoTrans, 1.0, A_g_clone, D_g, 0.0, D_g_test); printf("AA^-1:\n"); printm(D_g_test); gsl_matrix_free(A); gsl_matrix_free(R); gsl_matrix_free(A_clone); gsl_matrix_free(B); gsl_matrix_free(R2); gsl_matrix_free(B_clone); gsl_matrix_free(D); gsl_matrix_free(D_inverse); gsl_matrix_free(D_test); gsl_matrix_free(A_g); gsl_matrix_free(A_g_clone); gsl_matrix_free(D_g); gsl_matrix_free(D_g_test); gsl_matrix_free(A_T); gsl_matrix_free(C); gsl_matrix_free(I); gsl_matrix_free(leftside); gsl_vector_free(x); gsl_vector_free(b); gsl_vector_free(b_leftside); gsl_vector_free(b_g); gsl_vector_free(b_g_clone); gsl_vector_free(A_gx); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #define ERROR_FILE_OPEN -3 int main(void) { FILE *file; char c; file = fopen("x", "w+t"); if (file == NULL) { printf("ERROR CREATING/OPENING\n"); exit(ERROR_FILE_OPEN); } do { c = getchar(); fputc(c, file); fputc(c, stdout); } while (c != 27); fclose(file); return (0); }
C
#include "patchMatch.h" int* initialisation(int cols_s, int rows_s, int cols_t, int rows_t) { int* nnf = malloc(sizeof(int) * cols_t * rows_t); srand(time(NULL)); for(int i=0; i<cols_t*rows_t; i++){ nnf[i] = rand()%(cols_s*rows_s); } return nnf; } int iteration(Pyramid* source, Pyramid* source_filter, Pyramid* target, Pyramid* target_filter, int l, int q, int* nnf) { int pixelTarget = propagation(source, source_filter, target, target_filter, l, q, nnf); int pixelSource = search(source, source_filter, target, target_filter, l, pixelTarget, nnf); return pixelSource; } int search(Pyramid* source, Pyramid* source_filter, Pyramid* target, Pyramid* target_filter, int l, int q, int* nnf) { int w = max(source[l].cols, source[l].rows), pixel_x = 0, pixel_y = 0, pixel = 0, pixel_min = nnf[q], i = 0; float dist_min = dist(pixel_min, source, source_filter, q, target, target_filter, l), d = 0.0, alpha = powf(ALPHA, i), x = 0.0, y = 0.0; while( w*alpha > 1){ x = ((float)rand()/ (float)(RAND_MAX/3.0)) -1; y = ((float)rand()/ (float)(RAND_MAX/3.0)) -1; pixel_x = w*alpha*x; pixel_y = w*alpha*y; pixel = pixel_min + (pixel_x*source[l].cols + pixel_y); if(pixel < 0) pixel = 0; else if(pixel > source[l].cols*source[l].rows-1) pixel = source[l].cols*source[l].rows-1; d = dist(pixel, source, source_filter, q, target, target_filter, l); if( d < dist_min){ dist_min = d; pixel_min = pixel; } i++; alpha = powf(ALPHA, i); } return pixel_min; } int propagation(Pyramid* source, Pyramid* source_filter, Pyramid* target, Pyramid* target_filter, int l, int q, int* nnf) { int pixel_min = q; float dist_min = dist(nnf[pixel_min], source, source_filter, q, target, target_filter, l); int left = q - 1; if(left < 0) left = 0; float d = dist(nnf[left], source, source_filter, q, target, target_filter, l); if(d < dist_min){ dist_min = d; pixel_min = left; } int top = q - target[l].cols; if(top < 0) top = 0; d = dist(nnf[top], source, source_filter, q, target, target_filter, l); if(d < dist_min){ dist_min = d; pixel_min = top; } return pixel_min; } int patchMatch( Pyramid* source, Pyramid* source_filter, Pyramid* target, Pyramid* target_filter, int l, int q) { int pixelMatch = 0, tmp = 0; for(int k=0; k<NB_MAX_ITER; k++){ int* nnf = initialisation(source[l].cols, source[l].rows, target[l].cols, target[l].rows); tmp = iteration(source, source_filter, target, target_filter, l, q, nnf); if(k > 0){ if( dist(pixelMatch, source, source_filter, q, target, target_filter, l) > dist(tmp, source, source_filter, q, target, target_filter, l) ){ pixelMatch = tmp; } } else{ pixelMatch = tmp; } free(nnf); } return pixelMatch; }
C
#include <stdio.h> #include <math.h> struct Ponto2d pontoInicial; struct Ponto2d pontoFinal; // Estrutura de dados struct Ponto2d { float x; float y; }; void lerPontoInicial() { // Valor do ponto inicial X printf("Digite o valor X do ponto inicial: "); scanf("%f", &pontoInicial.x); // Valor do ponto inicial Y printf("Digite o valor Y do ponto inicial: "); scanf("%f", &pontoInicial.y); } void lerPontoFinal() { // Valor do ponto final X printf("Digite o valor X do ponto final: "); scanf("%f", &pontoFinal.x); // Valor do ponto final Y printf("Digite o valor Y do ponto Final: "); scanf("%f", &pontoFinal.y); } void medirDistancia() { // Potêncialização e calculo final entre os dois pontos float distancia = pow(pontoInicial.x - pontoFinal.x, 2) + pow(pontoInicial.y - pontoFinal.y, 2); // Imprime a raiz do calculo final printf("A distancia é: %0.2f\n", sqrt(distancia)); } float exibirValor(float valor) { // Exibe o valor do ponto informado na tela if (valor) { return valor; } else { return 0; } } int main() { int opcaoSelecionada; // Mapeamento de alternativas disponiveis void (*funcoes[4])(); funcoes[0] = lerPontoInicial; funcoes[1] = lerPontoFinal; funcoes[2] = medirDistancia; // Exibir menu de seleção para o usuário while (opcaoSelecionada != 4) { printf("\nO que deseja fazer?\n"); printf("[1] Digitar os valores do primeiro ponto. (x: %0.2f, y: %0.2f)\n", exibirValor(pontoInicial.x), exibirValor(pontoInicial.y)); printf("[2] Digitar os valores do segundo ponto. (x: %0.2f, y: %0.2f)\n", exibirValor(pontoFinal.x), exibirValor(pontoFinal.y)); printf("[3] Mostrar a distância entre os pontos.\n"); printf("[4] Sair.\n"); // Guarda o numero selecionado scanf("%d", &opcaoSelecionada); // Se a opção é 4 (Sair) encerra o programa if (opcaoSelecionada == 4) break; if (opcaoSelecionada < 1 || opcaoSelecionada > 4) { // Se a opção selecionada não é valida, mostra um aviso ao usuário printf("Opção invalida.\n\n"); } else { // Se for valido, chama a função rêferente ao numero selecionado funcoes[opcaoSelecionada - 1](); } } return 0; }
C
/* ** EPITECH PROJECT, 2018 ** CPool_2018 ** File description: ** Maxence Carpentier */ #include <stdlib.h> #include <stdio.h> #include "my.h" char *my_revstr(char *str) { int i2 = my_strlen(str) - 1; char c; for (int i = 0; i < i2; i++) { c = str[i]; str[i] = str[i2]; str[i2] = c; i2--; } return (str); }
C
#include "pila.h" #include "testing.h" #include <stddef.h> #include <stdio.h> #include <stdlib.h> //Pruebas unitarias del alumno void prueba_crear_destruir(){ printf("****Inicio de prueba crear y destruir pila****\n"); pila_t* pila = pila_crear(); print_test("Se creo la pila", true); pila_destruir(pila); print_test("Se destruyo la pila", true); } void prueba_apilar_desapilar(){ printf("****Inicio de prueba apilar y deapilar algunos elementos****\n"); pila_t* pila = pila_crear(); print_test("Se creo una pila", true); int num1, num2, num3, num4; //pruebo apilando puntero a enteros print_test("Se apila un puntero a entero", pila_apilar(pila, &num1)); print_test("El tope es dicho puntero a entero", pila_ver_tope(pila) == &num1); print_test("La pila no esta vacia", !pila_esta_vacia(pila)); print_test("Al desapilar se devuelve el tope correspondiente", &num1 == pila_desapilar(pila)); print_test("La pila ahora esta vacia", pila_esta_vacia(pila)); print_test("Apilamos un puntero a entero", pila_apilar(pila, &num2)); print_test("Apilamos otro puntero a entero", pila_apilar(pila, &num3)); print_test("Apilamos otro puntero a entero", pila_apilar(pila, &num4)); print_test("Verificamos que la pila no esta vacia", !pila_esta_vacia(pila)); print_test("Desapilamos correctamente", &num4 == pila_desapilar(pila)); print_test("Desapilamos correctamente", &num3 == pila_desapilar(pila)); print_test("Desapilamos correctamente", &num2 == pila_desapilar(pila)); print_test("La pila ahora esta vacia", pila_esta_vacia(pila)); pila_destruir(pila); print_test("Se destruyo la pila", true); } const size_t NUM_ELEMENTOS = 10000; void prueba_volumen(){ printf("****Inicio de prueba de volumen con %zu elementos****\n", NUM_ELEMENTOS); pila_t* pila = pila_crear(); print_test("Se creo una pila", true); /*Como tengo que llenar la pila de punteros distintos, elijo apilar punteros que corresponden a las posiciones de un arreglo de chars. Si se desea probar con un arreglo de otro tipo remplazar sizeof(char) por sizeof(tipo).*/ char* vector_volumen = malloc(NUM_ELEMENTOS * sizeof(char)); size_t errores_apilar = 0; size_t errores_desapilar = 0; for(size_t i = 0; i < NUM_ELEMENTOS; i++){ if(!pila_apilar(pila, vector_volumen + i * sizeof(char))) errores_apilar++; if(pila_ver_tope(pila) != vector_volumen + i * sizeof(char)) errores_apilar++; } print_test("Se apilaron todos los elementos", !errores_apilar); void* elem_desapilado; //en el proximo for castie a int el NUM_ELEMENTOS pues size_t rompe en este ciclo en cuenta regresiva (por ser sin signo) for(int j = (int) NUM_ELEMENTOS -1; j >= 0; j--){ elem_desapilado = pila_ver_tope(pila); if(elem_desapilado != pila_desapilar(pila)) errores_desapilar++; if(elem_desapilado != vector_volumen + j * sizeof(char)) errores_desapilar++;//chequeo que salen en el orden inverso a como los apile } print_test("Se desapilaron todos los elementos", !errores_desapilar); printf("Se registraron %zu errores en la prueba\n", errores_apilar + errores_desapilar); pila_destruir(pila); free(vector_volumen); print_test("Se destruyo la pila", true); } void prueba_apilar_NULL(){ printf("****Inicio de prueba de apilar elemento NULL****\n"); pila_t* pila = pila_crear(); print_test("Se creo una pila", true); print_test("Se apilo NULL", pila_apilar(pila, NULL)); print_test("El tope es efectivamente NULL", !pila_ver_tope(pila)); print_test("Se desapilo NULL", !pila_desapilar(pila)); pila_destruir(pila); print_test("Se destruyo la pila", true); } void prueba_desapilar_hasta_vacia(){ //esto cubre las pruebas 5 y 8 que pide la catedra printf("****Inicio de prueba de desapilar hasta estar vacia****\n"); pila_t* pila = pila_crear(); print_test("Se creo una pila", true); short num1, num2, num3; //probamos apilando punteros a short para variar pila_apilar(pila, &num1); pila_apilar(pila, &num2); pila_apilar(pila, &num3); print_test("Se apilaron tres elementos", true); pila_desapilar(pila); pila_desapilar(pila); pila_desapilar(pila); print_test("Se desapilaron los tres elementos", true); printf("Comprobemos que la pila se comporta como si fuese recien creada:\n"); print_test("La pila esta vacia", pila_esta_vacia(pila)); print_test("Desapilar es invalido (devuelve NULL)", !pila_desapilar(pila)); print_test("Ver tope es invalido (devuelve NULL)", !pila_ver_tope(pila)); print_test("La pila se comporta como si fuese recien creada", true); pila_destruir(pila); print_test("Se destruyo la pila", true); } void prueba_desapilar_vertope_cuando_creada(){ printf("****Inicio de prueba de chequear que desapilar y vertope cuando recien creada una pila son invalidas****\n"); pila_t* pila = pila_crear(); print_test("Se creo una pila", true); print_test("No se puede desapilar", !pila_desapilar(pila)); print_test("No se puede ver tope", !pila_ver_tope(pila)); pila_destruir(pila); print_test("Se destruyo la pila", true); } void prueba_esta_vacia_cuando_creada(){ printf("****Inicio de prueba que una pila recien creada esta vacia****\n"); pila_t* pila = pila_crear(); print_test("Se creo una pila", true); print_test("La pila esta vacia", pila_esta_vacia(pila)); pila_destruir(pila); print_test("Se destruyo la pila", true); } void pruebas_pila_alumno() { prueba_crear_destruir(); prueba_apilar_desapilar(); prueba_volumen(); prueba_apilar_NULL(); prueba_desapilar_hasta_vacia(); prueba_desapilar_vertope_cuando_creada(); prueba_esta_vacia_cuando_creada(); printf("---Finalizaron las pruebas del alumno---\n"); }
C
/* 计算 10000! 的结果并打印 运算时间在1S内 */ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #define PI 3.14159 #define E 2.718 int factorial_digit(int nMlutply); int main(void) { clock_t t1, t2;//计时器 t1 = clock(); int nResult[40001] = { 0 };//存放结果的数组 int nArrayMax = 40000;//数组尾部的位置 int nMlutply = 2;//初始乘数 int nResultPointer = 0;//数组指向的位置 int nCarry = 0;//进位数 int nFactorial[10000] = { 0 };//存放阶乘位数的数组 int nCount = 0; for (nCount = 1; nCount <= 10000; nCount++)//存放阶乘位数到数组中 { nFactorial[nCount - 1] = factorial_digit(nCount); } nResult[0] = 1;//初始化第一个元素为1 while (nMlutply <= 10000)//阶乘数 { nCarry = 0; nResultPointer = 0;//初始化进位和数组位置 while (nResultPointer <= nFactorial[nMlutply - 1] / 5)//检测到阶乘最大位数即可 数组从0开始 所以要-1 { nResult[nResultPointer] = nResult[nResultPointer] * nMlutply + nCarry;//乘以乘数 + 进位 nCarry = nResult[nResultPointer] / 100000;//获得进位 nResult[nResultPointer] %= 100000;//位数还原成一位 nResultPointer++;//向后移动 } nMlutply++; } t2 = clock();//计时器 nResultPointer = nFactorial[9999] - 1;//已知结果的长度 while (nResult[nResultPointer] == 0)//从后找不为0的数 即为结果的开头 { nResultPointer--; } printf("%d", nResult[nResultPointer]);//第一位可能不满足5位 nResultPointer--; while (nResultPointer >= 0) { printf("%05d", nResult[nResultPointer]); nResultPointer--; } printf("\r\nRun time is %dms", t2 - t1); system("pause"); return 0; } int factorial_digit(int nMlutply) { double nDigit = 0; nDigit = log10(sqrt(2 * PI*nMlutply)) + nMlutply * log10(nMlutply / E) + 1;//斯特林公式求阶乘位数 nDigit = (int)nDigit; return nDigit; }
C
/********************************************************************* ** PROYECTO DE AUTÓMATAS Y LENGUAJES - PRÁCTICA 1 ** generacion.c ** AUTORES: ** - Carlos Molinero Alvarado - [email protected] ** - Rafael Hidalgo Alejo - [email protected] ** ÚLTIMA MODIFICACIÓN: 28 de octubre de 2019. **********************************************************************/ #include <stdlib.h> #include <stdio.h> #include "generacion.h" /****************** ** PRIMERA PARTE ** *******************/ /** Implementación de funciones necesarias previamente especificadas: **/ void escribir_cabecera_bss(FILE* fpasm) { if(!fpasm) { fprintf(stderr, "escribir cabecera\n"); return; } fprintf(fpasm, "segment .bss\n"); fprintf(fpasm, "__esp resd 1\n"); return; } void escribir_subseccion_data(FILE* fpasm) { if(!fpasm) { fprintf(stderr, "escribir subseccion data\n"); return; } fprintf(fpasm, "segment .data\n"); fprintf(fpasm, "msg_error_division db \"División por cero\",0\n"); fprintf(fpasm, "msg_error_indice_vector db \"Error en el indice del vector\", 0\n"); } void declarar_variable(FILE* fpasm, char* nombre, int tipo, int tamano) { if(!fpasm || !nombre) { fprintf(stderr, "declarar variable\n"); return; } fprintf(fpasm,"_%s ", nombre); if(tipo == ENTERO || tipo == BOOLEANO) { fprintf(fpasm, "resd "); } fprintf(fpasm, "%d", tamano); fprintf(fpasm, "\n"); return; } void escribir_segmento_codigo(FILE* fpasm) { if(!fpasm) { fprintf(stderr, "escribir_segmento_codigo\n"); return; } fprintf(fpasm, "segment .text\n"); fprintf(fpasm, "global main\n"); fprintf(fpasm, "extern scan_int, scan_boolean, print_int, print_boolean, print_blank, print_endofline, print_string\n"); } void escribir_inicio_main(FILE* fpasm) { if(!fpasm) { fprintf(stderr, "escribir_inicio_main\n"); return; } fprintf(fpasm, "%s", "main:\n"); fprintf(fpasm, "%s", "mov dword [__esp], esp\n"); } void escribir_fin(FILE* fpasm) { if(!fpasm) { fprintf(stderr, "escribir_fin\n"); return; } fprintf(fpasm, "jmp near fin\n"); fprintf(fpasm, "fin_error_division:\n"); fprintf(fpasm, "push dword msg_error_division\n"); fprintf(fpasm, "call print_string\n"); fprintf(fpasm, "add esp, 4\n"); fprintf(fpasm, "call print_endofline\n"); fprintf(fpasm, "jmp near fin\n"); fprintf(fpasm, "fin_indice_fuera_rango:\n"); fprintf(fpasm, "push dword msg_error_indice_vector\n"); fprintf(fpasm, "call print_string\n"); fprintf(fpasm, "add esp, 4\n"); fprintf(fpasm, "call print_endofline\n"); fprintf(fpasm, "jmp near fin\n"); fprintf(fpasm, "fin:\n"); fprintf(fpasm, "mov esp, [__esp]\n"); fprintf(fpasm, "ret\n"); } void asignar(FILE* fpasm, char* nombre, int es_variable) { if(!fpasm || !nombre || (es_variable!=0 && es_variable!=1)) { fprintf(stderr, "asignar\n"); return; } if(es_variable == 1) { fprintf(fpasm, "pop dword _%s\n", nombre); } else { fprintf(fpasm, "pop dword [_%s]\n", nombre); } } /* FUNCIONES ARITMÉTICO-LÓGICAS BINARIAS */ void sumar(FILE* fpasm, int es_variable_1, int es_variable_2) { if(!fpasm || (es_variable_1!=0 && es_variable_1!=1) || (es_variable_2!=0 && es_variable_2!=1)) { fprintf(stderr, "sumar\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable_1 == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable_2 == 1) { fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "add eax, edx\n"); fprintf(fpasm, "push dword eax\n"); } void restar(FILE* fpasm, int es_variable_1, int es_variable_2){ if(!fpasm || (es_variable_1!=0 && es_variable_1!=1) || (es_variable_2!=0 && es_variable_2!=1)) { fprintf(stderr, "sumar\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable_1 == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable_2 == 1) { fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "sub eax, edx\n"); fprintf(fpasm, "push dword eax\n"); } void dividir(FILE* fpasm, int es_variable1, int es_variable2) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "dividir\n"); return; } fprintf(fpasm, "pop dword ecx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1) { fprintf(fpasm, "mov dword ecx, [ecx]\n"); } fprintf(fpasm, "cmp ecx, 0\n"); fprintf(fpasm, "je fin_error_division\n"); fprintf(fpasm, "cdq\n"); fprintf(fpasm, "idiv dword ecx\n"); fprintf(fpasm, "push dword eax\n"); } void multiplicar(FILE* fpasm, int es_variable1, int es_variable2) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "multiplicar\n"); return; } fprintf(fpasm, "pop dword ecx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1) { fprintf(fpasm, "mov dword ecx, [ecx]\n"); } fprintf(fpasm, "imul ecx\n"); fprintf(fpasm, "cdq\n"); fprintf(fpasm, "push dword eax\n"); } void o(FILE* fpasm, int es_variable_1, int es_variable_2) { if(!fpasm || (es_variable_1!=0 && es_variable_1!=1) || (es_variable_2!=0 && es_variable_2!=1)) { fprintf(stderr, "o\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable_1 == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable_2 == 1) { fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "or eax, edx\n"); fprintf(fpasm, "push dword eax\n"); } void y(FILE* fpasm, int es_variable_1, int es_variable_2) { if(!fpasm || (es_variable_1!=0 && es_variable_1!=1) || (es_variable_2!=0 && es_variable_2!=1)) { fprintf(stderr, "y\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable_1 == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable_2 == 1) { fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "and eax, edx\n"); fprintf(fpasm, "push dword eax\n"); } void cambiar_signo(FILE* fpasm, int es_variable){ if(!fpasm || (es_variable!=0 && es_variable!=1)) { fprintf(stderr, "cambiar_signo\n"); return; } fprintf(fpasm, "pop dword eax\n"); if(es_variable == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } fprintf(fpasm, "neg eax\n"); fprintf(fpasm, "push dword eax\n"); } void no(FILE* fpasm, int es_variable, int cuantos_no) { if(!fpasm || (es_variable!=0 && es_variable!=1)) { fprintf(stderr, "no\n"); return; } fprintf(fpasm, "pop dword eax\n"); if(es_variable == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } fprintf(fpasm, "or eax, eax\n"); fprintf(fpasm, "jz near negar_falso_%d\n", cuantos_no); fprintf(fpasm, "mov dword eax, 0\n"); fprintf(fpasm, "jmp near fin_negacion_%d\n", cuantos_no); fprintf(fpasm, "negar_falso_%d:\n", cuantos_no); fprintf(fpasm, "mov dword eax, 1\n"); fprintf(fpasm, "fin_negacion_%d:\n", cuantos_no); fprintf(fpasm, "push dword eax\n"); } /* FUNCIONES COMPARATIVAS */ void igual(FILE* fpasm, int es_variable1, int es_variable2, int etiqueta) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "igual\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1){ fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "cmp dword eax, edx\n"); fprintf(fpasm, "je near igual_%d\n", etiqueta); fprintf(fpasm, "push dword 0\n"); fprintf(fpasm, "jmp near fin_igual_%d\n", etiqueta); fprintf(fpasm, "igual_%d:\n", etiqueta); fprintf(fpasm, "push dword 1\n"); fprintf(fpasm, "fin_igual_%d:\n", etiqueta); } void distinto(FILE* fpasm, int es_variable1, int es_variable2, int etiqueta) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "distinto\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1){ fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "cmp dword eax, edx\n"); fprintf(fpasm, "jne near distinto_%d\n", etiqueta); fprintf(fpasm, "push dword 0\n"); fprintf(fpasm, "jmp near fin_distinto_%d\n", etiqueta); fprintf(fpasm, "distinto_%d:\n", etiqueta); fprintf(fpasm, "push dword 1\n"); fprintf(fpasm, "fin_distinto_%d:\n", etiqueta); } void menor_igual(FILE* fpasm, int es_variable1, int es_variable2, int etiqueta) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "menorigual\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1){ fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "cmp dword eax, edx\n"); fprintf(fpasm, "jle near menorigual_%d\n", etiqueta); fprintf(fpasm, "push dword 0\n"); fprintf(fpasm, "jmp near fin_menorigual_%d\n", etiqueta); fprintf(fpasm, "menorigual_%d:\n", etiqueta); fprintf(fpasm, "push dword 1\n"); fprintf(fpasm, "fin_menorigual_%d:\n", etiqueta); } void mayor_igual(FILE* fpasm, int es_variable1, int es_variable2, int etiqueta) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "mayorigual\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1){ fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "cmp dword eax, edx\n"); fprintf(fpasm, "jge near mayorigual_%d\n", etiqueta); fprintf(fpasm, "push dword 0\n"); fprintf(fpasm, "jmp near fin_mayorigual_%d\n", etiqueta); fprintf(fpasm, "mayorigual_%d:\n", etiqueta); fprintf(fpasm, "push dword 1\n"); fprintf(fpasm, "fin_mayorigual_%d:\n", etiqueta); } void menor(FILE* fpasm, int es_variable1, int es_variable2, int etiqueta) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "menor\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1){ fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "cmp dword eax, edx\n"); fprintf(fpasm, "jl near menor_%d\n", etiqueta); fprintf(fpasm, "push dword 0\n"); fprintf(fpasm, "jmp near fin_menor_%d\n", etiqueta); fprintf(fpasm, "menor_%d:\n", etiqueta); fprintf(fpasm, "push dword 1\n"); fprintf(fpasm, "fin_menor_%d:\n", etiqueta); } void mayor(FILE* fpasm, int es_variable1, int es_variable2, int etiqueta) { if(!fpasm || (es_variable1!=0 && es_variable1!=1) || (es_variable2!=0 && es_variable2!=1)) { fprintf(stderr, "mayor\n"); return; } fprintf(fpasm, "pop dword edx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable1 == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } if(es_variable2 == 1){ fprintf(fpasm, "mov dword edx, [edx]\n"); } fprintf(fpasm, "cmp dword eax, edx\n"); fprintf(fpasm, "jg near mayor_%d\n", etiqueta); fprintf(fpasm, "push dword 0\n"); fprintf(fpasm, "jmp near fin_mayor_%d\n", etiqueta); fprintf(fpasm, "mayor_%d:\n", etiqueta); fprintf(fpasm, "push dword 1\n"); fprintf(fpasm, "fin_mayor_%d:\n", etiqueta); } /* FUNCIONES DE ESCRITURA Y LECTURA */ void leer(FILE* fpasm, char* nombre, int tipo) { if(!fpasm || !nombre) { fprintf(stderr, "leer\n"); return; } fprintf(fpasm, "push dword _%s\n", nombre); if(tipo == ENTERO){ fprintf(fpasm, "call scan_int\n"); } else { fprintf(fpasm, "call scan_boolean\n"); } fprintf(fpasm, "add dword esp, 4\n"); } void escribir(FILE* fpasm, int es_variable, int tipo) { if(!fpasm || (es_variable!=0 && es_variable!=1)) { fprintf(stderr, "escribir\n"); return; } //Lo que hacemos es pop de lo que hay en pila. Dependiendo de lo que haya dentro, //hago el push para que almacene el valor, que es lo que espera recibir print. fprintf(fpasm, "pop dword eax\n"); if(es_variable == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); fprintf(fpasm, "push dword eax\n"); } else { fprintf(fpasm, "push dword eax\n"); } if(tipo == ENTERO) { fprintf(fpasm, "call print_int\n"); fprintf(fpasm, "call print_endofline\n"); } else { fprintf(fpasm, "call print_boolean\n"); fprintf(fpasm, "call print_endofline\n"); } fprintf(fpasm, "add dword esp, 4\n"); } /****************** ** SEGUNDA PARTE ** *******************/ /** Implementación de funciones necesarias previamente especificadas: **/ void escribir_operando(FILE* fpasm, char* nombre, int es_variable) { if(!fpasm || !nombre || (es_variable!=0 && es_variable!=1)) { fprintf(stderr, "escribir_operando\n"); return; } if(es_variable == 1) { fprintf(fpasm, "push dword _%s\n", nombre); } else { fprintf(fpasm, "push dword %s\n", nombre); } } void escribirParametro(FILE* fpasm, int pos_parametro, int num_total_parametros) { if(!fpasm) { fprintf(stderr, "escribirParametro\n"); return; } int d_ebp; d_ebp = 4*(1 + (num_total_parametros - pos_parametro)); fprintf(fpasm, "lea eax, [ebp + %d]\n", d_ebp); fprintf(fpasm, "push dword eax\n"); } void escribirVariableLocal(FILE* fpasm, int posicion_variable_local) { if(!fpasm) { fprintf(stderr, "escribirVariableLocal\n"); return; } int d_ebp; d_ebp = 4*posicion_variable_local; fprintf(fpasm, "lea eax, [ebp - %d]\n", d_ebp); fprintf(fpasm, "push dword eax\n"); } void declararFuncion(FILE * fpasm, char * nombre_funcion, int num_var_loc) { if(!fpasm || !nombre_funcion) { fprintf(stderr, "declararFuncion\n"); return; } fprintf(fpasm, "_%s:\n", nombre_funcion); fprintf(fpasm, "push ebp\n"); fprintf(fpasm, "mov ebp, esp\n"); fprintf(fpasm, "sub esp, %d\n", 4*num_var_loc); } void ifthenelse_inicio(FILE * fpasm, int exp_es_variable, int etiqueta) { if(!fpasm) { fprintf(stderr, "ifthenelse_inicio\n"); return; } fprintf(fpasm, "pop eax\n"); if(exp_es_variable == 1){ fprintf(fpasm, "mov eax, [eax]\n"); } fprintf(fpasm, "cmp eax, 0\n"); fprintf(fpasm, "je fin_then_%d\n", etiqueta); } void ifthen_inicio(FILE * fpasm, int exp_es_variable, int etiqueta) { if(!fpasm) { fprintf(stderr, "ifthen_inicio\n"); return; } fprintf(fpasm, "pop eax\n"); if(exp_es_variable == 1){ fprintf(fpasm, "mov eax, [eax]\n"); } fprintf(fpasm, "cmp eax, 0\n"); fprintf(fpasm, "je fin_then_%d\n", etiqueta); } void ifthen_fin(FILE * fpasm, int etiqueta) { if(!fpasm) { fprintf(stderr, "ifthen_fin\n"); return; } fprintf(fpasm, "fin_then_%d:\n", etiqueta); } void ifthenelse_fin_then(FILE * fpasm, int etiqueta) { if(!fpasm) { fprintf(stderr, "ifthenelse_fin_then\n"); return; } fprintf(fpasm,"jmp near fin_ifelse_%d\n", etiqueta); fprintf(fpasm, "fin_then_%d:\n", etiqueta); } void ifthenelse_fin(FILE * fpasm, int etiqueta) { if(!fpasm) { fprintf(stderr, "ifthenelse_fin\n"); return; } fprintf(fpasm, "fin_ifelse_%d:\n", etiqueta); } void while_inicio(FILE * fpasm, int etiqueta) { if(!fpasm) { fprintf(stderr, "while_inicio\n"); return; } fprintf(fpasm, "inicio_while_%d:\n", etiqueta); } void while_exp_pila(FILE * fpasm, int exp_es_variable, int etiqueta) { if(!fpasm) { fprintf(stderr, "while_exp_pila\n"); return; } fprintf(fpasm, "pop eax\n"); if(exp_es_variable > 0) { fprintf(fpasm, "mov eax, [eax]\n"); } fprintf(fpasm, "cmp eax, 0\n"); fprintf(fpasm, "je fin_while_%d\n", etiqueta); } void while_fin(FILE * fpasm, int etiqueta) { if(!fpasm) { fprintf(stderr, "while_fin\n"); return; } fprintf(fpasm, "jmp near inicio_while_%d\n", etiqueta); fprintf(fpasm, "fin_while_%d:\n", etiqueta); } void escribir_elemento_vector(FILE * fpasm, char* nombre_vector, int tam_max, int exp_es_direccion) { if(!fpasm || !nombre_vector) { fprintf(stderr, "escribir_elemento_vector\n"); return; } fprintf(fpasm, "pop dword eax\n"); if(exp_es_direccion == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } fprintf(fpasm, "cmp eax, 0\n"); fprintf(fpasm, "jl near fin_indice_fuera_rango\n"); fprintf(fpasm, "cmp eax, %d\n", tam_max-1); fprintf(fpasm, "jg near fin_indice_fuera_rango\n"); fprintf(fpasm, "mov dword edx, _%s\n", nombre_vector); fprintf(fpasm, "lea eax, [edx + eax*4]\n"); fprintf(fpasm, "push dword eax\n"); } void asignarDestinoEnPila(FILE* fpasm, int es_variable) { if(!fpasm || (es_variable!= 0 && es_variable!=1)) { fprintf(stderr, "asignarDestinoEnPila\n"); return; } fprintf(fpasm, "pop dword ebx\n"); fprintf(fpasm, "pop dword eax\n"); if(es_variable == 1) { fprintf(fpasm, "mov dword eax, [eax]\n"); } fprintf(fpasm, "mov dword [ebx], eax\n"); } void llamarFuncion(FILE * fpasm, char * nombre_funcion, int num_argumentos) { if(!fpasm || !nombre_funcion) { fprintf(stderr, "llamarFuncion\n"); return; } fprintf(fpasm, "call _%s\n", nombre_funcion); fprintf(fpasm, "add esp, %d\n", num_argumentos*4); fprintf(fpasm, "push dword eax\n"); } void retornarFuncion(FILE * fpasm, int es_variable) { if(!fpasm || (es_variable!= 0 && es_variable!=1)) { fprintf(stderr, "retornarFuncion\n"); return; } fprintf(fpasm, "pop eax\n"); if(es_variable == 1){ fprintf(fpasm, "mov dword eax, [eax]\n"); } fprintf(fpasm, "mov esp, ebp\n"); fprintf(fpasm, "pop ebp\n"); fprintf(fpasm, "ret\n"); } void operandoEnPilaAArgumento(FILE * fpasm, int es_variable) { if(!fpasm || (es_variable!=0 && es_variable!=1)) { fprintf(stderr, "operandoEnPilaAArgumento\n"); return; } if(es_variable == 1) { fprintf(fpasm, "pop eax\n"); fprintf(fpasm, "mov eax, [eax]\n"); fprintf(fpasm, "push eax\n"); } } void limpiarPila(FILE * fpasm, int num_argumentos) { if(!fpasm) { fprintf(stderr, "limpiarPila\n"); return; } fprintf(fpasm, "add esp, %d\n", num_argumentos*4); fprintf(fpasm, "push dword eax\n"); }
C
#pragma once //BM.h library #ifndef BM_H #define BM_H /* Definitions */ typedef struct { float **rows; int r_size; //rows int c_size; //columns } BM; /* Function prototypes */ BM* bm_make(int r_size, int c_size); /* The function attempts to construct a Matrix structure, allocating memory for its rows, and columns and initializing its entries to zero. If any memory allocation fails or the sizes of its row or columns are negative or zero the function returns a NULL pointer. */ void bm_destroy(BM *M); /* The function checks for NULL pointers, if the pointer isn't NULL then its values are set to zero, its memory is freed and its value set to NULL. */ void bm_write(BM *M, int r_pos, int c_pos, float data); /* The function writes the given value to the matrix r_pos row and c_pos column cell. */ float bm_read(BM *M, int r_pos, int c_pos); /* The function reads the given value to matrix r_pos row and c_pos column cell. */ void bm_rowswap(BM *M, int f_row, int s_row); /* The function swaps the Matrix f_row with s_row as long as those aren't NULL pointers nor the Matrix or the address containing it are. In case memory assignation fails the function does nothing. */ void bm_addrow(BM *M, int new_r_pos); /* The function adds a new row which elements are all zeros in new_r_pos position, does nothing in case new row memory assignation fails. */ void bm_print(BM *M); /* The function prints all Matrix entries in a tabular format as long as the given matrix is not null. */ int bm_isnull(BM *M); /* The function checks if the pointer to the structure and neither the structure nor the rows are null and returns the result value. */ BM* bm_sum(BM *f_M, BM *s_M); /* The function builds a new matrix of the same size as the given ones whose values are those resulting of the sum of the given matrices. The operation follows the math definition of sum of matrices. Returns NULL in case memory assignation for the resulting matrix fails or the given matrices are null. */ BM* bm_mult(BM *f_M, BM *s_M); /* The function builds a new matrix whose values are the multiplication of the given matrices. The operation follows the math definition for matrix multiplication In case of failure assigning memory for the new matrix or the given ones are null the function returns NULL */ #endif
C
#include <pthread.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <assert.h> /* Queue Structures */ typedef struct queue_node_s { struct queue_node_s *next; struct queue_node_s *prev; char c; } queue_node_t; typedef struct { struct queue_node_s *front; struct queue_node_s *back; pthread_mutex_t lock; } queue_t; /* Thread Function Prototypes */ void *producer_routine(void *arg); void *consumer_routine(void *arg); /* Global Data */ long g_num_prod; /* number of producer threads */ pthread_mutex_t g_num_prod_lock; /* Main - entry point */ int main(int argc, char **argv) { queue_t queue; pthread_t producer_thread, consumer_thread; void *thread1_return = NULL; void *thread2_return = NULL; int result = 0; /* Initialization */ printf("Main thread started with thread id %lu\n", pthread_self()); memset(&queue, 0, sizeof(queue)); pthread_mutex_init(&queue.lock, NULL); /* <<<<< BUG >>>>> A mutex is created by calling the pthread_mutex_init subroutine and the ID of the created mutex is returned to the calling thread through the mutex parameter. A mutex must be created once. In original code, we are calling pthread_mutex_init() only on queue.lock mutex but not on g_num_prod_lock. */ pthread_mutex_init(&g_num_prod_lock, NULL); g_num_prod = 1; /* there will be 1 producer thread */ /* Create producer and consumer threads */ result = pthread_create(&producer_thread, NULL, producer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create producer thread: %s\n", strerror(result)); exit(1); } printf("Producer thread started with thread id %lu\n", producer_thread); /* <<<<<BUG>>>>> Here, we calling pthread_join after pthread_detach. A detached thread can't be joined. So, it is a bug. If we want to wait for the producer thread to finish, we should call pthread_join() only. */ //result = pthread_detach(producer_thread); //if (0 != result) // fprintf(stderr, "Failed to detach producer thread: %s\n", strerror(result)); result = pthread_create(&consumer_thread, NULL, consumer_routine, &queue); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\n", strerror(result)); exit(1); } printf("Main has created the consumer thread..\n"); /* Join threads, handle return values where appropriate */ result = pthread_join(producer_thread, &thread2_return); if (0 != result) { fprintf(stderr, "Failed to join producer thread: %s\n", strerror(result)); pthread_exit(NULL); } result = pthread_join(consumer_thread, &thread1_return); if (0 != result) { fprintf(stderr, "Failed to join consumer thread: %s\n", strerror(result)); pthread_exit(NULL); } /* <<<<< BUG >>>>> 1. Wrong type casting. The value of count is returned as (void *) and saved at the address of thread1_return. So, to get the value for printing we just need tp type cast with (long). 2. In the original code, we are trying to free the void pointer. But, free is called when we have allocated some memory from the heap which is done using malloc/ calloc. Here, we are not allocating any dynamic memory and thus, there is no need to call free. We are just storing the value of count at the address of the void pointer. Alternate implementation: Instead of returning value, we can allocate some memory in heap and then, return a reference to that memory which would hold the value of count. In that case, we would be required to free the memory allocated dynamically. 3. It is not a bug but i thought of implementing this. In original code, we were handling the return value from one consumer thread only. I have made the producer thread to wait for the consumer thread and get the value of count. Producer thread would return this value to main. Finally, main can print the count value for both consumer threads as well as the total number of printed characters. */ printf("\nConsumer from main printed %lu characters.\n", (long)thread1_return); // Changed here ... free is not required printf("\nConsumer from producer printed %lu characters.\n", (long)thread2_return); printf("\nTotal printed %lu characters.\n", (long)thread2_return+(long)thread1_return); pthread_mutex_destroy(&queue.lock); pthread_mutex_destroy(&g_num_prod_lock); return 0; } /* Function Definitions */ /* producer_routine - thread that adds the letters 'a'-'z' to the queue */ /* <<<<< NOTE >>>>> I have removed detach funtion from here because I want to make the producer to wait for consumer threat created by it and get the return value which would be passed to the main function. */ void *producer_routine(void *arg) { queue_t *queue_p = arg; queue_node_t *new_node_p = NULL; pthread_t consumer_thread; int result = 0; void *thread_return = NULL; char c; result = pthread_create(&consumer_thread, NULL, consumer_routine, queue_p); if (0 != result) { fprintf(stderr, "Failed to create consumer thread: %s\n", strerror(result)); exit(1); } printf("Producer has created the consumer thread..\n"); for (c = 'a'; c <= 'z'; ++c) { /* Create a new node with the prev letter */ new_node_p = malloc(sizeof(queue_node_t)); new_node_p->c = c; new_node_p->next = NULL; /* Add the node to the queue */ pthread_mutex_lock(&queue_p->lock); printf("\nI am Producer (thread id) %lu\t", pthread_self()); printf("Adding to the Queue: %c i.e. %c\n", new_node_p->c, c); if (queue_p->back == NULL) { assert(queue_p->front == NULL); new_node_p->prev = NULL; queue_p->front = new_node_p; queue_p->back = new_node_p; } else { assert(queue_p->front != NULL); new_node_p->prev = queue_p->back; queue_p->back->next = new_node_p; queue_p->back = new_node_p; } pthread_mutex_unlock(&queue_p->lock); sched_yield(); } /* Decrement the number of producer threads running, then return */ /* <<<<< BUG >>>>> the prefix decrement operation on g_num_prod is not atomic. There may be some scenario when it is preempted in mid or running in parallel(in case of multi-processing) and its not updated value is read by the consumer thread. This may result in inconsistency. So, the operation should be performed after acquiring the lock g_num_prod_lock. */ pthread_mutex_lock(&g_num_prod_lock); --g_num_prod; pthread_mutex_unlock(&g_num_prod_lock); result = pthread_join(consumer_thread, &thread_return); if (0 != result) fprintf(stderr, "Failed to attach consumer thread: %s\n", strerror(result)); return thread_return; } /* consumer_routine - thread that prints characters off the queue */ void *consumer_routine(void *arg) { queue_t *queue_p = arg; queue_node_t *prev_node_p = NULL; long count = 0; /* number of nodes this thread printed */ printf("Consumer thread started with thread id %lu\n", pthread_self()); /* terminate the loop only when there are no more items in the queue * AND the producer threads are all done */ /* <<<<< BUG >>>>> In the original code, there is problem with locking and unlocking because of which the output is inconsistent. In second onwards iterations of while loop, we are unlocking the mutex without locking it. To, fix this, some modifications have been done in the code. pthread_mutex_lock(&queue_p->lock); has been moved inside the loop because we are making a check on queue status inside the if condition after aquiring lock. So, even if we don't get lock for the condition check in while, we are fine. pthread_mutex_lock(&g_num_prod_lock); has been added at the end of if block so that lock is there for the check of g_num_prod in the next iteration of while loop. */ pthread_mutex_lock(&g_num_prod_lock); while(queue_p->front != NULL || g_num_prod > 0) { pthread_mutex_unlock(&g_num_prod_lock); pthread_mutex_lock(&queue_p->lock); if (queue_p->front != NULL) { /* Remove the prev item from the queue */ prev_node_p = queue_p->front; if (queue_p->front->next == NULL) queue_p->back = NULL; else queue_p->front->next->prev = NULL; queue_p->front = queue_p->front->next; /* Print the character, and increment the character count */ printf("\nI am Consumer (thread id) %lu\t Extracting: %c", pthread_self(),prev_node_p->c); pthread_mutex_unlock(&queue_p->lock); free(prev_node_p); ++count; pthread_mutex_lock(&g_num_prod_lock); } else { /* Queue is empty, so let some other thread run */ pthread_mutex_unlock(&queue_p->lock); sched_yield(); } } pthread_mutex_unlock(&g_num_prod_lock); pthread_mutex_unlock(&queue_p->lock); return (void*)count; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <ctype.h> #include "main.h" int main(void) { int player, computer, result; srand((unsigned)time(NULL)); for(;;) { player = get_player_choice(); if (player == QUIT) return 0; computer = get_computer_choice(); result = get_result(player, computer); show_result(player, computer, result); } return 0; } /** * @brief Get the computer choice object * * @return int */ int get_computer_choice() { return rand() % 3; }
C
/********************************************************* * * @Proposit: Aquest fitxer conté el main on está definit * el cos del jos, és a dir, el menu principal. * @Autor: Nicole Marie Jimenez Burayag * @Data creacio: 17/03/2018 * @Data ultima modificacio: 09/05/2018 * ********************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "LS_allegro.h" #include "game.h" #include "ranking.h" int main () { FILE *f_taulell; Player player; Taulell taulell; char opcio; int gameover; int win; while (opcio != '3') { printf ("\nMenu:\n"); printf ("1- Nova partida\n"); printf ("2- Mostrar ranquing\n"); printf ("3- Sortir\n"); printf ("Opcio: "); scanf ("%c", &opcio); // Netegem el buffer perquè no ens agafi la \n while((getchar()) != '\n'); switch (opcio) { case '1': // Nova partida win = 0; player.nom_player = (char*)malloc(sizeof(char) * MAXNOM); if (player.nom_player == NULL) { printf ("Error en guardar memoria per el nom del jugador.\n"); } else { player.nom_taulell = (char*)malloc(sizeof(char) * MAXNOM); if (player.nom_taulell == NULL) { printf ("Error en guardar memoria per el nom del jugador.\n"); free (player.nom_player); } else { do { printf ("Introdueix nom del jugador: "); gets (player.nom_player); if (strlen(player.nom_player) > MAXNOM) { printf ("Error, el nom del jugador ha de tenir com a maxim 30 caracters.\n"); } } while (strlen(player.nom_player) > MAXNOM); do { printf ("Introdueix nom del fitxer: "); gets (player.nom_taulell); f_taulell = fopen (player.nom_taulell, "r"); if (!f_taulell) { printf ("\nError, no es troba el fitxer %s!\n\n", player.nom_taulell); } } while (!f_taulell); printf ("Informacio correcte.\n\n"); printf ("Processant informacio...\n"); taulell = sacarTaulell (f_taulell); printf ("Partida iniciada correctament.\n"); player.temps = 0; gameover = startGame (&taulell, &player, &win); if (gameover) { player.temps *= taulell.num_mines; printf ("\nEl jugador: %s\n", player.nom_player); printf ("Puntuacio: %d\n\n", player.temps); printf ("Partida finalitzada correctament!\n"); if (win) { addRanking (player); } } else { printf ("\nPartida finalitzada per jugador!\n"); } freeMemoria(&taulell, &player); } } break; case '2': // Mostrar ranquing mostrarRanking (); break; case '3': // Sortir printf ("\nGracies per jugar!\n"); break; default: // En cas d'error en l'opcio if (opcio < '0' || opcio > '9' ) { printf ("Error, opcio incorrecta. La opcio ha de ser un nombre.\n"); } else { printf ("Error, opcio incorrecta. Ha de ser un numero d'1 a 3.\n"); } break; } } return 0; }
C
#include "hashMap.h" #include <assert.h> #include <time.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /** * Allocates a string for the next word in the file and returns it. This string * is null terminated. Returns NULL after reaching the end of the file. * @param file * @return Allocated string or NULL. */ char* nextWord(FILE* file) { int maxLength = 16; int length = 0; char* word = malloc(sizeof(char) * maxLength); while (1) { char c = fgetc(file); if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '\'') { if (length + 1 >= maxLength) { maxLength *= 2; word = realloc(word, maxLength); } word[length] = c; length++; } else if (length > 0 || c == EOF) { break; } } if (length == 0) { free(word); return NULL; } word[length] = '\0'; return word; } /** * Loads the contents of the file into the hash map. * @param file * @param map */ void loadDictionary(FILE* file, struct HashMap* map) { printf("Loading dictionary, please wait...\n"); char* word = nextWord(file); while(word != NULL){ printf("Current word: %s\n", word); int idx = abs(HASH_FUNCTION(word)) % map->capacity; for(int i = 0; i < map->capacity; i++){ if(i == idx){ hashMapPut(map, word, 0); } } word = nextWord(file); } // FIXME: implement } int minMoves(int a, int b, int c){ if(a <= b && a <= c){ return a; } if(b <= a && b <= c){ return b; } return c; } int levDist(const char* input, int inLen,const char* word, int keyLen){ int cost; if(inLen == 0) return keyLen; if(keyLen == 0) return inLen; if(input[inLen - 1] == word[keyLen - 1]){ cost = 0; } else{ cost = 1; } int one = levDist(input, inLen - 1, word, keyLen) + 1; int two = levDist(input, inLen, word, keyLen - 1) + 1; int three = levDist(input, inLen - 1, word, keyLen - 1) + cost; return minMoves(one, two, three); } /* int leDist(char* input, char* key){ //returns the pointer to the link that contains the matching word? int inLen, keyLen, finVal; inLen = strlen(input); keyLen = strlen(key); printf("checking %s against %s\n", input, key); int mtrx[inLen + 1][keyLen + 1]; for(int i = 0; i <= inLen; i++){ //rows mtrx[i][0] = i; } for(int i = 0; i <= keyLen; i++){ //columns mtrx[0][i] = i; } for(int i = 1; i <= inLen; i++){ char c1; c1 = input[i - 1]; for(int j = 1; j <= keyLen; j++){ char c2; c2 = key[j - 1]; if(c1 == c2){ mtrx[i][j] = mtrx[i - 1][j - 1]; } else{ int del = mtrx[i - 1][j] + 1; int ins = mtrx[i][j - 1] + 1; int sub = mtrx[i - 1][j - 1] + 1; mtrx[i][j] = minMoves(del, ins, sub); } finVal = mtrx[i][j]; } } return finVal; } */ /** * Prints the concordance of the given file and performance information. Uses * the file input1.txt by default or a file name specified as a command line * argument. * @param argc * @param argv * @return */ int main(int argc, const char** argv) { // FIXME: implement struct HashMap* map = hashMapNew(1000); struct HashLink* cur1; struct HashLink* cur2; int moves; int notWord; FILE* file = fopen("dictionary.txt", "r"); clock_t timer = clock(); loadDictionary(file, map); timer = clock() - timer; printf("Dictionary loaded in %f seconds\n", (float)timer / (float)CLOCKS_PER_SEC); fclose(file); printf("hash map size: %d\n", hashMapSize(map)); char inputBuffer[256]; int quit = 0; int matching = 0; while (quit == 0) { printf("Inside the quit determined while loop\n"); printf("Enter a word or \"quit\" to quit: "); scanf("%s", inputBuffer); // char tmp[strlen(inputBuffer) + 1]; // strcpy(tmp, inputBuffer); int i = 0; notWord = 0; for(i = 0; i < strlen(inputBuffer); i++){ //puts user inputted word to lower case to aid comparisons // printf("%s\n", inputBuffer); if(isalpha(inputBuffer[i]) == 0){ notWord = 1; break; } if(inputBuffer[i] >= 'A' && inputBuffer[i] <= 'Z'){ inputBuffer[i] += 32; } } if (strcmp(inputBuffer, "quit") == 0) { quit = 1; break; } printf("%s\n", inputBuffer); assert(map != NULL); if(notWord == 0){ // printf("Inside the notWord determined while loop\n"); int len2; int len1 = strlen(inputBuffer); for(int i = 0; i < map->capacity; i++){ //iterates through all buckets(sentinels) cur1 = map->table[i]; while(cur1 != NULL){ assert(cur1 != NULL); len2 = strlen(cur1->key); moves = levDist(inputBuffer, len1, cur1->key, len2); //not sure how to catch the return...maybe a hash map link if(moves == 0){ matching = 1; printf("The word \"%s\" is spelled correctly. \n", inputBuffer); break; } else{ matching = 0; cur1->value = moves; cur1 = cur1->next; } } if(matching == 1) {break;} } if(matching == 0){ int count = 0; struct HashLink* minArr[5]; //creates hashlink array to hold the locations of the five closest words for(int j = 0; j < map->capacity; j++){ cur2 = map->table[j]; while(cur2 != NULL){ if(count < 5){ //fills the array with the first five words minArr[count]->key = cur2->key; minArr[count]->value = cur2->value; minArr[count]->next = NULL; count++; } else{ for(int k = 0; k < 5; k++){ //compares every word distance with distances in the array if(cur2->value < minArr[k]->value){ minArr[k]->key = cur2->key; //once a new distance is placed in an array location, jump out of array comparison loop minArr[k]->value = cur2->value; break; } } } } } printf("The inputted word:%s, is spelled incorrectly, did you mean; %s, %s, %s, %s, %s?\n", inputBuffer, minArr[0]->key, minArr[1]->key, minArr[2]->key, minArr[3]->key, minArr[4]->key); } } // Implement the spell checker code here.. } hashMapDelete(map); return 0; }
C
#include "holberton.h" /** * token - Splits a string * @str: command enter for the user * Return: array of each word of the string splited. */ char **token(char *str) { char *token, **tokencomplete; int i = 0, j = 1, position = 0; char delimit[] = " \t\r\n\v\f"; for (i = 0; str[i] != '\n'; i++) ; str[i] = '\0';/*Coloca caracter nulo en la entrada del usuario*/ for (i = 0; str[i] != '\0'; i++) { if (str[i] == ' ') j++; } tokencomplete = malloc(j * sizeof(char *)); if (tokencomplete == NULL) { free(tokencomplete); exit(0); } token = strtok(str, delimit); while (token != NULL) { tokencomplete[position] = malloc(sizeof(char) * _strlen(token) + 1); _strcpy(tokencomplete[position], token); token = strtok(NULL, delimit); position++; } tokencomplete[position] = NULL; return (tokencomplete); }
C
/* * Exclusive locks look great on paper, but they cause awful * performance regressions forcing all access to be sequential. * In this case the benefit of multithreading would be lost. * * There is nothing wrong with every thread in the application * reading a data structure at the same time, as long as no other * thread tries to change it. * On the other hand, if a thread is writing a data structure, other * threads should be prevented from both reading and writing it. * It is possible to do the same thing in multithreading applications. * The trick is to make it properly. * * The following design "Concurrent Control with Readers and Writers", * Communications of the ACM, vol 10,pp. 667-668, Oct. 1971 * gives preference to the readers. Here's the pseudo code for what is going on: Lock for Reader: Lock the Mutex Bump the count of readers If this is the first reader, lock the Semaphore(left=0) Release the Mutex Unlock for Reader: Lock the Mutex Decrement the count of readers If this is the last reader, unlock the Semaphore(left=1) Release the Mutex Lock for Writer: Lock the Semaphore(left=0) Unlock for Writer Unlock the Semaphore(left=1) */ #include <stdio.h> #include <stdlib.h> #include <windows.h> #include "MtVerify.h" #define MAX_TEXT 6 #define MAX_TIMEOUT 2000 typedef struct _Shared { // threads share this text resource char str[MAX_TEXT]; // locking mechanism HANDLE hMutex; HANDLE hSemaphore; int iReaders; } Shared ; Shared* NewShared() { Shared* pSh; pSh = malloc( sizeof(Shared) ); memset(pSh, 0, sizeof(Shared)); // initialize locking MTVERIFY( pSh->hMutex = CreateMutex(NULL, FALSE, NULL) ); MTVERIFY( pSh->hSemaphore = CreateSemaphore(NULL, 1, 1, NULL) ); pSh->iReaders = 0; return pSh; } // New void DeleteShared(Shared* pSh) { DWORD rc; MTVERIFY( (rc = WaitForSingleObject(pSh->hSemaphore, 0)) == WAIT_OBJECT_0 ); MTVERIFY( CloseHandle(pSh->hMutex) ); MTVERIFY( CloseHandle(pSh->hSemaphore) ); free(pSh); } // Delete void ReadLock(Shared* pSh) { DWORD rc; MTVERIFY( (rc = WaitForSingleObject(pSh->hMutex, MAX_TIMEOUT)) == WAIT_OBJECT_0 ); pSh->iReaders++; if(pSh->iReaders == 1) { MTVERIFY( (rc = WaitForSingleObject(pSh->hSemaphore, MAX_TIMEOUT)) == WAIT_OBJECT_0 ); } MTVERIFY( ReleaseMutex(pSh->hMutex) ); } // lock for read void ReadUnlock(Shared* pSh) { DWORD rc; MTVERIFY( (rc = WaitForSingleObject(pSh->hMutex, MAX_TIMEOUT)) == WAIT_OBJECT_0 ); pSh->iReaders--; if(pSh->iReaders == 0) { MTVERIFY( ReleaseSemaphore(pSh->hSemaphore, 1, NULL) ); } MTVERIFY( ReleaseMutex(pSh->hMutex) ); } // unlock last read void WriteLock(Shared* pSh) { MTVERIFY( WaitForSingleObject(pSh->hSemaphore, INFINITE) == WAIT_OBJECT_0 ); } // lock for write void WriteUnlock(Shared* pSh) { MTVERIFY( ReleaseSemaphore(pSh->hSemaphore, 1, NULL) ); } // unlock last write ////////////////////////////////////////////////////////////////////////// #define MAX_THREADS 9 DWORD WINAPI ThreadFunc(LPVOID n); Shared* gShared; int main() { int i; HANDLE hThrds[MAX_THREADS]; DWORD threadId; DWORD rc; gShared = NewShared(); strcpy(gShared->str, "abcdef"); printf("\n\tMain thread: gShared: %s", gShared->str); for(i=0; i < MAX_THREADS; ++i) { MTVERIFY( hThrds[i] = CreateThread( NULL, 0, ThreadFunc, (LPVOID)i, 0, &threadId) ); printf("\n\tLaunched thread %d", i); } rc = WaitForMultipleObjects( MAX_THREADS, hThrds, TRUE, INFINITE); MTVERIFY(rc >= WAIT_OBJECT_0 && rc < WAIT_OBJECT_0 + MAX_THREADS); printf("\n\tAll threads finished\n\n"); DeleteShared(gShared); return EXIT_SUCCESS; } // main DWORD WINAPI ThreadFunc(LPVOID n) { srand( GetTickCount() ); Sleep( (rand()%10)*300 + 500 ); if(((int)n) % 2) { // Writer WriteLock(gShared); sprintf(gShared->str, "%d%d%d%d%d%c", n,n,n,n,n,'\0'); printf("\n\tWriter Th: %d gShared: %s", n, gShared->str); WriteUnlock(gShared); } else { // Reader ReadLock(gShared); printf("\n\tReader Th: %d gShared: %s", n, gShared->str); ReadUnlock(gShared); } return (DWORD)n; }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "llist.h" int llisthead_init(int size, llisthead_t **h) { *h = malloc(sizeof(llisthead_t)); if (NULL == *h) return -1; (*h)->head.data = NULL; (*h)->head.prev = (*h)->head.next = &(*h)->head; (*h)->size = size; return 0; } static void insert(struct node_st *new, struct node_st *p, struct node_st *n) { new->next = n; new->prev = p; p->next = new; n->prev = new; } int llist_insert(llisthead_t *h, const void *data, insert_way_t way) { struct node_st *new = NULL; if (!(way == INSERT_HEAD || way == INSERT_TAIL)) return -1; new = malloc(sizeof(struct node_st)); if (NULL == new) return -1; new->data = malloc(h->size); if (NULL == new->data) { free(new); return -1; } memcpy(new->data, data, h->size); switch (way) { case INSERT_HEAD: insert(new, &h->head, h->head.next); break; case INSERT_TAIL: insert(new, h->head.prev, &h->head); break; default: break; } return 0; } static void delete(struct node_st *del) { del->prev->next = del->next; del->next->prev = del->prev; free(del->data); free(del); } int llist_delete(llisthead_t *h, const void *key, cmp_t *cmp) { struct node_st *cur; for (cur = h->head.next; cur != &h->head; cur = cur->next) { if (!cmp(cur->data, key)) { delete(cur); return 0; } } return -1; } void llist_traval(const llisthead_t *h, pri_t pri) { struct node_st *cur; for (cur = h->head.next; cur != &h->head; cur = cur->next) pri(cur->data); } void llist_destroy(llisthead_t *h) { while (h->head.next != &h->head) { delete(h->head.next); } free(h); } void *llist_pop(const llisthead_t *h) { if (h->head.next == &h->head && h->head.prev == &h->head) return NULL; return (h->head.next)->data; } void *llist_last(const llisthead_t *h) { if (h->head.next == &h->head && h->head.prev == &h->head) return NULL; return (h->head.prev)->data; } int llist_all_membs(const llisthead_t *h) { struct node_st *cur; int n = 0; for (cur = h->head.next; cur != &h->head; cur = cur->next) { n ++; } return n; } int llist_fetch(llisthead_t *h, const void *key, cmp_t *cmp, void *data) { struct node_st *cur; for (cur = h->head.next; cur != &h->head; cur = cur->next) { if (!cmp(cur->data, key)) { memcpy(data, cur->data, h->size); delete(cur); return 0; } } return -1; }
C
#include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { pid_t pid; pid = getpid(); printf("before fork: pid = %d\n", pid); fork(); if(pid == getpid()){ printf("This is a father print\n"); }else{ printf("This is child print, child pid = %d\n", getpid()); } return 0; }
C
/* ** Helper's for serializing and deserializing network packets */ /* ** pack() -- store data dictated by the format string in the buffer ** ** bits |signed unsigned float string ** -----+---------------------------------- ** 8 | c C ** 16 | h H f ** 32 | l L d ** 64 | q Q g ** - | s ** ** (16-bit unsigned length is automatically prepended to strings) */ unsigned int pack(unsigned char *buf, char *format, ...); /* ** unpack() -- unpack data dictated by the format string into the buffer ** ** bits |signed unsigned float string ** -----+---------------------------------- ** 8 | c C ** 16 | h H f ** 32 | l L d ** 64 | q Q g ** - | s ** ** (string is extracted based on its stored length, but 's' can be ** prepended with a max length) */ void unpack(unsigned char *buf, char *format, ...);
C
#include<stdio.h> int main() { int wi,wo,ho,it,ot; float ts,tm,tl; float re,be; scanf("%d%d%d%d%d",&wi,&wo,&ho,&it,&ot); ts=wi*0.08+wo*0.139+ho*0.135+it*1.128+ot*1.483; tm=wi*0.07+wo*0.13+ho*0.121+it*1.128+ot*1.483; tl=wi*0.06+wo*0.108+ho*0.101+it*1.128+ot*1.483; if(ts<183) ts=183; if(tm<383 ) tm=383; if(tl<983) tl=983; if(tm>ts&&tl>ts) re=ts; else if(tl>tm&&ts>tm) re=tm; else if(ts>tl&&tm>tl) re=tl; if(re<383) be=183; if(re>=383&&re<983) be=383;23 if(re>=983) be=983; printf("%.0f\n%.0f",re,be); return 0; }
C
#include <stdio.h> int next(int*, int, int); int stage_one(int*, int); int stage_two(int*, int, int); int main() { int array[10]; array[0] =7; array[1] =8; array[2] =9; array[3] =3; array[4] =2; array[5] =6; array[6] =6; array[7] =1; array[8] =4; array[9] =4; int meet = stage_one(array, 10); int begin; if (meet < 0) { begin = -1; } else { begin = stage_two(array, 10, meet); } printf("%d, %d\n", meet, begin); } /** * The next function for a particular struture. * * @param arr A pointer to the structure * @param ix The value for which to find 'next' * @return The next value. */ int next(int *arr, int length, int ix) { if (ix >= length) { return -1; } return *(arr + ix); } /** * Implements the first stage of tortoise & hare. * * @return -1 if no cycle found, or the index of the meeting pointers * if a cycle is found. */ int stage_one(int *structure, int length) { int tort = 0; int hare = 0; do { tort = next(structure, length, tort); if (tort < 0) {break;} hare = next(structure, length, hare); if (hare < 0) {tort = hare; break;} hare = next(structure, length, hare); if (hare < 0) {tort = hare; break;} } while (tort != hare); return tort; } /** * Finds the beginning of the cycle. * * @param structure The structure in which to find the cycle. * @param meet The value found in stage one of the algorithm. * @return The start of the cycle. */ int stage_two(int *structure, int length, int meet) { int tort1 = 0; int tort2 = meet; while (tort1 != tort2) { tort1 = next(structure, length, tort1); tort2 = next(structure, length, tort2); } return tort1; }
C
/** * block1.c * - First Test of FruitBlock's Fruit Tiles */ #include <gb/gb.h> #include "fruit.h" void detect_ground(int *x_coord, int *y_coord, int fruit_num); int main(void) { int x, y, st, key, z, i, j; x = 32; y = -8; st = 0; z = 1; i = 0; j = 0; set_sprite_data(1, 9, fruit); set_bkg_data(1, 9, fruit); wait_vbl_done(); set_sprite_tile(0, 1); //set_sprite_tile(1, 1); SHOW_BKG; move_sprite(st, x, y); //move_sprite(1, 200, 200); SHOW_SPRITES; key = 0; while (!0) { i++; j++; detect_ground(&x, &y, z); if (i > 10) { y++; move_sprite(st, x, y); i = 0; } /* key = joypad(); if (key == J_UP) { y--; move_sprite(st, x, y); } */ key = joypad(); if (key == J_DOWN) { y++; move_sprite(st, x, y); } key = joypad(); if (key == J_LEFT) { //x--; if (j > 15) { x -= 8; move_sprite(st, x, y); j = 0; } } key = joypad(); if (key == J_RIGHT) { //x++; if (j > 15) { x += 8; move_sprite(st, x, y); j = 0; } } key = joypad(); if (key == J_A) { if (i > 8) { z++; if (z > 7) { z = 1; } set_sprite_tile(0, z); } } delay(20); } reset(); } void detect_ground(int *x_coord, int *y_coord, int fruit_num) { char grounded = 0; unsigned char fruit_array[1]; fruit_array[0] = fruit_num; // Check for bottom of column if (*y_coord >= 144) { grounded = 1; } // Check for tiles beneath if (grounded) { set_bkg_tiles((*x_coord) >> 3, (*y_coord) >> 3, 1, 1, fruit_array); *x_coord = 32; *y_coord = -8; move_sprite(0, *x_coord, *y_coord); } }
C
#include <stdio.h> #include <string.h> int main() { FILE *f = fopen("./shells", "r"); if (f) { while (!feof(f)) { char s[200]; fgets(s, 200, f); if (feof(f)) break; s[strlen(s)-1] = 0; printf("%s\n", s); } fclose(f); } }
C
#include <stdlib.h> #include "stdio.h" #define N 20 struct pile { char a[N]; int sommet; } ; typedef struct pile pile; pile *init_pile(void) { pile *p; p = malloc(sizeof(struct pile)); p->sommet = -1; return p; } int pile_est_full(pile *p) { return (p->sommet == N - 1); } int pile_est_vide(pile *p) { return (p->sommet == -1); } void empile(pile *p, char c)/*既然参数是指针,就不用返回指针*/ { if(!pile_est_full(p)) { p->sommet += 1; p->a[p->sommet] = c; } } void depile(pile *p) { if(!pile_est_vide(p)) { p->sommet -= 1; } } char top(pile *p) { if(!pile_est_vide(p)) return (p->a[p->sommet]); else return ' '; } void affiche(pile *p, char *l) { int i = 0; int n = p->sommet; while(n != -1) { l[i] = p->a[n]; i += 1; n -= 1; } } void destroy(pile *p) { free(p); }
C
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <process.h> /* * execenv <var> <value-file> <command> {<arguments>} */ int main(int argc, char **argv) { char *name; char *value; FILE *fh; int size; int i; if(argc < 4) { fprintf(stderr,"Burble!\n"); exit(10); } name = argv[1]; fh = fopen(argv[2],"rb"); if(fh == NULL) { fprintf(stderr,"Could not open '%s' for reading\n",argv[2]); exit(20); } fseek(fh,0,SEEK_END); size = ftell(fh); fseek(fh,0,SEEK_SET); value = calloc(size+1,1); if(value == NULL) { fprintf(stderr,"Could not allocate %d bytes\n", size); exit(30); } fread(value,1,size,fh); fclose(fh); /* * replace all white space with real space */ for(i=0; i < size; i++) if(isspace(value[i])) value[i] = ' '; /* * Trim any white space of end of value */ while((size >= 1) && isspace(value[size-1])) { value[--size] = '\0'; } setenv(name,value); execvp(argv[3], argv+3); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS # include<stdio.h> # include<stdlib.h> int lifang(int a) { int b; b = a*a*a; //return b; } int main() { int lifang(int a); int i = 100; int a; int b; int c; int d; printf("ˮ\n"); for (i = 100; i < 1000; i++) { a = i / 100; b = (i-a * 100)/10; c = (i - a * 100) % 10; if (i == lifang(a) + lifang(b) + lifang(c)) { printf("%d\n", i); } } system("pause"); return 0; } int main() { int a; int sum; scanf("%d", &a); if (0<a<10) sum = 12345 * a; if (10 < a < 100) sum=102030405*a; printf("%d", sum); system("pause"); return 0; }
C
/* ============================================================================ Name : ListaCircular.c Author : IHMHR Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> typedef struct lista Tlista; struct lista { char dado; Tlista *prox; }; int isListavazia(Tlista *lst) { if(NULL == lst) { return 1; } else { return 0; } } Tlista* inserir(Tlista *anterior, char letra) { Tlista *aux = (Tlista*) malloc(sizeof(Tlista)); if(NULL == anterior) { aux->dado = letra; aux->prox = aux; return aux; } else { Tlista *auxN = anterior; aux->dado = letra; aux->prox = aux; aux->prox = anterior; do { auxN = auxN->prox; } while (auxN->prox != anterior); auxN->prox = aux; return aux; /*//dado //ligação do { // para no ultimo da lista aux2 = anterior; /*aux->dado = letra; aux->prox = aux2; aux2->prox = aux;*/ /*} while(aux2->prox != anterior); //ultimo no primeiro aux2->prox = anterior; return anterior;*/ } } void imprime(Tlista *lst) { if(NULL == lst) { printf("Lista vazia !"); } else { Tlista *aux = lst; do { printf("%c\n", lst->dado); lst = lst->prox; } while (aux != lst); } } Tlista* BuscaCircular(Tlista* lst, char letra) { if(isListavazia(lst)) { return NULL; //return lst; } else { Tlista *aux = lst; do { if(lst->dado == letra) { return lst; } lst = lst->prox; } while (aux != lst); return NULL; } } Tlista* liberaCircular(Tlista *lst) { /*while(!isListavazia(lst)) { Tlista *aux = lst; Tlista *aux2 = lst; lst = lst->prox; do { aux2 = aux2->prox; } while (aux != aux2->prox); free(aux); aux2->prox = lst; } return lst;*/ Tlista *aux = lst; Tlista *aux2 = lst->prox; if (aux->prox == aux) { free(aux); return NULL; } else { do { aux = aux2->prox; free(aux2); lst->prox = aux; // reposicionar aux2 aux2 = aux; } while (aux != lst); free(aux); } return NULL; } Tlista* removeLista(Tlista *lst, char letra) { if(isListavazia(lst)) { return lst; } else if(lst == lst->prox && letra == lst->dado) { free(lst); lst = NULL; return lst; } else if(lst->dado == letra) { Tlista *aux = lst; Tlista *aux2 = lst; do { aux2 = aux2->prox; } while(aux2->prox != lst); lst = lst->prox; aux2->prox = lst; free(aux); return lst; } else { Tlista *aux = lst; Tlista *aux2; do { if (aux->prox->dado == letra) { aux2 = aux->prox; aux->prox = aux->prox->prox; free(aux2); } else { aux = aux->prox; } } while (aux->prox != lst); return lst; } return lst; } int main(void) { Tlista *listaCompleta = NULL; listaCompleta = inserir(listaCompleta, 'F'); listaCompleta = inserir(listaCompleta, 'A'); listaCompleta = inserir(listaCompleta, 'C'); listaCompleta = inserir(listaCompleta, 'E'); imprime(listaCompleta); printf("\n"); //printf("%p", BuscaCircular(listaCompleta, 'A')); //printf("\n\n"); /*listaCompleta = liberaCircular(listaCompleta);*/ listaCompleta = removeLista(listaCompleta, 'C'); imprime(listaCompleta); //printf("%s", isListavazia(listaCompleta) ? "Lista Vazia" : "Lista CHEIA"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ps_size.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abukasa <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/04 12:54:45 by abukasa #+# #+# */ /* Updated: 2018/09/14 17:36:38 by abukasa ### ########.fr */ /* */ /* ************************************************************************** */ #include "ps.h" struct s_info largest_a(struct s_stack_a *head, struct s_info allinfo) { struct s_stack_a *temp; static struct s_info temp_info; int val_temp; int pos; int variables; temp = head; variables = 0; pos = 0; val_temp = temp->val; while (temp != NULL) { if (val_temp < temp->val) { val_temp = temp->val; pos = variables; } variables++; temp = temp->next; } allinfo.largest_a_pos = pos; allinfo.largest_a = val_temp; temp_info = allinfo; return (temp_info); } void smallest_b(struct s_stack_b **top_b) { struct s_stack_b *temp; int val_temp; int pos; int variables; temp = *top_b; variables = 0; pos = 0; val_temp = temp->val; while (temp != NULL) { if (val_temp > temp->val) { val_temp = temp->val; pos = variables; } variables++; temp = temp->next; } allinfo.smallest_b = val_temp; allinfo.count_b = variables; } int largest_b(struct s_stack_b **top_b) { struct s_stack_b *temp; int val_temp; int pos; int variables; temp = *top_b; variables = 0; pos = 0; val_temp = temp->val; while (temp != NULL) { if (val_temp < temp->val) { val_temp = temp->val; pos = variables; } variables++; temp = temp->next; } allinfo.largest_b = val_temp; allinfo.largest_b_pos = pos; allinfo.count_b = count_b(head_b); return (val_temp); } struct s_info smallest_a(struct s_stack_a *head, struct s_info allinfo) { struct s_stack_a *temp; static struct s_info temp_info; int val_temp; int pos; int variables; temp = head; variables = 0; pos = 0; val_temp = temp->val; while (temp != NULL) { if (val_temp > temp->val) { val_temp = temp->val; pos = variables; } variables++; temp = temp->next; } allinfo.smallest_a_pos = pos; allinfo.smallest_a = val_temp; temp_info = allinfo; return (temp_info); }
C
/*************************************************************************** * A toolbox for software optimization of QC-MDPC code based cryptosystems * Copyright (c) 2017 Nir Drucker, Shay Gueron * ([email protected], [email protected]) * The license is detailed in the file LICENSE.md, and applies to this file. * ***************************************************************************/ #include "sampling.h" #include "string.h" #include "assert.h" _INLINE_ status_t get_rand_mod_len(OUT uint32_t* rand_pos, IN const uint32_t len, IN OUT aes_ctr_prf_state_t* prf_state) { const uint64_t mask = MASK(bit_scan_reverse(len)); status_t res = SUCCESS; do { //Generate 128bit of random numbers res = aes_ctr_prf((uint8_t*)rand_pos, prf_state, sizeof(*rand_pos)); CHECK_STATUS(res); //Mask only relevant bits (*rand_pos) &= mask; //Break if a number smaller than len is found if ((*rand_pos) < len) { break; } } while (1==1); EXIT: return res; } _INLINE_ status_t make_odd_weight(IN OUT uint8_t* a, IN const uint32_t len, IN OUT aes_ctr_prf_state_t* prf_state) { uint32_t rand_pos = 0; if(((count_ones(a, R_SIZE) % 2) == 1)) { //Already odd return SUCCESS; } //Generate random bit and flip it status_t res = get_rand_mod_len(&rand_pos, len, prf_state); CHECK_STATUS(res); const uint32_t rand_byte = rand_pos >> 3; const uint32_t rand_bit = rand_pos & 0x7; a[rand_byte] ^= BIT(rand_bit); EXIT: return SUCCESS; } //IN: must_be_odd - 1 true, 0 not status_t sample_uniform_r_bits(OUT uint8_t* r, IN const seed_t* seed, IN const must_be_odd_t must_be_odd) { status_t res = SUCCESS; //For the seedexpander aes_ctr_prf_state_t prf_state = {0}; //Both h0 and h1 use the same context init_aes_ctr_prf_state(&prf_state, MAX_AES_INVOKATION, seed); //Generate random data res = aes_ctr_prf(r, &prf_state, R_SIZE); CHECK_STATUS(res); //Mask upper bits of the MSByte r[R_SIZE-1] &= MASK(R_BITS + 8 - (R_SIZE*8)); if(must_be_odd == MUST_BE_ODD) { res = make_odd_weight(r, R_BITS, &prf_state); CHECK_STATUS(res); } EXIT: return res; } #if defined(CONSTANT_TIME) || defined(VALIDATE_CONSTANT_TIME) _INLINE_ int is_new2(IN uint32_t wlist[], IN const uint32_t ctr) { for(uint32_t i = 0; i < ctr; i++) { if(wlist[i] == wlist[ctr]) { return 0; } } return 1; } #endif #ifdef CONSTANT_TIME _INLINE_ int is_new(IN idx_t wlist[], IN const uint32_t ctr) { for(uint32_t i = 0; i < ctr; i++) { if(wlist[i].val == wlist[ctr].val) { return 0; } } return 1; } void secure_set_bits(IN OUT uint8_t* a, IN const idx_t wlist[], IN const uint32_t a_len, IN const uint32_t weight); _INLINE_ void set_bit(IN uint8_t* a, IN const uint32_t pos, IN const uint32_t mask) { const uint32_t byte_pos = pos >> 3; const uint32_t bit_pos = pos & 0x7; a[byte_pos] |= (BIT(bit_pos) & mask); } //Assumption 1) fake_weight > waight // 3) paddded_len % 64 = 0! status_t generate_sparse_fake_rep(OUT uint8_t* a, OUT idx_t wlist[], IN const uint32_t weight, IN const uint32_t fake_weight, IN const uint32_t len, IN const uint32_t padded_len, IN OUT aes_ctr_prf_state_t *prf_state) { assert(padded_len % 64 == 0); assert(fake_weight >= weight); status_t res = SUCCESS; uint64_t ctr = 0; uint32_t real_wlist[weight]; //Initialize lists memset(wlist, 0, sizeof(idx_t)*fake_weight); memset(real_wlist, 0, sizeof(real_wlist)); //Generate fake_weight rand numbers do { res = get_rand_mod_len(&wlist[ctr].val, len, prf_state); CHECK_STATUS(res); ctr += is_new(wlist, ctr); } while(ctr < fake_weight); //Allocate weight real positions ctr = 0; do { res = get_rand_mod_len(&real_wlist[ctr], fake_weight, prf_state); CHECK_STATUS(res); ctr += is_new2(real_wlist, ctr); } while(ctr < weight); //Applying the indices in constant time uint32_t mask = 0; for(uint32_t j = 0; j < fake_weight; j++) { for(uint32_t i = 0; i < weight; i++) { mask = secure_cmp32(j, real_wlist[i]); //Turn on real val mask. wlist[j].used |= (-1U * mask); } } //Initialize to zero memset(a, 0, (len + 7) >> 3); //Assign values to "a" secure_set_bits(a, wlist, padded_len, fake_weight); EXIT: return res; } //Assumption 1) paddded_len % 64 = 0! status_t generate_sparse_rep(OUT uint8_t* a, OUT idx_t wlist[], IN const uint32_t weight, IN const uint32_t len, IN const uint32_t padded_len, IN OUT aes_ctr_prf_state_t *prf_state) { assert(padded_len % 64 == 0); status_t res = SUCCESS; uint64_t ctr = 0; //Generate fake_weight rand numbers do { res = get_rand_mod_len(&wlist[ctr].val, len, prf_state); CHECK_STATUS(res); wlist[ctr].used = -1U; ctr += is_new(wlist, ctr); } while(ctr < weight); //Initialize to zero memset(a, 0, (len + 7) >> 3); //Assign values to "a" secure_set_bits(a, wlist, padded_len, weight); EXIT: return res; } #else ////////////////////////////////////// //NON CONSTANT TIME implementation! ////////////////////////////////////// //Return 1 if set _INLINE_ int is_bit_set(IN const uint8_t* a, IN const uint32_t pos) { const uint32_t byte_pos = pos >> 3; const uint32_t bit_pos = pos & 0x7; return ((a[byte_pos] & BIT(bit_pos)) != 0); } _INLINE_ void set_bit(IN uint8_t* a, IN const uint32_t pos) { const uint32_t byte_pos = pos >> 3; const uint32_t bit_pos = pos & 0x7; a[byte_pos] |= BIT(bit_pos); } //Assumption fake_weight > waight status_t generate_sparse_fake_rep(OUT uint8_t* a, OUT idx_t wlist[], IN const uint32_t weight, IN const uint32_t fake_weight, IN const uint32_t len, IN const uint32_t padded_len, IN OUT aes_ctr_prf_state_t *prf_state) { UNUSED(fake_weight); #ifndef VALIDATE_CONSTANT_TIME return generate_sparse_rep(a, wlist, weight, len, padded_len, prf_state); #else //This part of code to be able to compare constant and // non constant time implementations. status_t res = SUCCESS; uint64_t ctr = 0; uint32_t real_wlist[weight]; idx_t inordered_wlist[fake_weight]; res = generate_sparse_rep(a, inordered_wlist, fake_weight, len, padded_len, prf_state); CHECK_STATUS(res); //Initialize to zero memset(a, 0, (len + 7) >> 3); //Allocate weight real positions do { res = get_rand_mod_len(&real_wlist[ctr], fake_weight, prf_state); CHECK_STATUS(res); wlist[ctr].val = inordered_wlist[real_wlist[ctr]].val; set_bit(a, wlist[ctr].val); ctr += is_new2(real_wlist, ctr); } while(ctr < weight); EXIT: return res; #endif } //Assumption fake_weight > waight status_t generate_sparse_rep(OUT uint8_t* a, OUT idx_t wlist[], IN const uint32_t weight, IN const uint32_t len, IN const uint32_t padded_len, IN OUT aes_ctr_prf_state_t *prf_state) { UNUSED(padded_len); status_t res = SUCCESS; uint64_t ctr = 0; //Initialize to zero memset(a, 0, (len + 7) >> 3); do { res = get_rand_mod_len(&wlist[ctr].val, len, prf_state); CHECK_STATUS(res); if (!is_bit_set(a, wlist[ctr].val)) { set_bit(a, wlist[ctr].val); ctr++; } } while(ctr < weight); EXIT: return res; } #endif
C
#include "trigger.h" #include "globals.h" #include "triggerLockoutTimer.h" #include "hitLedTimer.h" #include "transmitter.h" #include "supportFiles/buttons.h" #include "supportFiles/mio.h" #include <stdio.h> #include "supportFiles/leds.h" #include "supportFiles/switches.h" #include "supportFiles/interrupts.h" #define DEBOUNCE_DURATION (50e-3 * GLOBALS_TIMER_FREQUENCY) // 50 ms #define TRIGGER_PIN 10 // JF 2 #define TRIGGER_BUTTON 0x1 enum trigger_states {wait_for_change_st, wait_till_steady_st} trigger_state; bool ignoreGunInput; // Init trigger data-structures. void trigger_init() { trigger_state = wait_for_change_st; mio_setPinAsInput(TRIGGER_PIN); ignoreGunInput = mio_readPin(TRIGGER_PIN); if(ignoreGunInput) printf("Gun input high - assuming it is disconnected\r\n"); else printf("Gun input low - assuming it is connected\r\n"); } static bool enabled; // Enable the trigger state machine. The state-machine does nothing until it is enabled. void trigger_enable() { enabled = true; printf("enabled\r\n"); } bool triggerPressed() { return (buttons_read() & TRIGGER_BUTTON) || (!ignoreGunInput && mio_readPin(TRIGGER_PIN)); } // Standard tick function. void trigger_tick() { static int32_t debounceTimer; static bool debouncedTriggerValue; // Current state actions switch (trigger_state) { case wait_for_change_st: break; case wait_till_steady_st: debounceTimer++; //printf("%d\r\n", debounceTimer); break; } bool currentTriggerValue = triggerPressed(); // State transition switch (trigger_state) { case wait_for_change_st: // printf("%d, %d, %d\r\n", debouncedTriggerValue, currentTriggerValue, enabled); if(debouncedTriggerValue != currentTriggerValue && enabled) { // printf("changed\n"); debounceTimer = 0; trigger_state = wait_till_steady_st; } break; case wait_till_steady_st: if(debouncedTriggerValue == currentTriggerValue) { trigger_state = wait_for_change_st; } else if(debounceTimer >= 5000) //DEBOUNCE_DURATION) { debouncedTriggerValue = currentTriggerValue; if(debouncedTriggerValue && !triggerLockoutTimer_running() && !hitLedTimer_running()) { transmitter_run(); triggerLockoutTimer_start(); } trigger_state = wait_for_change_st; } break; } } // Performs test of the hitLedTimer void trigger_runTest() { trigger_init(); trigger_enable(); transmitter_init(); buttons_init(); triggerLockoutTimer_init(); switches_init(); mio_init(true); transmitter_setFrequencyNumber(switches_read()); printf("Transmitter frequency is set to the switch frequency. Press trigger to test, button 1 to exit\r\n"); u32 privateTimerTicksPerSecond = interrupts_getPrivateTimerTicksPerSecond(); leds_init(true); interrupts_initAll(true); interrupts_enableTimerGlobalInts(); interrupts_startArmPrivateTimer(); interrupts_enableSysMonGlobalInts(); interrupts_enableArmInts(); while (true) { if (interrupts_isrFlagGlobal) { interrupts_isrFlagGlobal = 0; if(buttons_read() & 0x2) { printf("Exiting\r\n"); break; } } } interrupts_disableArmInts(); }
C
#include "circularLinkedList.h" void printfNodeList(Node* list); int main() { Node* list = NULL; Node* currentNode = NULL; Node* newNode = NULL; /* 5 ߰*/ for (int i = 0; i < 5; i++) { newNode = createNode(i); //i ο 带 appendNode(&list, newNode); // 带 list ߰ } /*Ʈ */ printfNodeList(list); //Ʈ ° 忡 ο 带 printf("\ninsert newNode after thrid node...\n\n"); currentNode = getNodeAt(list, 2); //° ִ ȯ newNode = createNode(3000); //3000 ο 带 insertAfter(currentNode, newNode); //° ڿ newNode /*Ʈ */ printfNodeList(list); /* Ʈ ̺ 2踸ŭ ȯ ũƮ Ʈ Ȯ*/ printf("\ndouble print..\n\n"); for (int i = 0; i < getNodeCount(list) * 2; i++) { currentNode = getNodeAt(list, i); //list i° ġ 带 ´ printf("list[%d] : %d\n", i, currentNode->data); } /*ù° */ printf("\nremove first node...\n\n"); currentNode = getNodeAt(list, 0); removeNode(&list, currentNode); destoryNode(currentNode); printfNodeList(list); /*ι° */ printf("\nremove second node...\n\n"); currentNode = getNodeAt(list, 1); removeNode(&list, currentNode); destoryNode(currentNode); printfNodeList(list); /* */ printf("\ndestroy all nodes..\n"); int count = getNodeCount(list); //list for (int i = 0; i < count; i++) { currentNode = getNodeAt(list, i); //list i° ġ 带 ´ if (currentNode != NULL) { removeNode(&list, currentNode); //list destoryNode(currentNode); //ش ޸ } } return 0; } void printfNodeList(Node* list) { Node* currentNode = NULL; int count = getNodeCount(list); //list for (int i = 0; i < count; i++) { currentNode = getNodeAt(list, i); //list i° ġ 带 ´ printf("list[%d] : %d\n", i, currentNode->data); } }
C
// Functions to read a network stored in a GML file into a NETWORK struct // // Mark Newman 11 AUG 06 // // To use this software, #include "readgml.h" at the head of your program // and then call the following. // // Function calls: // int read_network(NETWORK *network, FILE *stream) // -- Reads a network from the FILE pointed to by "stream" into the // structure "network". For the format of NETWORK structs see file // "network.h". Returns 0 if read was successful. // void free_network(NETWORK *network) // -- Destroys a NETWORK struct again, freeing up the memory // Inclusions #include <stdlib.h> #include <stdio.h> #include <string.h> #include "network.h" // Constants #define LINELENGTH 1000 // Types typedef struct line { char *str; struct line *ptr; } LINE; // Globals LINE *first; LINE *current; // Function to read one line from a specified stream. Return value is // 1 if an EOF was encountered. Otherwise 0. int read_line(FILE *stream, char line[LINELENGTH]) { if (fgets(line,LINELENGTH,stream)==NULL) return 1; line[strlen(line)-1] = '\0'; // Erase the terminating NEWLINE return 0; } // Function to read in the whole file into a linked-list buffer, so that we // can do several passes on it, as required to read the GML format // efficiently int fill_buffer(FILE *stream) { int length; char line[LINELENGTH]; LINE *previous; if (read_line(stream,line)!=0) { first = NULL; // Indicates empty buffer return 1; } length = strlen(line) + 1; first = malloc(sizeof(LINE)); first->str = malloc(length*sizeof(char)); strcpy(first->str,line); previous = first; while (read_line(stream,line)==0) { length = strlen(line) + 1; previous->ptr = malloc(sizeof(LINE)); previous = previous->ptr; previous->str = malloc(length*sizeof(char)); strcpy(previous->str,line); } previous->ptr = NULL; // Indicates last line return 0; } // Function to free up the buffer again void free_buffer() { LINE *thisptr; LINE *nextptr; thisptr = first; while (thisptr!=NULL) { nextptr = thisptr->ptr; free(thisptr->str); free(thisptr); thisptr = nextptr; } } // Function to reset to the start of the buffer again void reset_buffer() { current = first; } // Function to get the next line in the buffer. Returns 0 if there was // a line or 1 if we've reached the end of the buffer. int next_line(char line[LINELENGTH]) { if (current==NULL) return 1; strcpy(line,current->str); current = current->ptr; return 0; } // Function to establish whether the network read from a given stream is // directed or not. Returns 1 for a directed network, and 0 otherwise. If // the GML file contains no "directed" line then the graph is assumed to be // undirected, which is the GML default behavior. int is_directed() { int result=0; char *ptr; char line[LINELENGTH]; reset_buffer(); while (next_line(line)==0) { ptr = strstr(line,"directed"); if (ptr==NULL) continue; sscanf(ptr,"directed %i",&result); break; } return result; } // Function to count the vertices in a GML file. Returns number of vertices. int count_vertices() { int result=0; char *ptr; char line[LINELENGTH]; reset_buffer(); while (next_line(line)==0) { ptr = strstr(line,"node"); if (ptr!=NULL) result++; } return result; } // Function to compare the IDs of two vertices int cmpid(VERTEX *v1p, VERTEX *v2p) { if (v1p->id>v2p->id) return 1; if (v1p->id<v2p->id) return -1; return 0; } // Function to allocate space for a network structure stored in a GML file // and determine the parameters (id, label) of each of the vertices. void create_network(NETWORK *network) { int i; int length; char *ptr; char *start,*stop; char line[LINELENGTH]; char label[LINELENGTH]; // Determine whether the network is directed network->directed = is_directed(); // Count the vertices network->nvertices = count_vertices(); // Make space for the vertices network->vertex = calloc(network->nvertices,sizeof(VERTEX)); // Go through the file reading the details of each vertex one by one reset_buffer(); for (i=0; i<network->nvertices; i++) { // Skip to next "node" entry do { next_line(line); } while (strstr(line,"node")==NULL); // Read in the details of this vertex do { // Look for ID ptr = strstr(line,"id"); if (ptr!=NULL) sscanf(ptr,"id %i",&network->vertex[i].id); // Look for label ptr = (strstr(line,"label")); if (ptr!=NULL) { start = strchr(line,'"'); if (start==NULL) { sscanf(ptr,"label %s",&label); } else { stop = strchr(++start,'"'); if (stop==NULL) length = strlen(line) - (start-line); else length = stop - start; strncpy(label,start,length); label[length] = '\0'; network->vertex[i].label = malloc((length+1)*sizeof(char)); strcpy(network->vertex[i].label,label); } } // If we see a closing square bracket we are done if (strstr(line,"]")!=NULL) break; } while (next_line(line)==0); } // Sort the vertices in increasing order of their IDs so we can find them // quickly later qsort(network->vertex,network->nvertices,sizeof(VERTEX),(void*)cmpid); } // Function to find a vertex with a specified ID using binary search. // Returns the element in the vertex[] array holding the vertex in question, // or -1 if no vertex was found. int find_vertex(int id, NETWORK *network) { int top,bottom,split; int idsplit; top = network->nvertices; if (top<1) return -1; bottom = 0; split = top/2; do { idsplit = network->vertex[split].id; if (id>idsplit) { bottom = split + 1; split = (top+bottom)/2; } else if (id<idsplit) { top = split; split = (top+bottom)/2; } else return split; } while (top>bottom); return -1; } // Function to determine the degrees of all the vertices by going through // the edge data void get_degrees(NETWORK *network) { int s,t; int vs,vt; char *ptr; char line[LINELENGTH]; reset_buffer(); while (next_line(line)==0) { // Find the next edge entry ptr = strstr(line,"edge"); if (ptr==NULL) continue; // Read the source and target of the edge s = t = -1; do { ptr = strstr(line,"source"); if (ptr!=NULL) sscanf(ptr,"source %i",&s); ptr = strstr(line,"target"); if (ptr!=NULL) sscanf(ptr,"target %i",&t); // If we see a closing square bracket we are done if (strstr(line,"]")!=NULL) break; } while (next_line(line)==0); // Increment the degrees of the appropriate vertex or vertices if ((s>=0)&&(t>=0)) { vs = find_vertex(s,network); network->vertex[vs].degree++; if (network->directed==0) { vt = find_vertex(t,network); network->vertex[vt].degree++; } } } return; } // Function to read in the edges void read_edges(NETWORK *network) { int i; int s,t; int vs,vt; int *count; double w; char *ptr; char line[LINELENGTH]; // Malloc space for the edges and temporary space for the edge counts // at each vertex for (i=0; i<network->nvertices; i++) { network->vertex[i].edge = malloc(network->vertex[i].degree*sizeof(EDGE)); } count = calloc(network->nvertices,sizeof(int)); // Read in the data reset_buffer(); while (next_line(line)==0) { // Find the next edge entry ptr = strstr(line,"edge"); if (ptr==NULL) continue; // Read the source and target of the edge and the edge weight s = t = -1; w = 1.0; do { ptr = strstr(line,"source"); if (ptr!=NULL) sscanf(ptr,"source %i",&s); ptr = strstr(line,"target"); if (ptr!=NULL) sscanf(ptr,"target %i",&t); ptr = strstr(line,"value"); if (ptr!=NULL) sscanf(ptr,"value %lf",&w); // If we see a closing square bracket we are done if (strstr(line,"]")!=NULL) break; } while (next_line(line)==0); // Add these edges to the appropriate vertices if ((s>=0)&&(t>=0)) { vs = find_vertex(s,network); vt = find_vertex(t,network); network->vertex[vs].edge[count[vs]].target = vt; network->vertex[vs].edge[count[vs]].weight = w; count[vs]++; if (network->directed==0) { network->vertex[vt].edge[count[vt]].target = vs; network->vertex[vt].edge[count[vt]].weight = w; count[vt]++; } } } free(count); return; } // Function to read a complete network int read_network(NETWORK *network, FILE *stream) { fill_buffer(stream); create_network(network); get_degrees(network); read_edges(network); free_buffer(); return 0; } // Function to free the memory used by a network again void free_network(NETWORK *network) { int i; for (i=0; i<network->nvertices; i++) { free(network->vertex[i].edge); free(network->vertex[i].label); } free(network->vertex); }
C
#include <stdio.h> int main() { int i, counter = 0; float R[5], arith_mean = 0; for(i=0; i<5; i++) { printf("R[%d] = ", i); scanf("%f", &R[i]); } for(i=0;i<5;i++) { if(R[i]>0) { counter++; arith_mean+=R[i]; } } getchar(); getchar(); arith_mean = arith_mean/counter; printf("counter = %d, arith_mean = %f", counter, arith_mean); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define BLACK 0 #define RED 1 typedef struct N{ int chave; int color; // 0=Black & 1=RED struct N * left; struct N * right; struct N * parent; } Node; void add(Node ** arvore,Node *novo); Node * createNode(); void imprimir(Node **arvore,int b); Node *grandeparent(Node *arvore); Node *uncle(Node *arvore); void insert_case1(Node *arvore); void insert_case2(Node *arvore); void insert_case3(Node *arvore); void insert_case4(Node *arvore); void insert_case5(Node *arvore); void rotate_left(Node *arvore); void rotate_right(Node *arvore); int main(){ Node *arvore; int escolha; arvore = NULL; do{ printf("1- Adicionar\n2-Imprimir\n3-Remover\n4-Sair\n---> "); scanf("%d",&escolha); switch(escolha){ case 1: add(&arvore,createNode()); // if(arvore->left == NULL && arvore->right == NULL){ // arvore->color = BLACK; // } // if(arvore->left != NULL){ // insert_case1(arvore->left); // } // if(arvore->right != NULL){ // insert_case1(arvore->right); // } break; case 2: imprimir(&arvore,1); break; case 3: break; } }while(escolha != 0); } void rotate_left(Node *arvore){ Node *aux; aux = arvore->right; arvore->right = arvore->left; arvore->left = arvore; arvore = aux; } void rotate_right(Node *arvore){ Node *aux; aux = arvore->left; arvore->left = arvore->right; arvore->right = arvore; arvore = aux; } void insert_case1(Node *arvore){ if(arvore->parent == NULL){ arvore->color = BLACK; }else{ insert_case2(arvore); } } void insert_case2(Node *arvore){ if(arvore->parent->color == BLACK) return; insert_case3(arvore); } void insert_case3(Node *arvore){ Node *u = uncle(arvore),*g; if(u != NULL && u->color == RED){ arvore->parent->color = BLACK; u->color = BLACK; g = grandeparent(arvore); g->color = RED; insert_case1(g); }else{ insert_case4(arvore); } } void insert_case4(Node *arvore){ Node *g = grandeparent(arvore); if(arvore == arvore->parent->right && arvore->parent == g->left){ rotate_left(arvore->left); arvore = arvore->left; }else if(arvore == arvore->parent->left && arvore->parent == g->right){ rotate_right(arvore->parent); arvore = arvore->right; } insert_case5(arvore); } void insert_case5(Node *arvore){ Node *g = grandeparent(arvore); arvore->parent->color = BLACK; g->color = RED; if(arvore == arvore->parent->left && arvore->parent == g->left){ rotate_right(g); }else{ rotate_left(g); } } Node *grandeparent(Node *arvore){ if(arvore != NULL && arvore->parent != NULL) return arvore->parent->parent; return NULL; } Node *uncle(Node *arvore){ Node *g = grandeparent(arvore); if(g == NULL) return NULL; if(arvore->parent == g->left) return g->right; return g->left; } void imprimir(Node **arvore,int b){ int i; if(*arvore == NULL){ for(i=0;i<b;i++){ printf(" "); } printf("*\n"); return; } imprimir(&(*arvore)->left,b+1); for(i=0;i<b;i++){ printf(" "); } printf("%d (%s)\n",(*arvore)->chave, (*arvore)->color == BLACK ? "BLACK" : "RED"); imprimir(&(*arvore)->right,b+1); } Node* createNode(){ Node *novo = malloc(sizeof(Node)); scanf("%d",&novo->chave); novo->color = 3; novo->left = NULL; novo->left = NULL; novo->parent = NULL; return novo; } void add(Node ** arvore, Node *novo){ if(*arvore == NULL){ *arvore = novo; return; } if((*arvore)->chave < novo->chave){ if((*arvore)->left != NULL){ add(&(*arvore)->left,novo); }else{ novo->parent = *arvore; (*arvore)->left = novo; return; } } if((*arvore)->chave > novo->chave){ if((*arvore)->right != NULL){ add(&(*arvore)->right,novo); }else{ novo->parent = *arvore; (*arvore)->right = novo; return; } } if(*arvore != NULL && (*arvore)->parent != NULL && (*arvore)->parent->parent != NULL ) insert_case1(*arvore); }
C
#include"OW.h" void ad_menu()//Ա˵ { int mark=1; for( ; mark==1; ) { switch(s_ad_menu()) { case 1:ad_brand();break; case 2:ad_order();break; case 3:ad_user();break; case 9:mark=0;break; case 0:quit();break; default :printf("\n\t\t\t\tr(sntq IJڣ,س....");getchar();getchar(); } } } int s_ad_menu()//Ա˵ѡ { int choice=-1; // while(choice!=0) // { system("cls");// printf("\t\t\t\t\t*************************************\n\n"); printf("\t\t\t\t\t** >>>ˮϵͳ<<< *\n\n"); printf("\t\t\t\t\t** λ:˵->Ա˵ **\n\n"); printf("\t\t\t\t\t** Ա %s,ӭ **\n\n",records[u_i].name); printf("\t\t\t\t\t** 1.ƷϢ **\n\n"); printf("\t\t\t\t\t** 2.Ϣ **\n\n"); printf("\t\t\t\t\t** 3.ûϢ **\n\n"); printf("\t\t\t\t\t** 9.˳¼ **\n\n"); printf("\t\t\t\t\t** 0.˳ **\n\n"); printf("\t\t\t\t\t*************************************\n\n"); printf("\t\t\t\t\t** ֽв>>"); scanf("%d",&choice); return choice; // } }
C
#include <stdio.h> #include <stdlib.h> int main() { int i,j; for (i=1;i<=7;i++) { printf("Looping yang ke %d\n",i); for (j=1;j<=10;j++) { printf("-angka %d-\n",j); } } return 0; }
C
#include <SDL/SDL.h> #include <GL/gl.h> #include <GL/glu.h> #include <stdlib.h> #include <stdio.h> /* Dimensions de la fenêtre */ static unsigned int WINDOW_WIDTH = 800; static unsigned int WINDOW_HEIGHT = 600; /* Nombre de bits par pixel de la fenêtre */ static const unsigned int BIT_PER_PIXEL = 32; /* Nombre minimal de millisecondes separant le rendu de deux images */ static const Uint32 FRAMERATE_MILLISECONDS = 1000 / 60; /* Couleurs de dessins possibles */ static const int COULEURS[][3] = { {255, 255, 255}, {239, 239, 239}, {206, 206, 206}, {100, 100, 100}, {0, 0, 0}, {173, 57, 14}, {30, 127, 203}, {127, 221, 76}, {167, 103, 38}, {136, 77, 167} }; /* Nombre de couleurs */ static const unsigned int NB_COULEURS = sizeof (COULEURS) / (3 * sizeof (int)); typedef struct Point { float x, y; /* Position 2D du point */ unsigned char r, g, b; /* Couleur du point */ struct Point* next; /* Point suivant à dessiner */ } Point, *PointList; typedef struct Primitive { GLenum primitiveType; PointList points; struct Primitive* next; } Primitive, *PrimitiveList; void selectColorView() { int i; glBegin(GL_QUADS); for (i = 0; i < NB_COULEURS; ++i) { glColor3ub(COULEURS[i][0], COULEURS[i][1], COULEURS[i][2]); if (i % 2 == 0) { glVertex2f(-1 + i * 2.f / NB_COULEURS, 1); glVertex2f(-1 + (i + 2) * 2.f / NB_COULEURS, 1); glVertex2f(-1 + (i + 2) * 2.f / NB_COULEURS, 0); glVertex2f(-1 + i * 2.f / NB_COULEURS, 0); } else { glVertex2f(-1 + (i - 1) * 2.f / NB_COULEURS, -1); glVertex2f(-1 + (i + 1) * 2.f / NB_COULEURS, -1); glVertex2f(-1 + (i + 1) * 2.f / NB_COULEURS, 0); glVertex2f(-1 + (i - 1) * 2.f / NB_COULEURS, 0); } } glEnd(); } Point* allocPoint(float x, float y, unsigned char r, unsigned char g, unsigned char b) { Point* point = (Point*) malloc(sizeof (point)); if (!point) { printf("Memory run out\n"); exit(1); } point->x = x; point->y = y; point->r = r; point->g = g; point->b = b; point->next = NULL; return point; } Primitive* allocPrimitive(GLenum primitiveType) { Primitive* primitive = (Primitive*) malloc(sizeof (primitive)); if (!primitive) { printf("Memory run out\n"); exit(1); } primitive->primitiveType = primitiveType; primitive->points = NULL; primitive->next = NULL; return primitive; } /* * Ajoute un point au début de la liste * Les points seront ainsi trier par ordre d'apparition */ void addPointToList(Point* point, PointList* list) { if (*list != NULL) { addPointToList(point, &(*list)->next); } else { *list = point; } } /* * Ajoute une primitive en fin de liste * Les primitives seront ainsi trier par ordre d'apparition (les plus récents "écrasent" les autres) */ void addPrimitive(Primitive* primitive, PrimitiveList* list) { if (*list != NULL) { addPrimitive(primitive, &(*list)->next); } else { *list = primitive; } } /* * Renvoie la primitive courante (dernière de la liste) */ PrimitiveList findLastPrimitive(PrimitiveList list) { while (list->next != NULL) { list = list->next; } return list; } void drawPoints(PointList list) { while (list != NULL) { glColor3ub(list->r, list->g, list->b); glVertex2f(list->x, list->y); list = list->next; } } void drawPrimitives(PrimitiveList list) { while (list != NULL) { glBegin(list->primitiveType); drawPoints(list->points); glEnd(); list = list->next; } } void deletePoints(PointList* list) { while (*list != NULL) { Point* nextPoint = (*list)->next; free(*list); *list = nextPoint; } } void deletePrimitives(PrimitiveList* list) { while (*list != NULL) { Primitive* next = (*list)->next; deletePoints(&(*list)->points); free(*list); *list = next; } } int main(int argc, char** argv) { int couleurActu = 4; /* numéro de la couleur par defaut */ char mode = 0; /* Mode de dessin = 0, choix couleur =1 */ PrimitiveList primitiveLst = NULL; addPrimitive(allocPrimitive(GL_POINTS), &primitiveLst); Point *tmpPoint = NULL; /* Initialisation de la SDL */ if (-1 == SDL_Init(SDL_INIT_VIDEO)) { fprintf(stderr, "Impossible d'initialiser la SDL. Fin du programme.\n"); return EXIT_FAILURE; } /* Désactivation du double buffering SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0);*/ /* Ouverture d'une fenêtre et création d'un contexte OpenGL */ if (NULL == SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, BIT_PER_PIXEL, SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_RESIZABLE)) { fprintf(stderr, "Impossible d'ouvrir la fenetre. Fin du programme.\n"); return EXIT_FAILURE; } /* Titre de la fenêtre */ SDL_WM_SetCaption("Paint", NULL); /* Boucle d'affichage */ int loop = 1; while (loop) { /* Récupération du temps au début de la boucle */ Uint32 startTime = SDL_GetTicks(); glClearColor(1, 1, 1, 1); glClear(GL_COLOR_BUFFER_BIT); if (mode == 1) { selectColorView(); } else { drawPrimitives(primitiveLst); } /* Echange du front et du back buffer : mise à jour de la fenêtre */ SDL_GL_SwapBuffers(); /* Boucle traitant les evenements */ SDL_Event e; while (SDL_PollEvent(&e)) { /* L'utilisateur ferme la fenêtre : */ if (e.type == SDL_QUIT) { loop = 0; break; } /* Quelques exemples de traitement d'evenements : */ switch (e.type) { /*On redimensionne le viewport*/ case SDL_VIDEORESIZE: WINDOW_WIDTH = e.resize.w; WINDOW_HEIGHT = e.resize.h; glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT); glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluOrtho2D(-1., 1., -1., 1.); SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, BIT_PER_PIXEL, SDL_OPENGL | SDL_GL_DOUBLEBUFFER | SDL_RESIZABLE); /* FIX ME - Écran en partie noir pendant le redimensionnement */ break; /* Clic souris */ case SDL_MOUSEBUTTONUP: /* glClearColor((e.button.x/255)%255,((e.button.y/255)%255),0,1); */ if (mode == 1) { couleurActu = 2 * (int) (e.button.x / (WINDOW_WIDTH * 2 / NB_COULEURS)); if (e.button.y >= WINDOW_HEIGHT / 2) { couleurActu++; } } else { tmpPoint = allocPoint(-1 + 2. * e.button.x / WINDOW_WIDTH, -(-1 + 2. * e.button.y / WINDOW_HEIGHT), COULEURS[couleurActu][0], COULEURS[couleurActu][1], COULEURS[couleurActu][2]); addPointToList(tmpPoint, &(findLastPrimitive(primitiveLst))->points); } break; /* Mouvement de souris */ case SDL_MOUSEMOTION: /* glClearColor((e.button.x%255)/255.0,((e.button.y%255)/255.0),0,1); */ break; /* Touche clavier */ case SDL_KEYUP: /* printf("touche pressée (code = %d)\n", e.key.keysym.sym); */ if (e.key.keysym.sym == SDLK_SPACE) { mode = 0; } else { switch (e.key.keysym.sym) { case SDLK_p: addPrimitive(allocPrimitive(GL_POINTS), &primitiveLst); break; case SDLK_l: addPrimitive(allocPrimitive(GL_LINES), &primitiveLst); break; case SDLK_t: addPrimitive(allocPrimitive(GL_TRIANGLES), &primitiveLst); break; case SDLK_c: addPrimitive(allocPrimitive(GL_QUADS), &primitiveLst); break; case SDLK_q: loop = 0; break; default: break; } } break; case SDL_KEYDOWN: if (e.key.keysym.sym == SDLK_SPACE) { mode = 1; } break; default: break; } } /* Calcul du temps écoulé */ Uint32 elapsedTime = SDL_GetTicks() - startTime; /* Si trop peu de temps s'est écoulé, on met en pause le programme */ if (elapsedTime < FRAMERATE_MILLISECONDS) { SDL_Delay(FRAMERATE_MILLISECONDS - elapsedTime); } } deletePrimitives(&primitiveLst); /* Liberation des ressources associées à la SDL */ SDL_Quit(); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> int main_child(int __attribute__((unused)) ac, char **av) { char hdr[80]; const char * bin = strrchr(av[0], '/'); snprintf(hdr, sizeof hdr, "%s[%d]", (bin != NULL) ? (bin + 1) : av[0], getpid()); printf("%s: Starting\n", hdr); fprintf(stderr, "%s: This is an error\n", hdr); printf("%s: Done\n", hdr); return 0; } int main_mother(int __attribute__((unused)) ac, char **av) { char hdr[80]; int fd[2]; pid_t pid; const char * bin = strrchr(av[0], '/'); snprintf(hdr, sizeof hdr, "%s[%d]", (bin != NULL) ? (bin + 1) : av[0], getpid()); printf("%s: Starting\n", hdr); if (pipe(fd) < 0) { fprintf(stderr, "%s: Failed to get stdout pipe : %m\n", hdr); goto err; } #ifdef F_GETPIPE_SZ printf("%s: pipe_in = <%d>, pipe_out = <%d>\n", hdr, fcntl(fd[0], F_GETPIPE_SZ), fcntl(fd[1], F_GETPIPE_SZ)); #endif pid = fork(); if (pid < 0) { fprintf(stderr, "%s: Failed to fork : %m\n", hdr); goto close_err; } if (pid == 0) { close(fd[0]); if (dup2(fd[1], STDOUT_FILENO) < 0) fprintf(stderr, "%s: Failed to set STDOUT_FILENO to pipe : %m\n", hdr); if (dup2(fd[1], STDERR_FILENO) < 0) fprintf(stderr, "%s: Failed to set STDERR_FILENO to pipe : %m\n", hdr); execl("./"CHILD_NAME, "./"CHILD_NAME, NULL); fprintf(stderr, "%s: Failed to execute <%s> : %m\n", hdr, CHILD_NAME); close(fd[1]); goto err; } close(fd[1]); for (;;) { char buff[1024]; ssize_t s; s = read(fd[0], buff, sizeof buff - 1); if (s < 0) { fprintf(stderr, "%s: Failed to read from child : %m\n", hdr); goto close_err; } if (s == 0) break; buff[s] = 0; printf("%s: stdout <%s>\n", hdr, buff); } close(fd[0]); close(fd[1]); return 0; close_err: close(fd[0]); close(fd[1]); err: return EXIT_FAILURE; } int main(int ac, char **av) { char * bin; bin = strrchr(av[0], '/'); if (bin == NULL) bin = av[0]; else bin ++; if (strcmp(bin, CHILD_NAME) == 0) exit(main_child(ac, av)); if (strcmp(bin, MOTHER_NAME) == 0) exit(main_mother(ac, av)); fprintf(stderr, "<%s> should be <mother> or <child>\n", bin); return 1; }
C
#include<math.h> #include<stdio.h> int main() { int x,y,r,p; printf("Enter cartesian values for x and y\n"); scanf ("%d%d",&x,&y); r= sqrt(x*x+y*y); p=tan(y/x); printf ("the polar coordinates of x and y are\n (%d,%d)",r,p); return 0; }
C
#include<stdio.h> #include<stdlib.h> char* copy(char* str); int compare(char* str, char* fstr); char* attend(char* str, char* fstr); int main() { char* str = (char*)malloc(sizeof(char)); char* cstr = (char*)malloc(sizeof(char)); printf("Please type two string."); scanf("%s", str); scanf("%s", cstr); char* new = attend(str, cstr); printf("copy over\n"); printf("%s\n", new); } char* copy(char* str) { return str; } int compare(char* str, char* fstr) { int i = 0; int over = 1; for(i=0;str[i]&&over&&fstr[i];i++) { if(str[i]==fstr[i]) { printf("letter %d of them is the same.\n", i+1); }else { over = 0; printf("they are not the same."); } } return 0; } char* attend(char* str, char* fstr) { char* new = (char*)malloc(sizeof(char)); int i = 0; int n = 0; for(i=0;str[i];i++) { new[i] = str[i]; } for(n=0;fstr[n];n++) { new[i+n] = fstr[n]; } return new; }
C
// creating a function to print the square of the given number. #include<stdio.h> int sqr(int a); int main() { printf("Enter the nuber: "); int a; scanf("%i",&a); int result=sqr(a); printf("%i",result); } int sqr(int a) { int c = a*a; return c; }
C
#include<stdio.h> void main(){ int i=97; int counter=0; for(;i<=122;){ printf("%c=%d\n",i,counter); counter++; } }
C
#include<stdio.h> #include<math.h> int digit(); int sumofdigit(); int factor(); int sumoffactor(); main() { int n,sum1,sum2; printf("Enter number:"); scanf("%d",&n); sumofdigit(n); // sum1=sumofdigit(); //sum2=sumoffactor(); // if(sum1==sum2) // { // printf("\n%d is Smith number.",&n); // } // else // printf("\n%d is not Smith number.",&n); } int sumofdigit(int num) { int reminder, sum; for(sum==0;num>0;num=num/10) { reminder=num%10; sum=sum+reminder; } return sum; } int
C
#include <stdio.h> #include <stdlib.h> #include <string.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ /*2) Uma string uma palavra se no contiver caracteres em branco. Dado um texto como entrada no teclado: a. Determinar a maior palavra e imprimi-la. b. Classificar as palavras em 3 classes e determinar a frequncia absoluta de ocorrncia delas em cada classe. Cada classe ser criada de acordo com o tamanho das palavras, da seguinte forma: classe 1 vai de 0 a 3 caracteres na palavra; classe 2 vai de 4 a 6 caracteres; e classe 3 a partir de 7 caracteres na palavra. Aps, imprimir a ocorrncia da seguinte forma: Classe das palavras Frequncia 0 --- 3 10 4 --- 6 8 A partir de 7 (7 ou mais) 12 OBS.: O tamanho da varivel que recebe os caracteres do teclado deve ser de 200, mas, para teste utilizar um valor menor. */ void maiorPalavra(char frase[]){ char temp[200], maior[200]; int i, j = 0; for(i = 0; i <= strlen(frase); i++){ if (i == 0){ for(i = 0; i <= strlen(frase); i++){ if (frase[i] != ' '){ maior[i] = frase[i]; } else{ break; } } } else{ if (frase[i] != ' '){ temp[j++] = frase[i]; } else{ if(strlen(temp) > strlen(maior)){ strcpy(maior, temp); } j = 0; } } } if(strlen(temp) > strlen(maior)){ strcpy(maior, temp); } printf("A maior palavra do texto digitado foi :%s\n", maior); } void classe(char frase[]){ int i, contador = 0, pequena = 0, media = 0, grande = 0; for(i = 0; i <= strlen(frase); i++){ if (frase[i] != ' '){ contador += 1; } else{ if (contador >= 0 && contador <= 3){ pequena += 1; } else if (contador > 3 && contador <=6){ media += 1; } else{ grande += 1; } contador = 0; } } if (contador >= 0 && contador <= 3){ pequena += 1; } else if (contador > 3 && contador <=6){ media += 1; } else{ grande += 1; } printf("Classe das palavras \t\tFrequencia\n0 --- 3 \t\t\t%d\n4 --- 6 \t\t\t%d\nA partir de 7(7 ou mais) \t%d\n", pequena, media, grande); } int main(int argc, char *argv[]) { char texto[200]; printf("Digite um texto :\n"); gets(texto); maiorPalavra(texto); classe(texto); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "netsys.h" #include "netprint.h" #include "netsocket.h" #define NETSOCKET_THREAD_PRIORITY (30) static void _NetSocketThread(NetSocketT *pSocket) { // NetPrintf( "NetSocket: thread started (%d)\n", pSocket->socket ); if (pSocket->pWriteFunc) { // call write callback pSocket->pWriteFunc(pSocket, pSocket->pUserData); } while(pSocket->status!=NETSOCKET_STATUS_DISCONNECTING) { if (pSocket->pReadFunc) { // call read callback pSocket->pReadFunc(pSocket, pSocket->pUserData); } else { break; } } // call abort callback if (pSocket->pAbortFunc) { pSocket->pAbortFunc(pSocket, pSocket->pUserData); } // NetPrintf( "NetSocket: thread end %d\n" , pSocket->socket); // invalidate socket pSocket->socket = INVALID_SOCKET; // invalidate thread pSocket->threadid = NETSYS_THREAD_INVALID; pSocket->status = NETSOCKET_STATUS_INVALID; } void NetSocketNew(NetSocketT *pSocket, void *pUserData) { pSocket->threadid = NETSYS_THREAD_INVALID; pSocket->status = NETSOCKET_STATUS_INVALID; pSocket->socket = INVALID_SOCKET; pSocket->pUserData = pUserData; pSocket->pReadFunc = NULL; pSocket->pWriteFunc = NULL; pSocket->pAbortFunc = NULL; } void NetSocketDelete(NetSocketT *pSocket) { NetSocketDisconnect(pSocket); } void NetSocketCopy(NetSocketT *pDest, NetSocketT *pSrc) { pDest->status = pSrc->status; pDest->socket = pSrc->socket; pDest->PeerAddr = pSrc->PeerAddr; } void NetSocketSetFunc(NetSocketT *pSocket, NetSocketFuncT pReadFunc, NetSocketFuncT pWriteFunc, NetSocketFuncT pAbortFunc) { pSocket->pReadFunc = pReadFunc; pSocket->pWriteFunc = pWriteFunc; pSocket->pAbortFunc = pAbortFunc; } int NetSocketAccept(NetSocketT *pListen, NetSocketT *pAccept) { int clntLen; clntLen = sizeof(pAccept->PeerAddr); pAccept->socket = accept( pListen->socket, (struct sockaddr *)&pAccept->PeerAddr, &clntLen ); if (pAccept->socket < 0) { NetPrintf("NetSocket: Failed to accept!\n"); NetSocketDisconnect(pListen); return -3; } pAccept->status = NETSOCKET_STATUS_CONNECTED; return 0; } int NetSocketProcess(NetSocketT *pSocket) { pSocket->threadid = NetSysThreadStart(_NetSocketThread, NETSOCKET_THREAD_PRIORITY, pSocket); if (pSocket->threadid <= 0) { NetPrintf("NetSocket: Failed to start socket thread!\n"); closesocket(pSocket->socket); pSocket->status = NETSOCKET_STATUS_INVALID; return -4; } return 0; } int NetSocketListen(NetSocketT *pSocket, int port) { struct sockaddr_in ListenAddr; int rc; // create socket pSocket->socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); if (pSocket->socket < 0) { NetPrintf( "NetSocket: Failed to create socket\n" ); return -1; } memset( &ListenAddr, 0 , sizeof(ListenAddr)); ListenAddr.sin_family = AF_INET; ListenAddr.sin_addr.s_addr = htonl(INADDR_ANY); ListenAddr.sin_port = htons(port); rc = bind( pSocket->socket, (struct sockaddr *) &ListenAddr, sizeof( ListenAddr) ); if ( rc < 0 ) { NetPrintf( "NetSocket: Socket failed to bind.\n" ); closesocket(pSocket->socket); return -3; } // NetPrintf( "NetSocket: bind returned %i port %d\n",rc, port ); rc = listen( pSocket->socket, 2 ); if ( rc < 0 ) { NetPrintf( "NetSocket: listen failed.\n" ); closesocket(pSocket->socket); return -4; } // NetPrintf( "NetSocket: listen returned %i\n", rc ); // create servering thread pSocket->status = NETSOCKET_STATUS_LISTENING; return NetSocketProcess(pSocket); } int NetSocketBindUDP(NetSocketT *pSocket, int port) { struct sockaddr_in ListenAddr; int rc; // create socket pSocket->socket = socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP ); if (pSocket->socket < 0) { NetPrintf( "NetSocket: Failed to create socket\n" ); return -1; } memset( &ListenAddr, 0 , sizeof(ListenAddr)); ListenAddr.sin_family = AF_INET; ListenAddr.sin_addr.s_addr = htonl(INADDR_ANY); ListenAddr.sin_port = htons(port); rc = bind( pSocket->socket, (struct sockaddr *) &ListenAddr, sizeof( ListenAddr) ); if ( rc < 0 ) { NetPrintf( "NetSocket: Socket failed to bind.\n" ); closesocket(pSocket->socket); return -3; } // NetPrintf( "NetSocket: bind returned %i port %d\n",rc, port ); // create servering thread pSocket->status = NETSOCKET_STATUS_LISTENING; return NetSocketProcess(pSocket); } static void _NetSocketConnect(NetSocketT *pSocket) { int rc; // connect /* NetPrintf("NetSocket: Connecting... %X:%d (%d)..\n", pSocket->PeerAddr.sin_addr, htons(pSocket->PeerAddr.sin_port), pSocket->socket); */ rc = connect(pSocket->socket, (struct sockaddr *)&pSocket->PeerAddr, sizeof(pSocket->PeerAddr)); if (pSocket->status==NETSOCKET_STATUS_DISCONNECTING) { NetPrintf("NetSocket: Connect aborted\n"); pSocket->status = NETSOCKET_STATUS_INVALID; if (pSocket->pAbortFunc) { // call abort callback pSocket->pAbortFunc(pSocket, pSocket->pUserData); } return; } if (rc < 0) { closesocket(pSocket->socket); NetPrintf("NetSocket: Connect failed (%d)\n", rc); pSocket->status = NETSOCKET_STATUS_INVALID; if (pSocket->pAbortFunc) { // call abort callback pSocket->pAbortFunc(pSocket, pSocket->pUserData); } return; } pSocket->status = NETSOCKET_STATUS_CONNECTED; /* NetPrintf("NetSocket: Connected! %d.%d.%d.%d:%d (%d)..\n", pSocket->PeerAddr.sin_addr[0], pSocket->PeerAddr.sin_addr[1], pSocket->PeerAddr.sin_addr[2], pSocket->PeerAddr.sin_addr[3], htons(pSocket->PeerAddr.sin_port), pSocket->socket); */ // call processing thread _NetSocketThread(pSocket); } int NetSocketConnect(NetSocketT *pSocket, unsigned ipaddr, int port) { struct sockaddr_in *addr; addr = (struct sockaddr_in *)&pSocket->PeerAddr; if (pSocket->status != NETSOCKET_STATUS_INVALID) { NetPrintf( "NetSocket: Already connected/ing...\n" ); return -1; } pSocket->status = NETSOCKET_STATUS_CONNECTING; // create socket pSocket->socket = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP ); if (pSocket->socket < 0) { NetPrintf( "NetSocket: Failed to create socket\n" ); return -1; } // set address memset( addr, 0 , sizeof(*addr)); // addr->sin_len = sizeof(*addr); addr->sin_family = AF_INET; addr->sin_addr.s_addr = ipaddr; addr->sin_port = htons(port); // create connection thread pSocket->threadid = NetSysThreadStart(_NetSocketConnect, NETSOCKET_THREAD_PRIORITY, pSocket); if (pSocket->threadid <= 0) { NetPrintf("NetSocket: Failed to start socket thread!\n"); closesocket(pSocket->socket); pSocket->status = NETSOCKET_STATUS_INVALID; return -5; } // connecting started return 0; } void NetSocketDisconnect(NetSocketT *pSocket) { // if (pSocket->status != NETSOCKET_STATUS_INVALID && pSocket->status != NETSOCKET_STATUS_DISCONNECTING && pSocket->status != NETSOCKET_STATUS_CONNECTING) if (pSocket->status == NETSOCKET_STATUS_LISTENING || pSocket->status == NETSOCKET_STATUS_CONNECTED) { pSocket->status = NETSOCKET_STATUS_DISCONNECTING; // NetPrintf("NetSocket: Disconnecting %i\n", pSocket->socket); closesocket(pSocket->socket); } } NetSocketStatusE NetSocketGetStatus(NetSocketT *pSocket) { return pSocket->status; } int NetSocketRecv(NetSocketT *pSocket, char *pBuffer, int nBytes, int flags) { int recvlen; recvlen = recv(pSocket->socket, pBuffer, nBytes, flags); if (recvlen <= 0) { NetSocketDisconnect(pSocket); return 0; } return recvlen; } int NetSocketRecvFrom(NetSocketT *pSocket, char *pBuffer, int nBytes, NetSocketAddrT *pAddr, int flags) { int recvlen; int fromlen = sizeof(*pAddr); recvlen = recvfrom(pSocket->socket, pBuffer, nBytes, flags, (struct sockaddr *)pAddr, &fromlen); if (recvlen <= 0) { NetSocketDisconnect(pSocket); return 0; } return recvlen; } int NetSocketSend(NetSocketT *pSocket, char *pBuffer, int nBytes, int flags) { return send(pSocket->socket, pBuffer, nBytes, flags); } int NetSocketSendTo(NetSocketT *pSocket, char *pBuffer, int nBytes, NetSocketAddrT *pAddr, int flags) { int result; result = sendto(pSocket->socket, pBuffer, nBytes, flags, (struct sockaddr *)pAddr, sizeof(*pAddr)); //NetPrintf("send udp %d:%08X:%d %d %d\n", pAddr->sin_family, pAddr->sin_addr, pAddr->sin_port, result, WSAGetLastError()); return result; } int NetSocketRecvBytes(NetSocketT *pSocket, char *pBuffer, int nBytes, int flags) { int nBytesRead = 0; while (nBytes > 0) { int RecvBytes; RecvBytes = NetSocketRecv(pSocket, pBuffer, nBytes, flags); if (RecvBytes <= 0) { return 0; } nBytes-=RecvBytes; nBytesRead+=RecvBytes; } // printf("NetSocket: RecvBytes %d\n", nBytesRead); return nBytesRead; } void NetSocketGetLocalAddr(NetSocketT *pSocket, NetSocketAddrT *pAddr) { int namelen = sizeof(*pAddr); getsockname(pSocket->socket, (struct sockaddr *)pAddr, &namelen); } void NetSocketGetRemoteAddr(NetSocketT *pSocket, NetSocketAddrT *pAddr) { int namelen = sizeof(*pAddr); getpeername(pSocket->socket, (struct sockaddr *)pAddr, &namelen); } int NetSocketAddrGetPort(NetSocketAddrT *pAddr) { return htons(pAddr->sin_port); } unsigned int NetSocketIpAddr(int a, int b, int c, int d) { return ((a&0xFF)<<0) | ((b&0xFF)<<8) | ((c&0xFF)<<16) | ((d&0xFF)<<24); } int NetSocketAddrIsEqual(NetSocketAddrT *pAddrA, NetSocketAddrT *pAddrB) { return (pAddrA->sin_addr == pAddrB->sin_addr) && (pAddrA->sin_port==pAddrB->sin_port); }
C
/* ** EPITECH PROJECT, 2021 ** MY STR TO WORLD ARRAY ** File description: ** NO DESCRIPTION FOUND */ #include "../../include/my.h" #include <stdlib.h> int is_char(char c, int status) { if (status == 1) { if ((c >= 65 && c <= 90) || (c >= 97 && c <= 122)) return (1); } else if (status == 2) { if (c >= 33 && c <= 126 && c != 58) return (1); } return (0); } int len(char *str) { int a = 0; int b = 0; while (str[a] != '\0'){ if (is_char(str[a], 1) == 1 && is_char(str[a + 1], 1) != 1){ b = b + 1; } a = a + 1; } return (b); } int len_of_word(char *str, int i) { while (str[i] != '\0') { if (!is_char(str[i], 1)) return (i); i++; } return (i); } char **my_str_to_word_array(char *str) { int y = len(str); char **result = malloc(sizeof(char *) * y + 1); int a = 0; int b = 0; int c = 0; while (b < y){ c = 0; result[b] = malloc(sizeof(char) * len_of_word(str, a)); while (str[a] != '\0' && is_char(str[a], 1) != 0 && str[a] != '\n') { result[b][c] = str[a]; c = c + 1; a = a + 1; } result[b][c] = '\0'; a = a + 1; b = b + 1; } return (result); }
C
#include "test_definitions.h" BeforeAll(sample_group_setup) { (void) state; /* unused */ print_message("Sample group setup performed\n"); return 0; } AfterAll(sample_group_teardown) { (void) state; /* unused */ print_message("Sample group teardown performed\n"); return 0; } static int sample_setup(void ** state) { (void) state; /* unused */ print_message("Sample setup performed\n"); return 0; } static int sample_teardown(void ** state) { (void) state; /* unused */ print_message("Sample teardown performed\n"); return 0; } UnitTest(null_test_pass) { assert_true(1); } UnitTest(null_test_setup, .setup=sample_setup) { assert_true(1); } UnitTest(null_test_teardown, .teardown=sample_teardown) { assert_true(1); } UnitTest(null_test_repeat, .repeat=3) { assert_true(1); } UnitTest(null_test_ignore, .ignore=1) { fail_msg("should have been ignored %s", __FILE__); } UnitTest(null_test_skip) { skip(); fail_msg("should have been skipped %s", __FILE__); } UnitTest(null_test_failure) { skip(); /* skipped - otherwise the build fails */ fail(); }
C
/* Creare una libreria per gestire un oggetto di tipo grafo * il grafo è composto da nodi e archi * ogni arco è connesso ad al più due nodi, ogni arco ha un costo (double) * ogni nodo è connesso a un numero variabile di archi * se un arco è connesso ad un nodo anche il nodo è connesso a quell'arco * Scrivere le seguenti funzioni: * 1. Dato un nodo ed un arco la funzione connette nodo ed arco * 2. Funzione che crea un arco e ne ritorna il puntatore * 3. Funzione che crea il nodo e ne rotorna il puntatore * 4. Funzione che dato un nodo ritorna tutti gli archi connessi * 5. Funzione che dato un nodo ritorna i nodi connessi * 6. Funzione che stampa a video per ogni nodo la lista degli archi connessi * 7. Funzione che dealloca la struttura */
C
#ifndef RL_H #define RL_H #include <math.h> #include "bits.h" /* * Implementation of run-length encoding. * 1. Get the first character c of the input string * 2. Count the consecutive occurences n of the character c * 3. Write c (CHAR_LENGTH bits) and n (COUNT_LENGTH bits) into the buffer * 4. Move the pointer to the character after the last occurence * 5. Repeat 1-4 until terminating character * * CHAR_LENGTH is calculated based on the alphabet size of the plaintext: * - CHAR_LENGTH = ceil(log_2(|alphabet| + 1)) * which is the minimum number of bits to have a bijective mapping from * the alphabet and a stopcode (0x0). * * COUNT_LENGTH is predefined (should be enough to store almost all of the run lengths) * * Sample resulting encoded buffer: * - Alphabet: a-zA-Z (52 characters + 1 stopcode) -> CHAR_LENGTH = 6 * - COUNT_LENGTH = 4 * 0 6 10 16 20 26 30 * |-----|----|-----|----|-----|----|-- .. * | c1 | n1 | c2 | n2 | c3 | n3 | * |-----|----|-----|----|-----|----|-- .. */ void rl_init(char *); char * rl_encode_run(char *, data *); data * rl_encode(char *, char *); char * rl_decode(char *, data *); int rl_benchmark(char *); #endif
C
#include "fractol.h" /* ** Magic start here. Let's see what fractol they want to see.... */ static void init_init(t_data *all) { all->real_change = 0; all->imagine_change = 0; } int main(int argc, char **argv) { t_data *all = malloc(sizeof(t_data)); all->image_height = 1000; all->image_width = 1000; all->zoom = 1; init_init(all); if (argc == 2) { all->mlx_ptr = mlx_init(); all->win_ptr = mlx_new_window(all->mlx_ptr, all->image_height, all->image_width, "Fractols - mpetruse"); if (ft_strcmp(argv[1], "mandelbrot") == 0) { all->name = "mandelbrot"; init_mandel(all); } else if (ft_strcmp(argv[1], "julia") == 0) { all->name = "julia"; init_julia(all); } else if (ft_strcmp(argv[1], "other") == 0) { all->name = "other"; sierpinski(all); } else ft_printf("Usage: ./fractol [julia] or [mandelbrot] or [other]"); mlx_hook(all->win_ptr, 2, 5, exit_key, all); mlx_mouse_hook(all->win_ptr, mouse_manage, all); mlx_hook(all->win_ptr, 6, 5, mouse_drag, all); mlx_loop(all->mlx_ptr); free(all); } else if (argc > 2) ft_printf("try ./fractol arg (ex. : ./fractol mendelbrot).Only one argument allowed"); else ft_printf("Don't forget the name of fractol: ./fractol arg (ex. : ./fractol mendelbrot)."); }
C
#include <stdio.h> long ids[200002]; int main() { long n; scanf("%ld", &n); for (long i = 0; i < n; i++) { long v; scanf("%ld", &v); ids[v-1] = i; } long ans = 1; for (long i = 1; i < n; i++) { if (ids[i-1] > ids[i]) ans++; } printf("%ld\n", ans); return 0; }
C
#define MAX 100 typedef char String[MAX]; void NhapChuoi(String str); void XuatChuoi(String str); int TinhChieuDai(String str); void ChenX_DauChuoi(String str, char x); void ChenX_CuoiChuoi(String str, char x); void ChenX_VT_BatKy(String str, char x, int vt); void Xoa_DauChuoi(String str); void Xoa_CuoiChuoi(String str); void Xoa_VT_BatKy(String str, int vt); void CatDau_ChenCuoi(String str); void CatCuoi_ChenDau(String str); void XoaTatCa_X(String str, char x); void ThayThe_X_Y(String str, char x, char y); void NhapChuoi(String str) { cout << "\nNhap chuoi: "; cin.ignore(MAX, '\n'); gets_s(str, MAX); } void XuatChuoi(String str) { cout << "\n" << str; } int TinhChieuDai(String str) { int kq = 0; for (int i = 0; str[i] != '\0'; i++) kq++; return kq; } void ChenX_DauChuoi(String str, char x) { int len, i; len = TinhChieuDai(str); for (i = len + 1; i > 0; i--) str[i] = str[i - 1]; str[0] = x; } void ChenX_CuoiChuoi(String str, char x) { int len; len = TinhChieuDai(str); str[len] = x; str[len + 1] = '\0'; } void ChenX_VT_BatKy(String str, char x, int vt) { int len, i; len = TinhChieuDai(str); for (i = len; i > vt; i--) str[i] = str[i - 1]; str[len + 1] = '\0'; str[vt] = x; } void Xoa_DauChuoi(String str) { int len, i; len = TinhChieuDai(str); for (i = 0; i < len; i++) str[i] = str[i + 1]; } void Xoa_CuoiChuoi(String str) { int len; len = TinhChieuDai(str); if (len > 0) str[len - 1] = '\0'; } void Xoa_VT_BatKy(String str, int vt) { int len, i; len = TinhChieuDai(str); for (i = vt; i < len; i++) str[i] = str[i + 1]; } void CatDau_ChenCuoi(String str) { int len, i; char ch; len = TinhChieuDai(str); ch = str[0]; for (i = 0; i < len; i++) str[i] = str[i + 1]; str[len - 1] = ch; } void CatCuoi_ChenDau(String str) { int len, i, ch; len = TinhChieuDai(str); ch = str[len - 1]; for (i = len - 1; i > 0; i--) str[i] = str[i - 1]; str[0] = ch; } void XoaTatCa_X(String str, char x) { int len, i; len = TinhChieuDai(str); for (i = 0; i < len; i++) if (str[i] == x) { Xoa_VT_BatKy(str, i); i--; } } void ThayThe_X_Y(String str, char x, char y) { int len, i; len = TinhChieuDai(str); for (i = 0; i < len; i++) if (str[i] == x) str[i] = y; }
C
/* Exercise 2-4. Write an alternate version of squeeze(s1, s2) that deletes * each character in s1 that matches any character in the string s2. */ #include <stdio.h> #include <string.h> void squeeze(char s1[], char s2[]) { int i, j, k; for (i = j = 0; s1[i] != '\0'; i++) { for (k = 0; s2[k] != '\0'; k++) { if (s1[i] == s2[k]) { goto outer; } } s1[j++] = s1[i]; outer:; } s1[j] = '\0'; } int main(void) { int i; char buf[32]; struct { char *s1; char *s2; } tt[] = { {"", ""}, {"abc", ""}, {"abc", "b"}, {"abc", "ac"}, {"abc", "abc"}, }; for (i = 0; i < sizeof(tt) / sizeof(*tt); i++) { strcpy(buf, tt[i].s1); squeeze(buf, tt[i].s2); printf("\"%s\" - \"%s\" = \"%s\"\n", tt[i].s1, tt[i].s2, buf); } }
C
/* * @copyright (c) 2008, Hedspi, Hanoi University of Technology * @author Huu-Duc Nguyen * @version 1.0 */ #include <stdio.h> #include <stdlib.h> #include <curses.h> #include "vm.h" CodeBlock *codeBlock; WORD* stack; WORD* global; int t; int b; int pc; int ps; int stackSize; int codeSize; int debugMode; void resetVM(void) { pc = 0; t = -1; b = 0; ps = PS_INACTIVE; } void initVM(void) { codeBlock = createCodeBlock(codeSize); stack = (Memory) malloc(stackSize * sizeof(WORD)); resetVM(); } void cleanVM(void) { freeCodeBlock(codeBlock); free(stack); } int loadExecutable(FILE* f) { loadCode(codeBlock,f); resetVM(); return 1; } int saveExecutable(FILE* f) { saveCode(codeBlock,f); return 1; } int checkStack(void) { return ((t >= 0) && (t <stackSize)); } int base(int p) { int currentBase = b; while (p > 0) { currentBase = stack[currentBase + 3]; p --; } return currentBase; } void printMemory(void) { int i; printf("Start dumping...\n"); for (i = 0; i <= t; i++) printf(" %4d: %d\n",i,stack[i]); printf("Finish dumping!\n"); } void printCodeBuffer(void) { printCodeBlock(codeBlock); } int run(void) { Instruction* code = codeBlock->code; int count = 0; int number; char s[100]; WINDOW* win = initscr(); nonl(); cbreak(); noecho(); scrollok(win,TRUE); ps = PS_ACTIVE; while (ps == PS_ACTIVE) { if (debugMode) { sprintInstruction(s,&(code[pc])); wprintw(win, "%6d-%-4d: %s\n",count++,pc,s); } switch (code[pc].op) { case OP_LA: t ++; if (checkStack()) stack[t] = base(code[pc].p) + code[pc].q; break; case OP_LV: t ++; if (checkStack()) stack[t] = stack[base(code[pc].p) + code[pc].q]; break; case OP_LC: t ++; if (checkStack()) stack[t] = code[pc].q; break; case OP_LI: stack[t] = stack[stack[t]]; break; case OP_INT: t += code[pc].q; checkStack(); break; case OP_DCT: t -= code[pc].q; checkStack(); break; case OP_J: pc = code[pc].q - 1; break; case OP_FJ: if (stack[t] == FALSE) pc = code[pc].q - 1; t --; checkStack(); break; case OP_HL: ps = PS_NORMAL_EXIT; break; case OP_ST: stack[stack[t-1]] = stack[t]; t -= 2; checkStack(); break; case OP_CALL: stack[t+2] = b; // Dynamic Link stack[t+3] = pc; // Return Address stack[t+4] = base(code[pc].p); // Static Link b = t + 1; // Base & Result pc = code[pc].q - 1; break; case OP_EP: t = b - 1; // Previous top pc = stack[b+2]; // Saved return address b = stack[b+1]; // Saved base break; case OP_EF: t = b; // return value is on the top of the stack pc = stack[b+2]; // Saved return address b = stack[b+1]; // saved base break; case OP_RC: t ++; echo(); wscanw(win,"%c",&number); noecho(); stack[t] = number; checkStack(); break; case OP_RI: t ++; echo(); wscanw(win,"%d",&number); noecho(); stack[t] = number; checkStack(); break; case OP_WRC: wprintw(win,"%c",stack[t]); t --; checkStack(); break; case OP_WRI: wprintw(win,"%d",stack[t]); t --; checkStack(); break; case OP_WLN: wprintw(win,"\n"); break; case OP_AD: t --; if (checkStack()) stack[t] += stack[t+1]; break; case OP_SB: t --; if (checkStack()) stack[t] -= stack[t+1]; break; case OP_ML: t --; if (checkStack()) stack[t] *= stack[t+1]; break; case OP_DV: t --; if (checkStack()) { if (stack[t+1] == 0) ps = PS_DIVIDE_BY_ZERO; else stack[t] /= stack[t+1]; } break; case OP_NEG: stack[t] = - stack[t]; break; case OP_CV: stack[t+1] = stack[t]; t ++; checkStack(); break; case OP_EQ: t --; if (stack[t] == stack[t+1]) stack[t] = TRUE; else stack[t] = FALSE; checkStack(); break; case OP_NE: t --; if (stack[t] != stack[t+1]) stack[t] = TRUE; else stack[t] = FALSE; checkStack(); break; case OP_GT: t --; if (stack[t] > stack[t+1]) stack[t] = TRUE; else stack[t] = FALSE; checkStack(); break; case OP_LT: t --; if (stack[t] < stack[t+1]) stack[t] = TRUE; else stack[t] = FALSE; checkStack(); break; case OP_GE: t --; if (stack[t] >= stack[t+1]) stack[t] = TRUE; else stack[t] = FALSE; checkStack(); break; case OP_LE: t --; if (stack[t] <= stack[t+1]) stack[t] = TRUE; else stack[t] = FALSE; checkStack(); break; case OP_BP: // Just for debugging debugMode = 1; break; default: break; } if (debugMode) { int command; int level, offset; int interactive = 1; do { interactive = 0; command = getch(); switch (command) { case 'a': case 'A': wprintw(win,"\nEnter memory location (level, offset):"); wscanw(win,"%d %d", &level, &offset); wprintw(win,"Absolute address = %d\n", base(level) + offset); interactive = 1; break; case 'm': case 'M': wprintw(win,"\nEnter memory location (level, offset):"); wscanw(win,"%d %d", &level, &offset); wprintw(win,"Value = %d\n", stack[base(level) + offset]); interactive = 1; break; case 't': case 'T': wprintw(win,"Top (%d) = %d\n", t, stack[t]); interactive = 1; break; case 'c': case 'C': debugMode = 0; break; case 'h': case 'H': ps = PS_NORMAL_EXIT; break; default: break; } } while (interactive); } pc ++; } wprintw(win,"\nPress any key to exit...");getch(); endwin(); return ps; }
C
#include <sys/types.h> #include <dirent.h> #include <unistd.h> #include <stdio.h> int my_readir(const char * path) { DIR *dir; struct dirent *ptr; if((dir=opendir(path))==NULL) { perror("opendir"); return -1; } while((ptr = readdir(dir))!=NULL) { printf("file name:%s\n",ptr->d_name); } closedir(dir); return 0; } int main(int argc,char **argv) { if(argc < 2) { printf("listfiel <target path>"); exit(1); } if(my_readir(argv[1])<0) { exit(1); } return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ /* Variables and functions */ scalar_t__ err ; int /*<<< orphan*/ fputs (char*,int /*<<< orphan*/ ) ; int /*<<< orphan*/ stderr ; void usage(void) { fputs("SORT\n", stderr); fputs("Sorts input and writes output to a file, console or a device.\n", stderr); if (err) { fputs("Invalid parameter\n", stderr); } fputs(" SORT [options] < [drive:1][path1]file1 > [drive2:][path2]file2\n", stderr); fputs(" Command | SORT [options] > [drive:][path]file\n", stderr); fputs(" Options:\n", stderr); fputs(" /R Reverse order\n", stderr); fputs(" /+n Start sorting with column n\n", stderr); fputs(" /? Help\n", stderr); }
C
/*海伦公式S=根号下p(p-a)(p-b)(p-c) 公式中a,b,c分别为三角形三边长,p为半周长,S为三角形的面积*/ #include<stdio.h> #include<math.h> int main() { float a,b,c,p,s; printf("请输入三角形三边的边长(两边之和大于第三边或两边之和小于第三边):"); scanf("%f%f%f",&a,&b,&c); p=(a+b+c)/2; s=sqrt(p*(p-a)*(p-b)*(p-c)); printf("三角形面积为%.2f\n",s); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_list_reverse_fun.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lucocozz <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/07/25 12:48:12 by lucocozz #+# #+# */ /* Updated: 2019/07/25 17:19:52 by lucocozz ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_list.h" static t_list *ft_list_at(t_list *begin_list, unsigned int nbr) { unsigned int i; i = 0; if (!begin_list) return (NULL); while (i < nbr && begin_list->next != NULL) { begin_list = begin_list->next; i++; } return (begin_list); } static int ft_list_size(t_list *begin_list) { int size; size = 0; while (begin_list) { begin_list = begin_list->next; size++; } return (size); } void ft_list_reverse_fun(t_list *begin_list) { int i; int j; void *tmp; t_list *end; i = 0; j = ft_list_size(begin_list); if (!begin_list || !begin_list->next) return ; while (i < j) { j--; end = ft_list_at(begin_list, j - i); tmp = end->data; end->data = begin_list->data; begin_list->data = tmp; i++; begin_list = begin_list->next; } }
C
#include <stdio.h> #include <sys/types.h> #include <regex.h> #include <memory.h> #include <stdlib.h> /* 金额格式的检查 *****.** 如100.00 1000000.10 10000.01 */ int main() { // char * bematch = "[email protected]"; // char * pattern = "h{3,10}(.*)@.{5}.(.*)"; char * bematch = "1000.0"; char * pattern = "([0-9]*)(.)([0-9]{2})"; char errbuf[1024]; char match[100]; regex_t reg; int err, nm = 10; regmatch_t pmatch[nm]; if ( regcomp( &reg, pattern, REG_EXTENDED ) < 0 ) { regerror( err, &reg, errbuf, sizeof(errbuf) ); printf( "err:%s\n", errbuf ); } err = regexec( &reg, bematch, nm, pmatch, 0 ); if ( err == REG_NOMATCH ) { printf("no match\n"); exit(-1); } else if (err) { regerror( err, &reg, errbuf, sizeof(errbuf) ); printf( "err:%s\n", errbuf ); exit(-1); } int i; for ( i = 0 ; i < 10 && pmatch[i].rm_so != -1 ; i++ ) { int len = pmatch[i].rm_eo - pmatch[i].rm_so; if (len) { memset( match, '\0', sizeof(match) ); memcpy( match, bematch + pmatch[i].rm_so, len ); printf( "%s\n", match ); } } return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<fcntl.h> #include<sys/shm.h> #include<sys/stat.h> #include<sys/wait.h> int main(){ key_t k=ftok("password",1); key_t kb=ftok("password",2); key_t kc=ftok("password",3); int s3=shmget(kc,4*sizeof(int),IPC_CREAT|0666); int s1=shmget(k,5*sizeof(float),IPC_CREAT|0666); int s2=shmget(kb,5*sizeof(int),IPC_CREAT|0666); float *a=(float*)shmat(s1,NULL,0); int *b=(int*)shmat(s2,NULL,0); int *c=(int*)shmat(s3,NULL,0); float tmp; printf("Started Client 3 execution...\n"); while(1){ if(!b[2]){ tmp=(3*a[2]+2*a[4])/5; if(tmp!=a[2] || abs(tmp-a[2])>0.001){ a[2]=tmp; b[2]=1; } else{ c[2]=1; b[2]=1; break; } } } printf("Client 3 temp: %f\n",a[2]); return 0; }
C
#include <stdio.h> #include "structs.h" #include <stdlib.h> struct process proc[10]; struct gantt g[10]; int n; int sum=0; void input() { printf("\nEnter no. of processes"); scanf("%d",&n); for(int i=0;i<n;++i) { printf("\nEnter process id of process%d\t",i); scanf("%d",&proc[i].pid); printf("\nEnter burst time of process%d\t",i); scanf("%d",&proc[i].burst_t); printf("\nEnter arrival time of process%d\t",i); scanf("%d",&proc[i].arr_t); //fflush(stdin); //proc[i].burst_t=0; //printf("\nEnter waiting time o") } } void sort() { int key; int i,j; for(i=1;i<n;++i) { key=proc[i].arr_t; j=i-1; while(j>0 && proc[i].arr_t > key) { proc[i+1].arr_t=proc[i].arr_t; j=i-1; } proc[i+1].arr_t=key; } printf("\nSorted"); } /*void sched() { int i=0; while(i<n) { sum=sum+proc[i].burst_t; proc[i].wt_t=sum-proc[i].burst_t; proc[i].fi_t=proc[i].wt_t+proc[i-1].burst_t; printf("\nWait time of process %d\t is=%d\t",i,proc[i].wt_t); printf("\nFinish time of process %d\t is %d\t",i,proc[i].fi_t); i=i+1; }*/ void assign_gantt() { int i; int start=0; while(i<n) { g[i].g_pid=proc[i].pid; g[i].start=start; g[i].end=g[i].start+proc[i].burst_t; start=g[i].end; proc[i].fi_t=g[i].end; //g[i].g_burst=proc[i].burst_t; //g[i].g_wt_t=proc[i].wt_t; } } void output() { int i=0; printf("\nProcess id:"); for(i=0;i<n;++i) { printf("%d\t|",proc[i].pid); } //i=0; /*printf("\nWaiting time:"); for(i=0;i<n;++i) { printf("%d\t|",proc[i].wt_t); }*/ //i=0; printf("\nArrival time"); for(i=0;i<n;++i) { printf("%d\t|",proc[i].arr_t); } printf("\nBurst time"); for(i=0;i<n;++i) { printf("%d\t|",proc[i].burst_t); } } void main() { input(); sort(); //sched(); assign_gantt(); //output(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "constants.h" #define paraHOSTNAME 1 #define paraPORT 2 #define paraGAMEKINDNAME 3 #define paraGAMEID 4 #define paraPLAYERNUMBER 6 #define paraVERSION 7 #define paraCOUNT 8 char isGameidAlreadyDefined[BUFFER_SIZE] = " "; char isPlayernumberAlreadyDefined[BUFFER_SIZE] = " "; char* cleanBlankspace(char* toClean){ char* bufferChar = toClean; char* toReturn = " "; if((toClean == NULL) || (strcmp(bufferChar," ") == 0) || (strcmp(bufferChar,"\0") == 0)|| (strcmp(bufferChar,"") == 0)){ //printf("\nEinem Parameter wurde kein Wert zugewiesen, baeh\n"); return ""; } while(bufferChar != NULL){ toReturn = strtok(bufferChar," "); if((strcmp(toReturn," "))!=0){ //Alle Leerzeichen wurden entfernt return toReturn; } bufferChar = strtok(NULL," "); } return ""; } short tellParam(char* para){ if( (strcmp(para,"id") == 0) || (strcmp(para,"gameid") == 0) || (strcmp(para,"gameID") == 0) || (strcmp(para,"gameId") == 0) || (strcmp(para,"GAMEID") == 0) || (strcmp(para,"g") == 0) ){ return paraGAMEID; } if( (strcmp(para,"port") == 0) || (strcmp(para,"portnumber") == 0) || (strcmp(para,"portNumber") == 0) || (strcmp(para,"PORTNUMBER") == 0)){ return paraPORT; } if( (strcmp(para,"host") == 0) || (strcmp(para,"hostName") == 0) || (strcmp(para,"hostname") == 0) || (strcmp(para,"hostNAME") == 0) || (strcmp(para,"HOSTNAME") == 0)){ return paraHOSTNAME; } if( (strcmp(para,"gamekindname") == 0) || (strcmp(para,"gameKindName") == 0) || (strcmp(para,"gamekind") == 0) || (strcmp(para,"GAMEKINDNAME") == 0)){ return paraGAMEKINDNAME; } if( (strcmp(para,"playernumber") == 0) || (strcmp(para,"p") == 0) || (strcmp(para,"playerNumber") == 0) || (strcmp(para,"PLAYERNUMBER") == 0)){ return paraPLAYERNUMBER; } if( (strcmp(para,"version") == 0) || (strcmp(para,"gameversion") == 0) || (strcmp(para,"gamerVersion") == 0) || (strcmp(para,"GAMEVERSION") == 0) || (strcmp(para,"VERSION") == 0) || (strcmp(para,"Version") == 0) ){ return paraVERSION; } if( (strcmp(para,"playercount") == 0) || (strcmp(para,"playerCount") == 0) || (strcmp(para,"PLAYERCOUNT") == 0) || (strcmp(para,"anzahlspieler") == 0) ){ return paraCOUNT; } return -1; } int assignParameters(char* ParameterLine){ char* paraLine = ParameterLine; char* assParameter; char* assValue; char paraDelimiter[] = "="; char gamverval[256]; if( (strcmp(paraLine,"")==0) || (strcmp(paraLine," ") == 0) ){ return 0; } //Line in Parameter und Wert aufteilen assParameter = strtok(paraLine,paraDelimiter); //Parameter paraLine = strtok(NULL,paraDelimiter); //zum wert springen assValue = strtok(paraLine,paraDelimiter); //Wert paraLine = strtok(NULL,paraDelimiter); //Parameter und Wert bereinigen assParameter = cleanBlankspace(assParameter); assValue = cleanBlankspace(assValue); //Parameter erkennen und der struktur zuweisen switch(tellParam(assParameter)){ case paraGAMEID: if(strcmp(isGameidAlreadyDefined," ") != 0){ strcpy(gamverval, "ID "); strcat(gamverval, isGameidAlreadyDefined); strcat(gamverval, "\n"); strcat(confiConst.gameID, gamverval); } else{ if((strcmp(assValue," ") == 0)||(strcmp(assValue,"") == 0)){ strcpy(confiConst.gameID, " "); return 0; } strcpy(gamverval, "ID "); strcat(gamverval, assValue); strcat(gamverval, "\n"); strcat(confiConst.gameID, gamverval); } break; case paraPLAYERNUMBER: if(strcmp(isPlayernumberAlreadyDefined," ") != 0){ strcpy(gamverval, "PLAYER "); strcat(gamverval, isPlayernumberAlreadyDefined); strcat(gamverval, "\n"); strcpy(confiConst.playerNumber, gamverval); } else{ strcpy(gamverval, "PLAYER "); strcat(gamverval, assValue); strcat(gamverval, "\n"); strcpy(confiConst.playerNumber, gamverval); } break; case paraPORT: strcpy(confiConst.portNumber, assValue); break; case paraGAMEKINDNAME: strcpy(confiConst.gameKindName, assValue); break; case paraHOSTNAME: strcpy(confiConst.hostName, assValue); break; case paraVERSION: strcpy(gamverval,"VERSION "); strcat(gamverval,assValue); strcat(gamverval,"\n"); strcpy(confiConst.gameVersion, gamverval); break; case paraCOUNT: strcpy(confiConst.playerCount, assValue); break; default: //printf("Parameter nicht erkannt: \"%s\" \n",assParameter); break; } return 0; } short checkStructurComplete(){ char scanVal[256]; //gameid if( (strcmp(confiConst.gameID, "") == 0) || (strcmp(confiConst.gameID, " ") == 0) || (strcmp(confiConst.gameVersion, "ID \n") == 0) || (strcmp(confiConst.gameVersion, "ID \n") == 0) ){ printf("GameID fehlt, bitte geben sie die GAMEID ein: "); scanf("%s",scanVal); strcpy(confiConst.gameID,"ID "); strcat(confiConst.gameID,scanVal); strcat(confiConst.gameID,"\n"); printf("Neue gameID: %s\n",confiConst.gameID); } //Hostname if( (strcmp(confiConst.hostName, "") == 0) || (strcmp(confiConst.hostName, " ") == 0) ){ printf("Hostname fehlt, Defaultwert nehmen? (y/n): "); scanf("%s",scanVal); if( (strcmp(scanVal,"y") == 0) || (strcmp(scanVal,"yes") == 0) ){ strcat(confiConst.hostName,"sysprak.priv.lab.nm.ifi.lmu.de"); printf("Default Hostname: %s\n",confiConst.hostName); } else{ printf("Hostname eingeben: "); scanf("%s",scanVal); strcat(confiConst.hostName,scanVal); printf("Neuer Hostname: %s\n",confiConst.hostName); } } //gameKindName if( (strcmp(confiConst.gameKindName, "") == 0) || (strcmp(confiConst.gameKindName, " ") == 0) ){ printf("Spielart fehlt, Defaultwert nehmen? (y/n): "); scanf("%s",scanVal); if( (strcmp(scanVal,"y") == 0) || (strcmp(scanVal,"yes") == 0) ){ strcpy(confiConst.gameKindName,"NMMORRIS\n"); printf("Default Spielart: %s\n",confiConst.gameKindName); } else{ printf("Spielart eingeben: "); scanf("%s",scanVal); strcpy(confiConst.gameKindName,scanVal); strcat(confiConst.gameKindName,"\n"); printf("Neue Spielart: %s\n",confiConst.gameKindName); } } //gameVersion if( (strcmp(confiConst.gameVersion, "") == 0) || (strcmp(confiConst.gameVersion, " ") == 0) || (strcmp(confiConst.gameVersion, "VERSION \n") == 0) || (strcmp(confiConst.gameVersion, "VERSION \n") == 0) ){ strcpy(confiConst.gameVersion,""); printf("Spielversion fehlt, Defaultwert nehmen? (y/n): "); scanf("%s",scanVal); if( (strcmp(scanVal,"y") == 0) || (strcmp(scanVal,"yes") == 0) ){ strcat(confiConst.gameVersion,"VERSION 2.0\n"); printf("Default Spielversion: %s\n",confiConst.gameVersion); } else{ printf("Spielversion eingeben: "); scanf("%s",scanVal); strcpy(confiConst.gameVersion,"VERSION "); strcat(confiConst.gameVersion,scanVal); strcat(confiConst.gameVersion,"\n"); printf("Neue Spielversion: %s\n",confiConst.gameVersion); } } //portNumber if( (strcmp(confiConst.portNumber, "") == 0) || (strcmp(confiConst.portNumber, " ") == 0) ){ strcpy(confiConst.portNumber,""); printf("Port fehlt, Defaultwert nehmen? (y/n): "); scanf("%s",scanVal); if( (strcmp(scanVal,"y") == 0) || (strcmp(scanVal,"yes") == 0) ){ strcat(confiConst.portNumber,"1357"); printf("Default Port: %s\n",confiConst.portNumber); } else{ printf("Port eingeben: "); scanf("%s",scanVal); strcat(confiConst.portNumber,scanVal); printf("Neuer Port: %s\n",confiConst.portNumber); } } //printf("\n Struktur:\n1.gameKindName: \"%s\"\n2.portNumber: \"%s\"\n3.hostName : \"%s\"\n4.gameID: \"%s\"\n5.playerNumber: \"%s\"\n6.gameVersion: \"%s\"\n", confiConst.gameKindName, confiConst.portNumber, confiConst.hostName, confiConst.gameID, confiConst.playerNumber, confiConst.gameVersion); return 0; } int read_configfile(char* paragameID, char* paraplayerNumber, char* configFileName){ FILE* file; char* filepath = " "; filepath = configFileName; //printf("\nREADCONF: parameter: gameID : \"%s\" ,playernumber : \"%s\" , configFileName: \"%s\" \n", paragameID,paraplayerNumber, configFileName); //Pruefen ob parameter gameID und playernumber valide sind if(strcmp(paragameID," ") != 0){ strcpy(isGameidAlreadyDefined,paragameID); } if(strcmp(paraplayerNumber," ") != 0){ strcpy(isPlayernumberAlreadyDefined,paraplayerNumber); isPlayernumberAlreadyDefined[0]--; //isPlayernumberAlreadyDefined = playerNumber; } //Datei oeffnen und ueberpruefen ob es die datei gibt, falls nicht wird client.conf eingelesen file = fopen(filepath, "r"); if(file == NULL){ //printf("\ninvalid configfilename or path, opening client.conf instead\n\n"); file=fopen("client.conf","r"); if(file == NULL){ //perror("client.conf does not exist either D: , READCONF"); return -1; } else{ //printf("opened client.conf successfully, woohoo \n"); } } //in line werden die einzelnen Zeilen zwischengespeichert char line[256]; char* configFileParameter; char delimiter[] = "\n"; while (fgets(line, sizeof(line), file)){ configFileParameter = strtok(line,delimiter); while(configFileParameter != NULL){ if( (strstr(configFileParameter, "§§$$")) != NULL || (strcmp(configFileParameter,"")==0) || (strcmp(configFileParameter," ")==0) ){ //printf("Line wird ignoriert: \"%s\" \n",configFileParameter); } else{ //printf("\nLine: \"%s\"\n",configFileParameter); if(assignParameters(configFileParameter) == -1){ perror("Error assigning Parameter from File to structure, READCONF"); } } configFileParameter = strtok(NULL,delimiter); } } checkStructurComplete(); fclose(file); return 0; }
C
#include <kipr/botball.h> #include <math.h> //#0 left + //#1 right - //analog(0)>=3500 black //low : low servo position f //high : high servo position void forward(int velocity,int distance) { clear_motor_position_counter(0); clear_motor_position_counter(1); mtp(0,velocity,distance); mtp(1,velocity,-distance); msleep(abs((float)distance/((float)velocity/1000))); //forward(velocity,distance as tik); //1cm = 100tik } void turn(int direction) { clear_motor_position_counter(0); clear_motor_position_counter(1); mtp(direction,1000,1250*pow(-1,direction)); mtp(pow(0.5,direction-1)-1,1000,1250*pow(-1,direction)); msleep(2200); //turn(n); //right: n = 0 //left: n = 1 //1300ms } void turna(int motor,int direction) { clear_motor_position_counter(0); clear_motor_position_counter(1); mtp(motor,1000,2525*direction); msleep(2550); //turn(m,n); //m : motor # //n : direction } int main() { int bound; int boundl; int boundr; int tsd; int tsdl; int tsdr; while(1) { tsd = analog(2); tsdl = analog(2)-100; tsdr = analog(2)+100; mav(0,1200); mav(1,-1200); while(1) { if (analog(2)>tsdr) { mav(0,1300); mav(1,-1200); } else if(analog(2)<tsdl) { mav(0,1200); mav(1,-1300); } else { mav(0,1200); mav(1,-1200); } } } }
C
#include<stdio.h> #include<string.h> #include<stdbool.h> void plainText(); void orignal(char*); void encryption(char*); void decryption(char*); bool check(char*); bool goes[10]; int length; int key=0; void main() { plainText(); } void plainText() { char message[10]; printf("Enter 9 digit message(must be small letters) > "); scanf("%s",message); printf("Enter key to encrypt the data > "); scanf("%d",&key); length=strlen(message); check(message) ? encryption(message) : printf("Does not satisfy The condition.\n") ; } void encryption(char* OrignalMessage) { printf("Orignal message > %s\n",OrignalMessage); char cipher[10]; int i=0; int capital = 0xDF; //used to capitalize the cipher text //encrypt orignal text while(i<length) { int temp=0; temp = (int)OrignalMessage[i] + key ; if(temp>122) { temp-=26; goes[i]=1; } cipher[i] = ( (char)temp & capital ); i++; } // print cipher text printf("Encrypted text > "); for(i=0;i<length;i++) { printf("%c",cipher[i]); } printf("\n"); decryption(cipher); } void decryption(char* CipherText) { char decryptedMessage[10]; int k=0; int small = 0x20; // convert Capital to small the decryptedMessage //Decrypt orignal text while(k<length) { CipherText[k] = (char)((int)CipherText[k] + small); if(goes[k] == 1) { decryptedMessage[k] = (char)((int)CipherText[k] + 26 - key); } else { decryptedMessage[k] = (char)((int)CipherText[k]-key); } k++; } // print decryptedMessage text printf("Decrypted text > "); for(k=0;k<length;k++) { printf("%c",decryptedMessage[k]); } } bool check(char* message) { int count=0; if(length>9) return 0; for(int i=0;message[i]!='\0';i++) { if(message[i] >='A' && message[i] <='Z') return 0; } return 1; }
C
#include <stdlib.h> #include <stdio.h> #include <pthread.h> // For getpid(), .. #include <sys/types.h> #include <unistd.h> // For time(), .. #include <time.h> // For perror(), errno, .. #include <errno.h> #include "thread.h" ///////////////////////////////////////////////////////////////////////////////////// void *print_str(void *arg) { // Cast char *str = (char *)arg; // printf("Child says; '%s'\n", str); // Exit pthread_exit( NULL ); return NULL; } int main1() { // Init the thread variable pthread_t thread; // Create the thread if( pthread_create( &thread, NULL, print_str, "Hello world" ) ) { perror("In thread.c: Error with 'pthread_create()'"); return errno; } // Close the thread if( pthread_join( thread, NULL ) ) { printf("In thread.c: Error with 'pthread_join()'\n"); return errno; } // Exit return 0; } ///////////////////////////////////////////////////////////////////////////////////// void *print_int(void *arg) { // Cast int *alea = (int *)arg; // printf("Child: number alea = %d\n", *alea); // Exit pthread_exit( NULL ); return NULL; } int main2(int base) { // Init the thread variable pthread_t thread; // Create the thread srand( getpid() ); int alea = rand() % base; // Create the thread if( pthread_create( &thread, NULL, print_int, &alea ) ) { perror("In thread.c: Error with 'pthread_create()'\n"); return errno; } // Join the thread if( pthread_join( thread, NULL ) ) { printf("In thread.c: Error with 'pthread_join()'\n"); return errno; } // Exit return 0; } ///////////////////////////////////////////////////////////////////////////////////// typedef struct { //Thread ID pthread_t tid; //Thread argument/parameter int targ; //Thread return value int tret; } thread_arg_t; void *init_alea(void *arg) { // Cast thread_arg_t *t = (thread_arg_t *)arg; // Init srand( time( NULL ) ); t->tret = rand() % t->targ; printf("Child: number alea = %d\n", t->tret); // Exit pthread_exit( NULL ); return NULL; } int main3(int base) { // Init the struct thread_arg_t t; // Fill the struct t.targ = base; t.tret = 0; // Create the thread if( pthread_create( &t.tid, NULL, init_alea, &t ) ) { perror("In thread.c: Error with 'pthread_create()'\n"); return errno; } // Join the thread if( pthread_join( t.tid, NULL) ) { printf("In thread.c: Error with 'pthread_join()'\n"); return errno; } // printf("Father: number alea = %d\n", t.tret); // Exit return 0; } ///////////////////////////////////////////////////////////////////////////////////// typedef struct { // Average of element float tab_average; // Number of element int count; // int *tab; } tabint_t; typedef struct { //Thread ID pthread_t tid; // tabint_t tabint; } thread_arg_t2; void *moyenne(void *arg) { // Cast thread_arg_t2 *t2= (thread_arg_t2 *)arg; // Sum elements int sum = 0; for( int i = 0 ; i < t2->tabint.count ; i++ ) sum += t2->tabint.tab[i]; // printf("Child: sum of elements = %d\n", sum); // Calcul average t2->tabint.tab_average = (float)sum / t2->tabint.count; // printf("Child: moy = %.2f\n", t2->tabint.tab_average ); // Exit pthread_exit( NULL ); return NULL; } int main4() { // Init the struct thread_arg_t2 thread; // Init average thread.tabint.tab_average = -1; // Fill the number of elements printf("Give me the number of elements: "); scanf("%d", &thread.tabint.count); thread.tabint.tab = malloc( thread.tabint.count * sizeof(int) ); // If malloc is good if( thread.tabint.tab ){ // Fill the table with few elements for( int i = 0 ; i < thread.tabint.count ; ++i) { printf("Give me a number: "); scanf("%d", &thread.tabint.tab[i]); } // Create the thread if( pthread_create( &thread.tid, NULL, moyenne, &thread ) ) { perror("In thread.c: Error with 'pthread_create()'\n"); return errno; } // Join the threads if( pthread_join( thread.tid, NULL ) ) { printf("In thread.c: Error with 'pthread_join()'\n"); return errno; } // printf("Father: moy = %.2f\n", thread.tabint.tab_average); // Relaese free(thread.tabint.tab); } else { printf("main4: wrong alloc of 'thread.tabint.tab'\n"); } return 0; } /////////////////////////////////////////////////////////////////////////////////////
C
#include <stdio.h> #include <stdlib.h> /* 1 */ void sorting(double *array[], int n); void show_array(double *array[], int n); int main(){ /* 2 */ double array[2]; double *index[3]; /* 2.1 */ for(int i = 0; i < 3; i++){ printf("--> "); index[i] = (double *)malloc(sizeof(double)); scanf("%lf", &array); index[i] = (double *)&array; } printf("index[%i] = {", 3); for(int i = 0; i < 3; i++){ if(i == 2){ printf("%lf}.\n", index[i]); }else{ printf("%lf, ", index[i]); } } /* 2.2 */ sorting(index, 3); //index -= 10; printf("\n\n"); /* 2.3 */ show_array(index, 3); return 0; } void sorting(double *array[], int n){ /* 3 */ double *x; /* 3.1 */ for(int i = 0; i < n; i++){ for(int j = i+1; j < n-1; j++){ if(array[i] > array[j]){ x = array[j]; array[j] = array[i]; array[i] = x; } } } } void show_array(double *array[], int n){ /* 4 */ printf("array[%i] = {", n); for(int i = 0; i < n; i++){ if(i == n -1){ printf("%lf}.\n", array[i]); }else{ printf("%lf, ", array[i]); } } }
C
#include <assert.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "macros.h" #include "mesh.h" #include "objloader.h" #define BUFSZ 1024 static void parse_vertex(const char *line, struct vec4 *v); static int parse_face(const char *line, struct pe_vidx *v); void pe_objload(struct mesh *m, const char *fname) { struct vec4 v; struct vec4 va; struct pe_vidx f[3]; FILE *fp; char buf[BUFSZ]; int i, nnorm, ntexture, npoints; assert(m != NULL); npoints = nnorm = ntexture = 0; fp = fopen(fname, "rb"); if (fp == NULL) error(1, "can't fopen file '%s'", fname); while (fgets(buf, sizeof(buf), fp) != NULL) { if (buf[0] == 'v') { if (buf[1] == ' ') { npoints++; memset(&v, 0, sizeof(v)); parse_vertex(buf + 2, &v); dbuf_push(&m->vertex, &v); } else if (buf[1] == 'n' && buf[2] == ' ') { memset(&va, 0, sizeof(va)); parse_vertex(buf + 3, &va); //push as vec3 dbuf_push(&m->norm, &va); nnorm++; } else if (buf[1] == 't' && buf[2] == ' ') { memset(&va, 0, sizeof(va)); parse_vertex(buf + 3, &va); //push as vec3 dbuf_push(&m->text, &va); ntexture++; } } else if (buf[0] == 'f' && buf[1] == ' ') { memset(&f, 0, sizeof(f)); parse_face(buf + 1, f); for (i = 0; i < 3; i++) dbuf_push(&m->idx, &f[i]); } } printf("OBJFILE:\n" "texture points = %d\n" "norm points = %d\n" "points = %d\n", ntexture, nnorm, npoints); fclose(fp); } static void parse_vertex(const char *line, struct vec4 *v) { sscanf(line, "%lf %lf %lf", &v->x, &v->y, &v->z); } //TODO: parse normals and textures vectors static int parse_face_row(const char *l, struct pe_vidx *v) { char *p; char *d = "/ \t"; p = (char *)l; v->v = v->n = v->t = -1; //OBJ initail idx is 1, decrement it // v v->v = atoi(l) - 1; p = l + strcspn(l, d); if (p[0] != '/') goto end; // v/t if (p[1] != '/') { v->t = atoi(p + 1) - 1; p += strcspn(l, d); if (p[0] != '/') goto end; } else { // v//n p++; } // v/t/n v->n = atoi(p + 1); end: p += strcspn(p, " \t"); return p - l; } static int parse_face(const char *line, struct pe_vidx *v) { int i, n; const char *p; char *d = " \t"; p = line; //printf("%s\n", line); for (i = 0; i < 3; i++) { n = strspn(p, d); if (n == 0 && i != 2) { warning("can't find triangle index %d, s = '%s'", i, p); exit(42); return 1; } p += n; p += parse_face_row(p, &v[i]); } return 0; }
C
//#pragma warning(disable:4996) //#include<stdio.h> //#include<conio.h> //#include<stdlib.h> //int main() //{ // FILE* fpSrc; // FILE* fpDest; // char caSrcFileName[20]; // char caDestFileName[20]; // scanf("%s", caSrcFileName, 20); // fopen(&fpSrc, caSrcFileName, "r"); // printf("\n"); // scanf("%s", caDestFileName, 20); // fopen(&fpDest, caDestFileName, "w"); // { // char temp; // while ((temp = getc(fpSrc)) != EOF) { // putc(temp, fpDest); // // } // } // fclose(fpSrc); // fclose(fpDest); //}
C
#include <stdio.h> int checkSymmetric(int a[], int n); void main() { int a[100], n, i; printf(" Number of elements: "); scanf("%d", & n); for (i = 0; i < n; i++) { printf("a[%d]= ", i); scanf("%d", & a[i]); } printf("\n Array's content:\n"); for (i = 0; i < n; i++) printf("%d ", a[i]); if (checkSymmetric(a, n)) printf("\n array is symmetric"); else printf("\n array is not symmetric "); } int checkSymmetric(int a[], int n) { int i = 0, j = n - 1; while (i <= j) { if (a[i] != a[j]) return 0; i++; j--; } return 1; }
C
#include "client.h" int fd; struct sockaddr_in addr; pthread_t tid; // socket init with given address int socket_init(char *str) { int ret = 0; // socket input fd = socket(AF_INET, SOCK_STREAM, 0); if (fd == -1) return (-1); // using IPv4, port : 12345, ip address : (input) addr.sin_family = AF_INET; addr.sin_port = htons(12345); addr.sin_addr.s_addr = inet_addr(str); // connect to socket ret = connect(fd, (struct sockaddr *)&addr, sizeof(addr)); // when failed if (ret == -1) return (ret); return (ret); } // when SIGINT or input exit cmd, thread cancel and return void sig_exit() { // send \0 to server shutdown(fd, SHUT_WR); // cancel thread pthread_cancel(tid); pthread_join(tid, NULL); write(1, "DB ENDED\n", 9); // close socket close(fd); exit(0); } // send user input to server void *socket_write(void *ptr) { char buf[128]; while (TRUE) { memset(buf, 0, sizeof(buf)); // if user input a cmd if (read(0, buf, sizeof(buf)) > 0) { write(1, "CLIENT >> ", 10); write(1, buf, strlen(buf)); // if user input exit if (strncmp(buf, "exit", 4) == 0) sig_exit(); // else send cmd to server write(fd, buf, strlen(buf)); } usleep(1000 * 500); } } // socket run void socket_run(char buf[128]) { // except 'connect ' + ip adrress int ret = socket_init(buf + 8); if (ret == -1) { write(1, "INIT ERROR\n", 11); exit(0); } write(1, "DB START\n", 9); // socket write start pthread_create(&tid, NULL, socket_write, NULL); // when message come, print it to host's window while (TRUE) { int size; memset(buf, 0, 128); size = read(fd, buf, 128); // print it if (size > 0) write(1, buf, strlen(buf)); // when shutdown come, exit program else if (size == 0) sig_exit(); usleep(1000 * 500); } }
C
/* You are given a natural number called n. Print all the prime divisors of n. Example: input -> 12 output -> 2^2 3^1 */ #include <stdio.h> static void PrimeDivisors (unsigned int n) { size_t d = 2; while (d * d <= n && n > 1) { if (n % d == 0) { size_t power = 0; while (n % d == 0) { power++; n /= d; } printf("%lu^%lu\n", d, power); } d++; } if (n > 1) printf("%u^1\n", n); } int main (void) { unsigned int n; scanf("%u", &n); PrimeDivisors(n); return 0; }
C
#include<stdio.h> #include<Windows.h> #define Maxsize 100 /**/ int* Input(int num);//Ϊϣ0λݴݣݴ1λʼ int* Shell_sort(int a[], int num);//ϣ void Print(int a[], int num);//ӡ int main() { printf("Ҫٸ:"); int num;//ٸ scanf_s("%d", &num); num = num + 1;//0λݴ,Ӧöһλ int* a; a = Input(num); /*ʼָתΪ飨ΪcԺܽ鴫*/ int i, b[Maxsize]; for (i = 0; i < num; i++) { b[i] = *(a + i); } /*ָתΪ飨ΪcԺܽ鴫*/ //򲢽תΪ a = Shell_sort(b, num); for (i = 0; i < num; i++) { b[i] = *(a + i); } printf("Ϊ\n"); Print(b, num);//ӡ system("pause"); return 0; } //Ϊϣ0λݴݣݴ1λʼ int* Input(int num) { int a[Maxsize] = { 0 }; int i; printf("\n"); int input;// for (i = 1; i < num; i++) { scanf_s("%d", &input); a[i] = input; } return a; } int* Shell_sort(int a[], int num)//ϣ { int i,j,dk;//dkΪ for (dk = num / 2; dk >= 1; dk = dk / 2) { for (i = dk + 1; i <= num; ++i) { if (a[i] < a[i - dk]) { a[0] = a[i]; for (j = i - dk; j > 0 && a[0] > a[j]; j = j - dk) { a[j + dk] = a[j]; } a[j + dk] = a[0]; } } } return a; } //ӡΪϣ0λݴݣݴ1λʼ void Print(int a[], int num) { int i; for (i = 1; i < num; i++) { printf("%d\t", a[i]); } printf("\n"); }
C
#include <stdio.h> #include <global.h> #include <input.h> #include <print.h> #include <memory.h> #include <cmd.h> #include <init.c> typedef struct state { int parent_ino; int my_ino; int rec_len; int name_len; char name[256]; u16 type; u16 links_count; int size; u16 uid; u16 gid; } STATE; // Gloabl Input and Expected Arrays char** Input = NULL; struct STATE* Expect[32]; void fill_expected(struct STATE* newState, char* line) { char* token = NULL, part = NULL; copyLine = NULL; char* tokens[10]; int i = 0; // Copy the line because we will destroy it copyLine = (char *) malloc(strlen(line) + 1 *sizeof(char)); strcpy(copyLine, line); //tokenize input before putting into expected token = strtok(line, " "); tokens[i++] = token; while (token = strtok(NULL, " ")) { tokens[i++] = token; } i=0; // Populate the expected state newState->parent_ino = strtol(tokens[i++], &part, 10); newState->my_ino = strtol(tokens[i++], &part, 10); newState->rec_len = strtol(tokens[i++], &part, 10); newState->name_len = strtol(tokens[i++], &part, 10); strcpy(newState->name, tokens[i++]); newState->type = strtol(tokens[i++], &part, 10); newState->links_count = strtol(tokens[i++], &part, 10); newState->size = strtol(tokens[i++], &part, 10); newState->uid = strtol(tokens[i++], &part, 10); newState->gid = strtol(tokens[i++], &part, 10); } int line_check(char* line) { char* commands[3] = { "mkdir", "creat", "cd"}; char* subStr = NULL; int i; // Check for blank line if (strlen(line) < 2) return 0; // Check if the line is a comment if (line[0] == '#') return 0; // Check if line has a command in it for (i = 0; i < 3; i++) { if ( subStr = strstr(line, commands[i]) ) //contains one of the command substrings return 1; } // If we are here, then the line must be an expected line return 2; } void populate_arrays(char* filename) // Eventually need to free all of the allocated memory after all test commands are performed { FILE* testfile = NULL; ssize_t read; ssize_t len = 256; char path[64]; char* line; int line_check = 0, i = 0, j = 0; bool isPair = false; struct state* temp_Expect = NULL; char* temp_command = NULL; // Create the path for the test file strcat(path, "test/"); strcat(path, filename); testfile = fopen(path, "r"); if (!testfile) { printf("Error opening file: %s\n", path); return; } // Start reading while ( (read = getline(&line, &len, testfile)) != -1) { line_check = check_line(line); // Input line if (line_check == 1) { //fill Input with newly allocated string temp_command = (char *) malloc(strlen(line) + 1 * sizeof(char)); strcpy(temp_command, line); //printf("temp_command: %s\n", temp_command); Input[i++] = temp_command; } // Expect Line if (line_check == 2) { // fill Expected with newly allocated Expect temp_Expect = (STATE *) malloc(sizeof(STATE)); fill_expected(temp_Expect, line); Expect[j++] = temp_Expect; } } } void quit_test() { int i = 0; MINODE* mip = NULL; for(i = 0; i < NMINODES; i++) { mip = &MemoryInodeTable[i]; if(mip->refCount > 0) iput(mip); } close(running->cwd->device); } bool isStateMatch(int argc, char* argv[], int device, STATE expected) { printf("Command: '%s' Parameter: '%s'\n", argv[0], argv[1]); bool error = false; char* path = argv[1]; char* dirname = NULL; char* basename = NULL; parse_path(path, &dirname, &basename); int parent_ino = getino(device, dirname); int my_ino = getino(device, path); INODE* parent_ip = get_inode(device, parent_ino); INODE* my_ip = get_inode(device, my_ino); char name[1024]; // Should only need 256 int rec_len = 0; int name_len = 0; u8* block = get_block(device, my_ip->i_block[0]); DIR* dp = (DIR*)block; rec_len = dp->rec_len; name_len = dp->name_len; strncpy(name, dp->name, name_len); name[name_len] = '\0'; // Parent Inode if(parent_ino != expected.parent_ino) { error = true; fprintf(stderr, "Parent Inode Number: %d" "\tExpected: %d\n", parent_ino, expected.parent_ino); } // My Inode if(my_ino != expected.my_ino) { error = true; fprintf(stderr, "My Inode Number: %d" "\tExpected: %d\n", my_ino, expected.my_ino); } //RETHINK if(strlen(basename) != expected.name_len) { error = true; fprintf(stderr, "Name Length: %d" "\tExpected: %d\n", strlen(basename), expected.name_len); } // Record Length if(rec_len != expected.rec_len) { error = true; fprintf(stderr, "Record Length: %d" "\tExpected: %d\n", rec_len, expected.rec_len); } // Name Length if(name_len != expected.name_len) { error = true; fprintf(stderr, "Name Length: %d" "\tExpected: %d\n", name_len, expected.name_len); } // Name if(strcmp(basename, expected.name) != 0) { error = true; fprintf(stderr, "Name: %s" "\tExpected: %d\n", basename, expected.my_ino); } // Type if((my_ip->i_mode & 0xF000) != expected.type) { error = true; fprintf(stderr, "Mode: %#o" "\tExpected: %#o\n", my_ip->i_mode, expected.my_ino); } // Links Count if(my_ip->i_links_count != expected.links_count) { error = true; fprintf(stderr, "Links Count: %d" "\tExpected: %d\n", my_ip->i_links_count, expected.links_count); } // Size if(my_ip->i_size != expected.size) { error = true; fprintf(stderr, "Size: %d" "\tExpected: %d\n", my_ip->i_size, expected.size); } // User ID if(my_ip->i_uid != expected.uid) { error = true; fprintf(stderr, "UID: %d" "\tExpected: %d\n", my_ip->i_uid, expected.uid); } // Group ID if(my_ip->i_gid != expected.gid) { error = true; fprintf(stderr, "GID: %d" "\tExpected: %d\n", my_ip->i_gid, expected.gid); } free(dirname); free(basename); free(parent_ip); free(my_ip); if(error) return false; else return true; } int main(int argc, char* argv[]) { // For each test file in directory test: { char* device_name = NULL; int device = 0, j = 0; char* test_file_names[3] = { "test0", "test1", NULL }; // get name of device device_name = argv[1]; initialize_fs(); mount_root(device_name); running = &ProcessTable[0]; running->status = READY; running->cwd = root; root->refCount++; running->uid = SUPER_USER; // Populate Arrays populate_arrays(test_file_names[j]); // Loop entire program for each test file? // Loops through all elements of Input int i = 0; while(true) { bool isMatch = false; char** cmd_argv = NULL; int cmd_argc = 0; int (*cmd_fptr)(int, char**) = NULL; if(!Input[i]) { quit_test(); break; } cmd_argv = parse(Input[i], " "); // Parse input into cmd argv[] while(cmd_argv[++cmd_argc]){} // Determine cmd argc cmd_fptr = get_cmd(cmd_argv[0]); // Get the command's function pointer cmd_fptr(cmd_argc, cmd_argv); // Execute the command with parameters // Check if current state matches expected state // If they don't match, stop testing for this test file // because the state mismatch will likely cascade after this point isMatch = isStateMatch(cmd_argc, cmd_argv, device, Expect[i]); free_array(cmd_argv); if(!isMatch) break; i++; } } return 0; }
C
#include <errno.h> #include <unistd.h> #include <sys/types.h> /* Set the foreground process group ID of FD set PGRP_ID. */ int tcsetpgrp (fd, pgrp_id) int fd; pid_t pgrp_id; { if (fd < 0) { _set_errno (EBADF); return -1; } _set_errno (ENOSYS); return 0; }
C
#define _CRT_SECURE_NO_WARNINGS //󾯸 #include <stdio.h> int main02() { int arr[10] = { 0,1,2,3,4,5,6,7,8,9 }; int size = sizeof(arr) / sizeof(arr[0]); for (int i = 0; i < size ; i++) { arr[i] = arr[i] + arr[size - 1]; arr[size - 1] = arr[i] - arr[size - 1]; arr[i] = arr[i] - arr[size - 1]; size--; } for (int i = 0; i < sizeof(arr) / sizeof(arr[0]); i++) { printf("%d\n", arr[i]); } return 0; }
C
#include "msrp_session.h" /* Contexts management */ /* Recursive function to get the full context path, considering its relay hops */ char *msrp_context_build_path(msrp_context *context) { if(!context) return NULL; if(!context->relay) return NULL; /* Get previous paths recursively */ char *path = msrp_context_build_path(context->through); if(context->through && !path) /* Previous hops have no path? */ return NULL; char *relay = msrp_peer_get_path(context->relay); if(!relay) return NULL; if(!context->through) /* Just one relay */ return relay; char *fullpath = calloc(strlen(path) + strlen(relay)+1, sizeof(char)); if(!fullpath) return NULL; /* Concatenate the paths from the previous hops and the context's relay */ sprintf(fullpath, "%s %s", path, relay); free(path); return fullpath; } /* Setup the external relay this context will refer to */ int msrp_context_setup_relay(msrp_context *context, char *address, unsigned short int port) { if(!context || !address || !port) return -1; /* TODO build relay */ return 0; } /* Free an existing context */ int msrp_context_free(msrp_context *context) { if(!context) return -1; free(context->name); if(context->relay) /* FIXME actually remove relay peer */ free(context->relay); free(context); return 0; } /* Sessions management */ /* Create a new session */ msrp_session *msrp_session_new(unsigned long int ID) { if(!ID) return NULL; msrp_session *session = calloc(1, sizeof(*session)); if(!session) return NULL; session->callid = NULL; session->context = NULL; session->session = NULL; session->from = NULL; session->to = NULL; session->fd = -1; int j = 0; for(j = 0; j < MSRP_MSG_BUFFER; j++) { session->in_msg[j] = NULL; session->out_msg[j] = NULL; } session->next = NULL; return session; } /* Set the local peer ("From") in this session */ int msrp_session_set_from(msrp_session *session, msrp_peer *from) { if(!session || !from) return -1; session->from = from; from->session = session; return 0; } /* Set the remote peer ("To") in this session */ int msrp_session_set_to(msrp_session *session, msrp_peer *to) { if(!session || !to) return -1; session->to = to; to->session = session; return 0; } /* Get the address for a peer (whose? "From"/"To") in this session */ char *msrp_session_get_address(msrp_session *session, char *whose) { if(!session || !whose) return NULL; msrp_peer *who = NULL; if(!strcasecmp(whose, "from")) who = session->from; else if(!strcasecmp(whose, "to")) who = session->to; if(!who) return NULL; return who->address; } /* Get the port for a peer (whose? "From"/"To") in this session */ unsigned short int msrp_session_get_port(msrp_session *session, char *whose) { if(!session || !whose) return 0; msrp_peer *who = NULL; if(!strcasecmp(whose, "from")) who = session->from; else if(!strcasecmp(whose, "to")) who = session->to; if(!who) return 0; return who->port; } /* Get the session ID for a peer (whose? "From"/"To") in this session */ char *msrp_session_get_sessionid(msrp_session *session, char *whose) { if(!session || !whose) return NULL; msrp_peer *who = NULL; if(!strcasecmp(whose, "from")) who = session->from; else if(!strcasecmp(whose, "to")) who = session->to; if(!who) return NULL; return who->sessionid; } /* Get the full MSRP URL path for a peer (whose? "From"/"To") in this session */ char *msrp_session_get_fullpath(msrp_session *session, char *whose) { if(!session || !whose) return NULL; msrp_peer *who = NULL; if(!strcasecmp(whose, "from")) who = session->from; else if(!strcasecmp(whose, "to")) who = session->to; if(!who) { local_events(MSRP_ERROR, "Invalid whose '%s'", who); return NULL; } return msrp_peer_get_path(who); /* TODO add paths from context */ } /* Get the accepted-types for a peer (whose? "From"/"To") in this session */ char *msrp_session_get_accepttypes(msrp_session *session, char *whose) { if(!session || !whose) return NULL; msrp_peer *who = NULL; if(!strcasecmp(whose, "from")) who = session->from; else if(!strcasecmp(whose, "to")) who = session->to; if(!who) return NULL; char *types = calloc(1, sizeof(char)); /* FIXME */ if(who->flags & MSRP_TEXT_PLAIN) { types = realloc(types, strlen(types) + strlen("text/plain ")); strcat(types, "text/plain "); } if(who->flags & MSRP_TEXT_HTML) { types = realloc(types, strlen(types) + strlen("text/html ")); strcat(types, "text/html "); } return types; } /* Get session from the associated file descriptor(s) */ msrp_session *msrp_session_get(int fd) { if(fd < 1) return NULL; msrp_session *session = NULL; msrp_peer *from = NULL, *to = NULL; MSRP_LIST_CHECK(sessions, NULL); MSRP_LIST_CROSS(sessions, sessions_lock, session) from = session->from; to = session->to; if(session->fd == fd) break; if(from) { if(from->fd == fd) break; } if(to) { if(to->fd == fd) break; } MSRP_LIST_STEP(sessions, sessions_lock, session); return session; } /* Setup the connection between the two peers of this session */ int msrp_session_connect(msrp_session *session) { if(!session) return -1; msrp_peer *from = session->from; msrp_peer *to = session->to; if(!from || !to) return -1; if(from->flags & MSRP_PASSIVE) /* Start server */ return msrp_peer_listen(from); else if(from->flags & MSRP_ACTIVE) /* Start client */ return msrp_peer_connect(from, to); else return -1; } /* Destroy an existing session */ int msrp_session_destroy(msrp_session *session) { if(!session) return -1; /* Remove from list of sessions */ MSRP_LIST_REMOVE(sessions, sessions_lock, session); /* FIXME we don't take care of the whole session, peers are destroyed outside */ free(session); return 0; } /* Peers management */ /* Create a new peer entity */ msrp_peer *msrp_peer_new(char *sessionid) { msrp_peer *peer = calloc(1, sizeof(*peer)); if(!peer) return NULL; if(!sessionid) { /* Create a new random Session-ID */ peer->sessionid = calloc(13, sizeof(char)); random_string(peer->sessionid, 13); } else { /* Copy the SDP-negotiated ID */ peer->sessionid = calloc(strlen(sessionid)+1, sizeof(char)); if(!peer->sessionid) { free(peer); return NULL; } peer->sessionid = strcpy(peer->sessionid, sessionid); } local_events(MSRP_LOG, "Created peer with Session-ID %s", peer->sessionid); peer->session = NULL; peer->path = NULL; peer->address = NULL; peer->port = 0; peer->sockaddr = NULL; peer->fd = -1; peer->flags = 0; peer->rights = 0; peer->content = 0; peer->opaque = NULL; return peer; } /* Set the transport address for this peer */ int msrp_peer_set_address(msrp_peer *peer, char *address, unsigned short int port) { if(!peer || !address) return -1; peer->address = calloc(strlen(address)+1, sizeof(char)); if(!peer->address) return -1; strcpy(peer->address, address); peer->port = port; return 0; } /* Set the options for this peer */ int msrp_peer_set_options(msrp_peer *peer, int content, int flags) { if(!peer) return -1; peer->content = content; peer->flags = flags; return 0; } /* Update the read/write rights for this peer */ int msrp_peer_set_rights(msrp_peer *peer, int rights) { if(!peer) return -1; peer->rights = rights; return 0; } /* Get the path for this peer */ char *msrp_peer_get_path(msrp_peer *peer) { if(!peer) return NULL; if(!peer->path) { /* Build the full MSRP path */ peer->path = calloc(20 + strlen(peer->address) + strlen(peer->sessionid), sizeof(char)); if(!peer->path) return NULL; sprintf(peer->path, "msrp://%s:%hu/%s;tcp", peer->address, peer->port, peer->sessionid); } return peer->path; } /* If this is a local peer, have it bind to the provided port */ int msrp_peer_bind(msrp_peer *peer) { if(!peer) return -1; /* Create a socket and bind it to the provided port */ peer->sockaddr = calloc(1, sizeof(peer->sockaddr)); peer->sockaddr->sin_family = AF_INET; peer->sockaddr->sin_addr.s_addr = INADDR_ANY; peer->fd = socket(AF_INET, SOCK_STREAM, 0); if(peer->fd < 0) return -1; int yes = 1; if(setsockopt(peer->fd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) < 0) { close(peer->fd); peer->fd = -1; return -1; } unsigned short int port = peer->port; int retry = 0, success = 0, randomport = 0; if(!port) randomport++; for (retry = 0; retry < 100; retry++) { /* This could be needed for the random port */ if(randomport) port = 2000 + random() % 8000; peer->sockaddr->sin_port = htons(port); if(bind(peer->fd, (struct sockaddr *)(peer->sockaddr), sizeof(struct sockaddr)) < 0) { if(!randomport) { /* Port was explicit, fail */ close(peer->fd); peer->fd = -1; return -1; } } else { success++; break; } } if(success) peer->port = port; else { close(peer->fd); peer->fd = -1; return -1; } return 0; } /* If this is a passive local peer, have it start listening (server) */ int msrp_peer_listen(msrp_peer *peer) { if(!peer) return -1; if(!(peer->flags & MSRP_PASSIVE)) return -1; if(peer->fd < 1) return -1; /* Start listening on the provided port */ if(listen(peer->fd, 5) < 0) { close(peer->fd); peer->fd = -1; return -1; } msrp_recv_add_fd(peer->fd); if(peer->session) peer->session->fd = peer->fd; return 0; } /* If this is an active local peer, have it start connecting (client) */ int msrp_peer_connect(msrp_peer *peer, msrp_peer* dst) { if(!peer || !dst) return -1; if(!(peer->flags & MSRP_ACTIVE)) return -1; if(!(dst->flags & MSRP_PASSIVE)) return -1; if(peer->fd < 1) return -1; /* We're going to be the client, connect to the other peer */ dst->sockaddr = calloc(1, sizeof(dst->sockaddr)); dst->sockaddr->sin_family = AF_INET; dst->sockaddr->sin_port = htons(dst->port); if(inet_aton(dst->address, &(dst->sockaddr->sin_addr)) == 0) { /* Not a numeric IP... */ struct hostent *host = gethostbyname(dst->address); /* ...resolve name */ if(!host) { local_events(MSRP_ERROR, "Invalid host for address %s", dst->address ? dst->address : "???.???.???.???"); return -1; } dst->sockaddr->sin_addr = *(struct in_addr *)host->h_addr_list; } if(connect(peer->fd, (struct sockaddr *)dst->sockaddr, sizeof(struct sockaddr_in)) < 0) { local_events(MSRP_ERROR, "Couldn't connect to %s:%hu", dst->address, dst->port); return -1; } local_events(MSRP_LOG, "Connected at %s:%hu", dst->address, dst->port); dst->fd = peer->fd; msrp_recv_add_fd(dst->fd); if(peer->session->type == MSRP_ENDPOINT) local_ep_callback(MSRP_LOCAL_CONNECT, peer->session->session, 0, NULL, 0); /* TODO what else? */ return 0; } /* Destroy an existing peer entity */ int msrp_peer_destroy(msrp_peer *peer) { if(!peer) return -1; if(peer->path) free(peer->path); if(peer->address) free(peer->address); if(peer->sockaddr) free(peer->sockaddr); if(peer->sessionid) free(peer->sessionid); shutdown(peer->fd, SHUT_RDWR); close(peer->fd); free(peer); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct node{ int data; struct node *next; }nodetype; nodetype* insert(nodetype*); nodetype* dequeue(nodetype*); void display(nodetype*); int main(){ nodetype *front=NULL,*rear=NULL; int ch; do{ printf("\n1 Insert \n2 Delete \n3 Display \n4 Exit \n Enter your choice :"); scanf("%d",&ch); switch(ch){ case 1: rear = insert(rear); if(front==NULL) front=rear; break; case 2: front = dequeue(front); if(front==NULL) rear=front; break; case 3: display(front); break; case 4: break; } }while(ch<=3&&ch>0); return 0; } nodetype* insert(nodetype *rear){ nodetype *p=NULL; int num; printf("\nEnter the value to be inserted :"); scanf("%d",&num); p=(nodetype*)malloc(sizeof(nodetype)); if(p!=NULL) p->data=num; else printf("\nmemory not allocated"); if(rear==NULL) rear=p; else{ rear->next=p; rear=p; } rear->next=NULL; return rear; } nodetype* dequeue(nodetype *front){ nodetype *temp=NULL; if(front==NULL) printf("\nqueue is empty"); else{ temp=front; printf("\ndeleted value is %d",front->data); front=front->next; free(temp); } return front; } void display(nodetype *front){ if(front!=NULL){ while(front!=NULL){ printf("\n%d",front->data); front=front->next; } } else printf("\nqueue is empty"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* comb.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: alcaroff <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/12 19:26:30 by alcaroff #+# #+# */ /* Updated: 2018/10/14 22:16:45 by alcaroff ### ########.fr */ /* */ /* ************************************************************************** */ #include "lem_in.h" static int is_same_path(t_list *path1, t_list *path2) { while (path1 && path2) { if (path1->content != path2->content) return (0); path1 = path1->next; path2 = path2->next; } return (1); } static int path_cmp(t_list *path1, t_list *path2) { t_list *save; save = path2; while (path1) { path2 = save; while (path2) { if ((t_room *)path1->content == (t_room *)path2->content && ((t_room *)path2->content)->type == 0) return (1); path2 = path2->next; } path1 = path1->next; } return (0); } static int path_is_in_comb(t_list *comb, t_list *path) { while (comb) { if (path_cmp(path, comb->content) || is_same_path(path, comb->content)) return (1); comb = comb->next; } return (0); } static int score(t_list *comb) { int score; score = 0; score += ft_lstlen(comb) * 100; while (comb) { score -= ft_lstlen((t_list *)comb->content) / 2; comb = comb->next; } return (score); } int ft_find_comb(t_list *paths, t_list *path, t_list **comb, t_list *current_comb) { t_list *paths_cpy; if (path) { ft_lstnewadd(NULL, 0, &current_comb); current_comb->content = path; } if (score(*comb) < score(current_comb)) { ft_lstfree(comb); *comb = ft_lstcpy(current_comb); } paths_cpy = paths; while (paths_cpy) { if (!path_is_in_comb(current_comb, paths_cpy->content)) ft_find_comb(paths, paths_cpy->content, comb, current_comb); paths_cpy = paths_cpy->next; } if (current_comb) free(current_comb); return (0); }
C
#include "bubblesort.h" /////////////////////////////////////////////////////// //////////仿照qsort写自己的冒泡排序通用函数//////////////// /////////////////////////////////////////////////////// int cmp(const void* e1,const void* e2)//比较函数 { return *(int*)e2 - *(int*)e1; } int main() { int arr[10] = { 9,0,8,7,6,5,4,1,3,2 }; bubsort(arr, 10, 4, cmp); for (int i = 0; i < 10; i++) { printf("%d", arr[i]); } return 0; }
C
#include<stdio.h> #include<conio.h> void main() { long int n,m=1,rem,ans=0; printf("\nEnter Your Decimal No : "); scanf("%d",&n); while(n>0) { rem=n%8; ans=(rem*m)+ans; n=n/8; m=m*10; } printf("\nConvert into Octal No is : %d",ans); }
C
// Driverlib includes #include "rom.h" #include "rom_map.h" #include "hw_memmap.h" #include "hw_common_reg.h" #include "hw_types.h" #include "hw_ints.h" #include "uart.h" #include "interrupt.h" #include "pinmux.h" #include "utils.h" #include "prcm.h" // Common interface include #include "uart_if.h" //***************************************************************************** // MACROS //***************************************************************************** #define APPLICATION_VERSION "1.1.1" #define APP_NAME "UART Eko" #define CONSOLE UARTA0_BASE #define UartGetChar() MAP_UARTCharGet(CONSOLE) #define UartPutChar(c) MAP_UARTCharPut(CONSOLE,c) #define MAX_STRING_LENGTH 80 volatile int g_iCounter = 0; static void DisplayBanner(char * AppName) { Report("\n\n\n\r"); Report("\t\t *************************************************\n\r"); Report("\t\t CC3200 %s Uygulamasi \n\r", AppName); Report("\t\t *************************************************\n\r"); Report("\n\n\n\r"); } void main() { char cString[MAX_STRING_LENGTH+1]; char cCharacter; int iStringLength = 0; PinMuxConfig(); //rx,tx pin ayarlari InitTerm(); //uart terminal init ClearTerm(); //terminal temizlendi DisplayBanner(APP_NAME); Message("\t\t****************************************************\n\r"); Message("\t\t\t CC3200 UART Eko Kullanimi \n\r"); Message("\t\t Yazilan veri RX bacagina gider. \n\r"); Message("\t\t Gelen veri terminale yazilir \n\r") ; Message("\t\t Not: maksimum 80 karakter olabilir. \n\r"); Message("\t\t Yazdiktan sonra ENTER tusuna basin \n\r"); Message("\t\t ****************************************************\n\r"); Message("\n\n\n\r"); Message("CMD# "); while(1) { cCharacter = UartGetChar(); //gelen karakteri oku g_iCounter++; //sayaci bir arttir if(cCharacter == '\r' || cCharacter == '\n' || (iStringLength >= MAX_STRING_LENGTH -1)) //entera basilirsa { if(iStringLength >= MAX_STRING_LENGTH - 1) //butun karakterleri yazma { UartPutChar(cCharacter); cString[iStringLength] = cCharacter; iStringLength++; } cString[iStringLength] = '\0'; iStringLength = 0;// sifirla Report("\n\rCMD# %s\n\r\n\rCMD# ", cString); } else { UartPutChar(cCharacter); cString[iStringLength] = cCharacter; iStringLength++; } } }
C
#include <stdio.h> #include <stdlib.h> int Compare(const void *e1, const void *e2) { int *p1 = (int*)e1; int *p2 = (int*)e2; return (*p1 - *p2); } int main() { int size, sum = 0, i; int *arr = NULL; double average = 0.0; printf(" ԷϽðڽϱ? :"); scanf("%d", &size); arr = malloc(sizeof(int) * size); printf("%d ԷϽÿ", size); for (i = 0; i < size; i++) { scanf("%d", &arr[i]); } qsort(arr, size, sizeof(int), Compare); for (i = 0; i < size; i++) printf("%d ", arr[i]); free(arr); arr = NULL; return 0; }
C
#include<stdio.h> #include<stdlib.h> void mymemset(void *ptr,int val,int len) { if(ptr!=NULL && len > 0) { unsigned char *temp=ptr; int i=0; for(i=0;i<len;i++) { *temp++=(unsigned char)val; } } } int main() { char *ptr; ptr=(char *)malloc(sizeof(char)); mymemset(ptr,'a',sizeof(ptr)); puts(ptr); }
C
/****************************************************************************** * Created by Jarni Vanmal * freertos_hello_world.c: Using Buttons ******************************************************************************/ /* FreeRTOS includes. */ #include "FreeRTOS.h" #include "task.h" #include "queue.h" #include "timers.h" /* Xilinx includes. */ #include "xil_printf.h" #include "xparameters.h" #define TIMER_ID 1 #define DELAY_10_SECONDS 10000UL #define DELAY_1_SECOND 1000UL #define TIMER_CHECK_THRESHOLD 9 static void prvSend( void *pvParameters ); static void prvReceive( void *pvParameters ); static void vTimerCallback( TimerHandle_t pxTimer ); static TaskHandle_t xSend; static TaskHandle_t xReceive; static QueueHandle_t xQueue = NULL; static TimerHandle_t xTimer = NULL; //------------------------------------------------------------------- #include "xgpio_l.h" #define BUTTON_CHANNEL 1 int main( void ) { const TickType_t x10seconds = pdMS_TO_TICKS( DELAY_10_SECONDS ); print("Project 6: Using Buttons\n\r"); print("By Jarni Vanmal\n\r"); xTaskCreate( prvSend, ( const char * ) "Send", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY, &xSend ); xTaskCreate( prvReceive, ( const char * ) "Receive", configMINIMAL_STACK_SIZE, NULL, tskIDLE_PRIORITY + 1, &xReceive ); xQueue = xQueueCreate( 1, sizeof( u32 ) ); // We use u32 data in the queue for this project configASSERT( xQueue ); xTimer = xTimerCreate( (const char *) "Timer", x10seconds, pdFALSE, (void *) TIMER_ID, vTimerCallback); configASSERT( xTimer ); xTimerStart( xTimer, 0 ); vTaskStartScheduler(); for( ;; ); } /*-----------------------------------------------------------*/ static void prvSend( void *pvParameters ) { const TickType_t x1second = pdMS_TO_TICKS( DELAY_1_SECOND ); u32 sendData; for( ;; ) { vTaskDelay( x1second ); sendData = XGpio_ReadReg(XPAR_GPIO_0_BASEADDR, ((BUTTON_CHANNEL - 1) * XGPIO_CHAN_OFFSET) + XGPIO_DATA_OFFSET); xQueueSend( xQueue, &sendData, 0UL ); } } static void prvReceive( void *pvParameters ) { u32 RecvData; for( ;; ) { xQueueReceive( xQueue, &RecvData, portMAX_DELAY ); switch(RecvData) { case 1: xil_printf("Button 1\n\r"); break; case 2: xil_printf("Button 2\n\r"); break; case 4: xil_printf("Button 3\n\r"); break; case 8: xil_printf("Button 4\n\r"); break; // case 16:xil_printf("Button 5\n\r"); break; } } } static void vTimerCallback( TimerHandle_t pxTimer ) { xil_printf( "Stopped after 10 seconds."); vTaskDelete( xSend ); vTaskDelete( xReceive ); }