language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <dlfcn.h> #include <ffi.h> #include <malloc.h> #include <stdlib.h> int main() { //拿函数指针 void *lib_handle = dlopen("./test_return.so", RTLD_NOW|RTLD_GLOBAL); void* functionPtr = dlsym(lib_handle, "testFunc"); int argCount = 2; //按ffi要求组装好参数类型数组 ffi_type **ffiArgTypes = alloca(sizeof(ffi_type *) *argCount); ffiArgTypes[0] = &ffi_type_sint; ffiArgTypes[1] = &ffi_type_sint; //按ffi要求组装好参数数据数组 void **ffiArgs = alloca(sizeof(void *) *argCount); void *ffiArgPtr = alloca(ffiArgTypes[0]->size); int *argPtr = ffiArgPtr; *argPtr = 8; ffiArgs[0] = ffiArgPtr; void *ffiArgPtr2 = alloca(ffiArgTypes[1]->size); int *argPtr2 = ffiArgPtr2; *argPtr2 = 2; ffiArgs[1] = ffiArgPtr2; //生成 ffi_cfi 对象,保存函数参数个数/类型等信息,相当于一个函数原型 ffi_cif cif; ffi_type *returnFfiType = &ffi_type_sint; ffi_status ffiPrepStatus = ffi_prep_cif_var(&cif, FFI_DEFAULT_ABI, (unsigned int)0, (unsigned int)argCount, returnFfiType, ffiArgTypes); if (ffiPrepStatus == FFI_OK) { //生成用于保存返回值的内存 void *returnPtr = NULL; if (returnFfiType->size) { returnPtr = alloca(returnFfiType->size); } //根据cif函数原型,函数指针,返回值内存指针,函数参数数据调用这个函数 ffi_call(&cif, functionPtr, returnPtr, ffiArgs); //拿到返回值 int returnValue = *(int *)returnPtr; printf("ret: %d \n", returnValue); } } #if 0 int main() { ffi_cif cif; void *lib_handle = dlopen("./test_return.so", RTLD_NOW|RTLD_GLOBAL); void * entry_point = dlsym(lib_handle, "test_return_sshort"); ffi_status status = ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 0, &ffi_type_sshort, NULL); signed short ret; ffi_call(&cif, entry_point, &ret, NULL); fprintf(stderr, "%d\n", (signed short)ret); return 0; } #endif
C
// See LICENSE for license details. #include <stdio.h> #include "hbird_sdk_hal.h" #ifdef SOC_HBIRD #ifdef BOARD_HBIRD_EVAL #define BTN1_GPIO_OFS 30 #define BTN2_GPIO_OFS 31 #define PLIC_BTN1_INT (8+BTN1_GPIO_OFS) #define PLIC_BTN2_INT (8+BTN2_GPIO_OFS) #endif #endif #ifdef SOC_HBIRD #ifdef BOARD_HBIRD_EVAL // plic btn1 interrupt handler void plic_btn1_handler(void) { printf("Enter Button 1 interrupt\n"); gpio_clear_interrupt(GPIO, SOC_BUTTON_1_GPIO_OFS, GPIO_INT_RISE); gpio_toggle(GPIO, SOC_LED_BLUE_GPIO_MASK); } // plic btn2 interrupt handler void plic_btn2_handler(void) { printf("Enter Button 2 interrupt\n"); gpio_clear_interrupt(GPIO, SOC_BUTTON_2_GPIO_OFS, GPIO_INT_RISE); gpio_toggle(GPIO, SOC_LED_GREEN_GPIO_MASK); } #endif #endif #ifdef SOC_HBIRDV2 #if (defined BOARD_DDR200T) || (defined BOARD_MCU200T) // plic btn interrupt handler void plic_btn_handler(void) { int mask; printf("Enter PLIC GPIOA Interrupt\n"); mask = gpio_clear_interrupt(GPIOA); switch (mask) { case SOC_BUTTON_U_GPIO_MASK: printf("Cause: Button U \n"); gpio_toggle(GPIOA, SOC_LED_0_GPIO_MASK); printf("LED 0 Toggled \n"); break; case SOC_BUTTON_D_GPIO_MASK: printf("Cause: Button D \n"); gpio_toggle(GPIOA, SOC_LED_1_GPIO_MASK); printf("LED 1 Toggled \n"); break; case SOC_BUTTON_L_GPIO_MASK: printf("Cause: Button L \n"); gpio_toggle(GPIOA, SOC_LED_2_GPIO_MASK); printf("LED 2 Toggled \n"); break; case SOC_BUTTON_R_GPIO_MASK: printf("Cause: Button R \n"); gpio_toggle(GPIOA, SOC_LED_3_GPIO_MASK); printf("LED 3 Toggled \n"); break; case SOC_BUTTON_C_GPIO_MASK: printf("Cause: Button C \n"); gpio_toggle(GPIOA, SOC_LED_4_GPIO_MASK); printf("LED 4 Toggled \n"); break; default: break; } } #endif #endif void board_gpio_init(void) { #ifdef SOC_HBIRD #ifdef BOARD_HBIRD_EVAL gpio_enable_input(GPIO, SOC_BUTTON_GPIO_MASK); gpio_set_pue(GPIO, SOC_BUTTON_GPIO_MASK, GPIO_BIT_ALL_ONE); gpio_enable_output(GPIO, SOC_LED_GPIO_MASK); gpio_write(GPIO, SOC_LED_GPIO_MASK, GPIO_BIT_ALL_ZERO); // Initialize the button as rising interrupt enabled gpio_enable_interrupt(GPIO, SOC_BUTTON_GPIO_MASK, GPIO_INT_RISE); #endif #endif #ifdef SOC_HBIRDV2 #if (defined BOARD_DDR200T) || (defined BOARD_MCU200T) gpio_enable_input(GPIOA, SOC_BUTTON_GPIO_MASK); gpio_enable_output(GPIOA, SOC_LED_GPIO_MASK); gpio_write(GPIOA, SOC_LED_GPIO_MASK, GPIO_BIT_ALL_ZERO); // Initialize the button as rising interrupt enabled gpio_enable_interrupt(GPIOA, SOC_BUTTON_GPIO_MASK, GPIO_INT_RISE); #endif #endif } int main(int argc, char **argv) { int32_t returnCode; board_gpio_init(); #ifdef SOC_HBIRD #ifdef BOARD_HBIRD_EVAL // inital plic int0 interrupt returnCode = PLIC_Register_IRQ(PLIC_BTN1_INT, 1, plic_btn1_handler); // inital plic int1 interrupt returnCode = PLIC_Register_IRQ(PLIC_BTN2_INT, 2, plic_btn2_handler); #endif #endif #ifdef SOC_HBIRDV2 #if (defined BOARD_DDR200T) || (defined BOARD_MCU200T) // inital plic GPIOA interrupt returnCode = PLIC_Register_IRQ(PLIC_GPIOA_IRQn, 1, plic_btn_handler); #endif #endif // Enable interrupts in general. __enable_irq(); printf("Wait for Interrupt \n"); // Wait button 1 and button 2 pressed to trigger interrupt while (1); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "./models/movie.h" #include "./views/views.h" int main() { int i; int status = 1; // Status del programa /* Collecion de peliculas */ MovieCollection* catalog; catalog = (MovieCollection*) malloc(sizeof(MovieCollection)); catalog->movies = (Movie*) malloc(sizeof(Movie)); catalog->size = 0; /* Muestra el programa */ while(status == 1) { status = views__renderMenu(catalog); } /* Limpia la memoria */ for(i = 0; i < catalog->size; i++) // Limpia pelicula por pelicula. { movie__freeMovie(&(catalog->movies[i])); } free(catalog->movies); free(catalog); return 0; }
C
/************************************************************************* > File Name: my_signal.c > Author: Linuxer_liu > Mail: > Created Time: 2017年07月31日 星期一 16时29分54秒 ************************************************************************/ #include<stdio.h> #include<stdlib.h> #include<signal.h> #include<sys/types.h> void test1(int signo) { printf("SIGINT\n") ; } void test2(int signo) { printf("SIGQUIT\n") ; } int main(void) { signal(SIGINT,test1) ; signal(SIGQUIT,test2); while(1) ; return 0; }
C
//#define _CRT_SECURE_NO_WARNINGS 1 // //#include <stdio.h> //#include <stdlib.h> //#include <assert.h> //#include <stdbool.h> // //typedef struct Position //{ // int row; // int col; //}pos; // //bool ispass(char** board, char* word, int row, int col, pos next, int k, int len) //{ // if (next.row < row && next.row >= 0 && next.col < col && next.col >= 0 && board[next.row][next.col] == word[k]) // { // return true; // } // else // { // return false; // } //} // //bool getword(char** board, char* word, int row, int col, pos cur, int k, int len) //{ // // if (k == len - 1) // { // return true; // } // // pos next; // board[cur.row][cur.col] = 2; // // // // next = cur; // next.row -= 1; // if (ispass(board, word, row, col, next, k + 1, len)) // { // if (getword(board, word, row, col, cur, k, len)) // { // return true; // } // } // // // // next = cur; // next.row += 1; // if (ispass(board, word, row, col, next, k + 1, len)) // { // if (getword(board, word, row, col, cur, k, len)) // { // return true; // } // } // // // // next = cur; // next.col -= 1; // if (ispass(board, word, row, col, next, k + 1, len)) // { // if (getword(board, word, row, col, cur, k, len)) // { // return true; // } // } // // // // next = cur; // next.col += 1; // if (ispass(board, word, row, col, next, k + 1, len)) // { // if (getword(board, word, row, col, cur, k, len)) // { // return true; // } // } // // return false; //} // //bool exist(char** board, int boardSize, int boardColSize, char* word) //{ // int row = boardSize; // int col = boardColSize; // int k = 0;//word[k] // int len = strlen(word); // pos cur = { 0,0 }; // if (getword(board, word, row, col, cur, k, len)) // { // return true; // } // else // { // return false; // } //} // //int main() //{ // int N = 0, M = 0; // while (scanf("%d%d", &N, &M) != EOF) // { // //Թ // //ȴ // //Ƕλ飬ȴһNָָ飬ָ鴢ָ룬ָָָΪָ // //ָÿָ붼Ϊָ룬ÿָָΪÿһ // int** Maze = (int**)malloc(sizeof(int*) * N); // for (int i = 0; i < N; i++) // { // //Maze[i]int*һָ룬ٵĿռ䴢int // Maze[i] = (int*)malloc(sizeof(int) * M); // } // // //Թ // for (int i = 0; i < N; i++) // { // for (int j = 0; j < M; j++) // { // scanf("%d", &Maze[i][j]); // } // } // // exist({ {'A', 'B', "C", "E"},{"S", "F", "C", "S"},{"A", "D", "E", "E"} }, N, M, "ABCCED"); // // for (int i = 0; i < N; i++) // { // free(Maze[i]); // } // free(Maze); // Maze = NULL; // } // return 0; //}
C
/* ** my_atoi.c for my_atoi in /home/artha/signal_test ** ** Made by dylan renard ** Login <[email protected]> ** ** Started on Fri Feb 17 12:38:33 2017 dylan renard ** Last update Fri Feb 17 12:52:31 2017 dylan renard */ #include "my.h" int my_atoi(char *nb) { int final; int sign; int i; int j; final = 0; sign = 1; j = 1; if (nb[0] == '-') { sign = -1; nb++; } i = my_strlen(nb) - 1; while (i != -1) { final = final + ((nb[i] - '0') * j); i--; j *= 10; } return (final * sign); }
C
void LabInfo(){ //Task 1 cout<< "Cian Baynes"<< endl; cout<< "Lab 2"<<endl; } void LabInfo1(int x, int y){ //Task 2 if (x>y){ cout<<"The largest value is "<<x<<endl; } else{ cout<<"The largest value is "<<y<<endl; } } void Numberlarge(){ //Task 3 int num=0; cout<<"\n\nEnter a number between 1 and 100"<< endl; cin>>num; if (num>=1 && num<=100){ cout<<"The number is within range\n\n"<<endl; } else{ cout<<"The number is outside of the range\n\n"<<endl; } } void radius(){ //Task 5 float Pi=3.14159; float Rad=0; float Area=0; cout<<"\n\nEnter the radius of the circle that you would like the area to?"<<endl; cin>>Rad; Area=(Pi*Rad*Rad); cout<<"The area of the circle is "<<Area<<"m^2"<<endl; } void rectangle(){ //Task 6 int length=0; int height=0; int recarea=0; cout<<"\n\nEnter the height of the rectangle"<<endl; cin>>height; cout<<"Enter the length of the rectangle"<<endl; cin>>length; recarea=(length*height); cout<<"The area of the rectangle is "<<recarea<<"m^2"<<endl; } void tempertaure(){ //Task 7 int temp=0; int hum=0; cout<<"\n\nEnter the humidity"<<endl; cin>>hum; cout<<"Enter the temperature"<<endl; cin>>temp; if ((temp>=95) || (hum>=90)){ cout<<"ALARM ALARM, The temperature or humidity is outside of range"<<endl; } else { cout<<"The temperature and humidity are within range\n\n"<<endl; system("pause"); } } void RadiusLoop(){ //Task 8 float radi=0; float PI=3.14159; float area=0; for (radi=1; radi<=120; ++radi){ area=(PI*radi*radi); cout<<area<<"m^2 with the radius from 1-120"<<endl; } } void Tempconversion(){ //Task 9 float temp=0; float cel=0; float fahr=0; char convert=0; cout<<"\n\nEnter temperature to convert"<<endl; cin>>temp; fahr=((temp * 9/5) + 32); cel= ((temp - 32) * 5/9); cout<<"Type a for celsius to fahrenheit conversion\nType b for fahrenheit to celsius conversion\n"<<endl; cin>>convert; switch(convert){ case 'a': cout<<"The temperature is "<<fahr<<"F\n\n"<<endl; break; case 'b': cout<<"The temperature is "<<cel<<"C\n\n"<<endl; break; } system("pause"); } void evennumbers(){ //Task 10 for (int num1=0; num1<=1000; ++num1){ if (num1%2==0){ cout<<num1<<endl; } } } void oddnumbers(){ //Task 11 int oddnum1=0; int oddnum2=0; cout<<"\n\nEnter number 1:"<<endl; cin>>oddnum1; cout<<"Enter number 2:"<<endl; cin>>oddnum2; cout<<"The odd numbers between the two numbers entered are:"<<endl; for (int oddnum3 = oddnum1; oddnum3<=oddnum2; oddnum3++){ if (oddnum3%2==1){ cout<<oddnum3<<endl; } } } void q11array(){ //Task 12 int x[6]; x[0]=0; x[1]=0; x[2]=0; x[3]=0; x[4]=0; x[5]=0; cout<<"Please enter first number of 6 numbers for the array"<<endl; cin>>x[0]; cout<<"Please enter second number of 6 numbers for the array"<<endl; cin>>x[1]; cout<<"Please enter third number of 6 numbers for the array"<<endl; cin>>x[2]; cout<<"Please enter fourth number of 6 numbers for the array"<<endl; cin>>x[3]; cout<<"Please enter fifth number of 6 numbers for the array"<<endl; cin>>x[4]; cout<<"Please enter sixth number of 6 numbers for the array"<<endl; cin>>x[5]; cout<<"\nThe odd numbers in the array are:"<<endl; for (int i=0; i<6; ++i){ if (x[i]%2==1){ cout<<x[i]<<endl; } } } void randomnumbers(){ //Task 13 float v1=0; float v2=0; float v3=0; float v4=0; float v5=0; float v6=0; v1=rand()%10; v2=rand()%1000+1; v3=rand()%50+185; v4=rand()%100+1087; v5=rand()%165+35; v6=rand()%19872; cout<<"\n\nThe random numbers are: "<<v1<<" "<<v2<<" "<<v3<<" "<<v4<<" "<<v5<<" "<<v6<<endl; } void question14(){ //Task 14 /* Print the numbers 5 through 9: */ int i=5; while (i < 10){ cout <<i<<endl; i++; } /* Finding the sum 1 + 2 + 3 + ... + 20 */ i = 1; int sum =0; while (i<=20) { sum = sum + i; i = i + 1; } cout << "The sum = " <<sum<<endl; /* Average a list of grades terminated by -1 */ sum = 0; int count = 0; int grade=0; cout << "Enter grade (-1 to end): "; // prompt user for grade cin >> grade; // read grade while (grade != -1) { sum = sum + grade; count = count + 1; /* Get next grade */ cout << "Enter grade (-1 to end): "; cin >> grade; } if (count > 0) cout << "Average is " << (double) sum / count<<endl; system ("pause"); } void Question15(){ //Task 15 for (int i=0; i<10; i++){ cout<<"finished"<<endl; } int i=0; while (i<10){ ++i; cout<<"finished"<<endl; } int x=0; do { cout<<"finished"<<endl; ++x; }while(x<10); }
C
#include "editor.h" void disable_raw_mode(t_termios orig_termios) { tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios); } t_termios enable_raw_mode(void) { t_termios new_termios; t_termios orig_termios; tcgetattr(STDIN_FILENO, &orig_termios); new_termios = orig_termios; new_termios.c_lflag &= ~(ICANON | ECHO | ISIG); new_termios.c_iflag &= ~(ICRNL | IXON); new_termios.c_oflag &= ~(OPOST); new_termios.c_cc[VMIN] = 0; new_termios.c_cc[VTIME] = 1; tcsetattr(STDIN_FILENO, TCSAFLUSH, &new_termios); return (orig_termios); }
C
/* hello-world.c * * time tutorial * https://www.youtube.com/watch?v=Qoed2uBwF_o */ #include <stdio.h> #include <time.h> #include <unistd.h> // Sleep function. int main(int argc, char **argv) { printf("Hello World\n"); // Get time. time_t now = time(NULL); printf("%ld\n", now); // # of seconds since Jan. 1, 1970 midnight. // Convert time to a string with ctime. char *string_now = ctime(&now); printf("%s\n", string_now); // Get time broken out into parts. struct tm *gm_time = gmtime(&now); // Grenigs time. printf("tm_sec: %d\n", gm_time->tm_sec); printf("tm_min: %d\n", gm_time->tm_min); printf("tm_hour: %d\n", gm_time->tm_hour); printf("tm_mday: %d\n", gm_time->tm_mday); printf("tm_mon: %d\n", gm_time->tm_mon); // Starting from 0. printf("tm_year: %d\n", gm_time->tm_year); // Years from 1900. printf("tm_wday: %d\n", gm_time->tm_wday); printf("tm_yday: %d\n", gm_time->tm_yday); printf("tm_isdst: %d\n", gm_time->tm_isdst); printf("\n"); struct tm *cur_time = localtime(&now); printf("tm_sec: %d\n", cur_time->tm_sec); printf("tm_min: %d\n", cur_time->tm_min); printf("tm_hour: %d\n", cur_time->tm_hour); printf("tm_mday: %d\n", cur_time->tm_mday); printf("tm_mon: %d\n", cur_time->tm_mon); // Starting from 0. printf("tm_year: %d\n", cur_time->tm_year); // Years from 1900. printf("tm_wday: %d\n", cur_time->tm_wday); printf("tm_yday: %d\n", cur_time->tm_yday); printf("tm_isdst: %d\n", cur_time->tm_isdst); char s[100]; strftime(s, 100, "%c", cur_time); printf("%s\n", s); return 0; }
C
#pragma once #ifndef FAT_H #define FAT_H #include <stdio.h> #include <stdint.h> #include <assert.h> #include "fat_structure.h" struct fat_data { char *memory; /* pole predstavuje fat disk*/ size_t memory_size; /* velikost pole memory */ struct boot_record *boot_record; /* boot record Fat disku */ uint32_t *fat1; /* prvni kopie fat tabulky */ uint32_t *fat2; /* druha kopie fat tabulky */ unsigned int start_of_fat; /* index zacatku fat tabulek */ unsigned int fat_record_size; /* Velikost zaznamu ve fat tabulce */ unsigned int fat_size; /* Velikost fat tabulky */ unsigned int start_of_root_dir; /* index zacatku root slozky */ unsigned int max_dir_entries; /* maximalni pocet zaznamu ve slozce */ }; /** * Z fat data nacte fat disk a inicializuje potrebne struktury v f_data podle dat ve fat disku * * @param f_data struktura obsahujici informace o nactenem fat disku * @return -1 pri chybe, 0 pri uspechu */ int fat_init(struct fat_data *f_data); /** * Vycisti alokovanou pamet ve strukture f_data * * @param f_data struktura obsahujici informace o nactenem fat disku */ void close_fat(struct fat_data *f_data); /** * Vytvori prazdny soubor ve fat na danem miste * * @param f_data struktura obsahujici informace o nactenem fat disku * @param new_file nastavi na nove vytvoreny soubor * @param file_name jmeno vytvareneho souboru * @param act_fat_position pozice adresare ve kterem vytvarime soubor * @param dir_position pozice zaznamu o souboru ve slozce vzhledem k celemu disku * @return chybovy kod nebo 0 pri uspechu */ int fat_create_file(struct fat_data *f_data, struct dir_file **new_file, const char *file_name, uint32_t act_fat_position, unsigned long *dir_position); /** * Vrati zaznam o souboru nacteneho z fat disku nachazici se ve slozce zacinajici na act_fat_position * * @param f_data struktura obsahujici informace o nactenem fat disku * @param file_name jmeno hledaneho souboru * @param file_type typ hledaneho souboru 0 - dir 1 - file * @param act_fat_position pozice adresare ve kterem hledame soubor * @param dir_position pozice zaznamu o souboru ve slozce vzhledem k celemu disku * @return zaznam nalezeneho souboru nebo NULL */ struct dir_file *fat_get_object_info_by_name(struct fat_data *f_data, const char *file_name, unsigned int file_type, uint32_t act_fat_position, unsigned long *dir_position); /** * Smaze soubor ve FAT v danem adresari s danym jmenem. * * @param f_data struktura obsahujici informace o nactenem fat disku * @param file_name jmeno hledaneho souboru * @param act_fat_position pozice adresare ve kterem hledame soubor * @return chybovy kod nebo 0 pri uspechu */ int fat_delete_file_by_name(struct fat_data *f_data, const char *file_name, uint32_t act_fat_position); /** * Smaze soubor ve FAT v dany zaznamem file a pozici zaznamu position. * * @param f_data struktura obsahujici informace o nactenem fat disku * @param file zaznam predstavujici soubor, ktery se smaze * @param position pozice zaznamu v nadrazene slozce vzhledem k celemu fat disku * @return chybovy kod nebo 0 pri uspechu */ int fat_delete_file_by_file(struct fat_data *f_data, struct dir_file *file, unsigned long position); /** * Precte dany soubor od dane pozice a vysledek ulozi do buffer. * * @param f_data struktura obsahujici informace o nactenem fat disku * @param file zaznam souboru ze ktereho se bude cist * @param buffer pole do ktereho se budou nacitat data * @param buffer_size velikost bufferu * @param read pocet prectenych znaku * @param offset od ktere pozice se bude v souboru cist * @return chybovy kod nebo 0 pri uspechu */ int fat_read_file(struct fat_data *f_data, struct dir_file *file, char *buffer, unsigned int buffer_size, size_t *read, unsigned long offset); /** * Zapise data z bufferu do daneho souboru. Zapis zacne od pozice offset a puvodni data se prepisi. * Offset nesmi byt vetsi nez je velikost souboru. Souboru je zmenena velikost v zavislosti na * zapsanych datech * * @param f_data struktura obsahujici informace o nactenem fat disku * @param file zaznam souboru ze ktereho se bude cist * @param dir_position pozice zaznamu v nadrazene slozce vzhledem k celemu fat disku * @param buffer pole ze ktereho se budou nacitat data * @param buffer_size velikost bufferu * @param writed pocet zapsanych znaku * @param offset od ktere pozice se bude v souboru zapisovat * @return chybovy kod nebo 0 pri uspechu */ int fat_write_file(struct fat_data *f_data, struct dir_file *file, unsigned long dir_position, char *buffer, unsigned int buffer_size, size_t *writed, unsigned long offset); /** * Vytrovy novy prazdny adresar na zvolenem miste. * * @param f_data struktura obsahujici informace o nactenem fat disku * @param new_dir zaznam adresare, ktery se vytvori * @param dir_name jmeno hledaneho adresare * @param act_fat_position pozice adresare ve kterem hledame adresar * @param dir_position pozice zaznamu vytvoreneho souboru v nadrazene slozce vzhledem k celemu disku * @return chybovy kod nebo 0 pri uspechu */ int fat_create_dir(struct fat_data *f_data, struct dir_file **new_dir, const char *dir_name, uint32_t act_fat_position, unsigned long *dir_position); /** * Smaze prazdny adresar ve FAT. * * @param f_data struktura obsahujici informace o nactenem fat disku * @param dir_name jmeno hledaneho adresare * @param act_fat_position pozice adresare ve kterem hledame adresar * @return chybovy kod nebo 0 pri uspechu */ int fat_delete_empty_dir(struct fat_data *f_data, const char *dir_name, uint32_t act_fat_position); /** * Nacte veskere zaznamy o souborech a slozkach v adresari * * @param f_data struktura obsahujici informace o nactenem fat disku * @param act_fat_position index do fat tabulky zacatku prohledavane slozky * @param files pocet vracenych zaznamu * @param positions pozice zaznamu nactenych souboru v adresari vzhledem k celemu fat disku * @return pole(pointer) nactenych zaznamu, NULL pri chybe */ struct dir_file *fat_read_dir(struct fat_data *f_data, uint32_t act_fat_position, uint32_t *files, unsigned long * positions); /** * Nastavi velikost soubour na hodnotu danou file_size a uvolni nepotrebne clustery. * file_size nesmi byt vetsi nez je skutecna velikost souboru * * @param f_data struktura obsahujici informace o nactenem fat disku * @param file zaznam souboru, ktery se bude zmensovat * @param file_size nova velikost souboru * @param dir_position pozice zaznamu v nadrazene slozce vzhledem k celemu fat disku * @return chybovy kod nebo 0 pri uspechu */ int fat_set_file_size(struct fat_data *f_data, struct dir_file * file, size_t file_size, unsigned long dir_position); #endif
C
#ifndef __ACTIVITY1_H_ #define __ACTIVITY1_H_ /** * @file activity1.h * @author Charanya () * @brief Project to Blink an LED connected to AVR328 MCU GPIO Pin if Push button of the car seat is closed and heater switch is turned ON * @version 0.1 * @date 2021-04-23 * * @copyright Copyright (c) 2021 * */ /** * Include files */ #include <avr/io.h> #include <util/delay.h> /** * Macro Definitions */ #define ON (1) /**< LED state HIGH */ #define OFF (0) /**< LED state LOW */ #define LED_ON_TIME (200) /**< LED ON time in milli seconds */ #define LED_OFF_TIME (100) /**< LED OFF time in milli seconds */ /** * Macro Definitions */ #define LED (PORTB) /**< LED Port Number */ #define LED_PIN (PB0) /**< LED Pin Number */ #define BUTTON (PORTD) /** Push Button Port Number of the car seat */ #define BUTTON_PIN (PD0) /** Push Button Pin Number of the car seat */ #define SWITCH (PORTC) /** Switch Port Number of the Heater */ #define SWITCH_PIN (PC0) /** Switch Pin Number of the car Heater */ /** * Function Definitions */ /** * @brief initialize the pull up natured peripherals */ void peripheral_init(void); /** * @brief Change the state of the LED Pin according to the state of the push button in car seat and heater switch * * @param state Pin level to which the LED Pin should be set */ void led_on(uint8_t state); void led_off(uint8_t state); /** * @brief Function to generate delay in micro seconds * * @param[in] delay_time Delay in Micro seconds * */ void delay_ms(uint32_t delay_time); #endif /** __ACTIVITY1_H_ */
C
#include <stdio.h> #include <stdlib.h> #include "esparsa.h" //KPS void Esparsa_init(TEsparsa *E){ E->inicio=NULL; E->fin=NULL; E->numElem=0; } int Esparsa_isEmpty(TEsparsa *E){ return E->numElem==0; } int Esparsa_length(TEsparsa *E){ return E->numElem; } void Esparsa_insert(TEsparsa *E,int pos,TElemento e){ TNodo *nodo=malloc(sizeof(TNodo)); nodo->pos=pos; nodo->elem=e; nodo->sig=NULL; if (Esparsa_isEmpty(E)){ E->inicio=nodo; E->fin=nodo; } else{ E->fin->sig=nodo; E->fin=nodo; } (E->numElem)++; } void Esparsa_sumar(TEsparsa *A,TEsparsa *B,TEsparsa *C){ //Tendremos dos nodos que recorran la lista A y B respectivamente TNodo *crtnodoA=A->inicio; TNodo *crtnodoB=B->inicio; TElemento suma; int pos; //EL bucle acaba cuando una de las lista acaba while (crtnodoA!=NULL && crtnodoB!=NULL){ // si las pos de ambos crtnodos son iguales, la sumamos; if (crtnodoA->pos==crtnodoB->pos){ suma=crtnodoA->elem+crtnodoB->elem; Esparsa_insert(C,crtnodoA->pos,suma); crtnodoA=crtnodoA->sig; crtnodoB=crtnodoB->sig; } else{ //Si no es así, insertamos en C el menos de estos y avanzamos ese crtnodo; if (crtnodoA->pos<crtnodoB->pos){ Esparsa_insert(C,crtnodoA->pos,crtnodoA->elem); crtnodoA=crtnodoA->sig; } if (crtnodoA->pos>crtnodoB->pos){ Esparsa_insert(C,crtnodoB->pos,crtnodoB->elem); crtnodoB=crtnodoB->sig; } } } //En caso alguna esparsa no haya acabado, se insertará en C //Si A no acabó while (crtnodoA!=NULL){ Esparsa_insert(C,crtnodoA->pos,crtnodoA->elem); crtnodoA=crtnodoA->sig; } //SI B no acabó while (crtnodoB!=NULL){ Esparsa_insert(C,crtnodoB->pos,crtnodoB->elem); crtnodoB=crtnodoB->sig; } } void Esparsa_print(TEsparsa *E){ //imprime hasta que acabe if (!Esparsa_isEmpty(E)){ TNodo *crtnodo=E->inicio; while(crtnodo!=NULL){ printf("%d %d ",crtnodo->pos,crtnodo->elem); crtnodo=crtnodo->sig; } printf("\n"); } }
C
#include <stdio.h> #include <stdlib.h> #include <mpi.h> #include <time.h> #define N 1600 #define P 2 int main(int argc, char* argv[]){ int rank, new_rank, size, new_size, reorder; int buff[(N/P) * (N/P)]; int dims[3], period[3],coords[3], A[3][N][N]; int localMax = 0; int globalMaxR = 0; int globalMaxG = 0; int globalMaxB = 0; srand(time(NULL)); MPI_Init(&argc, &argv); MPI_Comm_rank(MPI_COMM_WORLD,&rank); MPI_Comm_size(MPI_COMM_WORLD, &size); MPI_Status status; MPI_Comm new_comm; MPI_Request request; //Creo el tipo de datos MPI_Type_vector MPI_Datatype block; MPI_Type_vector(N/P, N/P, N, MPI_INT, &block); MPI_Type_commit(&block); //creo la topologa cartesiana dims[0]=3; dims[1]=P; dims[2]=P; reorder=0; period[0]=0; period[1]=1; period[2]=0; MPI_Cart_create(MPI_COMM_WORLD, 3, dims, period, reorder, &new_comm); MPI_Comm_rank(new_comm,&new_rank); MPI_Comm_size(new_comm, &new_size); //si soy el proceso maestro... if(new_rank==0){ //inicializo la matriz con valores aleatorios de 0 a 255 for(int k=0; k<3; k++){ for(int i=0; i<N; i++){ for(int j=0; j<N; j++){ A[k][i][j]=rand()%256; // printf("%d ",A[k][i][j]); }//printf("\n"); }//printf("\n\n"); } //reparto los cuadrantes de las matrices entre los 12 procesos for(int k=0; k<3; k++){ for(int i = 0; i < P; i++){ for(int j =0; j< P ; j++){ coords[0] = k; coords[1] = i; coords[2] = j; MPI_Cart_rank(new_comm, coords, &new_rank); //printf("soy %d y envio a %d\n", new_rank, A[k][i * (N/P)][j * (N/P)]); MPI_Isend(&(A[k][i * (N/P)][j * (N/P)]), 1, block, new_rank, 1, new_comm, &request); } new_rank=0; } } //proceso 0 recibe su cuadrante y calcula su maximo MPI_Recv(&buff, (N/P)*(N/P), MPI_INT, 0, 1, new_comm, &status); //printf("Soy el proceso 0: "); for(int p = 0; p < (N/P)*(N/P); p++){ if(buff[p] > localMax){ localMax = buff[p]; } //printf("%d ", buff[p]); } printf("Soy el proceso 0. Mi maximo local es %d\n", localMax); } else { //los procesos 1-11 reciben su cuadrante y calculan su maximo MPI_Recv(&buff, (N/P)*(N/P), MPI_INT, 0, 1, new_comm, &status); // printf("Soy el proceso %d: ", new_rank); for(int p = 0; p < (N/P)*(N/P); p++){ if(buff[p] > localMax){ localMax = buff[p]; } // printf("%d ", buff[p]); } printf("\nSoy el proceso %d. Mi maximo local es %d\n", new_rank, localMax); } //Cada proceso enva el maximo del cuadrante que han recibido al maestro con diferente etiqueta, dependiendo de su matriz(sea R,G o B) if(new_rank<4){ MPI_Isend(&localMax, 1, MPI_INT, 0, 1, new_comm, &request); }else if (new_rank<8){ MPI_Isend(&localMax, 1, MPI_INT, 0, 2, new_comm, &request); }else{ MPI_Isend(&localMax, 1, MPI_INT, 0, 3, new_comm, &request); } //Si es el maestro recibe los maximos locales de los demas procesos y calcula con ello el maximo de cada una de las 3 matrices (R, G y B) if(new_rank == 0){ int num; for(int i = 0; i < size; i ++){ MPI_Recv(&num, 1, MPI_INT, i, MPI_ANY_TAG, new_comm, &status); if(i < 4){ printf("El proceso %d ha enviado como maximo el numero %d que pertenece a la matriz R\n", i, num); if(num > globalMaxR){ globalMaxR = num; } } else if (i < 8){ printf("El proceso %d ha enviado como maximo el numero %d que pertenece a la matriz G\n", i, num); if(num > globalMaxG){ globalMaxG = num; } }else if (i < 12){ printf("El proceso %d ha enviado como maximo el numero %d que pertenece a la matriz B\n", i, num); if(num > globalMaxB){ globalMaxB = num; } } } //Se imprime el maximo de R, G y B printf("\nEl valor maximo de la matriz R es %d \n", globalMaxR); printf("\nEl valor maximo de la matriz G es %d \n", globalMaxG); printf("\nEl valor maximo de la matriz B es %d \n", globalMaxB); } MPI_Finalize(); return 0; }
C
/* program can be found at: http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/fork/create.html */ /* fork2.c similiar to fork1.c but uses the sleep command to synchronise the parent and the child */ #include <stdio.h> #include<unistd.h> #include <sys/types.h> #define MAX_COUNT 20 void ChildProcess(void); /* child process prototype */ void ParentProcess(void); /* parent process prototype */ void main(void) { pid_t pid; pid = fork(); // fork creates a copy of the current process if (pid < 0) printf("error unable to fork process; ending program"); if (pid == 0) ChildProcess(); else { printf("the fork command returns the PID of the child: %d\n",pid); ParentProcess(); } } void ChildProcess(void) { int i,x, pid1, pid2; pid1 = getpid(); // get PID of the parent process pid2 = getppid(); // get the grand partent of the process for (i = 1; i <= MAX_COUNT; i++){ printf("\tThis line is from child (pid number %d) the pid of the childs parent is %d, value = %d\n",pid1,pid2, i); for (x=0; x<1000000;x++); // code to slow the process } printf(" *** Child process is done ***\n"); } void ParentProcess(void) { int i,x, pid1; pid1= getpid(); sleep(1); // puts the parent process to sleep.... for (i = 1; i <= MAX_COUNT; i++){ printf("This line is from parent (Pid %d), value = %d\n",pid1, i); for(x=0; x<1000000;x++); // code to slow process } printf("*** Parent is done ***\n"); }
C
/* -- PCF Operating System -- * See [docs\COPYRIGHT.txt] for more info */ /** @file lib\include\libc\internal.h @brief Libc internal use */ #ifndef LIB_INCLUDE_LIBC_INTERNAL_H #define LIB_INCLUDE_LIBC_INTERNAL_H /** @brief Float type struct */ typedef struct { /** @brief Mantissa */ unsigned mantissa:23; /** @brief Exponent */ unsigned exponent:8; /** @brief Sign */ unsigned sign:1; } float_t; /** @brief Double type struct */ typedef struct { /** @brief Mantissa low */ unsigned mantissal:32; /** @brief Mantissa high */ unsigned mantissah:20; /** @brief Exponent */ unsigned exponent:11; /** @brief Sign */ unsigned sign:1; } double_t; /** @brief Long Double type struct */ typedef struct { /** @brief Mantissa low */ unsigned mantissal:32; /** @brief Mantissa high */ unsigned mantissah:32; /** @brief Exponent */ unsigned exponent:15; /** @brief Sign */ unsigned sign:1; } long_double_t; #endif
C
#include <stdio.h> int min(int, int); int max(int, int); int main() { int n = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { int a = 0; int b = 0; scanf("%d %d", &a, &b); int minv = min(a,b); int maxv = max(a,b); if (minv % 2 == 0) { minv++; } else { minv += 2; } int sum = 0; for (int j = minv; j < maxv; j+=2) { sum += j; } printf("%d\n", sum); } return 0; } int min(int a, int b) { if (a < b) { return a; } else { return b; } } int max(int a, int b) { if (a > b) { return a; } else { return b; } }
C
/** * Auteur : Nicolas Levasseur * * Ce programme a ete concu pour tester trois methodes d'integration numeriques * (methode des trapezes, de Simpson et de Simpson 3/8). On a pense a la * modularite du code, donc on utilise pas la fonction exponentielle directement * mais elle est passee en argument aux diverses methodes. On execute le code * tant que l'utilisateur le demande. */ #include <stdio.h> #include <math.h> /** * Cette fonction trouve la valeur exacte (si on ne prend pas en compte l'erreur * introduite sur les doubles par C) de l'integrale entre borneInf et borneSup * de la fonction exponentielle. * * borneInf : Borne inferieure de l'integrale definie * borneSup : Borne superieure de l'integrale definie * * return : La fonction exponentielle evaluee a la borne supperieure moins la * fonction exponentielle a la borne inferieure */ double integrale_exacte(float borneInf, float borneSup){ return exp(borneSup) - exp(borneInf); } /** * On trouve la valeur de l'integrale par la methode des trapezes de la * fonction exponentielle entre borneInf et borneSup. * * nTermes : Nombre de termes a calculer pour la sommation * borneInf : Borne inferieure d'integration * borneSup : Borne superieure d'integration * fonction : Fonction a integrer * * return : Valeur de l'integrale approximee */ double Trapeze(int nTermes, float borneInf, float borneSup, double (*fonction)(double)) { /* Hauteur d'un trapeze (largeur dx) */ const double hauteur = (borneSup - borneInf) / nTermes; /* Terme par lequel on va multiplier la hauteur des trapezes pour obtenir * l'integrale finale */ double integrale = (fonction(borneInf) + fonction(borneSup)) / 2; for (int i = 1; i < nTermes; i++) integrale += fonction(borneInf + i * hauteur); return hauteur * integrale; } /** * On trouve la valeur de l'integrale par la methode de Simpson d'une fonction * entre borneInf et borneSup. * * nTermes : Nombre de termes a calculer pour la sommation * borneInf : Borne inferieure d'integration * borneSup : Borne superieure d'integration * fonction : Fonction a integrer * * return : Valeur de l'integrale approximee */ double Simpson(int nTermes, float borneInf, float borneSup, double (*fonction)(double)) { /* Pas d'integration (largeur dx) */ const double pas = (borneSup - borneInf) / nTermes; /* Terme par lequel on va multiplier le pas / 3 pour obtenir l'integrale * finale */ double integrale = fonction(borneInf) + fonction(borneSup); for (int i = 1; i < nTermes; i++) { if (i % 2) integrale += 4 * fonction(borneInf + i * pas); else integrale += 2 * fonction(borneInf + i * pas); } return pas / 3 * integrale; } /** * On trouve la valeur de l'integrale par la methode de Simpson 3/8 d'une * fonction entre borneInf et borneSup. * * nTermes : Nombre de termes a calculer pour la sommation * borneInf : Borne inferieure d'integration * borneSup : Borne superieure d'integration * fonction : Fonction a integrer * * return : Valeur de l'integrale approximee */ double Simpson3Sur8(int nTermes, float borneInf, float borneSup, double (*fonction)(double)) { /* Pas d'integration (largeur dx) */ const double pas = (borneSup - borneInf) / nTermes; /* Terme par lequel on va multiplier 3 * pas / 8 pour obtenir l'integrale * finale */ double integrale = fonction(borneInf) + fonction(borneSup); for(int i = 1; i < nTermes; i++) { if(i % 3) integrale += 3 * fonction(borneInf + i * pas); else integrale += 2 * fonction(borneInf + i * pas); } return 3 * pas / 8 * integrale; } /** * Cette fonction montre le resultat d'une integration numerique a l'utilisateur * et divers parametres importants de cette integration. * * nom : Nom de la methode utilisee pour integrer * nTermes : nombre de termes necessaires a l'integration * borneInf : Borne inferieure d'integration * borneSup : Borne superieure d'integration * integraleExacte : Valeur veritable de l'integrale * fonction : Fonction a integrer * methode : Methode d'integration utilisee */ void montre_resultats(const char nom[], int nTermes, float borneInf, float borneSup, double integraleExacte, double (*fonction)(double), double (*methode)(int, float, float, double (*f)(double))) { double integraleApprox = methode(nTermes, borneInf, borneSup, fonction); double erreur = fabs(integraleApprox - integraleExacte) / integraleExacte * 100; printf("%-12s %8d %19.14f %10.6lf%%\n", nom, nTermes, integraleApprox, erreur); } int main(){ /* Bornes d'integrations */ float borneInf, borneSup; /* Reponse de l'utilisateur */ char rep; do { /* On recupere les bornes d'integrations */ printf("Entrez les bornes: "); scanf("%f%f", &borneInf, &borneSup); /* On trouve la valeur exacte de l'integrale */ double integraleExacte = integrale_exacte(borneInf, borneSup); printf("Valeur exacte: %19.14f\n", integraleExacte); printf("Methode Intervalles Valeur approximee Erreur\n\n"); /* Boucle sur le nombre de termes utilises pour calculer l'integrale */ for(int nTermes = 6; nTermes <= 30; nTermes += 6){ montre_resultats("Trapeze", nTermes, borneInf, borneSup, integraleExacte, exp, Trapeze); montre_resultats("Simpson", nTermes, borneInf, borneSup, integraleExacte, exp, Simpson); montre_resultats("Simpson 3/8", nTermes, borneInf, borneSup, integraleExacte, exp, Simpson3Sur8); printf("\n"); } printf( "Voulez-vous continuer? Taper 'o' si oui, n'importe quelle autre " "touche pour quitter.\n"); scanf(" %c", &rep); printf("\n"); } while(rep == 'o'); return 0; } /* Entrez les bornes: 0 1 Valeur exacte: 1.71828182845905 Methode Intervalles Valeur approximee Erreur Trapeze 6 1.72225749247148 0.231374% Simpson 6 1.71828916992083 0.000427% Simpson 3/8 6 1.71829829247231 0.000958% Trapeze 12 1.71927608944639 0.057864% Simpson 12 1.71828228843802 0.000027% Simpson 3/8 12 1.71828286255749 0.000060% Trapeze 18 1.71872375064165 0.025719% Simpson 18 1.71828191936081 0.000005% Simpson 3/8 18 1.71828203291292 0.000012% Trapeze 24 1.71853041528076 0.014467% Simpson 24 1.71828185722555 0.000002% Simpson 3/8 24 1.71828189317032 0.000004% Trapeze 30 1.71844092568213 0.009259% Simpson 30 1.71828184024268 0.000001% Simpson 3/8 30 1.71828185496873 0.000002% Voulez-vous continuer? Taper 'o' si oui, n'importe quelle autre touche pour quitter. o Entrez les bornes: -1 0 Valeur exacte: 0.63212055882856 Methode Intervalles Valeur approximee Erreur Trapeze 6 0.63358312388374 0.231374% Simpson 6 0.63212325960142 0.000427% Simpson 3/8 6 0.63212661560056 0.000958% Trapeze 12 0.63248632700496 0.057864% Simpson 12 0.63212072804537 0.000027% Simpson 3/8 12 0.63212093925212 0.000060% Trapeze 18 0.63228313291414 0.025719% Simpson 18 0.63212059226945 0.000005% Simpson 3/8 18 0.63212063404294 0.000012% Trapeze 24 0.63221200880961 0.014467% Simpson 24 0.63212056941117 0.000002% Simpson 3/8 24 0.63212058263451 0.000004% Trapeze 30 0.63217908742608 0.009259% Simpson 30 0.63212056316352 0.000001% Simpson 3/8 30 0.63212056858092 0.000002% Voulez-vous continuer? Taper 'o' si oui, n'importe quelle autre touche pour quitter. o Entrez les bornes: -1 1 Valeur exacte: 2.35040238728760 Methode Intervalles Valeur approximee Erreur Trapeze 6 2.37212517685413 0.924216% Simpson 6 2.35056148681103 0.006769% Simpson 3/8 6 2.35075574460899 0.015034% Trapeze 12 2.35584061635522 0.231374% Simpson 12 2.35041242952225 0.000427% Simpson 3/8 12 2.35042490807287 0.000958% Trapeze 18 2.35281999933237 0.102859% Simpson 18 2.35040437457987 0.000085% Simpson 3/8 18 2.35040685214215 0.000190% Trapeze 24 2.35176241645134 0.057864% Simpson 24 2.35040301648339 0.000027% Simpson 3/8 24 2.35040380180961 0.000060% Trapeze 30 2.35127284221421 0.037034% Simpson 30 2.35040264508287 0.000011% Simpson 3/8 30 2.35040296702037 0.000025% Voulez-vous continuer? Taper 'o' si oui, n'importe quelle autre touche pour quitter. o Entrez les bornes: -1.5 1.5 Valeur exacte: 4.25855891018963 Methode Intervalles Valeur approximee Erreur Trapeze 6 4.34691140764325 2.074704% Simpson 6 4.25999469497233 0.033715% Simpson 3/8 6 4.26169853074054 0.073725% Trapeze 12 4.28071583468034 0.520292% Simpson 12 4.25865064369270 0.002154% Simpson 3/8 12 4.25876379670942 0.004811% Trapeze 18 4.26841212467614 0.231374% Simpson 18 4.25857710513704 0.000427% Simpson 3/8 18 4.25859971430526 0.000958% Trapeze 24 4.26410246529756 0.130174% Simpson 24 4.25856467550330 0.000135% Simpson 3/8 24 4.25857185810276 0.000304% Trapeze 30 4.26210711795574 0.083319% Simpson 30 4.25856127324214 0.000055% Simpson 3/8 30 4.25856422074276 0.000125% Voulez-vous continuer? Taper 'o' si oui, n'importe quelle autre touche pour quitter. n */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* possibilite.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: itouaila <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/29 18:45:46 by itouaila #+# #+# */ /* Updated: 2018/07/29 19:26:53 by itouaila ### ########.fr */ /* */ /* ************************************************************************** */ #include "sudoku.h" #include "possibilite.h" #include "arbre.h" #include "solve.h" int check_possibilite(int t[9][9],int i, int j, t_sudoku **debut) { int k; int cp; k = 1; cp = 0; while (k < 10) { if (!is_in_square(t, i - i % 3, j - j % 3, k)) { if (!is_in_row(t, i, j, k)) { if (!is_in_col(t, i, j, k)) { add_posibilite(debut, k, i, j); cp = cp + 1; } } } k++; } return (cp); } int parcours(t_arbre *root, int value) { t_sudoku *list; int trouve; t_arbre *tmp; trouve = 0; tmp = root->next; while (tmp) { list = tmp->debut; while (list) { if (value == list->value) { trouve = 1; supp_arbre(root, list->value); break ; } list = list->next; } if (trouve) return (trouve); tmp = tmp->next; } return (trouve); } t_arbre *remplir(int t[9][9], int si, int sj, int *cp, t_sudoku **debut) { t_arbre *a; int i; int j; a = NULL; i = si - 3; while (i < si) { j = sj - 3; while (j < sj) { if (t[i][j] == 0) { *cp = 0; *debut = NULL; *cp = check_possibilite(t, i, j, debut); add_arbre(&a, *debut); } j++; } i++; } return (a); } void is_unique(int t[9][9], int cp,t_sudoku *debut,t_arbre *root) { t_sudoku tmp; if (cp != 1) { tmp = recherche_possibilite(root); if (tmp.value != 0) { t[tmp.i][tmp.j] = tmp.value; } } else if (cp == 1 && debut) { tmp = *debut; t[tmp.i][tmp.j] = tmp.value; } } void solve_square(int t[9][9], int cp, t_sudoku *debut, t_arbre *root) { int ligne; int column; int si; int sj; ligne = 0; si = 0; sj = 0; while (ligne < 3) { column = 0; si += 3; sj = 0; while (column < 3) { sj += 3; root = remplir(t, si, sj, &cp, &debut); is_unique(t, cp, debut , root); root = NULL; column++; } ligne++; } } t_sudoku recherche_possibilite(t_arbre *root) { t_sudoku l1= {0, NULL,'n', -1, -1}; t_sudoku *l3; t_arbre *tmp; int trouve; tmp = root; while (root) { l3 = root->debut; while (l3) { trouve = parcours(root,l3->value); if (trouve == 0) { l1 = *l3; return (l1); } l3 = l3->next; } root = root->next; } return (l1); }
C
/*! \file main.c \brief This file is the entry point for paragon's various components \date Started 11/27/09 \author George \version\verbatim $Id: omp_main.c 9585 2011-03-18 16:51:51Z karypis $ \endverbatim */ #include "simdocs.h" #include <pthread.h> #ifndef NTHREADS #define NTHREADS 2 #endif pthread_cond_t condThreadDone, condWorkReady; pthread_mutex_t lockThreadDone, lockWorkReady; int threadsFinished; int workReady; pthread_mutex_t lockCurrentlyIdle; pthread_cond_t condCurrentlyIdle; int currentlyIdle; pthread_mutex_t lockCanFinish; pthread_cond_t condCanFinish; int canFinish; struct ThreadData { int queryDoc; gk_csr_t *mat; gk_csr_t *subMat; gk_fkv_t *hits; int nhits; params_t *params; }; void *findSimilarDoc(void *data) { int i, j, nhits; int32_t *marker; gk_fkv_t *hits, *cand; FILE *fpout; int numRowsToWork; params_t *params; //index or row number of matrix to work on int queryDoc, prevQueryDoc; gk_csr_t *mat; gk_csr_t *subMat; //get the data passed to the thread struct ThreadData *threadData = (struct ThreadData *) data; mat = threadData->mat; subMat = threadData->subMat; params = threadData->params; /* allocate memory for the necessary working arrays */ hits = gk_fkvmalloc(subMat->nrows, "ComputeNeighbors: hits"); marker = gk_i32smalloc(subMat->nrows, -1, "ComputeNeighbors: marker"); cand = gk_fkvmalloc(subMat->nrows, "ComputeNeighbors: cand"); threadData->hits = hits; prevQueryDoc = -1; queryDoc = threadData->queryDoc; while (1) { //set thread as idle and signal to main thread, //all threads should be idle before starting pthread_mutex_lock(&lockCurrentlyIdle); currentlyIdle++; pthread_cond_signal(&condCurrentlyIdle); pthread_mutex_unlock(&lockCurrentlyIdle); //wait for restart signal from main thread for execution pthread_mutex_lock(&lockWorkReady); while (!workReady) { //TODO: is prev query equal to curr query check necessary pthread_cond_wait(&condWorkReady, &lockWorkReady); } pthread_mutex_unlock(&lockWorkReady); //get the new query doc queryDoc = threadData->queryDoc; /* find the best neighbors for the query document */ if (params->verbosity > 0) printf("Working on query %7d\n", queryDoc); /* find the neighbors of the ith document */ nhits = gk_csr_GetSimilarRows(subMat, mat->rowptr[queryDoc+1]-mat->rowptr[queryDoc], mat->rowind+mat->rowptr[queryDoc], mat->rowval+mat->rowptr[queryDoc], GK_CSR_COS, params->nnbrs, params->minsim, hits, marker, cand); threadData->nhits = nhits; //enter the mutex and increment the threads finished counter //get the mutex lock pthread_mutex_lock(&lockThreadDone); //increment the threads finished counter threadsFinished++; //signal the main thread pthread_cond_signal(&condThreadDone); //release the mutex lock pthread_mutex_unlock(&lockThreadDone); // Wait for permission to finish pthread_mutex_lock(&lockCanFinish); while (!canFinish) { pthread_cond_wait(&condCanFinish , &lockCanFinish); } pthread_mutex_unlock(&lockCanFinish); prevQueryDoc = queryDoc; } gk_free((void **)&hits, &marker, &cand, LTERM); pthread_exit(0); } //from two sorted array will find top nsim values in linear time //finaltop hits is of size nsim, and after this function call will contain // top nsim of combined both hits1 and hits 2, return number of top values in final array int findTopKHits(gk_fkv_t *finalTopHits, int nsim, gk_fkv_t *hits1,\ int countHit1, gk_fkv_t *hits2, int countHit2) { int start1, start2, finalStart; start1 = 0, start2 = 0, finalStart = 0; while (start1 < countHit1 && start2 < countHit2 && finalStart < nsim) { if (hits1[start1].key > hits2[start2].key) { finalTopHits[finalStart++] = hits1[start1]; start1++; } else { finalTopHits[finalStart++] = hits2[start2]; start2++; } } while (start1 < countHit1 && finalStart < nsim ) { //hits2 exhausted finalTopHits[finalStart++] = hits2[start1++]; } while (start2 < countHit2 && finalStart < nsim ) { //hits1 exhausted finalTopHits[finalStart++] = hits2[start2++]; } return finalStart; } /*************************************************************************/ /*! Reads and computes the neighbors of each document */ /**************************************************************************/ void ComputeNeighbors(params_t *params) { int i, j, k; gk_csr_t *mat; gk_fkv_t *hits; FILE *fpout; int nnzCount; int nnzPerThread; int remainingNNZ; int prevRowUsed; int prevNNZCount; int tempNNZCount; int queryDoc; int tempHitCount; int nsim; int numLastChunkRows; struct ThreadData threadData[NTHREADS]; pthread_t p_threads[NTHREADS]; pthread_attr_t attr; printf("Reading data for %s...\n", params->infstem); mat = gk_csr_Read(params->infstem, GK_CSR_FMT_CSR, 1, 0); printf("#docs: %d, #nnz: %d.\n", mat->nrows, mat->rowptr[mat->nrows]); //get the nonzero count nnzCount = mat->rowptr[mat->nrows]; /* compact the column-space of the matrices */ gk_csr_CompactColumns(mat); /* perform auxiliary normalizations/pre-computations based on similarity */ gk_csr_Normalize(mat, GK_CSR_ROW, 2); /* allocate memory for the necessary working arrays */ hits = gk_fkvmalloc(params->nnbrs*NTHREADS, "ComputeNeighbors: hits"); /* create the inverted index */ gk_csr_CreateIndex(mat, GK_CSR_COL); /* create the output file */ fpout = (params->outfile ? gk_fopen(params->outfile, "w",\ "ComputeNeighbors: fpout") : NULL); /* prepare threads */ pthread_attr_init(&attr); pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM); //initialize conditional variables pthread_cond_init(&condThreadDone, NULL); pthread_cond_init(&condWorkReady, NULL); pthread_cond_init(&condCurrentlyIdle, NULL); pthread_cond_init(&condCanFinish, NULL); //initialize mutex pthread_mutex_init(&lockThreadDone, NULL); pthread_mutex_init(&lockWorkReady, NULL); pthread_mutex_init(&lockCurrentlyIdle, NULL); pthread_mutex_init(&lockCanFinish, NULL); //initialize initial conditional flags currentlyIdle = 0; workReady = 0; canFinish = 0; //initialize initial queryDoc queryDoc = 0; //divide the matrix based on nnz among threads //work per thread nnzPerThread = mat->rowptr[mat->nrows] / NTHREADS; prevRowUsed = -1; //create threads gk_startwctimer(params->timer_1); for (i=0; i < NTHREADS; i++) { if (prevRowUsed == -1) { prevNNZCount = 0; } else { //prev row used represent the last row used in iteration prevNNZCount = mat->rowptr[prevRowUsed + 1]; } //assign the suitable number of rows to the thread for (j = prevRowUsed + 1; j < mat->nrows; j++) { tempNNZCount = mat->rowptr[j] - prevNNZCount; if (tempNNZCount >= nnzPerThread) { break; } } //decrement to get the right j that can fit j--; //prepare data for thread i //assign the submatrix to work on if (i == NTHREADS - 1) { //last thread then assign all remaining rows threadData[i].subMat = gk_csr_ExtractSubmatrix(mat, prevRowUsed + 1, \ (mat->nrows - 1) - (prevRowUsed)); } else { //extract the submatrix starting from prevRowUsed + 1 row till j-1 row //and [(j - 1) - prevRowUsed + 1)] rows threadData[i].subMat = gk_csr_ExtractSubmatrix(mat, prevRowUsed + 1, \ j - (prevRowUsed)); } //create the inverted index gk_csr_CreateIndex(threadData[i].subMat, GK_CSR_COL); threadData[i].mat = mat; threadData[i].queryDoc = queryDoc; threadData[i].params = params; prevRowUsed = j; pthread_create(&p_threads[i], &attr, findSimilarDoc, (void *) &threadData[i]); } //wait for threads to complete, and assign the next job for (i=0; i < mat->nrows; i++) { gk_startwctimer(params->timer_2); //wait for all threads to be idle before giving them work pthread_mutex_lock(&lockCurrentlyIdle); while (currentlyIdle != NTHREADS) { pthread_cond_wait(&condCurrentlyIdle, &lockCurrentlyIdle); } pthread_mutex_unlock(&lockCurrentlyIdle); //all threads are waiting for work, signal to start //prevent them from finishing canFinish = 0; //signal them to start working //signal threads to start again pthread_mutex_lock(&lockWorkReady); //assign new queries to thread/jobs for (j = 0; j < NTHREADS; j++) { threadData[j].queryDoc = i; } threadsFinished = 0; workReady = 1; pthread_cond_broadcast(&condWorkReady); pthread_mutex_unlock(&lockWorkReady); //wait for all threads to complete pthread_mutex_lock(&lockThreadDone); while (threadsFinished < NTHREADS) { pthread_cond_wait(&condThreadDone, &lockThreadDone); } pthread_mutex_unlock(&lockThreadDone); //threads finished their job and are waiting for finish flag authorization //prevent them from starting again workReady = 0; currentlyIdle = 0; gk_stopwctimer(params->timer_2); gk_startwctimer(params->timer_3); //process the thread outputs tempHitCount = 0; numLastChunkRows = 0; for (j = 0; j < NTHREADS; j++) { for (k = 0; k < threadData[j].nhits; k++) { hits[tempHitCount] = threadData[j].hits[k]; hits[tempHitCount].val += numLastChunkRows; tempHitCount++; } numLastChunkRows += threadData[j].subMat->nrows; } /*for (j = 1; j < NTHREADS; j++) { tempHitCount = findTopKHits(hits, params->nnbrs, threadData[j].hits,\ threadData[j].nhits, threadData[0].hits, \ threadData[0].nhits); //hits now contained the combined top k hits //copy these to threadData[0] for next iteration threadData[0].nhits = tempHitCount; for (k = 0; k < tempHitCount; k++) { threadData[0].hits[k] = hits[k]; } }*/ nsim = 0; //sort the hits if (params->nnbrs == -1 || params->nnbrs >= tempHitCount) { //all similarities required or //similarity required > num of candidates remain after prunning nsim = tempHitCount; } else { nsim = gk_min(tempHitCount, params->nnbrs); gk_dfkvkselect(tempHitCount, nsim, hits); gk_fkvsortd(nsim, hits); } gk_stopwctimer(params->timer_3); gk_startwctimer(params->timer_4); /* write the results in the file */ if (fpout) { //fprintf(fpout, "%8d %8d\n", i, nsim); for (j=0; j < nsim; j++) fprintf(fpout, "%8d %8d %.3f\n", i, hits[j].val, hits[j].key); } gk_stopwctimer(params->timer_4); //allow threads to finish pthread_mutex_lock(&lockCanFinish); canFinish = 1; pthread_cond_broadcast(&condCanFinish); pthread_mutex_unlock(&lockCanFinish); } gk_stopwctimer(params->timer_1); /* cleanup and exit */ if (fpout) gk_fclose(fpout); gk_csr_Free(&mat); return; } /*************************************************************************/ /*! This is the entry point for finding simlar patents */ /**************************************************************************/ int main(int argc, char *argv[]) { params_t params; int rc = EXIT_SUCCESS; cmdline_parse(&params, argc, argv); printf("********************************************************************************\n"); printf("sd (%d.%d.%d) Copyright 2011, GK.\n", VER_MAJOR, VER_MINOR, VER_SUBMINOR); printf(" nnbrs=%d, minsim=%.2f\n", params.nnbrs, params.minsim); gk_clearwctimer(params.timer_global); gk_clearwctimer(params.timer_1); gk_clearwctimer(params.timer_2); gk_clearwctimer(params.timer_3); gk_clearwctimer(params.timer_4); gk_startwctimer(params.timer_global); ComputeNeighbors(&params); gk_stopwctimer(params.timer_global); printf(" wclock: %.2lfs\n", gk_getwctimer(params.timer_global)); printf(" timer1: %.2lfs\n", gk_getwctimer(params.timer_1)); printf(" timer2: %.2lfs\n", gk_getwctimer(params.timer_2)); printf(" timer3: %.2lfs\n", gk_getwctimer(params.timer_3)); printf(" timer4: %.2lfs\n", gk_getwctimer(params.timer_4)); printf("********************************************************************************\n"); exit(rc); }
C
#include <stdio.h> #include<stdlib.h> typedef struct { int data; struct Node* leftchild; struct Node* Rightchild; }Node; Node* initNode(int data, Node* leftchild, Node* Rightchild) { Node* node = (Node*)malloc(sizeof(Node)); node->data = data; node->leftchild = leftchild; node->Rightchild = Rightchild; return node; } void preorder(Node* root) { //ȸ if (root) { printf("%d ", root->data);//ڱڽ Ѵ. preorder(root->leftchild);// 湮Ѵ. preorder(root->Rightchild);// 湮Ѵ. } } //30-17-5-23-48-37-50 void inorder(Node* root) {//ȸ if (root) { inorder(root->leftchild); printf("%d ", root->data); inorder(root->Rightchild); } } void postorder(Node* root) {//ȸ if (root) { postorder(root->leftchild); postorder(root->Rightchild); printf("%d ", root->data); } } int main(void) { Node* n7 = initNode(46, NULL, NULL); Node* n6 = initNode(16, NULL, NULL); Node* n5 = initNode(2, NULL, NULL); Node* n4 = initNode(6, NULL, NULL); Node* n3 = initNode(11, n6, n7); Node* n2 = initNode(89, n4, n5); Node* n1 = initNode(23, n2, n3); printf("< ȸ>\n"); preorder(n1); printf("\n"); printf("\n"); printf("< ȸ>\n"); inorder(n1); printf("\n"); printf("\n"); printf("< ȸ>\n"); postorder(n1); printf("\n"); printf("\n"); system("pause"); return 0; }
C
/* * Docked - Mains Idle state */ #include <stdio.h> #include <string.h> #include <rob_system.h> #include <task_handler_types.h> #include <state_machine_server.h> #include <shutdown_state.h> #include <docked_charging_state.h> #include <mobile_state.h> #include <docked_mainsidle_state.h> /* * MANIFEST CONSTANTS */ #define DOCKED_MAINSIDLE_STATE_NAME "Docked - MainsIdle" /* Not longer than STATE_NAME_STRING_LENGTH - 1 characters */ /* * TYPES */ /* * STATIC FUNCTIONS: EVENT HANDLERS */ /* * PUBLIC FUNCTIONS */ void transitionToDocked_MainsIdle (RoboOneState *pState) { /* Fill in default handlers first */ defaultImplementation (pState); memcpy (&(pState->name[0]), DOCKED_MAINSIDLE_STATE_NAME, strlen (DOCKED_MAINSIDLE_STATE_NAME) + 1); /* +1 for terminator */ printDebug ("\n*** Transitioning to %s state.\n", &(pState->name[0])); /* Now hook in the event handlers for this state */ pState->pEventTasksAvailable = transitionToMobile; pState->pEventInsufficientPower = transitionToShutdown; pState->pEventShutdown = transitionToShutdown; pState->pEventInsufficientCharge = transitionToDocked_Charging; /* No entry actions, all done in the docked main state */ }
C
#include <stdio.h> int main(){ long long int n,k; long long int num,count; scanf("%lld%lld",&n,&k); count=0; while(n--){ scanf("%lld",&num); if(num%k==0){ count++; } } printf("%lld",count); return 0; }
C
#include <stdio.h> #include "SDL.h" #include "imagen.h" #include "Mugimendua.h" IMG irudiak[MAX_IMG]; int irudiKop = 0; int id = 0; int irudiaKargatu(char* fileName) { int colorkey; SDL_Surface* surface; if (irudiKop < MAX_IMG) { surface = SDL_LoadBMP(fileName); if (surface == NULL) { fprintf(stderr, "Couldn't load %s: %s\n", fileName, SDL_GetError()); return -1; } else { colorkey = SDL_MapRGB(surface->format, 255, 0, 255); SDL_SetColorKey(surface, SDL_TRUE, colorkey); (irudiak + irudiKop)->texture = SDL_CreateTextureFromSurface(renderer, surface); (irudiak + irudiKop)->dest.x = irudiak[irudiKop].dest.y = 0; (irudiak + irudiKop)->dest.w = surface->w; (irudiak + irudiKop)->dest.h = surface->h; SDL_FreeSurface(surface); (irudiak + irudiKop)->id = id; irudiKop++; id++; } } else { printf("Gehienezko irudi kopurua zeharkatu da. Ezin dira irudi gehiago jarri.\n"); return -1; } return id - 1; } void irudiaMugitu(int numImg, float x, float y) { int id = 0; id = irudiarenPosizioaAurkitu(numImg); (irudiak + id)->dest.x = (int)x; (irudiak + id)->dest.y = (int)y; } void irudiakMarraztu(void) { for (int i = 0; i < irudiKop; i++) irudiaMarraztu((irudiak + i)->texture, &(irudiak + i)->dest); } void irudiaKendu(int id) { int i = 0, pos = 0; pos = irudiarenPosizioaAurkitu(id); SDL_DestroyTexture((irudiak + pos)->texture); for (i = pos; i < irudiKop; i++) *(irudiak + i) = *(irudiak + i + 1); irudiKop--; } int irudiarenPosizioaAurkitu(int id) { for (int i = 0; i < irudiKop; i++) if (id == (irudiak + i)->id) return i; return -1; }
C
/** * @file lab5_2.c * @brief Визначення чи є число простим * * @author Vasilyazhenko Dmitriy * @date 21-dec-2020 * @version 1.0 */ /** * функція для визначення чи є число простим * * Послідовність дій: * - створення змінних для заданого числа та результату * - процес визначення чи є число прости, за допомогою циклу for та умов * @return успішний код повернення з програми (res) * @param res результат визначення */ char s1mple(int num) { int number = num; char res; if (number > 1) { for (int i = 2; i < number; i++){ if (number % i == 0){ res = '-'; break; } else { res = '+'; } } } return res; } /** * Головна функція. * * Послідовність дій: * - створення змінної res * - виклик функціїї * @return успішний код повернення з програми (0) */ int main(){ char res; res = s1mple(14); return 0; }
C
//Mike Carrigan #include <stdio.h> #include <string.h> #include <stdlib.h> int convert_to_hex (char* hex_string1){ int len = strlen(hex_string1); int value=0, placeValue = 1; for(int i = (len-1); i>=0; i--){ char temp = hex_string1[i]; if(temp >= '0' && temp <= '9'){ value += (temp - 48) * placeValue; //use 48 as ASCII 0 = 48 } else if(temp >= 'A' && temp <= 'F'){ value += (temp - 55) * placeValue; //use 55 because ASCII A = 65 } else if(temp >= 'a' && temp <= 'f'){ value += (temp - 87) * placeValue; //Use 87 because ASCII a = 97 } placeValue = placeValue * 16; //Adapt for place value } return value; } char* remove_substring (char* s1){ char* s2 = strstr(s1, "&&|"); //Locates the first time &&| is used and saves the memory address int diff = s2-s1; //used to find the array location of first char in delimeter char* s3 = malloc(strlen(s1)+1); char* s4 = malloc(strlen(s1)+1); memmove(s3,s1,diff); //copys all of string leading up to delimeter to new string strcpy(s4,&s1[diff+3]); //copys all of string after delimeter to new string strcat(s3,s4); //concatenates the before delimeter and after delimeter strings return(s3); }
C
#include "Blaisdell_PA3.h" /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: *makeNode * Description: make a new node containing a single element of the expression * Precondition: StackNode structure must be defined, "theElement" must be passed in as an argument * Postcondition: a new node containing "theElement" as its data is created and returned *********************************************************************************/ StackNode *makeNode (char theElement) { // declare variables: StackNode *pMem = NULL; // initialize node with dynamic memory allocation pMem = (StackNode *) malloc (sizeof (StackNode)); // load the data into the node and set it's pointer pMem -> theElement = theElement; pMem -> theNextElement = NULL; return pMem; } // end *makeNode function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: getInput * Description: prompt the user for and read in a mathematical expression in * infix notation to be converted to postfix notation * Precondition: inFix must be declared * Postcondition: inFix will be loaded with the infix expression *********************************************************************************/ void *getInput (char *inFix) { // prompt the user to enter a mathematical expression printf ("Enter a mathematical expression using infix notation: \n"); // read the input from the user into the pointer passed in from the calling function // not sure why this doesn't work when I call this function from the // switch-case function // gets (inFix); scanf (" %s", inFix); // but this works just fine so I'm going with it } // end getInput function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: convertNotation * Description: convert an infix expression to postfix notation * Precondition: an infix notation expression entered by the user from getinput function, * passed in to the function via the inFix string pointer * Postcondition: the expression in postfix notation form, postFix string is updated *********************************************************************************/ void convertNotation (StackNode **convertStack, char *inFix, char *postFix) { // declare necessary variables: int inFixIndex = 0, postFixIndex = 0; char temp = '\0'; // begin by pushing a left paren onto the stack to note the end of the stack push (convertStack, '('); // append a right paren to the end of the infix notation array to note the end of the array inFix[strlen(inFix)] = ')'; // while the stack is not empty, evaluate each character and perform the appropriate // action: while ((temp = stackTop (*convertStack)) != '\0') { // if the character at the current inFix index position is an integer, put it at // the end of postFix if ((inFix[inFixIndex]) >= 48 && (inFix[inFixIndex] <= 57)) { postFix[postFixIndex++] = inFix[inFixIndex++]; } // end if integer // if the character at the current inFix index position is a left paren, // put it on the stack else if ((inFix[inFixIndex] == '(')) { push (convertStack, inFix[inFixIndex++]); } // end if left paren // if operator is a high precedence, *, /, ^, or % and the operator on the stack is also // *, /, ^, or % // if the character at the current inFix index position is a *, /, ^, or % // operator, pop all operators from the top of the stack with equal precedence // and put them at the end of postFix, then put this one on the end of postFix else if (((inFix[inFixIndex] == '*') || (inFix[inFixIndex] == '/') || (inFix[inFixIndex] == '^') || (inFix[inFixIndex] == '%')) && ((temp == '*') || (temp == '/') || (temp == '^') || (temp == '%'))) { while ((temp == '*') || (temp == '/') || (temp == '^') || (temp == '%')) { temp = pop (convertStack); postFix[postFixIndex++] = temp; temp = stackTop (*convertStack); } // end keep popping from stack if equal or greater operator precedence (*, /, ^, %) // now put the current operator on the stack push (convertStack, inFix[inFixIndex++]); } // end if inFix[inFixIndex] is a *, /, ^, or % operator and last character on the stack is // also a *, /, ^, or % operator // if the operator is a + or a - and the operator on the stack is, well, anything, else if (((inFix[inFixIndex] == '+') || (inFix[inFixIndex] == '-')) && ((temp == '+') || (temp == '-') || (temp == '*') || (temp == '/') || (temp == '^') || (temp == '%'))) { // while there is an operator on the top of the stack, keep going: while ((temp == '+') || (temp == '-') || (temp == '*') || (temp == '/') || (temp == '^') || (temp == '%')) { temp = pop (convertStack); postFix[postFixIndex++] = temp; temp = stackTop (*convertStack); } // end keep popping from stack if equal or greater operator precedence (+, -, *, /, ^, %) push (convertStack, inFix[inFixIndex++]); } // end if inFix[inFixIndex] is a + or - operator and last character on the stack is // also a + or - or *, /, ^, or % operator // otherwise, the current operator is lower precedence than the one on the stack // so put it on the end of postFix else if (((inFix[inFixIndex] == '*') || (inFix[inFixIndex] == '/') || (inFix[inFixIndex] == '^') || (inFix[inFixIndex] == '%') || (inFix[inFixIndex] == '+') || (inFix[inFixIndex] == '-')) && ((temp != '*') || (temp != '/') || (temp != '^') || (temp != '%') || (temp != '+') || (temp != '-'))) { push (convertStack, inFix[inFixIndex++]); } // end if operator is anything and there is no operator on the top of the stack // if inFix[inFixIndex] is a right paren: else if (inFix[inFixIndex] == ')') { while ((temp = stackTop (*convertStack)) != '(') { temp = pop (convertStack); postFix[postFixIndex++] = temp; temp = stackTop (*convertStack); } // end while not left paren if ((temp = stackTop (*convertStack)) == '(') { temp = pop (convertStack); temp = '\0'; inFixIndex++; } // end pop and discard left paren if its at the top of the stack } // end if inFix[inFixIndex] is right paren ')' } // end while loop for converting } // end convertNotation function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: push * Description: push a character onto the stack * Precondition: theStack must be created and initialized * Postcondition: the new character will be on the top of the stack *********************************************************************************/ void push (StackNode **theStack, char theElement) { StackNode *element = makeNode (theElement); element -> theNextElement = *theStack; *theStack = element; } // end push function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: pop * Description: Removes the top element from the stack and returns it to the calling function * Precondition: a character variable must be decalared to hold the result of the function * theStack must exist and be initialized and must not be empty! * Postcondition: the top element of the stack will be deleted and it's value returned * to the calling function. *********************************************************************************/ char pop (StackNode **theStack) { // decalare necessary variables: StackNode *pTemp = NULL; char temp = '\0'; // move the node to a temp node, move the pointer to the first node to the next node pTemp = *theStack; *theStack = (*theStack) -> theNextElement; // put the value of the top node into a temp variable temp = pTemp -> theElement; // free the temp node free (pTemp); // return the value of the character that was in the top node return temp; } // end pop function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: printStack * Description: Prints all of the values in the stack, I used this for debugging * Precondition: The stack must be declared and initialized and not empty * Postcondition: the contents of the stack will be printed to the screen *********************************************************************************/ void printStack (StackNode *theStack) { // use while nodes in stack are not null while (theStack != NULL) { printf ("%c", theStack -> theElement); theStack = theStack -> theNextElement; } // end while loop // put a newline for readability putchar ('\n'); } // end printStack function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: stackTop * Description: returns the value of the data in the top node of the stack * Precondition: stack must be declared, initialized * Postcondition: the value of the data in the node at the top of the stack is * returned to the calling function. *********************************************************************************/ char stackTop (StackNode *convertStack) { // declare a temp variable char temp = '\0'; // if the stack is not empty, store the value of the top node if (convertStack != NULL) { temp = convertStack -> theElement; } // return the value to the calling function return temp; } // end stackTop function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: evaluatePostFix * Description: Evaluates the postFix notation expression * Precondition: postFix array must exist and not be empty, convert stack must exist * Postcondition: the value of the evaluated expression will be left in the top node * of the convertStack and stored as an integer and returned to the calling function *********************************************************************************/ int evaluatePostFix (StackNode **convertStack, char *postFix) { // declare variables: int postFixIndex = 0, x = 0, y = 0, z = 0, theAnswer; char theOperator = '\0'; // append \0 to end of postFix array to make it a string postFix[strlen(postFix)] = '\0'; // while the string position is not null character while (postFix[postFixIndex] != '\0') { // if current character is an integer, put it on the stack: if ((postFix[postFixIndex] >= 48) && (postFix[postFixIndex] <= 57)) { push (convertStack, postFix[postFixIndex++]); } // end if postFix[postFixIndex] is an integer // if current character is a operator, pop previous two integers into variables x & y // and evaluate x operator y and put the result back on the stack if ((postFix[postFixIndex] == '*') || (postFix[postFixIndex] == '/') || (postFix[postFixIndex] == '^') || (postFix[postFixIndex] == '%') || (postFix[postFixIndex] == '+') || (postFix[postFixIndex] == '-')) { // store previous two integers in temp variables as integers // (convert from ascii characters to ascii integers by lowering // ascii value by 48) x = pop (convertStack) - 48; y = pop (convertStack) - 48; // put the operator into a variable we can work with: theOperator = postFix[postFixIndex]; // use switch case to evaluate the expressions switch (theOperator) { case '+': z = y + x; break; case '-': z = y - x; break; case '*': z = y * x; break; case '/': z = y / x; break; case '^': z = exponent(y,x); // use custom exponent funtion break; case '%': z = y % x; break; default: printf ("Invalid character\n"); break; } // push the answer onto the stack push (convertStack, z + 48); postFixIndex++; // increment the index } // end if postFix[postFixIndex] is an operator } // end while postFix[postFixIndex] != 0 theAnswer = pop (convertStack) - 48; return theAnswer; } // end evaluatePostFix function /********************************************************************************* * Programmer: Marcus Blaisdell * Student ID: 097868639 * Class: CptS 122, Spring 2015; Lab Section 3 * Programming Assignment: * Date: 02/16/2015 * Function: exponent * Description: raises a number to a power * Precondition: the number and the power must be passed in as variables * Postcondition: the calculated value is returned as an integer *********************************************************************************/ int exponent (int number, int exponent) { // declare necessary variables; int loop = 0, answer = number; // loop as many times as the value of the exponent // multiply the answer by the number that many times for (loop = 0; loop < exponent; loop++) { answer = answer * number; } return answer; } // end exponent function
C
#include "uls.h" static void set_for_back_ground(char foreground, char background); static void set_bits_color(char *perms); static void set_type_color(char *perms); static bool is_executeble(char *perms); void mx_enable_color(char *perms, int flags) { if (!MX_F_ISGU(flags)) { return; } set_type_color(perms); set_bits_color(perms); } static void set_for_back_ground(char foreground, char background) { char *color = NULL; char *result_color = NULL; if (foreground != -1 && background != -1) { color = mx_strdup("[30;40m"); color[2] = foreground; color[5] = background; } else if (foreground != -1) { color = mx_strdup("[30m"); color[2] = foreground; } else if (background != -1) { color = mx_strdup("[40m"); color[2] = background; } result_color = mx_strjoin("\x1b", color); mx_printstr(result_color); mx_strdel(&result_color); mx_strdel(&color); } static void set_bits_color(char *perms) { if (perms[3] == 's' && is_executeble(perms)) { set_for_back_ground(MX_BLACK, MX_RED); } if (perms[6] == 's' && is_executeble(perms)) { set_for_back_ground(MX_BLACK, MX_CYAN); } if (perms[0] == 'd' && perms[8] == 'w' && perms[9] == 't') { set_for_back_ground(MX_BLACK, MX_GREEN); } if (perms[0] == 'd' && perms[8] == 'w' && perms[9] != 't') { set_for_back_ground(MX_BLACK, MX_BROWN); } } static void set_type_color(char *perms) { if (perms[0] == 'd') set_for_back_ground(MX_BLUE, -1); if (perms[0] == 'l') set_for_back_ground(MX_MAGENTA, -1); if (perms[0] == 's') set_for_back_ground(MX_GREEN, -1); if (perms[0] == 'p') set_for_back_ground(MX_BROWN, -1); if (perms[0] == 'b') set_for_back_ground(MX_BLUE, MX_CYAN); if (perms[0] == 'c') set_for_back_ground(MX_BLUE, MX_BROWN); if (perms[0] == '-' && is_executeble(perms)) { set_for_back_ground(MX_RED, -1); } } static bool is_executeble(char *perms) { return perms[3] == 'x' || perms[6] == 'x' || perms[9] == 'x'; }
C
#include <stdio.h> #define MAX 1000 int main() { int plantacao[MAX][MAX]; int lin, col; int m, n; int max; int cur; int i, j, k, l; scanf(" %d %d %d %d", &lin, &col, &m, &n); max = 0; for (i = 0; i < lin; i++) for (j = 0; j < col; j++) scanf(" %d", &(plantacao[i][j])); for (i = 0; i < lin; i += m) { for (j = 0; j < col; j += n) { cur = 0; for (k = i; k < (i + m); k++) for (l = j; l < (j + n); l++) cur += plantacao[k][l]; if (cur > max) max = cur; } } printf("%d\n", max); return 0; }
C
#include<stdio.h> #include<stdlib.h> typedef struct Node* PtrNode; typedef PtrNode List; typedef PtrNode Position; struct Node { int ele; Position next; }; void InitLinkList(List L) { L->ele=0; L->next=NULL; } int IsEmpty(List L) { return L->next==NULL; } Position Find(int x,List L) { Position p; p = L->next; while(p!=NULL&&p->ele!=x) p = p->next; return p; } Position FindPrevious(int x,List L) { Position p; p = L->next; while (p->next!=NULL&&p->next->ele!=x) { p=p->next; } return p; } int IsLast(Position p,List L) { return p->next == NULL; } void Delete(int x,List L) { Position p,tmpCell; p = FindPrevious(x,L); if(!IsLast(p,L)) { tmpCell = p->next; p->next = tmpCell->next; free(tmpCell); } } void Insert(int x,List L,Position p) { Position tmpCell; tmpCell = malloc(sizeof(struct Node)); if(tmpCell == NULL) return ; tmpCell->ele = x; tmpCell->next = p->next; p->next = tmpCell; } void PrintLinkList(List L) { Position p; p = L->next; while(p!=NULL) { printf("%d ",p->ele); p = p->next; } } int main() { List L = (List)malloc(sizeof(struct Node)); InitLinkList(L); Insert(0,L,L); Insert(1,L,L->next); printf("%d\n",L->next->ele); printf("%d\n",L->next->next->ele); printf("%d\n",FindPrevious(1,L)->ele); Delete(1,L); Insert(2,L,L->next); PrintLinkList(L); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "huffman.h" static int t_cmp(TreeNode* p1, TreeNode* p2){ return (int)((p1)->count - ( p2)->count); } /** static int t2_cmp(TreeNode* p1, TreeNode* p2){ if ((p1)->count == ((p2)->count)){ if ((p2)->left != NULL || (p2)->right != NULL){ return -1; } else{ return 1; } } else if((p1)->count > (p2)->count){ return 1; } else{ return -1; } }*/ int main(int argc, char* argv[]) { if (argc != 5){ return EXIT_FAILURE; } char *input = argv[1]; char *output_1 = argv[2]; char *output_2 = argv[3]; char *output_3 = argv[4]; long int asciiCount[256] = {0}; FILE *fp_input = fopen(input, "r"); if (fp_input == NULL){ return EXIT_FAILURE; } build_count_ascii(fp_input, asciiCount); fclose(fp_input); //int (*cmp_fn)(TreeNode *, TreeNode*) = t_cmp; //TreeNode *tree = NULL; Node *head = malloc(sizeof(*head)); //head = NULL;/ malloc(sizeof(*head)); head = NULL; Node *new = malloc(sizeof(*new)); if (new == NULL){ return EXIT_FAILURE; } //new=NULL; TreeNode *temp = malloc(sizeof(*temp)); if (temp == NULL){ return EXIT_FAILURE; } //temp= NULL; //int count = 0; for (int i=0; i<256; i++){ if(asciiCount[i] > 0){ /**Node *new = malloc(sizeof(*new)); if (new == NULL){ return EXIT_FAILURE; } TreeNode* temp = malloc(sizeof(*temp)); if (temp == NULL){ return EXIT_FAILURE; }**/ temp->value=i; temp->count = asciiCount[i]; temp->left = NULL; temp->right= NULL; new->ptr = temp; new->next = NULL; p_enqueue(&head, &new, t_cmp); /** free_tree(new->ptr); free(new); free_tree(temp);**/ } } // free_tree(new->ptr); // free(new); // free_tree(temp); //build_tree(head, asciiCount); //cmp_fn = t2_cmp; TreeNode *thead = huff_tree(head, t_cmp); //output 1 FILE *fp_o_1 = fopen(output_1, "w"); if (fp_o_1 == NULL){ return EXIT_SUCCESS; } //int *path = malloc(sizeof(*path) * count); //path = NULL; int path[256] = {0}; huff_traverse(thead, path, 0, fp_o_1); //free(path); fclose(fp_o_1); //output 2 FILE *fp_o_2 = fopen(output_2, "w"); if (fp_o_2 == NULL){ return EXIT_SUCCESS; } post_order(thead, fp_o_2); //fputc('0', fp_o_2); fclose(fp_o_2); //output 3 FILE *fp_in_3 = fopen(output_2, "r"); if (fp_in_3 == NULL){ return EXIT_SUCCESS; } char *header = malloc(sizeof(*header)*152); FILE *fp_o_3 = fopen(output_3, "w"); if (fp_o_3 == NULL){ return EXIT_SUCCESS; } header_bits(fp_in_3, header, fp_o_3); fclose(fp_in_3); fclose(fp_o_3); //free_tree(thead); free_tree(thead); free(new); free(head); //free(path); free(header); //free_tree(new->ptr); //free(new); //free_tree(temp); return EXIT_SUCCESS; }
C
/* * Author: Danielle Tucker * TCSS 371 * Date 7 October 2012 * Assignment 2 Simulating Logic Gates * logic_gate.h includes the function prototypes for logic gates */ #ifndef LOGIC_GATE_H #define LOGIC_GATE_H /** * bit not(bit); * Returns the logical NOT of the bit provided. */ bit not(bit); /** * bit and(bit, bit); * Takes two bits and returns the logical AND of the bits. */ bit and(bit, bit); /** * bit or(bit, bit); * Takes two bits and returns the logical OR of the bits. */ bit or(bit, bit); /** * bit xor(bit, bit); * Takes two bits and returns the logical EXCLUSIVE OR of the bits */ bit xor(bit, bit); /** * bit nand(bit, bit); * Takes two bits and returns the logical NOT AND of the bits */ bit nand(bit, bit); /** * bit nor(bit, bit); * Takes two bits and returns the logical NOT OR of the bits */ bit nor(bit, bit); // used to simulate logical NOT OR gate #endif //#ifndef LOGIC_GATE_H
C
#include "FLOAT.h" FLOAT F_mul_F(FLOAT a, FLOAT b) { int index=0; if(a<0) { a=-a; index++; } if(b<0) { b=-b; index++; } unsigned int a1=(a>>16); unsigned int b0=b&0xffff; unsigned int a0=a&0xffff; unsigned int b1=(b>>16); unsigned int c0=(a0*b0)/0xffff; unsigned int c1=a1*b0+a0*b1+c0; unsigned int c2=(a1*b1)<<16; c2+=c1; if(index%2==0) return c2; else return -c2; } FLOAT F_div_F(FLOAT a, FLOAT b) { unsigned int i,ans,nb; nb=31; unsigned int a0=a&0xffff; unsigned int a1=(a>>16); unsigned int a11=(a0<<16); ans=0; for (i=1;i<=32;++i) { if(a1>=b) { ans+=a1/b; a1=a1%b; } a1<<=1; a1+=(a11>>nb); if(a11>>nb) a11-=(1<<nb);ans=(ans<<1); nb--; } return ans; } FLOAT f2F(float a) { int b=*(int *)&a; unsigned int b1=b; int mid=b>>23; if(b<0)mid=mid&0xff; unsigned int back; if(b<0) back=b1-(mid<<23)-(1<<31); else back=b1-(mid<<23); back+=(1<<23); if(mid>=127) { mid-=127; mid+=16; if(mid>=23) back<<=(mid-23); else { back=back>>(23-mid); } } else { int mid1=mid-127; mid1+=16; back>>=(23-mid1); } int back1=back; if(b<0) back1=-back1; return back1; } FLOAT Fabs(FLOAT a) { return a >=0 ? a : -a; return 0; } FLOAT sqrt(FLOAT x) { FLOAT dt, t = int2F(2); do { dt = F_div_int((F_div_F(x, t) - t), 2); t += dt; } while(Fabs(dt) > f2F(1e-4)); return t; } FLOAT pow(FLOAT x, FLOAT y) { /* we only compute x^0.333 */ FLOAT t2, dt, t = int2F(2); do { t2 = F_mul_F(t, t); dt = (F_div_F(x, t2) - t) / 3; t += dt; } while(Fabs(dt) > f2F(1e-4)); return t; }
C
#ifndef LISTA_H #define LISTA_H #include <stdbool.h> #include <stdlib.h> #include <string.h> typedef struct nodo_lista { char* cliente; size_t visitas; struct nodo_lista* prox; } nodo_lista_t; typedef struct lista { nodo_lista_t* primero; nodo_lista_t* ultimo; size_t largo; } lista_t; typedef struct lista_iter{ nodo_lista_t* actual; lista_t* lista; } lista_iter_t; // Crea una lista vacia void lista_crear(lista_t *lista); //Recibe como parametro una lista y un string y agrega el string a la //lista bool lista_agregar_cliente(lista_t *lista, char *cliente); //Recibe como parametro una lista y devuelve un booleano indicando //si esta o no vacia bool lista_esta_vacia(const lista_t *lista); //Destruye la lista que recibe por parametro void lista_destruir(lista_t* lista); //Recibe por parametro una lista y un string y devuelve un booleano //indicando si pudo sumar una aparicion de dicho string a la lista bool lista_sumar_visita(lista_t *lista, char *cliente); //Crea un iterador de la lista que recibe por parametro void lista_iter_crear(lista_t *lista,lista_iter_t *iter); //Avanza el iterador de la lista que recibe por parametro bool lista_iter_avanzar(lista_iter_t *iter); //Recibe por parametro un iterador y devuelve la cadena en la cual //se encuentra actualmente char *lista_iter_ver_actual_cliente(const lista_iter_t *iter); //Devuelve un size_t indicando el valor sobre el cual se encuentra //actualmente el iterador size_t lista_iter_ver_actual_visitas(const lista_iter_t *iter); //Indica si el iterador que recibe como parametro esta al final bool lista_iter_al_final(const lista_iter_t *iter); //Destruye el iterador de la lista void lista_iter_destruir(lista_iter_t *iter); #endif // LISTA_H
C
#include <stdio.h> int main(){ int x1,y1,z1,x2,y2,z2; printf("Enter (x1,y1,z1) &(x2,y2,z2) for vector : xi + yj + zk "); scanf("%d %d %d %d %d %d",&x1,&y1,&z1,&x2,&y2,&z2); printf("Dot product of vectors : %d",x1*x2 + y1*y2 + z1*z2); return 0; }
C
// Room: /d/oldpine/epath2.c inherit ROOM; void create() { set("short", "小石橋"); set("long", @LONG 你現在正站在一座長滿青苔的古橋上,橋下是一條山澗,幾股清泉 在亂石之中向山下奔流,橋北邊不遠處有一個瀑布(waterfall) ,從山 壁上猶如一條白練般垂了下來,瀑布兩旁的石壁十分陡峭,高度和山澗 旁的松林相差了近三、四十丈。 LONG ); set("item_desc", ([ "waterfall": "這個瀑布從數百丈高的山壁上衝激而下,流入一個山澗底的小水潭\n" ",水潭兩邊的石壁垂下許\多的藤蔓(vine),你注意到瀑布後面似乎\n" "有什麼東西在發著光。\n", "vine": "其中有一根藤蔓距離你比較近,你可以試著抓住(hold)藤蔓,看看\n" "能不能像泰山一樣蕩過去,看看瀑布後面有什麼?\n" "對了,提醒你一點,這座石橋下面是高約百丈的山澗深谷....。\n" ]) ); set("exits", ([ /* sizeof() == 2 */ "west" : "/d/oldpine/epath1", "east" : "/d/oldpine/epath3", ])); set("outdoors", "oldpine"); setup(); } void init() { add_action("do_hold_vine", ({ "hold", "grab" }) ); } int do_hold_vine(string arg) { if( !arg || arg!= "vine" ) return notify_fail("你要抓住什麼?\n"); message_vision("$N爬上石橋的護欄,伸手往不遠處的一根藤蔓抓去....\n", this_player()); if( random((int)this_player()->query_skill("dodge")) < 5 ) { message_vision("\n只聽見一聲殺豬般的慘叫,$N已經往山澗中墜了下去。\n\n", this_player()); tell_room(__DIR__"waterfall", "你聽到有人高聲驚叫,一條人影從上方掉了下來,「撲通」一聲跌進潭中。\n"); this_player()->move(__DIR__"waterfall"); } else { message_vision("$N手腳俐落地攀附著藤蔓,慢慢地爬下山澗....。\n", this_player() ); tell_room(__DIR__"passage", "忽然一條人影從南邊的簾幕穿了出來。\n"); this_player()->move(__DIR__"passage"); } return 1; }
C
#include "hash_table.h" #include <stdlib.h> #include <stdio.h> int main(void) { hash_table_t *my_table = htable_init(128); long int i; /* Turn off buffering of the standart output stream */ setvbuf(stdout, NULL, _IONBF, 0); /* Fill our table with 100000 trash elements */ printf("Filling tree with numbers from 1 to 100000 ... "); i = 5; for (i = 0; i < 100000; i++) { int *x = malloc(sizeof(int)); *x = i; htable_insert(my_table, x); } printf("Done\n"); /* Searchprintf("Disposing hash-table ... "); our table for 100000 times. Each time we look for different values */ printf("Searching for 100000 times for digits from 1 to 100000 ... "); for (i = 100000; i >=0; i--) { void* node = htable_search(my_table, &i); } printf("Done\n"); printf("Disposing hash-table ... "); htable_dispose(my_table); printf("Done\n"); return 0; }
C
/* Scrivere un programma che chieda all’utente una stringa composta da parentesi aperte e chiuse: (,),[,],{,} e che verifichi se le coppie e l’ordine delle (,),[,],{,} sono corretti. Utilizzare uno stack. */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define MAX 4096 typedef struct nodo{ char valore; struct nodo *next; } Nodo; bool is_empty(Nodo *head); Nodo* pop(Nodo *head); Nodo* push(Nodo* head, char parentesi); int main(){ char* stringa = (char*) malloc(MAX*sizeof(char)); printf("Inserire una stringa di parentesi: "); scanf("%s", stringa); int i = 0; Nodo* head = (Nodo*) malloc(sizeof(Nodo)); bool parentesi_sbagliata = false; while(stringa[i]!='\0' && !parentesi_sbagliata){ if(stringa[i]=='(' || stringa[i]=='[' || stringa[i]=='{'){ head = push(head, stringa[i]); } else if(stringa[i]==')' || stringa[i]==']' || stringa[i]=='}'){ char p = head->valore; head = pop(head); if(stringa[i]!=p+1 && stringa[i]!=p+2){ printf("Errore nella chiusura delle parentesi!\n"); parentesi_sbagliata = true; } } i++; } if(!parentesi_sbagliata){ printf("Tutte le parentesi sono state aperte e chiuse correttamente!\n"); } return 0; } bool is_empty(Nodo *head){ if (head == NULL) return true; else return false; } Nodo* push(Nodo* head, char parentesi){ //Passo il puntatore per referenza if(is_empty(head)){ head->next = NULL; // elemento è già allocato head->valore = parentesi; } else{ Nodo* elemento = (Nodo*) malloc(sizeof(Nodo)); elemento->next = head; elemento->valore = parentesi; head = elemento; } return head; } Nodo* pop(Nodo *head){ Nodo* ret = head; //Mi serve una variabile di appoggio perchè se sostituisco la testa poi non ce l'ho più if(is_empty(head)){ return NULL; } else{ head = ret->next; } return head; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<time.h> #include<math.h> #include<ctype.h> const int max_x=61, max_y=31, max_stars=max_x*max_y, max_pairs=max_stars/2; char galaxy[max_y][max_x]; // frame buffer int star_number, pair_number; /********************************************** STRUCTS *******************************************************/ struct galaxy_size { int star_no; int pair_no; }; // stores all the details about a star struct star_data { int id; double x; double y; char name[25]; }; // array to store all the stars struct star_data stars[max_stars]; // store all the star pairs struct pair_data { int id; int star1_id; char star1_name[25]; int star2_id; char star2_name[25]; double star_distance; }; // array to store all the pairs struct pair_data star_pairs[max_pairs]; // remove leading space of string char *ltrim (char *trim_s) { int i = 0, n = strlen(trim_s) ; while (isspace((unsigned char) trim_s[i])) i++ ; //if (i != 0) strcpy (trim_s, trim_s + i); for (int j = 0 ; i <= n ; i++, j++) trim_s[j] = trim_s[i]; return trim_s; } // remove trailing space of string char *rtrim (char *trim_s) { int i = strlen (trim_s) - 1 ; // strlen(trim_s) -1 = last index of the string while (isspace((unsigned char) trim_s[i]) && i >= 0) // check space in string i-- ; // move to previous index, til isspace() is true trim_s[i+1] = '\0'; // terminate new string by replace i+1 with \0 to end the string at i; return trim_s; } /********************************************** VOID FUNCTIONS *******************************************************/ // clear the frame buffer by filling it with whitespace void clear() { for(int i = 0; i<=max_y -1; i++) // scan row (y) { for(int j = 0; j<=max_x-1; j++) //scan column (x) { galaxy[i][j] = ' '; } } } // reset the universe void reset() { int i; for (i = 0; i <= max_stars - 1; i++) { stars[i].id = -1; stars[i].x = -1; stars[i].y = -1; strcpy(stars[i].name, " "); } for (i = 0; i <= max_pairs - 1; i++) { star_pairs[i].id = -1; star_pairs[i].star1_id = -1; strcpy(star_pairs[i].star1_name, " "); star_pairs[i].star2_id = -1; strcpy(star_pairs[i].star2_name, " "); star_pairs[i].star_distance = -1; } star_number = 0; pair_number = 0; } // stores the character to the frame buffer void plot(int x, int y, char c) { galaxy[y][x] = c; } // copy the string write_s to the frame buffer void write_at(int x, int y, char *write_s) { int i; for(i = 0; i <= strlen(write_s); i++) { if (x+i <= max_x - 1) plot(x + i, y, write_s[i]); // stop plotting if x+i is out of range of frame buffer else return; } } // clears the terminal and print the frame buffer void refresh() { int i, j, x, y; char star_name[25]; // initialise the frame buffer to whitespace clear(); // fill the frame buffer for (i = 0; i <= star_number - 1; i++) { x = (int) stars[i].x; y = (int) stars[i].y; strcpy(star_name, stars[i].name); if (strcmp(star_name, " ") == 0) plot(x, y, '.'); else plot(x, y, '*'); } // clears the terminal system("clear"); // print the entire frame buffer for(i = 0; i <= max_y - 1; i++) // check the row y { for(j = 0; j <= max_x - 1; j++) // check the column x { printf("%c", galaxy[i][j]); } printf("\n"); } } //find star exist at x, y int find_star(int star_x, int star_y) { int i, star_id = -1; for(i = 0; i <=max_stars-1; i++) { if(stars[i].x == star_x && stars[i].y == star_y) return star_id = stars[i].id; } return star_id; } // generates random stars void bang(int num) { int i, x, y, star_found = -1; for(i = 0; i<=num-1; i++) { do { x = rand()%max_x; y = rand()%max_y; star_found = find_star(x, y); } while (star_found != -1); stars[i].id = i; stars[i].x = x; stars[i].y = y; } printf("The Big Bang has occurred\n"); } // print the stars void list_stars() { int i; char name[25]; if (star_number == 0) { printf("The universe have not been created!"); return; } for (i = 0; i <= star_number-1; i++) { printf("Star %.2i\n", stars[i].id); if(strcmp(stars[i].name, " ") !=0) printf("Name: %s\n", stars[i].name); // if the star has been named this will be printed printf("Coords:(%.3lf, %.3lf)\n", stars[i].x, stars[i].y); printf("\n"); } } //print pairs of stars void list_pair() { int i; if (pair_number == 0) { printf("No pair has been created yet!\n"); return; } for (i = 0; i <= pair_number - 1; i++) { printf("Pair %i\n:", star_pairs[i].id); printf("Distance:%lf light years\n", star_pairs[i].star_distance); printf("Star %i\n",star_pairs[i].star1_id); printf("Name: %s\n", star_pairs[i].star1_name); printf("Coords:%.3lf, %.3lf\n", stars[star_pairs[i].star1_id].x, stars[star_pairs[i].star1_id].y); printf("Star %i\n",star_pairs[i].star2_id); printf("Name: %s\n", star_pairs[i].star2_name); printf("Coords:%.3lf, %.3lf\n", stars[star_pairs[i].star2_id].x, stars[star_pairs[i].star2_id].y); printf("******************************\n"); } } //find and create closest stars pair void name_star() { int i,j, star_id1 = -1, star_id2 = -1, star_index1 = -1, star_index2 = -1; char input_str[25]="\0", star_name1[25]="\0", star_name2[25] = "\0",name_command; double min_distance = sqrt(pow(max_x,2)+pow(max_y,2)), distance_x, distance_y, star_distance; if (star_number == 0) { printf("The universe have not been created!"); return; } // find closest pair for (i = 0; i<=star_number - 2; i++) { // if the star already got a name if (strcmp(stars[i].name, " ") != 0) continue; for(j = i + 1; j<=star_number - 1; j++) { if (strcmp(stars[j].name, " ") !=0) continue; // calculate distances distance_x = fabs(stars[i].x - stars[j].x); distance_y = fabs(stars[i].y - stars[j].y); star_distance = sqrt(pow(distance_x,2)+pow(distance_y,2)); if (star_distance < min_distance) { min_distance = star_distance; star_id1 = stars[i].id; star_index1 = i; star_id2 = stars[j].id; star_index2 = j; } } } // if there is no pair left if ( star_id1 == -1 && star_id2 == -1 ) { printf("Sorry, no pairs were found.\nWish you a better luck in the next universe.\n"); return; } printf("The closest pair of stars are no. %i and %i\n", star_id1, star_id2); printf("They are %lf light years apart\n", min_distance); printf("Would you like to name this pair (y/n)? "); // ask user whether to name pair scanf("%c", &name_command); while(getchar() != '\n'); // clear unwanted characters remain in stdin // if user decide not to name if (name_command != 'y') { printf("You have chosen not to name this pair\n"); return; } // input name of user do { printf("Enter your full name: "); fgets(input_str, 26, stdin); if (input_str[strlen(input_str)-1] != '\n') while(getchar() != '\n'); //Clear unwanted characters remain in stdin. after fgets if (input_str[strlen(input_str)-1] == '\n') input_str[strlen(input_str)-1] ='\0'; //remove \n out of input strcpy(star_name1, rtrim(ltrim(input_str))); } while (star_name1[0] == '\0'); // ensure the user enters a string // input name of user's spouse do { printf("Enter your spouse's full name: "); fgets(input_str, 26, stdin); if (input_str[strlen(input_str)-1] != '\n') while(getchar() != '\n'); //Clear unwanted characters remain in stdin. after fgets if (input_str[strlen(input_str)-1] == '\n') input_str[strlen(input_str)-1] ='\0'; //remove \n out of input strcpy(star_name2, rtrim(ltrim(input_str))); } while (star_name2[0] == '\0'); // assigned star pairs pair_number = pair_number + 1; star_pairs[pair_number - 1].id = pair_number - 1; star_pairs[pair_number - 1].star1_id = star_id1; strcpy(star_pairs[pair_number - 1].star1_name, star_name1); star_pairs[pair_number - 1].star2_id = star_id2; strcpy(star_pairs[pair_number - 1].star2_name, star_name2); star_pairs[pair_number - 1].star_distance = min_distance; // assigned name to stars strcpy(stars[star_index1].name, star_name1); strcpy(stars[star_index2].name, star_name2); printf("Congratulation a pair of stars has been name after you and your spouse\n"); } void show_name() { int i, j, x, y, star_id1, star_id2, star_x, star_x1, star_y1, star_x2, star_y2, write_x, write_y, pair_id = -1; char input_str[25], star_name[25], star_name1[25], star_name2[25], pair_full_name[55] = "\0"; // input user's name do { printf("Enter your full name: "); fgets(input_str, 26, stdin); if (input_str[strlen(input_str)-1] != '\n') while(getchar() != '\n'); //Clear unwanted characters remain in stdin. after fgets if (input_str[strlen(input_str)-1] == '\n') input_str[strlen(input_str)-1] ='\0'; //remove \n out of input strcpy(star_name, rtrim(ltrim(input_str))); } while (star_name[0] == '\0'); // ensure the user enters a string // check if name is given or in the star_pair array for (i = 0; i <= pair_number - 1; i++) { if (strcmp(star_name, star_pairs[i].star1_name) == 0 || strcmp(star_name, star_pairs[i].star2_name) == 0) { pair_id = star_pairs[i].id; star_id1 = star_pairs[i].star1_id; strcpy(star_name1, star_pairs[i].star1_name); star_x1 = stars[star_pairs[i].star1_id].x; star_y1 = stars[star_pairs[i].star1_id].y; star_id2 = star_pairs[i].star2_id; strcpy(star_name2, star_pairs[i].star2_name); star_x2 = stars[star_pairs[i].star2_id].x; star_y2 = stars[star_pairs[i].star2_id].y; break; } } if (pair_id == -1) { printf("Star name is not found.\n"); return; } strcat(pair_full_name, star_name1); strcat(pair_full_name, " & "); strcat(pair_full_name, star_name2); // finding the y coordinate to copy string write_y = (star_y1 <= star_y2) ? star_y2 + 1 : star_y1 + 1; write_x = (star_y1 <= star_y2) ? star_x2 - strlen(pair_full_name)/2 + 1 : star_x1 - strlen(pair_full_name)/2 + 1; if(write_y > max_y - 1) { write_y = (star_y1 <= star_y2) ? star_y1 - 1 : star_y2 - 1; write_x = (star_y1 <= star_y2) ? star_x1 - strlen(pair_full_name)/2 + 1 : star_x2 - strlen(pair_full_name)/2 + 1; } if (write_x + strlen(pair_full_name) - 1 > max_x -1) { write_x = max_x - 1 - strlen(pair_full_name) + 1; } if (write_x < 0 ) { write_x = 0; } clear(); // fill the frame buffer for (i = 0; i <= star_number - 1; i++) { x = (int) stars[i].x; y = (int) stars[i].y; strcpy(star_name, stars[i].name); if (strcmp(star_name, " ") == 0) plot(x, y, '.'); else plot(x, y, '*'); } write_at(write_x, write_y, strcat(strcat(star_name1, " & "), star_name2)); // clears the terminal system("clear"); // print the entire frame buffer for(i = 0; i <= max_y - 1; i++) // check the row y { for(j = 0; j <= max_x - 1; j++) // check the column x { printf("%c", galaxy[i][j]); } printf("\n"); } } void save_galaxy() { FILE *ptr_galaxy; struct galaxy_size g_size; ptr_galaxy = fopen("universe.bin", "wb"); if(!ptr_galaxy) { printf("Unable to save file!\n"); return; } // assign star number g_size.star_no = star_number; // assign pair number g_size.pair_no = pair_number; // save the star and pair number fwrite(&g_size, sizeof(g_size), 1, ptr_galaxy); // save the struct of stars and star_pairs if (fwrite(&stars, sizeof(struct star_data), star_number, ptr_galaxy) != star_number) { printf("Error when saving the universe.\n"); return; } if (fwrite(&star_pairs, sizeof(struct pair_data), pair_number, ptr_galaxy) != pair_number) { printf("Error when saving the universe.\n"); return; } // close the file fclose(ptr_galaxy); printf("Thanks, you have saved the universe!\n"); } void load_galaxy() { FILE *ptr_galaxy; struct galaxy_size g_size; ptr_galaxy = fopen("universe.bin", "rb"); // if user hasn't save yet if (!ptr_galaxy) { printf("Unable to open file! Have you save your universe?\n"); return; } reset(); // read star and pair number fread(&g_size, sizeof(g_size), 1, ptr_galaxy); // read the stars array from file, check if fread read the block number = g_size.star_no if (fread(&stars, sizeof(struct star_data), g_size.star_no, ptr_galaxy) < g_size.star_no) { printf("Error when load the universe from saved file!\n"); return; } star_number = g_size.star_no; // read the star_pairs array from file, check if fread returns the block number = g_size.pair_no if (fread(&star_pairs, sizeof(struct pair_data), g_size.pair_no, ptr_galaxy) < g_size.pair_no) { printf("Error when load the universe from saved file!\n"); return; } pair_number = g_size.pair_no; // close the file fclose(ptr_galaxy); printf("Congratulations, your universe has been restored.\n"); } /********************************************** MAIN FUNCTION *******************************************************/ int main() { time_t t; char game_command[7], g_command[15]; int game_stop, command_id; game_stop = 0; srand((unsigned) time(&t)); printf("Welcome to the Big Bang Simulation.\n"); while (game_stop == 0) { command_id = 0; printf(">>>"); //scanf( " %s", game_command); fgets(g_command, 16, stdin); if (g_command[strlen(g_command)-1] != '\n') while(getchar() != '\n'); //Clear unwanted characters remain in stdin. after fgets if (g_command[strlen(g_command)-1] == '\n') g_command[strlen(g_command)-1] ='\0'; //remove \n out of input sscanf(g_command, "%s %d", game_command, &command_id); // the CLI // the bang command if (strcmp(game_command, "bang") == 0) { if (command_id > 0 && command_id <= max_stars) { reset(); star_number = command_id; bang(star_number); } else printf("Invalid star number.\n"); } // the list command else if (strcmp(game_command, "list") == 0) { list_stars(); } // the name command else if (strcmp(game_command, "name") == 0) { name_star(); } // the pairs command else if (strcmp(game_command, "pairs") == 0) { list_pair(); } // the draw command else if (strcmp(game_command, "draw") == 0) { refresh(); } // the show command else if (strcmp(game_command, "show") == 0) { show_name(); } // the save command else if (strcmp(game_command, "save") == 0) { save_galaxy(); } // the load command else if (strcmp(game_command, "load") == 0) { load_galaxy(); } // the quit command else if (strcmp(game_command, "quit") == 0) { game_stop = 1; printf("You have quit the program.\n"); } else { printf("Invalid command.\n"); } } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> /////////////////////////////////////////////// int porownanie_lancuchow(char *A, char *B) { int i=0; while(A[i]!=NULL || B[i]!=NULL) { if((int)A[i]<(int)B[i]) return 1; if((int)A[i]>(int)B[i]) return 0; i++; } if(A[i]==NULL && B[i]==NULL) return 1; if(A[i]==NULL && B[i]!=NULL) return 1; else return 0; } /////////////////////////////////////////////// int Partition(int **A,int p, int r) { char* x=A[r-1]; //element wyznaczajacy podzial int i=p-1; char* tmp; for(int j=p;j<r;j++) { //if(A[j]<=x) if(porownanie_lancuchow(A[j],x)) { i++; tmp=A[j]; A[j]=A[i]; A[i]=tmp; } } if(i<r) return i; else return i-1; } void Quicksort(int **A,int p, int r) { int q; if(p<r) { q=Partition(A,p,r); Quicksort(A,p,q); Quicksort(A,q+1,r); } } /////////////////////////////////////////////// void counting_sort(char **A,char **Pomocnicza,int *dlugosci,int pozycja,int ilosc) { int *dlugosc_pomocnicza = (int*) malloc(ilosc * sizeof(*dlugosc_pomocnicza)); /* for(int i=0;i<ilosc;i++) { dlugosc_pomocnicza[i]=dlugosci[i]; } for(int i=0;i<ilosc;i++) { Pomocnicza[i]=A[i]; } */ int tablica_zliczajaca[27]; for(int i=0;i<27;i++) { tablica_zliczajaca[i]=0; } for(int i=0;i<ilosc;i++) { if(dlugosci[i]-1<pozycja) tablica_zliczajaca[0]++; else tablica_zliczajaca[(int)A[i][pozycja]-96]++; } for(int i=1;i<27;i++) { tablica_zliczajaca[i]+=tablica_zliczajaca[i-1]; } for(int i=ilosc-1;i>=0;i--) { if(dlugosci[i]-1<pozycja) { tablica_zliczajaca[0]--; Pomocnicza[tablica_zliczajaca[0]]=A[i]; dlugosc_pomocnicza[tablica_zliczajaca[0]]=dlugosci[i]; } else { tablica_zliczajaca[(int)A[i][pozycja]-96]--; Pomocnicza[tablica_zliczajaca[(int)A[i][pozycja]-96]]=A[i]; dlugosc_pomocnicza[tablica_zliczajaca[(int)A[i][pozycja]-96]]=dlugosci[i]; } } for(int i=0;i<ilosc;i++) { dlugosci[i]=dlugosc_pomocnicza[i]; A[i]=Pomocnicza[i]; } } void Radix_sort(char **A,char **Pomocnicza,int *dlugosci,int ilosc) { int max_index=0; for(int i=0;i<ilosc;i++) if(dlugosci[i]>max_index) max_index=i; for(int i=max_index-1;i>=0;i--) { counting_sort(A,Pomocnicza,dlugosci,i,ilosc); } } int main() { int licznik=0; // FILE *plik; char nazwisko[50]; //nazwa pliku wejsciowego char nazwaPliku[]="Nazwiska2.txt"; if((plik=fopen(nazwaPliku,"r"))==NULL) { printf("Nie moglem otworzyc pliku\n"); exit(1); } while(feof(plik)==0) { fscanf(plik,"%s",nazwisko); licznik++; } char **pomocnicza = (char**) malloc(licznik * sizeof(char**)); char **nazwiska = (char**) malloc(licznik * sizeof(char**)); char **nazwiska_dla_quicksort = (char**) malloc(licznik * sizeof(char**)); int *dlugosc_nazwisk = (int*) malloc(licznik * sizeof(*dlugosc_nazwisk)); rewind(plik); int j=0; for(int i=0;i<licznik;i++) { pomocnicza[i]=(char*) malloc(50*sizeof(char)); nazwiska[i]=(char*) malloc(50 * sizeof(char)); nazwiska_dla_quicksort[i]=(char*) malloc(50 * sizeof(char)); fscanf(plik,"%s",nazwiska[i]); j=0; while(nazwiska[i][j]!=NULL) { dlugosc_nazwisk[i]=j; j++; } dlugosc_nazwisk[i]++; nazwiska_dla_quicksort[i]=nazwiska[i]; } clock_t start; double czas1,czas2,czas3,czas4; start=clock(); Quicksort(nazwiska_dla_quicksort,0,licznik); czas1=((double)(1000*(clock()-start))/CLOCKS_PER_SEC); FILE *plik2; plik2=fopen("posortowaneQuicksortem.txt","w"); for(int i=0;i<licznik;i++) { fprintf(plik2,"%s\n",nazwiska_dla_quicksort[i]); } start=clock(); Radix_sort(nazwiska,pomocnicza,dlugosc_nazwisk,licznik); czas2=((double)(1000*(clock()-start))/CLOCKS_PER_SEC); FILE *plik3; plik3=fopen("posortowaneRadixSortem.txt","w"); for(int i=0;i<licznik;i++) { fprintf(plik3,"%s\n",nazwiska[i]); } printf("Czas wykonania Quicksort: %f\n",czas1); printf("Czas wykonania RadixSort: %f\n",czas2); //DLA JEDNAKOWEJ DLUGOSCI srand(time(NULL)); int x=200000; char **dla_jednakowej_dlugosci_1 = (char**) malloc(x * sizeof(char**)); char **dla_jednakowej_dlugosci_2 = (char**) malloc(x * sizeof(char**)); char **dla_jednakowej_dlugosci_3 = (char**) malloc(x * sizeof(char**)); for(int i = 0; i<x;i++) { dla_jednakowej_dlugosci_1[i]=(char*) malloc(3*sizeof(char)); dla_jednakowej_dlugosci_2[i]=(char*) malloc(3*sizeof(char)); dla_jednakowej_dlugosci_3[i]=(char*) malloc(3*sizeof(char)); for(int j=0;j<3;j++) { dla_jednakowej_dlugosci_1[i][j]=(char)((rand()%26)+97); dla_jednakowej_dlugosci_2[i][j]=dla_jednakowej_dlugosci_1[i][j]; } } start=clock(); Quicksort(dla_jednakowej_dlugosci_1,0,x); czas3=((double)(1000*(clock()-start))/CLOCKS_PER_SEC); FILE *plik4; plik4=fopen("posortowaneQuicksortemTeSamejDlugosci.txt","w"); for(int i=0;i<x;i++) { fprintf(plik4,"%s\n",dla_jednakowej_dlugosci_1[i]); } int dlugosc_niepotrzebna[200000]; for(int i=0;i<x;i++) dlugosc_niepotrzebna[i]=3; start=clock(); Radix_sort(dla_jednakowej_dlugosci_2,dla_jednakowej_dlugosci_3,dlugosc_niepotrzebna,x); czas4=((double)(1000*(clock()-start))/CLOCKS_PER_SEC); FILE *plik5; plik5=fopen("posortowaneRadixSortemTeSamejDlugosci.txt","w"); for(int i=0;i<x;i++) { fprintf(plik5,"%s\n",dla_jednakowej_dlugosci_2[i]); } printf("Czas wykonania Quicksort dla tej samej dlugosci: %f\n",czas3); printf("Czas wykonania RadixSort dla tej samej dlugosci: %f\n",czas4); fclose(plik); fclose(plik2); fclose(plik3); fclose(plik4); fclose(plik5); }
C
#include <stdio.h> #include <stdlib.h> #include <limits.h> #define MIN(a,b) (((a)<(b))?(a):(b)) #define MAX(a,b) (((a)>(b))?(a):(b)) #define SIZE 100 typedef struct item { float value, weight; } Item; int compare (const void * a, const void * b) { Item *left = (Item*) a; Item *right = (Item*) b; return ( (right->value / right->weight) - (left->value / left->weight) ); } double fractional_knapsack(Item *arr, int n, int w) { float weight, acum, remain; int i; qsort(arr, n, sizeof(Item), compare); weight = 0; acum = 0; for (i = 0; i < n; i++) { if (weight + arr[i].weight <= w) { weight += arr[i].weight; acum += arr[i].value; } else { remain = w- weight; acum += arr[i].value * (remain / arr[i].weight); } } return acum; } int main(int argc, char* argv[]) { int i, n; float w; Item *arr; scanf("%i %f", &n, &w); arr = (Item*) malloc(sizeof(Item) * n); for (i = 0; i < n; i++) { scanf("%f %f", &arr[i].value, &arr[i].weight); } printf("Maximum value we can obtain = %.2f\n", fractional_knapsack(arr, n, w)); free(arr); return 0; }
C
#include"string.h" #include"stdio.h" main() { char mot[100]="Tram nam trong coi nguoi ta"; char hai[100]=" Chu tai chu menh kheo la ghet nhau"; char ba[100]="Trai qua mot cuoc be dau"; char bon[100]=" Nhung dieu trong thay ma dau dn long"; clrscr(); printf("\nCau \" %s\". Co chieu dai :%d ky tu ",mot,strlen(mot)); printf("\nCau \" %s\". Co chieu dai :%d ky tu ",hai,strlen(hai)); printf("\nCau \" %s\". Co chieu dai :%d ky tu ",ba,strlen(ba)); printf("\nCau \" %s\". Co chieu dai :%d ky tu ",bon,strlen(bon)); strcat(mot,hai); strcat(ba,bon); printf("\n"); printf("\n PHEP CONG CHUOI KY TU \n"); printf("\n + Dem cau 1 + cau 2"); printf("\nHai cau %s",mot); printf("\n - Co chieu dai: %d ky tu :",strlen(mot)); printf("\n"); printf("\n + Dem cau 3 + cau 4"); printf("\nHai cau %s",ba); printf("\n - Co chieu dai : %d ky tu",strlen(ba)); getch(); } 
C
#include <stdio.h> int main() { int a = 0, flag; int vetor[10], iguais[10]; for (int i = 0; i < 10; i++) { printf("Entre com o elemento %d°: ", i + 1); scanf("%d", &vetor[i]); } for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { flag = 0; if (vetor[i] == vetor[j] && i != j) { for (int w = 0; w < 10; w++) { if (iguais[w] == vetor[j]) flag = 1; } if (flag == 0) { iguais[a] = vetor[i]; a++; } } } } printf("\n\nSaída --> "); for (int i = 0; i < a; i++) printf("%d ", iguais[i]); printf("\n\n"); return (0); }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <ctype.h> #include <stdbool.h> #include <stdarg.h> #include <sys/time.h> #include <limits.h> #include <errno.h> #include <assert.h> #define ARRAY_SIZE(arr) (sizeof(arr) / sizeof((arr)[0])) enum state { STOP, ECHO, PAUSE, LATCH, GENERATE, }; /* Возможные события конечного автомата: прием цифры, прием управляющего * символа, истечение таймаута или разрыв соединения. Цифры и управляющие * символы представляются в кодировке ASCII (т.е. '1', '2', 'e', 's' и т.д.) * Для остальных событий используется перечислимый тип enum event. */ enum event { PERIOD_EXPIRATION = 256, GENERATE_EXPIRATION, CONNECTION_CLOSED, }; struct repeater { unsigned int index; int listen_sock; int data_sock; enum state state; /* Данные для состояния PAUSE. */ struct timeval pause_expiration; /* Данные для состояния GENERATE. */ struct timeval period_expiration; struct timeval generate_expiration; char generated_char; struct timeval generate_period; }; static const char *state2str(enum state state) { const char *strings[] = { [STOP] = "stop", [ECHO] = "echo", [PAUSE] = "pause", [LATCH] = "latch", [GENERATE] = "generate", }; return strings[state]; } static const char *event2str(int event) { static char str[2]; switch (event) { case PERIOD_EXPIRATION: return "period-expiration"; case GENERATE_EXPIRATION: return "generate-expiration"; case CONNECTION_CLOSED: return "connection-closed"; default: break; } if (!isalnum(event)) return NULL; sprintf(str, "%c", event); return str; } static int init_repeater(struct repeater *r, unsigned int index) { struct sockaddr_in addr = { .sin_family = AF_INET, .sin_port = htons(9000 + r->index), .sin_addr = {INADDR_ANY}, }; int option = 1; int ret; r->listen_sock = socket(AF_INET, SOCK_STREAM, 0); if (!r->listen_sock) { fprintf(stderr, "Failed to create socket: %s\n", strerror(errno)); return -1; } ret = setsockopt(r->listen_sock, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)); if (ret < 0) { fprintf(stderr, "Failed to set socket option: %s\n", strerror(errno)); goto on_error; } ret = bind(r->listen_sock, (struct sockaddr *)&addr, sizeof(addr)); if (ret < 0) { fprintf(stderr, "Failed to bind to server: %s\n", strerror(errno)); goto on_error; } ret = listen(r->listen_sock, 1); if (ret < 0) { fprintf(stderr, "Failed to put socket into listening state: %s\n", strerror(errno)); goto on_error; } r->generate_period.tv_sec = 1; r->state = STOP; return 0; on_error: close(r->listen_sock); r->listen_sock = -1; return -1; } /* Функция форматирует сообщение с помощью vsnprintf() и записывает его в * передающий сокет повторителя с помощью send(). * int vsnprintf( char *s, size_t n, const char *format, va_list ap ); * Запись форматированной строки в строку с ограничением на количество выводимых символов. * Значения для вывода передаются в функцию в виде списка va list */ static int send_data(struct repeater *r, const char *fmt, ...) { va_list ap; char response[100]; va_start(ap, fmt); vsnprintf(response, sizeof(response), fmt, ap); int ret = send(r->data_sock, response, strlen(response), 0); if (ret < 0) return -1; return 0; } static void run_state_machine(struct repeater *r, int event) { enum state old_state = r->state; const char *event_str = event2str(event); struct timeval now; int ret; if (!event_str) return; if (event == CONNECTION_CLOSED) { printf("Connection lost\n"); r->state = STOP; return; } printf("Received event '%s' in state %s\n", event_str, state2str(r->state)); gettimeofday(&now, NULL); switch (r->state) { case STOP: if (event == 'e') r->state = ECHO; else if (event == 'l') r->state = LATCH; break; /* Фрагмент кода отвечает за обработку событий в состояниях ECHO и * PAUSE. Чтобы отличать цифры, от управляющих символов, можно * использовать функцию isdigit(). Для работы со временем использовать * макросы timeradd(), timersub(), timercmp(). Вывод повторяемых цифр * или времени до истечения задержки производится с помощью * send_data(). */ case ECHO: if (isdigit(event)) { ret = send_data(r, "Echoing digit '%c'\n", event); if (ret < 0) goto on_error; } else if (event == 's') { r->state = STOP; } else if (event == 'p') { struct timeval pause = {.tv_sec = 3}; timeradd(&now, &pause, &r->pause_expiration); r->state = PAUSE; } break; case PAUSE: if (isdigit(event)) { struct timeval left; if (timercmp(&now, &r->pause_expiration, >)) { r->state = ECHO; } else { timersub(&r->pause_expiration, &now, &left); ret = send_data(r, "%ld seconds left\n", left.tv_sec); if (ret < 0) goto on_error; } } break; case LATCH: if (event == 's') r->state = STOP; else if (isdigit(event)) { struct timeval generate = {.tv_sec = 5}; timeradd(&now, &generate, &r->generate_expiration); timeradd(&now, &r->generate_period, &r->period_expiration); r->generated_char = event; r->state = GENERATE; } break; case GENERATE: if (timercmp(&now, &r->generate_expiration, >)) { r->state = LATCH; } else if (timercmp(&now, &r->period_expiration, >=)) { struct timeval period = {.tv_sec = 1}; timeradd(&now, &period, &r->period_expiration); ret = send_data(r, "%c\n", r->generated_char); if (ret < 0) goto on_error; } break; } if (r->state != old_state) printf("Transitioning to state %s\n", state2str(r->state)); return; on_error: return; } int main(int argc, char *argv[]) { struct repeater repeaters[10]; int ret; int i; memset(repeaters, 0, sizeof(repeaters)); for (i = 0; i < ARRAY_SIZE(repeaters); i++) { repeaters[i].index = i; repeaters[i].listen_sock = -1; repeaters[i].data_sock = -1; } for (i = 0; i < ARRAY_SIZE(repeaters); i++) { ret = init_repeater(&repeaters[i], i); if (ret < 0) goto on_error; } while (1) { fd_set fds; int max_fd = 0; /* Наибольший файловый дескриптор, находящийся * в множестве fds. */ struct timeval now, timeout = {.tv_sec = LONG_MAX}, candidate; FD_ZERO(&fds); /* Фрагмент кода переьирает все повторители и добавляет * необходимый файловый дескриптор в множество fds: дескриптор * слушающего сокета, если соединение еще не установлено, * дескриптор передающего сокета - если установлено. */ for (i = 0; i < ARRAY_SIZE(repeaters); ++i) { struct repeater *r = &repeaters[i]; int sock = r->data_sock < 0 ? r->listen_sock : r->data_sock; FD_SET(sock, &fds); max_fd = (sock > max_fd) ? sock + 1 : max_fd; } /* Фрагмент кода задает значение timeout - разницу между * текущим временем и самым ранним временем истечения для всех * активных таймеров. Используется функция gettimeofday() и * макросы timeradd(), timersub(), timercmp(). Следует учесть, * что таймеры активны только у повторителей в состоянии * GENERATE. Если активных таймеров нет, timeout остается без * изменений. */ /* ... УСЛОЖНЕННАЯ ЗАДАЧА ... */ gettimeofday(&now, NULL); for (int i = 0; i < 10; i++) { if (repeaters[i].state == GENERATE) { timersub(&repeaters[i].period_expiration, &now, &candidate); if (timercmp(&candidate, &timeout, <)) { timeout = candidate; } } } ret = select(max_fd + 1, &fds, NULL, NULL, &timeout); if (ret < 0) { fprintf(stderr, "select() failed: %s\n", strerror(errno)); goto on_error; } /* Фрагмент кода проверяет все активные таймеры и генерирует * события GENERATE_EXPIRATION или PERIOD_EXPIRATION для * сработавших таймеров. Используется функция gettimeofday() и * макросы timeradd(), timersub(), timercmp(). */ if (ret == 0) { gettimeofday(&now, NULL); for (int i = 0; i < 10; i++) { if (repeaters[i].state == GENERATE) { if(timercmp(&now,&repeaters[i].generate_expiration, >=)) run_state_machine(&repeaters[i],GENERATE_EXPIRATION); else if (timercmp(&now,&repeaters[i].period_expiration, >=)) run_state_machine(&repeaters[i],PERIOD_EXPIRATION); } } } /* Фрагмент кода перебирает все повторители и проверяет * готовность их файловых дескрипторах. Если готов к чтению * слушающий сокет, программа принимает новое передающее * соединение, если готов передающий сокет, программа читает из * него данные и передает их в качестве событий на вход * конечного автомата. Если передающее соединение завершилось, * программа отправляет автомату событие CONNECTION_CLOSED. */ for (i = 0; i < ARRAY_SIZE(repeaters); i++) { struct repeater *r = &repeaters[i]; if (FD_ISSET(r->listen_sock, &fds)) { r->data_sock = accept(r->listen_sock, NULL, NULL); if (r->data_sock < 0) { fprintf(stderr, "Failed to accept data " "connection: %s\n", strerror(errno)); goto on_error; } } else if (r->data_sock > 0 && FD_ISSET(r->data_sock, &fds)) { char ch; ret = recv(r->data_sock, &ch, 1, MSG_DONTWAIT); if (ret < 0) goto on_error; if (ret == 0) { close(r->data_sock); r->data_sock = -1; run_state_machine(r,CONNECTION_CLOSED); continue; } run_state_machine(r, ch); } } } for (i = 0; i < ARRAY_SIZE(repeaters); i++) { if (repeaters[i].listen_sock >= 0) close(repeaters[i].listen_sock); if (repeaters[i].data_sock >= 0) close(repeaters[i].data_sock); } return 0; on_error: for (i = 0; i < ARRAY_SIZE(repeaters); i++) { if (repeaters[i].listen_sock >= 0) close(repeaters[i].listen_sock); if (repeaters[i].data_sock >= 0) close(repeaters[i].data_sock); } return 1; }
C
# include<stdio.h> struct node{ int data; struct node *next; }; void append(struct node** head_ref, int new_data){ struct node* new_node = (struct node*) malloc(sizeof(struct node)); struct node *last = *head_ref; new_node->data= new_data; new_node->next=NULL; if(*head_ref==NULL) { *head_ref = new_node; return; } while(last->next!=NULL) last=last->next; last->next=new_node; return; } void printList(struct node *node){ while(node != NULL) { printf(" %d",node->data); node=node->next; } } int main(){ struct node* head = NULL; append(&head,6); printf("\nThe linked list is :"); printList(head); append(&head,10); append(&head,1); append(&head,5); printf("\nThe linked list is :"); printList(head); return 0; }
C
#include <string> #include <iostream> std::string plus(std::string s1, std::string s2) { int len1 = s1.length(), len2 = s2.length(); int pre = 0, temp; std::string ans = ""; for (int i = len1 - 1, j = len2 - 1; i >= 0 || j >= 0 || pre; i--, j--) { if (i >= 0 && j >= 0) { temp = (s1[i] - '0') + (s2[j] - '0') + pre; if (temp >= 10) temp -= 10, pre = 1; else pre = 0; ans = char('0' + temp) + ans; } else { if (i >= 0) { temp = (s1[i] - '0') + pre; if (temp >= 10) temp -= 10, pre = 1; else pre = 0; ans = char('0' + temp) + ans; } else if (j >= 0) { temp = (s2[j] - '0') + pre; if (temp >= 10) temp -= 10, pre = 1; else pre = 0; ans = char('0' + temp) + ans; } else { ans = char('0' + pre--) + ans; } } } return ans; } int main() { int t, b, times; std::cin >> t; std::string big_number, result; while (t--) { std::cin >> big_number >> b; while (true) if (big_number[0] == '0') big_number.erase(0, 1); else break; if (big_number == "" || b == 0) { std::cout << "0" << std::endl; continue; } result = ""; while (b) { times = b % 10; b /= 10; while (times--) result = plus(result, big_number); big_number += "0"; } std::cout << result << std::endl; } }
C
#include "hello.h" GtkWidget *janela; GtkWidget *conteiner; GtkWidget *botao; GtkWidget *rotulo; lista * lista_de_textos; void hello (void){ // Muando o texto do rotulo mudar_rotulo(rotulo, lista_de_textos->texto); // Mudando o texto atual para o proximo da lista lista_de_textos = lista_de_textos->prox; } int main (int argc, char *argv[]){ // criando a lista de textos lista_de_textos = (lista []){ {.texto = "Hello mundo!!", NULL}, // 1 {.texto = "Eu amo C!!", NULL}, // 2 {.texto = "C para seres humanos!", NULL}, // 3 {.texto = "Outra coisa aleatória!", NULL}, // 4 {.texto = "Acesse robocopgay.github.io", NULL} // 5 }; organize_lista(lista_de_textos, 5); // inicializando configurações padrões da biblioteca gtk_init (&argc, &argv); // criando a janela principal janela = gtk_window_new (GTK_WINDOW_TOPLEVEL); // quando o usuário fechar a janela, ela será fechada gtk_signal_connect (GTK_OBJECT (janela), "destroy", GTK_SIGNAL_FUNC (gtk_main_quit), NULL); // criando um rótulo com o texto "..." rotulo = gtk_label_new("..."); // criando um botão com o texto "Clique em mim" botao = gtk_button_new_with_label ("Clique em mim"); // criando um conteiner para guardar os componentes acima (rotulo, botao) conteiner = gtk_vbox_new((gint *)5,(gint *)5); // quando o usuário clicar no botão ele vai chamar a função hello gtk_signal_connect (GTK_OBJECT (botao), "clicked", GTK_SIGNAL_FUNC (hello), NULL); // adicionando componentes ao conteiner gtk_container_add(GTK_BOX(conteiner), rotulo); gtk_container_add(GTK_BOX(conteiner), botao); // adicionando o conteiner à janela gtk_container_add (GTK_CONTAINER (janela), conteiner); // tornando os componentes visíveis gtk_widget_show_all (janela); // iniciando a execução do aplicativo gráfico gtk_main(); return 0; }
C
#include "shell.h" /** * _strcat - concatenate two strings * @dest: string to be appended to * @src: string to append * Return: concatenated string */ char *_strcat(char *dest, char *src) { int len = 0; int len2 = 0; int total_len = 0; int j = 0; /* find total length of both strings to _realloc */ while (dest[len] != '\0') { len++; total_len++; } while (src[len2] != '\0') { len2++; total_len++; } /* _realloc because dest was malloced outside of function */ dest = _realloc(dest, len, sizeof(char) * total_len + 1); while (src[j] != '\0') { dest[len] = src[j]; len++; j++; } dest[len] = '\0'; return (dest); }
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 */ int SQLITE_ERROR ; int SQLITE_OK ; int /*<<< orphan*/ assert (int) ; char* fts5ConfigSkipArgs (char const*) ; char* fts5ConfigSkipBareword (char const*) ; char* fts5ConfigSkipWhitespace (char const*) ; int /*<<< orphan*/ memcpy (char*,char const*,int) ; char* sqlite3Fts5MallocZero (int*,int) ; int /*<<< orphan*/ sqlite3_free (char*) ; int sqlite3Fts5ConfigParseRank( const char *zIn, /* Input string */ char **pzRank, /* OUT: Rank function name */ char **pzRankArgs /* OUT: Rank function arguments */ ){ const char *p = zIn; const char *pRank; char *zRank = 0; char *zRankArgs = 0; int rc = SQLITE_OK; *pzRank = 0; *pzRankArgs = 0; if( p==0 ){ rc = SQLITE_ERROR; }else{ p = fts5ConfigSkipWhitespace(p); pRank = p; p = fts5ConfigSkipBareword(p); if( p ){ zRank = sqlite3Fts5MallocZero(&rc, 1 + p - pRank); if( zRank ) memcpy(zRank, pRank, p-pRank); }else{ rc = SQLITE_ERROR; } if( rc==SQLITE_OK ){ p = fts5ConfigSkipWhitespace(p); if( *p!='(' ) rc = SQLITE_ERROR; p++; } if( rc==SQLITE_OK ){ const char *pArgs; p = fts5ConfigSkipWhitespace(p); pArgs = p; if( *p!=')' ){ p = fts5ConfigSkipArgs(p); if( p==0 ){ rc = SQLITE_ERROR; }else{ zRankArgs = sqlite3Fts5MallocZero(&rc, 1 + p - pArgs); if( zRankArgs ) memcpy(zRankArgs, pArgs, p-pArgs); } } } } if( rc!=SQLITE_OK ){ sqlite3_free(zRank); assert( zRankArgs==0 ); }else{ *pzRank = zRank; *pzRankArgs = zRankArgs; } return rc; }
C
#include "bundle7/bundle7.h" #include "bundle7/eid.h" #include "upcn/bundle.h" #include "cbor.h" #include <assert.h> #include <inttypes.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> // -------------------------------- // Endpoint Identifier (EID) Parser // -------------------------------- static inline size_t decimal_digits(uint32_t number) { size_t digits = 0; while (number != 0) { digits++; number /= 10; } return digits; } static CborError eid_parse_dtn(CborValue *it, char **eid); static CborError eid_parse_ipn(CborValue *it, char **eid); CborError bundle7_eid_parse_cbor(CborValue *it, char **eid) { CborValue recursed; CborError err; size_t length; uint64_t schema; if (!cbor_value_is_array(it) || !cbor_value_is_length_known(it)) return CborErrorIllegalType; // Array must contain 2 items if (cbor_value_get_array_length(it, &length) != CborNoError) return CborErrorIllegalType; if (length != 2) return CborErrorIllegalType; // Enter EID array err = cbor_value_enter_container(it, &recursed); if (err) return err; // EID schema (first element) if (!cbor_value_is_unsigned_integer(&recursed)) return CborErrorIllegalType; cbor_value_get_uint64(&recursed, &schema); // Second item (schema specific) err = cbor_value_advance_fixed(&recursed); if (err) return err; // Call schema specific parsing functions switch (schema) { case BUNDLE_V7_EID_SCHEMA_DTN: err = eid_parse_dtn(&recursed, eid); break; case BUNDLE_V7_EID_SCHEMA_IPN: err = eid_parse_ipn(&recursed, eid); break; // unknown schema default: return CborErrorIllegalType; } // SSP parsing returned error if (err) return err; assert(cbor_value_at_end(&recursed)); // Leave EID array err = cbor_value_leave_container(it, &recursed); if (err) { free(*eid); return err; } return CborNoError; } CborError eid_parse_dtn(CborValue *it, char **eid) { CborError err; size_t length; uint64_t num; // Special case: // // null-EID ("dtn:none") // if (cbor_value_is_unsigned_integer(it)) { cbor_value_get_uint64(it, &num); // The only allowd value here is zero if (num != 0) return CborErrorIllegalType; // Go to end of array cbor_value_advance_fixed(it); // Allocate output buffer *eid = malloc(9); if (*eid == NULL) return CborErrorOutOfMemory; memcpy(*eid, "dtn:none", 9); return CborNoError; } // The SSP of the "dtn" schema is a CBOR text string if (!cbor_value_is_text_string(it)) return CborErrorIllegalType; // Determine SSP length. We do not check if the length is known because // this is already done in cbor_value_get_string_length(). If the // length is unknown a CborErrorUnknownLength will be returned err = cbor_value_get_string_length(it, &length); if (err) return err; // Remaining bytes are not sufficient if ((size_t) (it->parser->end - it->ptr) < length) return CborErrorUnexpectedEOF; // The number of bytes written to the buffer will be written to the // length variable length += 1; // '\0' termination // Allocate output buffer for "dtn:" prefix + SSP *eid = malloc(4 + length); if (*eid == NULL) return CborErrorOutOfMemory; // Copy prefix memcpy(*eid, "dtn:", 4); // Copy SSP + '\0' and advance iterator to next element after SSP. err = cbor_value_copy_text_string(it, *eid + 4, &length, it); if (err) { free(*eid); return err; } return CborNoError; } CborError eid_parse_ipn(CborValue *it, char **eid) { CborValue recursed; CborError err; uint64_t nodenum, servicenum; // Enter array if (!cbor_value_is_array(it) || !cbor_value_is_length_known(it)) return CborErrorIllegalType; err = cbor_value_enter_container(it, &recursed); if (err) return err; // Node number // ----------- if (!cbor_value_is_unsigned_integer(&recursed)) return CborErrorIllegalType; cbor_value_get_uint64(&recursed, &nodenum); // Advance to service number err = cbor_value_advance_fixed(&recursed); if (err) return err; // Service number // -------------- if (!cbor_value_is_unsigned_integer(&recursed)) return CborErrorIllegalType; cbor_value_get_uint64(&recursed, &servicenum); err = cbor_value_advance_fixed(&recursed); if (err) return err; // Expect end of array if (!cbor_value_at_end(&recursed)) return CborErrorIllegalType; // Leave array err = cbor_value_leave_container(it, &recursed); if (err) return err; // "ipn:" + nodenum + "." + servicenum + "\0" size_t length = 4 + decimal_digits(nodenum) + 1 + decimal_digits(servicenum) + 1; // Allocate string memory *eid = malloc(length); if (*eid == NULL) return CborErrorOutOfMemory; // We use snprintf() because sprintf() would use a different // malloc() memory allocator then the bundle7 library. snprintf(*eid, length, "ipn:%"PRIu64".%"PRIu64, nodenum, servicenum); return CborNoError; } char *bundle7_eid_parse(const uint8_t *buffer, size_t length) { char *eid = NULL; CborValue it; CborParser parser; CborError err; err = cbor_parser_init(buffer, length, 0, &parser, &it); if (err != CborNoError) return NULL; err = bundle7_eid_parse_cbor(&it, &eid); if (err != CborNoError) return NULL; return eid; } // ------------------------------------ // Endpoint Identifier (EID) Serializer // ------------------------------------ //static const uint8_t _dtn_none[3] = { // 0x82, 0x01, 0x00 //}; CborError serialize_dtn_none(CborEncoder *encoder) { CborEncoder recursed; cbor_encoder_create_array(encoder, &recursed, 2); cbor_encode_uint(&recursed, BUNDLE_V7_EID_SCHEMA_DTN); cbor_encode_uint(&recursed, 0); cbor_encoder_close_container(encoder, &recursed); return CborNoError; } CborError serialize_dtn(const char *eid, CborEncoder *encoder) { CborEncoder recursed; size_t ssp_length = strlen(eid) - 4; // EID container cbor_encoder_create_array(encoder, &recursed, 2); // Schema cbor_encode_uint(&recursed, BUNDLE_V7_EID_SCHEMA_DTN); // SSP cbor_encode_text_string(&recursed, eid + 4, ssp_length); // EID container cbor_encoder_close_container(encoder, &recursed); return CborNoError; } CborError serialize_ipn(const char *eid, CborEncoder *encoder) { CborEncoder inner, ssp; uint32_t nodenum, servicenum; // Parse node and service numbers if (sscanf(eid, "ipn:%"PRIu32".%"PRIu32, &nodenum, &servicenum) != 2) return CborErrorIllegalType; // EID container cbor_encoder_create_array(encoder, &inner, 2); // Schema cbor_encode_uint(&inner, BUNDLE_V7_EID_SCHEMA_IPN); // SSP cbor_encoder_create_array(&inner, &ssp, 2); cbor_encode_uint(&ssp, nodenum); cbor_encode_uint(&ssp, servicenum); cbor_encoder_close_container(&inner, &ssp); // EID container cbor_encoder_close_container(encoder, &inner); return CborNoError; } size_t bundle7_eid_get_max_serialized_size(const char *eid) { // We use "string length + cbor_encode_uint(string length - 4)" as an // upper bound of the required buffer size. // // schema: // "ipn:" / "dtn:" > 1byte CBOR array header + 1byte schema number // // This means that there are 2 byte remaining unused. // // ipn: // SSP string representation is always longer than numerical // representation. The dot "." string literal reservers the space // for the CBOR array header // // dtn: // The CBOR encoded SSP requires an header encoding the string // length. Therefore we add the size of this header to the bound. // The SSP is "string length - 4" bytes long. // const size_t length = strlen(eid); return length + bundle7_cbor_uint_sizeof(length); } uint8_t *bundle7_eid_serialize_alloc(const char *eid, size_t *length) { size_t buffer_size = bundle7_eid_get_max_serialized_size(eid); uint8_t *buffer = malloc(buffer_size); // We could not allocate enough memory if (buffer == NULL) return NULL; int written = bundle7_eid_serialize(eid, buffer, buffer_size); if (written <= 0) { free(buffer); return NULL; } // Shorten buffer to correct length uint8_t *compress = realloc(buffer, written); // Something went south during realloc, clear buffer and abort if (compress == NULL) { free(buffer); return NULL; } *length = (size_t) written; return compress; } CborError bundle7_eid_serialize_cbor(const char *eid, CborEncoder *encoder) { size_t str_length = strlen(eid); // Special case: null-EID if (str_length == 8 && strncmp(eid, "dtn:none", 8) == 0) return serialize_dtn_none(encoder); // DTN (allows empty SSPs) if (str_length >= 4 && strncmp(eid, "dtn:", 4) == 0) return serialize_dtn(eid, encoder); // IPN else if (str_length > 4 && strncmp(eid, "ipn:", 4) == 0) return serialize_ipn(eid, encoder); // Unknwon schema else return CborErrorIllegalType; } int bundle7_eid_serialize(const char *eid, uint8_t *buffer, size_t buffer_size) { CborEncoder encoder; CborError err; cbor_encoder_init(&encoder, buffer, buffer_size, 0); err = bundle7_eid_serialize_cbor(eid, &encoder); // A non-recoverable error occured if (err != CborNoError && err != CborErrorOutOfMemory) return -1; // Out of memory (buffer too small) if (cbor_encoder_get_extra_bytes_needed(&encoder) > 0) return 0; return cbor_encoder_get_buffer_size(&encoder, buffer); }
C
#include <math.h> #include <stdlib.h> #include <assert.h> #include "polygon.h" typedef struct polygon { List *points; Vector *velocity; double red; double green; double blue; } Polygon; Polygon *polygon_init(List *points, Vector *start_vel, double red, double green, double blue) { Polygon *polygon = malloc(sizeof(Polygon)); assert(polygon != NULL); polygon->points = points; polygon->velocity = start_vel; polygon->red = red; polygon->green = green; polygon->blue = blue; return polygon; } List *get_polygon_points(Polygon *polygon) { return polygon->points; } Vector *get_polygon_velocity(Polygon *polygon) { return polygon->velocity; } double get_polygon_red(Polygon *polygon) { return polygon->red; } double get_polygon_green(Polygon *polygon) { return polygon->green; } double get_polygon_blue(Polygon *polygon) { return polygon->blue; } void set_velocity(Polygon *polygon, Vector *new_vel) { Vector *old_velocity = polygon->velocity; polygon->velocity = new_vel; free(old_velocity); } double polygon_area(Polygon *polygon) { List *points_list = get_polygon_points(polygon); size_t n = list_size(points_list); Vector *v_n = list_get(points_list, n-1); Vector *v_1 = list_get(points_list, 0); double shoelace_sum = vec_cross(*v_n, *v_1); /* Used first formula on wiki with 2 summations and 2 other terms. */ for (size_t i = 0; i <= n-2; i++) { Vector *v_i = list_get(points_list, i); Vector *v_i_plus_one = list_get(points_list, i+1); shoelace_sum += vec_cross(*v_i, *v_i_plus_one); } return .5 * fabs(shoelace_sum); } Vector polygon_centroid(Polygon *polygon) { List *points_list = get_polygon_points(polygon); double area = polygon_area(polygon); double c_x = 0; double c_y = 0; for (size_t i = 0; i < list_size(points_list); i++) { /** * we need to prepare for the event that we reach the end of the * vector_list and we need the first vector for our i+1 term. To prevent * an out of bounds error, we will just set v_i_plus_one to the first * element and if we are not at the last element, we can just set the i+1 * term as usual. Otherwise, we use the 0th Vector for our i+1 */ Vector *v_i_plus_one = list_get(points_list, 0); if (i != list_size(points_list)-1) { v_i_plus_one = list_get(points_list, i+1); } Vector *v_i = list_get(points_list, i); double common_term_in_sum = vec_cross(*v_i, *v_i_plus_one); c_x += (v_i->x + v_i_plus_one->x) * common_term_in_sum; c_y += (v_i->y + v_i_plus_one->y) * common_term_in_sum; } c_x /= (6 * area); c_y /= (6 * area); return vec_init(c_x, c_y); } void polygon_translate(Polygon *polygon, Vector translation) { List *points_list = get_polygon_points(polygon); for (size_t i = 0; i < list_size(points_list); i++) { Vector *current_vec = list_get(points_list, i); Vector new_vec = vec_add(*(Vector *)current_vec, translation); free(current_vec); list_set(points_list, i, create_vector_p(new_vec)); } } void polygon_rotate(Polygon *polygon, double angle, Vector point) { List *points_list = get_polygon_points(polygon); for (size_t i = 0; i < list_size(points_list); i++) { Vector *v_i = list_get(points_list, i); /** * we first move the vector back to the origin, rotate, and then * move the vector back to where it was to get respect to the given * point to rotate about. */ Vector v_i_origin = vec_subtract(*v_i, point); Vector v_i_origin_rotate = vec_rotate(v_i_origin, angle); Vector rotated_vec = vec_add(v_i_origin_rotate, point); free(v_i); list_set(points_list, i, create_vector_p(rotated_vec)); } } void polygon_free(Polygon *polygon) { list_free(polygon->points); vector_free(polygon->velocity); }
C
/*-*- mode:c;indent-tabs-mode:t;c-basic-offset:8;tab-width:8;coding:utf-8 -*-│ │vi: set et ft=c ts=8 tw=8 fenc=utf-8 :vi│ ╚──────────────────────────────────────────────────────────────────────────────╝ │ │ │ Musl Libc │ │ Copyright © 2005-2014 Rich Felker, et al. │ │ │ │ Permission is hereby granted, free of charge, to any person obtaining │ │ a copy of this software and associated documentation files (the │ │ "Software"), to deal in the Software without restriction, including │ │ without limitation the rights to use, copy, modify, merge, publish, │ │ distribute, sublicense, and/or sell copies of the Software, and to │ │ permit persons to whom the Software is furnished to do so, subject to │ │ the following conditions: │ │ │ │ The above copyright notice and this permission notice shall be │ │ included in all copies or substantial portions of the Software. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, │ │ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF │ │ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. │ │ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY │ │ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, │ │ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE │ │ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. │ │ │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/math.h" #include "libc/tinymath/feval.internal.h" #include "libc/tinymath/kernel.internal.h" asm(".ident\t\"\\n\\n\ Musl libc (MIT License)\\n\ Copyright 2005-2014 Rich Felker, et. al.\""); asm(".include \"libc/disclaimer.inc\""); // clang-format off /* "A Precision Approximation of the Gamma Function" - Cornelius Lanczos (1964) "Lanczos Implementation of the Gamma Function" - Paul Godfrey (2001) "An Analysis of the Lanczos Gamma Approximation" - Glendon Ralph Pugh (2004) approximation method: (x - 0.5) S(x) Gamma(x) = (x + g - 0.5) * ---------------- exp(x + g - 0.5) with a1 a2 a3 aN S(x) ~= [ a0 + ----- + ----- + ----- + ... + ----- ] x + 1 x + 2 x + 3 x + N with a0, a1, a2, a3,.. aN constants which depend on g. for x < 0 the following reflection formula is used: Gamma(x)*Gamma(-x) = -pi/(x sin(pi x)) most ideas and constants are from boost and python */ static const double pi = 3.141592653589793238462643383279502884; /* sin(pi x) with x > 0x1p-100, if sin(pi*x)==0 the sign is arbitrary */ static double sinpi(double x) { int n; /* argument reduction: x = |x| mod 2 */ /* spurious inexact when x is odd int */ x = x * 0.5; x = 2 * (x - floor(x)); /* reduce x into [-.25,.25] */ n = 4 * x; n = (n+1)/2; x -= n * 0.5; x *= pi; switch (n) { default: /* case 4 */ case 0: return __sin(x, 0, 0); case 1: return __cos(x, 0); case 2: return __sin(-x, 0, 0); case 3: return -__cos(x, 0); } } #define N 12 //static const double g = 6.024680040776729583740234375; static const double gmhalf = 5.524680040776729583740234375; static const double Snum[N+1] = { 23531376880.410759688572007674451636754734846804940, 42919803642.649098768957899047001988850926355848959, 35711959237.355668049440185451547166705960488635843, 17921034426.037209699919755754458931112671403265390, 6039542586.3520280050642916443072979210699388420708, 1439720407.3117216736632230727949123939715485786772, 248874557.86205415651146038641322942321632125127801, 31426415.585400194380614231628318205362874684987640, 2876370.6289353724412254090516208496135991145378768, 186056.26539522349504029498971604569928220784236328, 8071.6720023658162106380029022722506138218516325024, 210.82427775157934587250973392071336271166969580291, 2.5066282746310002701649081771338373386264310793408, }; static const double Sden[N+1] = { 0, 39916800, 120543840, 150917976, 105258076, 45995730, 13339535, 2637558, 357423, 32670, 1925, 66, 1, }; /* n! for small integer n */ static const double fact[] = { 1, 1, 2, 6, 24, 120, 720, 5040.0, 40320.0, 362880.0, 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0, 1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0, 121645100408832000.0, 2432902008176640000.0, 51090942171709440000.0, 1124000727777607680000.0, }; /* S(x) rational function for positive x */ static double S(double x) { double_t num = 0, den = 0; int i; /* to avoid overflow handle large x differently */ if (x < 8) for (i = N; i >= 0; i--) { num = num * x + Snum[i]; den = den * x + Sden[i]; } else for (i = 0; i <= N; i++) { num = num / x + Snum[i]; den = den / x + Sden[i]; } return num/den; } /** * Calculates gamma function of 𝑥. */ double tgamma(double x) { union {double f; uint64_t i;} u = {x}; double absx, y; double_t dy, z, r; uint32_t ix = u.i>>32 & 0x7fffffff; int sign = u.i>>63; /* special cases */ if (ix >= 0x7ff00000) /* tgamma(nan)=nan, tgamma(inf)=inf, tgamma(-inf)=nan with invalid */ return x + INFINITY; if (ix < (0x3ff-54)<<20) /* |x| < 2^-54: tgamma(x) ~ 1/x, +-0 raises div-by-zero */ return 1/x; /* integer arguments */ /* raise inexact when non-integer */ if (x == floor(x)) { if (sign) return 0/0.0; if (x <= sizeof fact/sizeof *fact) return fact[(int)x - 1]; } /* x >= 172: tgamma(x)=inf with overflow */ /* x =< -184: tgamma(x)=+-0 with underflow */ if (ix >= 0x40670000) { /* |x| >= 184 */ if (sign) { fevalf(0x1p-126/x); if (floor(x) * 0.5 == floor(x * 0.5)) return 0; return -0.0; } x *= 0x1p1023; return x; } absx = sign ? -x : x; /* handle the error of x + g - 0.5 */ y = absx + gmhalf; if (absx > gmhalf) { dy = y - absx; dy -= gmhalf; } else { dy = y - gmhalf; dy -= absx; } z = absx - 0.5; r = S(absx) * exp(-y); if (x < 0) { /* reflection formula for negative x */ /* sinpi(absx) is not 0, integers are already handled */ r = -pi / (sinpi(absx) * absx * r); dy = -dy; z = -z; } r += dy * (gmhalf+0.5) * r / y; z = pow(y, 0.5*z); y = r * z * z; return y; }
C
/* ** EPITECH PROJECT, 2018 ** n4s.c ** File description: ** algo etc */ #include <string.h> #include <stdlib.h> #include "my.h" static void print_n_reset(char *str) { my_putstr(str); str = get_next_line(0); } static void algo(float weel_rotate_left, float weel_rotate_right) { float weel_rotate; if (weel_rotate_left < weel_rotate_right) weel_rotate = weel_rotate_left; else weel_rotate = weel_rotate_right; if (weel_rotate >= 2000) print_n_reset("CAR_FORWARD:1\n"); else { my_putstr("CAR_FORWARD:"); my_put_nbr_float(0.000410 * weel_rotate + -0.0241); print_n_reset("\n"); } } static void weel_dir(float weel_rotate) { if (weel_rotate >= 1500) print_n_reset("0.008\n"); else { my_put_nbr_float(-0.00000000015 * weel_rotate * weel_rotate * weel_rotate + 0.0000007 * weel_rotate * weel_rotate - 0.001 * weel_rotate + 0.6); print_n_reset("\n"); } } static void rotate(float left, float right, float weel_rotate_left, float weel_rotate_right) { float coef = left - right; if (coef < 0) my_putstr("WHEELS_DIR:-"); else my_putstr("WHEELS_DIR:"); if (weel_rotate_left < weel_rotate_right) weel_dir(weel_rotate_left); else weel_dir(weel_rotate_right); } int need_for_steak(char *str, char **tab) { my_putstr("START_SIMULATION\n"); while ((str = get_next_line(0)) == NULL); my_putstr("CAR_FORWARD:1.1585123\n"); str = get_next_line(0); (str == NULL) ? exit(84) : 0; while (1) { my_putstr("GET_INFO_LIDAR\n"); str = get_next_line(0); (str == NULL) ? exit(84) : 0; tab = strtowordarray(str, ':'); algo(atof(tab[17]), atof(tab[21])); rotate(atof(tab[3]), atof(tab[34]), atof(tab[17]), atof(tab[21])); if (strcmp(tab[35], "Track Cleared") == 0) { print_n_reset("stop_simulation\n"); return 0; } } return 0; }
C
#include "MenusAndErrPresenters.h" #include "../services/MVPutils.h" /*** menus PHEs ***/ /* generalMenuPHE is the PHE function used for all the menus of the program * (both simple and complex menus. it gets the menu model, view state, an array of states representing * the state the button number leads to, number of buttons in the menu, the stateId, the current button selected * the current value of the values button (if applicable), and the max value of the values button (if applicable) */ StateId generalMenuPHE(void* model, void* viewState, void* logicalEvent, StateId states[], int numOfButtons, StateId stateId, int* currButton, int* currValue, int maxValue){ StateId returnStateId = stateId; if (logicalEvent == NULL || viewState == NULL || model == NULL) return returnStateId; /* get the logical event, viewState and menuModel */ logicalEventRef menuEvent = logicalEvent; ViewStateref menuView = viewState; MenuDataRef menuModel = menuModel; /* switch over event types */ switch(menuEvent->type){ case(DO_QUIT): /* exit the program */ returnStateId = QUIT; break; case(SELECT_CURR_BUTTON): returnStateId = states[*currButton]; /* set the correct return stateId according to the button and state arr*/ menuView->currButton = *currButton; /* update the current button in the view */ break; case(MARK_NEXT_BUTTON): changeSelectedButton(menuView->buttonsArr[*currButton], menuView->buttonsArr[(*currButton+1)%numOfButtons]); /* update the selected button in the view */ *currButton = (*currButton + 1)%numOfButtons; /* update the button number */ menuView->currButton = *currButton;/* update the current button in the view */ break; case(SELECT_BUTTON_NUM): *currButton = menuEvent->buttonNum; /* get the number of button from the event */ returnStateId = states[menuEvent->buttonNum]; /* set the correct return stateId according to the button and state arr*/ menuView->currButton = *currButton; /* update the current button in the view */ break; case(MARK_VALUES_BUTTON): changeSelectedButton(menuView->buttonsArr[*currButton], menuView->buttonsArr[FIRST_BUTTON]); /* update the selected button in the view */ *currButton = FIRST_BUTTON; /* update the button number */ menuView->currButton = *currButton; /* update the current button in the view */ break; case(INCREASE_VALUE): increaseValuesButton(currValue, maxValue, menuView->buttonsArr[FIRST_BUTTON]); /* update the value */ changeSelectedButton(menuView->buttonsArr[*currButton], menuView->buttonsArr[FIRST_BUTTON]); /* update the selected button in the view */ *currButton = FIRST_BUTTON; /* update the button number */ menuView->currButton = *currButton; /* update the current button in the view */ break; case(DECREASE_VALUE): decreaseValuesButton(currValue, MIN_VALUE, menuView->buttonsArr[FIRST_BUTTON]); /* update the value */ changeSelectedButton(menuView->buttonsArr[*currButton], menuView->buttonsArr[FIRST_BUTTON]); /* update the selected button in the view */ *currButton = FIRST_BUTTON; /* update the button number */ menuView->currButton = *currButton; /* update the current button in the view */ break; case(NO_EVENT): break; default: break; } free(logicalEvent); /* free logical event */ return returnStateId; } /* the phe function for main menu. calls generalMenuPHE */ StateId mainMenuPHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = MAIN_MENU; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef mainMenuModel = model; /* create an array of return stateIds according to the buttons: */ StateId mainMenuStates[MAIN_MENU_NUM_BUTTONS] = {CHOOSE_CAT, LOAD_GAME, WORLD_BUILDER, EDIT_GAME, QUIT}; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, mainMenuStates, MAIN_MENU_NUM_BUTTONS, returnStateId, &mainMenuModel->mainMenuButton, NULL, 0); if (returnStateId == WORLD_BUILDER) /* set edited world to 0 if we're going to world builder from main menu */ mainMenuModel->editedWorld = 0; mainMenuModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for choose cat. Calls generalMenuPHE */ StateId chooseCatPHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = CHOOSE_CAT; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef chooseCatModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId chooseCatStates[COMMON_MENU_NUM_BUTTONS] = {CHOOSE_MOUSE, CAT_SKILL, chooseCatModel->preChooseCat}; if (chooseCatModel->preChooseCat == PLAY_GAME) /* set the first button to go to play game if we came from play game */ chooseCatStates[0]=PLAY_GAME; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, chooseCatStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &chooseCatModel->chooseCatButton, NULL, 0); if (returnStateId == CHOOSE_MOUSE){ /* human was pressed and we are before playing the game */ chooseCatModel->isCatHuman = 1; chooseCatModel->preChooseMouse = CHOOSE_CAT; } else if (returnStateId == PLAY_GAME && chooseCatModel->chooseCatButton == 0){ /* human was pressed and we are in play game */ chooseCatModel->isCatHuman = 1; chooseCatModel->catSkill = DEFAULT_SKILL; } else if (returnStateId == CAT_SKILL) /* update the current skill in a temp value */ chooseCatModel->currValueTemp = chooseCatModel->catSkill; else if (returnStateId == LOAD_GAME) /* back was pressed */ chooseCatModel->chooseCatButton = 0; chooseCatModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for choose mouse. Calls generalMenuPHE */ StateId chooseMousePHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = CHOOSE_MOUSE; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef chooseMouseModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId chooseMouseStates[COMMON_MENU_NUM_BUTTONS] = {PLAY_GAME, MOUSE_SKILL, chooseMouseModel->preChooseMouse}; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, chooseMouseStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &chooseMouseModel->chooseMouseButton, NULL, 0); if (returnStateId == PLAY_GAME && chooseMouseModel->chooseMouseButton == 0){ /* human was pressed */ chooseMouseModel->isMouseHuman = 1; chooseMouseModel->mouseSkill = DEFAULT_SKILL; } else if (returnStateId == MOUSE_SKILL) /* update the current skill in a temp value */ chooseMouseModel->currValueTemp = chooseMouseModel->mouseSkill; else if (returnStateId == CHOOSE_CAT || returnStateId == CAT_SKILL) /* back was pressed */ chooseMouseModel->chooseMouseButton = 0; chooseMouseModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for cat skill. Calls generalMenuPHE */ StateId catSkillPHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = CAT_SKILL; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef catSkillModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId catSkillStates[COMMON_MENU_NUM_BUTTONS] = {CAT_SKILL, CHOOSE_MOUSE, CHOOSE_CAT}; if (catSkillModel->preChooseCat == PLAY_GAME) catSkillStates[1]=PLAY_GAME; /* set the second button to go to play game if we came from play game */ /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, catSkillStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &catSkillModel->catSkillButton, &catSkillModel->currValueTemp, MAX_SKILL_VALUE); if (returnStateId == PLAY_GAME || returnStateId == CHOOSE_MOUSE){ /* Done button was pressed */ catSkillModel->isCatHuman = 0; /* cat us a machine */ catSkillModel->catSkill = catSkillModel->currValueTemp; /* set cat skill once done is pressed */ if (returnStateId == CHOOSE_MOUSE){ /* update pre choose mouse in model */ catSkillModel->preChooseMouse = CAT_SKILL; } } else if (returnStateId == CHOOSE_CAT){ /* back was pressed and we go back to choose cat */ catSkillModel->catSkillButton = 0; if (catSkillModel->preChooseCat == MAIN_MENU) /* we pressed back when we are not during game */ catSkillModel->catSkill = DEFAULT_SKILL; /* set skill to deafult skill */ } catSkillModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for mouse skill. Calls generalMenuPHE */ StateId mouseSkillPHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = MOUSE_SKILL; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef mouseSkillModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId mouseSkillStates[COMMON_MENU_NUM_BUTTONS] = {MOUSE_SKILL, PLAY_GAME, CHOOSE_MOUSE}; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, mouseSkillStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &mouseSkillModel->mouseSkillButton, &mouseSkillModel->currValueTemp, MAX_SKILL_VALUE); if (returnStateId == PLAY_GAME){ /* Done button was pressed */ mouseSkillModel->isMouseHuman = 0; /* set mouse as machine */ mouseSkillModel->mouseSkill = mouseSkillModel->currValueTemp; } else if (returnStateId == CHOOSE_MOUSE){ /* back was pressed */ mouseSkillModel->mouseSkillButton = 0; /* set button to 0 for when we get back */ } mouseSkillModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for load game menu. calls generalMenuPHE */ StateId loadGamePHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = LOAD_GAME;/* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef loadGameModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId loadGameStates[COMMON_MENU_NUM_BUTTONS] = {LOAD_GAME, CHOOSE_CAT, MAIN_MENU}; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, loadGameStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &loadGameModel->loadGameButton, &loadGameModel->loadGameWorld, MAX_WORLD); if (returnStateId == CHOOSE_CAT){ /* done was pressed */ loadGameModel->preChooseCat = LOAD_GAME; /* update the pre choose cat stateId */ loadGameModel->loadFromFile = 1; /* update load from file to 1 */ } loadGameModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for edit game menu. calls generalMenuPHE */ StateId editGamePHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = EDIT_GAME; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef editGameModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId editGameStates[COMMON_MENU_NUM_BUTTONS] = {EDIT_GAME, WORLD_BUILDER, MAIN_MENU}; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, editGameStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &editGameModel->editGameButton, &editGameModel->editedWorld, MAX_WORLD); if (returnStateId == WORLD_BUILDER){ /* done was pressed */ editGameModel->preWorldBuilder = EDIT_GAME; /* update pre world builder */ editGameModel->loadFromFile = 1; /* set load from file to 1 */ } editGameModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; } /* The phe function for save world menu. calls generalMenuPHE */ StateId saveWorldPHE(void* model, void* viewState, void* logicalEvent){ StateId returnStateId = SAVE_WORLD; /* default return stateId */ if (model == NULL) return returnStateId; MenuDataRef saveWorldModel = model; /* get the model data */ /* create an array of return stateIds according to the buttons: */ StateId saveWorldStates[COMMON_MENU_NUM_BUTTONS] = {SAVE_WORLD, WORLD_BUILDER, WORLD_BUILDER}; /* get stateId by logical event, and update model and view */ returnStateId = generalMenuPHE(model, viewState, logicalEvent, saveWorldStates, COMMON_MENU_NUM_BUTTONS, returnStateId, &saveWorldModel->saveWorldButton, &saveWorldModel->currValueTemp, MAX_WORLD); if (returnStateId == WORLD_BUILDER){ /* done or back were pressed */ saveWorldModel->preWorldBuilder = SAVE_WORLD; if (saveWorldModel->saveWorldButton == 1){ /* done was pressed */ saveWorldModel->loadFromFile = 1; /* tell wb to use file to load the grid */ saveWorldModel->editedWorld = saveWorldModel->currValueTemp; /* set edited world to curr value */ /* save the grid data to the correct file and free it */ saveGameDataToFile(saveWorldModel->editedWorld, saveWorldModel->isCatFirst, saveWorldModel->gameGridData); freeGridData(saveWorldModel->gameGridData); /* free grid data */ saveWorldModel->gameGridData = NULL; } else if (saveWorldModel->saveWorldButton == 2) /* back was pressed */ saveWorldModel->loadFromFile = 0; /* tell wb to use char ** to load the grid */ } saveWorldModel->retStateId = returnStateId; /* update returnStateId in model */ return returnStateId; }
C
/* ** EPITECH PROJECT, 2019 ** strace ** File description: ** print_regs.c */ #include "strace.h" void print_regs(long long int syscallnb, struct user_regs_struct regs) { print_name(syscallnb, regs); print_params(syscallnb, regs); print_retval(regs); } void print_name(long long int syscallnb, struct user_regs_struct regs) { printf("%s(", tab_syscalls[syscallnb].name); } void print_params(long long int syscallnb, struct user_regs_struct regs) { char *a = "0x%lx, 0%lx, 0%lx, 0%lx"; char *b = "0x%lx, 0%lx, 0%lx, 0%lx, 0%lx"; char *c = "0x%lx, 0%lx, 0%lx, 0%lx, 0%lx, 0%lx"; switch(tab_syscalls[syscallnb].nb_params){ case 1: printf("0x%lx", regs.rdi); break; case 2: printf("0x%lx, 0x%lx", regs.rdi, regs.rsi); break; case 3: printf("0x%lx, 0%lx, 0%lx", regs.rdi, regs.rsi, regs.rdx); break; case 4: printf(a, regs.rdi, regs.rsi, regs.rdx, regs.r10); break; case 5: printf(b, regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8); break; case 6: printf(c, regs.rdi, regs.rsi, regs.rdx, regs.r10, regs.r8, regs.r9); break; default: return; } } void print_retval(struct user_regs_struct regs) { printf(") = 0x%lx\n", regs.rax); }
C
/******************************************************************************* * Company: * * Project: GPS frequency standard * * Description: conversion functions for raw byte arrays <-> number formats * * Filename: convert.h * * Author: Tobias Plüss <[email protected]> * * Creation-Date: 11.04.2020 ******************************************************************************/ #ifndef __CONVERT_H__ #define __CONVERT_H__ /******************************************************************************* * INCLUDE FILES ******************************************************************************/ #include <stdint.h> /******************************************************************************* * CONSTANT DEFINITIONS ******************************************************************************/ /******************************************************************************* * MACRO DEFINITIONS ******************************************************************************/ /* pseudo functions for unpack and pack: */ /* unsigned 8-bit - works directly on the buffer, but is nicer to have the same interface as for the other data types */ #define pack_u8_le(x, y, z) { x[y] = z; } #define unpack_u8_le(x, y) ((uint8_t)x[y]) #define pack_i8_le(x, y, z) { x[y] = (uint8_t)z; } #define unpack_i8_le(x, y) ((int8_t)x[y]) /* signed 16-bit - works the same as for unsigned, but has an embedded cast */ #define pack_i16_le(x, y, z) pack_u16_le(x, y, (uint16_t)(z)) #define unpack_i16_le(x, y) ((int16_t)unpack_u16_le(x, y)) /* signed 32-bit - works the same as for unsigned, but has an embedded cast */ #define pack_i32_le(x, y, z) pack_u32_le(x, y, (uint32_t)(z)) #define unpack_i32_le(x, y) ((int32_t)unpack_u32_le(x, y)) /******************************************************************************* * TYPE DEFINITIONS ******************************************************************************/ /******************************************************************************* * FUNCTION PROTOTYPES (PUBLIC) ******************************************************************************/ /*============================================================================*/ extern void pack_u32_le(uint8_t* buffer, uint32_t offset, uint32_t value); /*------------------------------------------------------------------------------ Function: convert a unsigned 32-bit number to 4 bytes and store it in a buffer (little endian) in: buffer -> buffer to put the bytes into offset -> offset into the buffer value -> value to be packed out: none ==============================================================================*/ /*============================================================================*/ extern uint32_t unpack_u32_le(const uint8_t* data, uint32_t offset); /*------------------------------------------------------------------------------ Function: retrieve a unsigned 32 bit number from raw data (little endian) in: data -> raw data offset -> offset into the buffer out: returns the number ==============================================================================*/ /*============================================================================*/ extern void pack_u16_le(uint8_t* buffer, uint32_t offset, uint16_t value); /*------------------------------------------------------------------------------ Function: convert a unsigned 16-bit number to 2 bytes and store it in a buffer (little endian) in: buffer -> buffer to put the bytes into offset -> offset into the buffer value -> value to be packed out: none ==============================================================================*/ /*============================================================================*/ extern uint16_t unpack_u16_le(const uint8_t* data, uint32_t offset); /*------------------------------------------------------------------------------ Function: retrieve a unsigned 16 bit number from raw data (little endian) in: data -> raw data offset -> offset into the buffer out: returns the number ==============================================================================*/ /*============================================================================*/ extern void pack_u16_be(uint8_t* buffer, uint32_t offset, uint16_t value); /*------------------------------------------------------------------------------ Function: convert a unsigned 16-bit number to 2 bytes and store it in a buffer (big endian) in: buffer -> buffer to put the bytes into offset -> offset into the buffer value -> value to be packed out: none ==============================================================================*/ /*============================================================================*/ extern uint16_t unpack_u16_be(const uint8_t* data, uint32_t offset); /*------------------------------------------------------------------------------ Function: retrieve a unsigned 16 bit number from raw data (big endian) in: data -> raw data offset -> offset into the buffer out: returns the number ==============================================================================*/ /******************************************************************************* * END OF CODE ******************************************************************************/ #endif
C
#include <sys/ipc.h> #include <sys/shm.h> #include <pthread.h> #include <signal.h> #include "TimeFunc.h" //#define SIZE 1000 //////////////////////////////////Global Var/////////////////////////// int *washedcars; int *machine; double *timeWash; int *flag; pthread_mutex_t mutex; pthread_cond_t IsMachine; struct timeval startT, nowT; ////////////////////////////////////////////////// //////////// Run function for thread//////////////////////////////// int RunThread(void* id) { int ID=(int)id; struct timeval Wasingtime; pthread_mutex_lock(&mutex); if(*machine<=0) pthread_cond_wait(&IsMachine,&mutex); *machine-=1; ///// critical section -reduce washing machine pthread_mutex_unlock(&mutex);// gettimeofday(&Wasingtime, NULL); printf("Im: %d Enter to wash in time: %lf\n", ID, GetTime(startT, UpdateTime(nowT))); usleep((int)(pow(10, 6) * nextTime(1.0 / 3.0)*-1)); printf("Im: %d Finish wash in time: %lf\n", ID, GetTime(startT, UpdateTime(nowT))); pthread_mutex_lock(&mutex); *timeWash += GetTime(Wasingtime, UpdateTime(nowT));//// critical section *washedcars += 1; *machine+=1; pthread_cond_signal(&IsMachine); pthread_mutex_unlock(&mutex); pthread_exit(NULL); } void UserStop(){ signal(SIGINT,UserStop); *flag=1;} //////////////////////////////////////////////////////// int main() { int t=1; int N, run ; float avgC ; void *status; pthread_t *Cars; pthread_attr_t attr; printf("enter num of wash station(1-5):\nnum of run time program(in seconds)\nnum of avg arrival car to station:\n"); scanf("%d%d%f", &N,&run,&avgC); /////////////////////// inition pointers////////////////////////////////// washedcars=(int *)calloc(1,sizeof(int)); machine=(int *)calloc(1,sizeof(int)); timeWash=(double *)calloc(1,sizeof(double)); flag=(int*)calloc(1,sizeof(int)); Cars=(pthread_t *)calloc(1,sizeof(pthread_t)); *machine=N;/////// number of washing machine pthread_mutex_init(&mutex, NULL); pthread_cond_init(&IsMachine,NULL); pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE); gettimeofday(&startT, NULL); //------------------START---------------------------------// while ( GetTime(startT, UpdateTime(nowT))<=run && *flag==0) { signal(SIGINT,UserStop); pthread_create(&Cars[t],&attr,RunThread,(void*)t); printf("FFF%d",*flag); printf("\nIm: %d {{Enterd to Queue}} in time: %lf\n", t, GetTime(startT, UpdateTime(nowT))); t++; usleep((int)(pow(10,6)*nextTime(1.0/avgC))*-1); } printf("\n--------------------------After Time Ended-------------------------------\n\n"); ////////////////////////////////////// waiting for end of all threads int i; for (i = t-1; i >=1; i--) { pthread_join(Cars[i],&status); } ////////////////////////////////////////// End program//////////// printf("\n\n{///////////End program////////////}\n"); printf("car washed--> [%d], in Total run Time: %lf(s)\n", *washedcars, GetTime(startT, UpdateTime(nowT))); printf("avg wash time: %lf(s)\n", *timeWash / (*washedcars)); ////////////////////////////////////////////////// //////////////// free memory and destroy mutex and attributes free(washedcars); free(machine); free(timeWash); pthread_attr_destroy(&attr); pthread_mutex_destroy(&mutex); pthread_exit(NULL); return EXIT_SUCCESS; }
C
#include<unistd.h> #include<stdlib.h> #include<stdio.h> #include<string.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<sys/msg.h> #include<pthread.h> /* * Without tools we do not know what thread is accessing what * I would like to use mutex but this is suppose to show * why we need to use mutex/semaphore. With this program * there is no guarentee what is is going to happen. The two * threads with desync form one another in that the couters * will write over top of one another. If the counter is * wrong then we run into the issues of using invalid * numbers as the recently sent number in the array. * */ #define BUFSIZE 10 int count = 0; int list[BUFSIZE]; void* producer(void* x){ int item = rand() % 10; while(1){ item = rand() % 10; if(count >= BUFSIZE){ sleep(1); continue; } printf("Sending: %d\n", item); list[count++] = item;//insert_item(item); count+=1; } } void* consumer(void* x){ int item; while(1){ if(count < 0){ sleep(1); continue; } printf("Revieving: %d\n", item); item = list[count--];//item = remove_item(); count-=1; } } int main(int argc, char** argv){ pthread_t T[2]; int rc1, rc2; rc1 = pthread_create(&T[0], NULL, producer, NULL); rc2 = pthread_create(&T[1], NULL, consumer, NULL); pthread_join(T[0], NULL); pthread_join(T[1], NULL); exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/io.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include "mex.h" /* % setparallel(port, byte) % % port: number of parallel port (1, 2, 3). % NOTE: parallel port bases used are machine dependent % and may need to be changed when moving across machines. % % byte: one byte representing 8 bits of state for the 8 pins of the port % */ void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { int value = 1; int port = 0; unsigned long base = 0; /*----- Check for proper number of arguments. -----*/ if(nrhs!=2) { mexErrMsgTxt("port and value required"); } port = mxGetScalar(prhs[0]); value = mxGetScalar(prhs[1]); if (port == 0) base = 0x378; else if (port == 1) base = 0x6000; else if (port == 2) base = 0x6800; /* printf("value is %d\n",value); */ if (ioperm(base,1,1)) /*fprintf(stderr, "Couldn't get the port at %x\n", base), exit(1);*/ perror("ioperm"); outb(value, base); }
C
#include <stdio.h> #include <unistd.h> void a() { extern int count; count++; } void b() { extern int count; count++; } void c() { extern int count; count++; } int count; int main() { a(); b(); c(); b(); printf("count = %d\n", count); pause(); return 0; }
C
#include <stdio.h> typedef struct { int row; int col; } pt; typedef struct { pt pt1, pt2; } rect; int area(const rect *p_rect){ int area = (p_rect -> pt1.row - p_rect -> pt2.row) * (p_rect -> pt1.col - p_rect -> pt2.col); return area >= 0 ? area : 0 - area; } int main(){ rect r1 = {}; printf("Enter a rectangle's position: "); scanf("%d %d %d %d", &(r1.pt1.row), &(r1.pt1.col), &(r1.pt2.row), &(r1.pt2.col)); printf("Area is %d\n", area(&r1)); }
C
/* ** EPITECH PROJECT, 2018 ** libmy ** File description: ** strdup.c */ #include "my/string.h" char *my_strdup(const char *src) { size_t len = my_strlen(src); char *dest = my_calloc(len + 1, sizeof(char)); if (dest != NULL) dest = my_strncpy(dest, src, len); return (dest); } char *my_strndup(const char *src, size_t n) { size_t len = my_strnlen(src, n); char *dest = my_calloc(len + 1, sizeof(char)); if (dest != NULL) dest = my_strncpy(dest, src, len); return (dest); }
C
#include<stdio.h> int main() { int n,k; scanf("%d %d",&n,&k); int i; int a[100001]; int s[100001]={0},ans,x; for(i=0;i<n;i++) { scanf("%d",&a[i]); int x=(i+1)%k; s[x]+=a[i]; } int min=1111111111; for(i=1;i<k;i++) { if(min>s[i]) { min=s[i]; ans=i; } } if(min>s[0]) ans=k; printf("%d\n",ans); return 0; }
C
#include <stdio.h> #include <string.h> char nibbletochar(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return 255; } int main(int argv, char *argc[]) { unsigned int i, j; if (argv != 2) return 1; j = (strlen(argc[1])/2) << 1; for (i = 0; i < j; i+=2) printf("%c", (char) (nibbletochar(argc[1][i]) << 4) | nibbletochar(argc[1][i+1])); return 0; }
C
/* Authors: W. R. Stevens, B. Fenner, A. M. Rudoff */ #include "unpifi.h" int main(int argc, char **argv) { int n; char ifname[IFNAMSIZ]; struct if_nameindex *ifptr, *save; if (argc != 1) err_quit("usage: prifnameindex"); /* print all the interface names and indexes */ for (save = ifptr = If_nameindex(); ifptr->if_index > 0; ifptr++) { printf("name = %s, index = %d\n", ifptr->if_name, ifptr->if_index);; if ( (n = If_nametoindex(ifptr->if_name)) != ifptr->if_index) err_quit("if_nametoindex returned %d, expected %d, for %s", n, ifptr->if_index, ifptr->if_name); If_indextoname(ifptr->if_index, ifname); if (strcmp(ifname, ifptr->if_name) != 0) err_quit("if_indextoname returned %s, expected %s, for %d", ifname, ifptr->if_name, ifptr->if_index); } n = if_nametoindex("fkjhkjhgjhgjhgdjhguyetiuyiuyhkjhkjdh"); if (n != 0) err_quit("if_nametoindex returned %d for fkjh...", n); n = if_nametoindex(""); if (n != 0) err_quit("if_nametoindex returned %d for (null)", n); if (if_indextoname(0, ifname) != NULL) err_quit("if_indextoname error for 0"); if (if_indextoname(888888, ifname) != NULL) err_quit("if_indextoname error for 888888"); if_freenameindex(save); exit(0); }
C
#include <stdio.h> int main() { int i, n, result; printf("n의 값을 입력하시오: "); scanf("%d", &n); result = 0; for(i = 0 ; i < n ; i++) { result += (i + 1) * (i + 1); } printf("계산한 값은 %d입니다.\n", result); return 0; }
C
/* Q1. Write a menu driven program to do the following on single linked list :- a. Reverse the linked list using change of the address (Change the link/next of each node) b. Reverse the list by changing the value (Use stack)*/ //------------------------ CODE ------------------------------------------[NITIN KUMAR] #include <stdio.h> #include <stdlib.h> typedef struct node { int data; struct node *next; } node; node *accept() { node *start = NULL, *q, *temp; char ch = 'Y'; int count = 1; while (ch != 'N' && ch == 'Y') { temp = (node *)malloc(sizeof(node)); printf("Enter Data in Node %d:\n", count); scanf("%d", &(temp->data)); temp->next = NULL; if (start == NULL) start = temp; else { for (q = start; q->next != NULL; q = q->next); q->next = temp; } printf("Enter N to exit or Y to continue\n"); scanf(" %c", &ch); count++; } return start; } void reverse_1(node **start) { node *prev = NULL; node *current = *start; node *Next = NULL; while (current != NULL) { Next = current->next; current->next = prev; prev = current; current = Next; } *start = prev; } void display_ll(node *start) { node *q; if (start == NULL) printf("No Elements\n"); else { for (q = start; q != NULL; q = q->next) printf("%d\n", (q->data)); } } int stack[50]; int top = -1; void reverse_2(node *start) { node *q; q = start; while (q != NULL) { stack[++top] = q->data; q = q->next; } } void display_s(int *stack) { while (top >= 0) printf("%d\n", stack[top--]); } void main() { node *start = NULL; int choice; printf("0)Exit\n"); printf("1)Reverse Using Address\n"); printf("2)Reverse using Stack\n"); scanf("%d", &choice); while (choice != 0 && choice <= 2) { switch (choice) { case 0: printf("Exit the Program...\n"); break; case 1: start = accept(); printf("\nOriginal Order\n"); display_ll(start); reverse_1(&start); printf("\nReverse Order\n"); display_ll(start); break; case 2: start = accept(); printf("\nOriginal Order\n"); display_ll(start); printf("\nReverse Order\n"); reverse_2(start); display_s(stack); break; } printf("\n\n0)Exit\n"); printf("1)Reverse Using Address\n"); printf("2)Reverse using Stack\n"); scanf("%d", &choice); if (choice == 0) printf("\n\nExit the Program.....\n\n"); } }
C
#pragma once #include "Basic.h" // Directed Graph typedef int T ; // Template for understanding typedef struct Vertex { T m_Data ; bool m_bVisit ; int m_iIndex ; struct Vertex * m_pNext ; struct Edge * m_pAdjacencyList ; // Point Edges that connected with current Vertex } Vertex ; typedef struct Edge { int m_iWeight ; struct Edge * m_pNext ; // Point Edges that have same Vertex m_pFrom struct Vertex * m_pFrom ; struct Vertex * m_pTarget ; } Edge ; typedef struct Graph { int m_iVertexCnt ; struct Vertex * m_pVertices ; } Graph ; Graph * CreateGraph () ; // Create Graph and return void DestroyGraph ( Graph * G ) ; // Destroy Graph Vertex * CreateVertex ( T Data ) ; // Create Vertex with T Data and return void DestroyVertex ( Vertex * V ) ; // Destroy Vertex Edge * CreateEdge ( Vertex * pFrom , Vertex * pTarget , int iWeight ) ; // Create Edge and return void DestroyEdge ( Edge * E ) ; // Destroy Edge void AddVertex ( Graph * G , Vertex * V ) ; // Add Vertex V into Graph G void AddEdge ( Vertex * V , Edge * E ) ; // Add Edge E connected with Vertex V void PrintGraph ( Graph * G ) ; // Print current Graph G
C
#include "main.h" #include <unistd.h> /** * print_square - functions to print a square * @size: the size of the square * * Return: void */ void print_square(int size) { int j = size; int i; if (size <= 0) _putchar('\n'); else while (size > 0) { for (i = 0; i < j; i++) { _putchar('#'); } _putchar('\n'); size--; } }
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* get_next_line.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: brey-gal <[email protected]> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2019/05/28 16:49:21 by brey-gal #+# ## ## #+# */ /* Updated: 2019/06/24 17:16:03 by brey-gal ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "../includes/wolf3d.h" char *line_splitter(char **str, int i, int j) { char *line; char *tmp; if ((*str)[i] == '\n') { line = ft_strsub(*str, 0, i); tmp = ft_strsub(*str, i + 1, j - i); *str = ft_strcpy(*str, tmp); free(tmp); } else { line = ft_strsub(*str, 0, i); (*str)[0] = '\0'; } return (line); } char *line_counter(char **str) { int i; int j; i = 0; j = 0; if (!(*str)) return (NULL); if ((*str)[i] == '\0') return (NULL); while ((*str)[i] != '\n' && (*str)[i]) i++; while ((*str)[j]) j++; return (line_splitter(str, i, j)); } int line_reader(char *buf) { int i; i = 0; while (buf[i]) { if (buf[i] == '\n') return (1); i++; } return (0); } int get_next_line(const int fd, char **line) { static char *str; char *tmp; int ret; char buf[BUFF_SIZE + 1]; int new_line; new_line = 0; if (line == NULL || fd < 0) return (-1); while (new_line == 0 && (ret = read(fd, buf, BUFF_SIZE)) != 0) { if (ret < 0) return (-1); buf[ret] = '\0'; if (!(str)) str = ft_strnew(1); tmp = ft_strjoin(str, buf); free(str); str = tmp; new_line = line_reader(buf); } if ((*line = line_counter(&str)) == NULL) return (0); return (1); }
C
#include <inc/x86.h> #include <inc/pmap.h> void notbusy(void) { while(inb(0x1F7) & 0x80); // wait for disk not busy } void readsect(u_char *dst, u_int count, u_int offset) { notbusy(); outb(0x1F2, count); outb(0x1F3, offset); outb(0x1F4, offset>>8); outb(0x1F5, offset>>16); outb(0x1F6, (offset>>24)|0xE0); outb(0x1F7, 0x20); // cmd 0x20 - read sectors notbusy(); insl(0x1F0, dst, count*512/4); } // read count bytes at offset from kernel into addr dst // might copy more than asked /* void readseg_kern(u_int va, u_int count, u_int offset) { u_int i; count += (offset & 511); // translate from bytes to sectors offset /= 512; // count += (offset & 511); fucking order, offset should not change for this computation // read more bytes count = (count+511)/512; count++; // kernel starts at sector 1 offset++; // if this is too slow, we could read lots of sectors at a time. // we'd write more to memory than asked, but it doesn't matter -- // we load in increasing order. for(i=0; i<count; i++){ readsect((u_char*)va, 1, offset+i); va += 512; } } */ void readseg_kern(u_int va, u_int count, u_int offset) { u_int i, j; char* sect = (char*)(KERNBASE+0x7E00); printf("offset = %x\n", offset); for(i = 0; i < count; i++) { *((u_char*)va + i) = *(sect + offset + i); printf("%x ", *(sect + offset + i)); } /* // round down to sector boundary; offset will round later i = va&511; count += i; va -= i; // translate from bytes to sectors offset /= 512; count = (count+511)/512; // kernel starts at sector 1 //offset++; // if this is too slow, we could read lots of sectors at a time. // we'd write more to memory than asked, but it doesn't matter -- // we load in increasing order. for(i=0; i<count; i++){ for(j = 0; j < 512; j++) { *((u_char*)va + j) = *((sect + offset*512 + i*512) + j); } va += 512; } */ }
C
#include<stdio.h> #include<string.h> int main() { int n; printf("\nEnter the greatest number in pattern "); scanf("%d",&n); int a[n]; for(int m=0;m<n;m++) { a[m] = n-m; } int i,j,k,l; for( i=0;i<n;i++) { for( j=0;j<n-i;j++) { printf(" "); printf("%d",a[j]); } for( k=i*2;k>0;k--) { if(i>10) { printf(" "); } printf(" "); } for( l=n-1-i;l>=0;l--) { printf(" "); printf("%d",a[l]); } printf("\n"); } return 0; }
C
#include <sys/syscall.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define __NR_ptreecall 356 struct prinfo { pid_t parent_pid; /* process id of parent, set 0 if it has no parent*/ pid_t pid; /* process id */ pid_t first_child_pid; /* pid of youngest child, set 0 if it has no child */ pid_t next_sibling_pid; /* pid of older sibling, set 0 if it has no sibling*/ long state; /* current state of process */ long uid; /* user id of process owner */ char comm[64]; /* name of program executed */ }; void printTree(struct prinfo *buf, int *nr) { int pidArray[1000] = {0}; int tab = 0; printf("There are %d processes!\n", *nr); printf("%s,%d,%ld,%d,%d,%d,%d\n", buf[0].comm, buf[0].pid, buf[0].state, buf[0].parent_pid, buf[0].first_child_pid, buf[0].next_sibling_pid, buf[0].uid); int i=1; while(i < *nr) { if(buf[i].parent_pid == buf[i-1].pid) { tab++; } else if (buf[i].parent_pid != buf[i-1].parent_pid) { int backtrack = buf[i-1].parent_pid; tab--; while(buf[i].parent_pid!=buf[pidArray[backtrack]].parent_pid) { backtrack = buf[pidArray[backtrack]].parent_pid; tab--; } } // else if(buf[i].parent_pid != buf[i-1].parent_pid) // { // int backtrack = buf[i-1].parent_pid; // int cur = buf[i].parent_pid; // //tab--; // while(cur != buf[pidArray[backtrack]].parent_pid) // { // backtrack = buf[pidArray[backtrack]].parent_pid; // tab--; // } // } pidArray[buf[i].pid] = i; int j = 0; while(j < tab) { printf("\t"); j++; } printf("%s,%d,%ld,%d,%d,%d,%ld\n", buf[i].comm, buf[i].pid, buf[i].state, buf[i].parent_pid, buf[i].first_child_pid, buf[i].next_sibling_pid, buf[i].uid); i++; } } int main() { struct prinfo *buf = malloc(1000 * sizeof(struct prinfo)); int *nr = malloc(sizeof(int)); if (buf == NULL || nr == NULL) { printf("Allocation error!\n"); return 0; } syscall(__NR_ptreecall, buf, nr); printTree(buf,nr); free(buf); free(nr); return 0; }
C
#ifndef OBJ_CONT_INCLUDED #define OBJ_CONT_INCLUDED /* cont - continuation object */ #include "cv.h" #include "mem_mixvec.h" /* * Eventually, there may be multiple sizes of continuations, with * different numbers of saved values. The functions below with prefix * "cont_" operate on any continuation. The ones prefixed "contN_" * only operate on a specific continuation size. */ extern obj_t make_cont3(cont_proc_t proc, obj_t cont, obj_t env); extern obj_t make_cont4(cont_proc_t proc, obj_t cont, obj_t env, obj_t arg); extern obj_t make_cont5(cont_proc_t proc, obj_t cont, obj_t env, obj_t arg1, obj_t arg2); extern obj_t make_cont6(cont_proc_t proc, obj_t cont, obj_t env, obj_t arg1, obj_t arg2, obj_t arg3); static inline bool is_cont (obj_t); static inline bool is_cont3 (obj_t); static inline bool is_cont4 (obj_t); static inline bool is_cont5 (obj_t); static inline bool is_cont6 (obj_t); static inline cont_proc_t cont_proc (obj_t cont); static inline obj_t cont_cont (obj_t cont); static inline obj_t cont_env (obj_t cont); static inline obj_t cont4_arg (obj_t cont); static inline obj_t cont5_arg1(obj_t cont); static inline obj_t cont5_arg2(obj_t cont); static inline obj_t cont6_arg1(obj_t cont); static inline obj_t cont6_arg2(obj_t cont); static inline obj_t cont6_arg3(obj_t cont); OBJ_TYPE_PREDICATE(cont3); // bool is_cont3(obj_t); OBJ_TYPE_PREDICATE(cont4); // bool is_cont4(obj_t); OBJ_TYPE_PREDICATE(cont5); // bool is_cont5(obj_t); OBJ_TYPE_PREDICATE(cont6); // bool is_cont6(obj_t); static inline bool is_cont(obj_t obj) { return is_cont3(obj) || is_cont4(obj) || is_cont5(obj) || is_cont6(obj); } static inline cont_proc_t cont_proc(obj_t cont) { CHECK(is_cont(cont), "must be continuation", cont); return (cont_proc_t)mixvec_1_3_get_int(cont, 0); } static inline obj_t cont_cont(obj_t cont) { CHECK(is_cont(cont), "must be continuation", cont); return mixvec_1_3_get_ptr(cont, 0); } static inline obj_t cont_env(obj_t cont) { CHECK(is_cont(cont), "must be cont", cont); return mixvec_1_3_get_ptr(cont, 1); } static inline obj_t cont4_arg(obj_t cont) { CHECK(is_cont4(cont), "must be cont4", cont); return mixvec_1_3_get_ptr(cont, 2); } static inline obj_t cont5_arg1(obj_t cont) { CHECK(is_cont5(cont), "must be cont5", cont); return mixvec_1_4_get_ptr(cont, 2); } static inline obj_t cont5_arg2(obj_t cont) { CHECK(is_cont5(cont), "must be cont5", cont); return mixvec_1_4_get_ptr(cont, 3); } static inline obj_t cont6_arg1(obj_t cont) { CHECK(is_cont6(cont), "must be cont6", cont); return mixvec_1_5_get_ptr(cont, 2); } static inline obj_t cont6_arg2(obj_t cont) { CHECK(is_cont6(cont), "must be cont6", cont); return mixvec_1_5_get_ptr(cont, 3); } static inline obj_t cont6_arg3(obj_t cont) { CHECK(is_cont6(cont), "must be cont6", cont); return mixvec_1_5_get_ptr(cont, 4); } #endif /* !OBJ_CONT_INCLUDED */
C
#include <stdio.h> char *ft_strcapitalize(char *str); int main(void) { char str1[] = "oi, tudo bem? 42palavras quarenta-e-duas; cinquenta+e+um"; printf ("Antes: %s\n", str1); printf ("Depois: %s\n", ft_strcapitalize (str1)); return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <time.h> //#define rok 2011 int rok; bool popraw=false; #define DEBUG /* Zadeklarować strukturę Pracownik o polach przechowujących: imię, nazwisko, stanowisko, staż pracy, rok urodzenia i miejsce urodzenia. Napisać: X funkcję pobierającą dane pojedynczego pracownika; X funkcję pobierającą dane do tablicy pracowników podanej jako parametr, o długości podanej jako parametr; X funkcję wypisującą dane pojedynczego pracownika; X funkcję wypisującą zawartość tablicy pracowników podanej jako parametr, o długości podanej jako parametr; X funkcję zwracającą pracownika o największym stażu (parametrami funkcji mają być tablica pracowników i jej długość); X funkcję zwracającą średni wiek pracowników w tablicy (parametrami funkcji mają być tablica pracowników i jej długość); X funkcję wypisującą wszystkie osoby pracujące na stanowisku podanym jako parametr (parametrami funkcji mają być tablica pracowników, jej długość oraz poszukiwane stanowisko); * funkcję zwracającą wartość logiczną mówiącą, czy w tablicy są osoby urodzone w tym samym mieście (parametrami funkcji mają być tablica pracowników i jej długość); * funkcję wypisującą wszystkie stanowiska występujące w tablicy oraz liczbę osób zatrudnionych na poszczególnych stanowiskach (parametrami funkcji mają być tablica pracowników i jej długość); oraz program pobierający tablicę pracowników o podanej przez użytkownika długości i testujący na niej działanie powyższych funkcji. */ //wiem ze brzydkie ale kodzilem w tramwaju i nie moglem googlac ;) float itof(int i) { char *buf = malloc(sizeof(float)); float ret; sprintf(buf,"%d",i); ret = atof(buf); free(buf); return ret; } void hack() { if(popraw) { int zero=0; char *buf; getline(&buf,&zero,stdin); free(buf); popraw=false; } } char* chomp(char* str) { if(str[strlen(str)-1]=='\n') str[strlen(str)-1]='\0'; return str; } struct Pracownik { char* imie; char* nazwisko; int stanowisko; int staz; int rok_urodzenia; char* miejsce_urodzenia; }; typedef struct Pracownik Pracownik; Pracownik pobierz() { Pracownik ret; char* imie=NULL; char* nazwisko=NULL; int stanowisko; int staz; int rok_urodzenia; char* miejsce_urodzenia=NULL; int zero = 0; printf("Podaj imie: "); hack(); getline(&imie,&zero,stdin); chomp(imie); ret.imie=imie; printf("Podaj nazwisko: "); hack(); getline(&nazwisko,&zero,stdin); chomp(nazwisko); ret.nazwisko=nazwisko; printf("Podaj stanowisko: "); scanf("%d",&stanowisko); ret.stanowisko=stanowisko; printf("Podaj staz: "); scanf("%d",&staz); ret.staz=staz; printf("Podaj rok urodzenia: "); scanf("%d",&rok_urodzenia); popraw=true; ret.rok_urodzenia=rok_urodzenia; ///* printf("Podaj miejsce urodzenia: "); hack(); getline(&miejsce_urodzenia,&zero,stdin); chomp(miejsce_urodzenia); ret.miejsce_urodzenia=miejsce_urodzenia; //*/ return ret; } void pobierz_tab(Pracownik* arr, int n) { int i; for(i=0; i<n; i++) { #ifdef DEBUG printf("Teraz pobiore pracownika nr %d.\n",i+1); #endif arr[i]=pobierz(); printf("\n"); } } void wypisz(Pracownik tmp) { printf("Imie: %s\n",tmp.imie); printf("Nazwisko: %s\n",tmp.nazwisko); printf("Stanowisko: %d\n",tmp.stanowisko); printf("Staz: %d\n",tmp.staz); printf("Rok urodzenia: %d\n",tmp.rok_urodzenia); printf("Miejsce urodzenia: %s\n\n",tmp.miejsce_urodzenia); } void wypisz_tab(Pracownik* arr, int n) { int i; for(i=0; i<n; i++) { printf("Pracownik %d:\n",i+1); wypisz(arr[i]); } } Pracownik* najwiekszy_staz(Pracownik* arr, int n) { int i; int max=arr[0].staz; Pracownik* max_ptr = &arr[0]; for(i=0; i<n; i++) { if (arr[i].staz>max) { max=arr[i].staz; max_ptr=&arr[i]; } } return max_ptr; } float sredni_wiek(Pracownik* arr, int n) { int i,suma=0; for(i=0;i<n; i++) { suma+=rok-arr[i].rok_urodzenia; } return itof(suma)/itof(n); } void na_stanowisku(Pracownik* arr, int n, int stanowisko) { int i; int tmp=0; Pracownik* ret; #ifdef DEBUG printf("Przeszukuje...\n"); #endif for(i=0; i<n; i++) { if(arr[i].stanowisko==stanowisko) { tmp++; } } if(tmp==0) { printf("Brak pracownikow na podanym stanowisku.\n"); return; } else { printf("Znaleziono %d rekordow.\n",tmp); } #ifdef DEBUG printf("Alokuje...\n"); #endif ret = malloc(sizeof(Pracownik)*tmp); #ifdef DEBUG printf("Wypelniam...\n"); #endif tmp=0; for(i=0; i<n; i++) { if(arr[i].stanowisko==stanowisko) { ret[tmp]=arr[i]; tmp++; } } #ifdef DEBUG printf("tmp=%d\n",tmp); printf("Wypisuje...\n"); #endif wypisz_tab(ret,tmp); #ifdef DEBUG printf("Zwalniam...\n"); #endif free(ret); } bool ur_w_tym_samym(Pracownik* arr, int n) { int i,i2; bool ret=false; for(i=0; i<n; i++) { if(i!=n) { for(i2=i+1; i2<n; i2++) { #ifdef DEBUG printf("Porownuje %s z %s.\n",arr[i].miejsce_urodzenia,arr[i2].miejsce_urodzenia); #endif if(strcmp(arr[i].miejsce_urodzenia, arr[i2].miejsce_urodzenia)==0) ret=true; } } } return ret; } int znajdz(int* arr, int len, int val) { int i; #ifdef DEBUG printf("jest_w(,len=%d,val=%d)...", len, val); #endif for(i=0; i<len; i++) { if(arr[i]==val) { #ifdef DEBUG printf("zwracam PRAWDE\n"); #endif return i; } } #ifdef DEBUG printf("zwracam FALSZ\n"); #endif return -1; } int* dodaj_do(int* arr,int len,int val) { #ifdef DEBUG printf("-->dodaj_do(len=%d,val=%d,newsize=%d)\n",len,val,sizeof(int)*(len+1)); #endif arr=realloc(arr,sizeof(int)*(len+1)); arr[len]=val; #ifdef DEBUG printf("-->arr[len]=%d\n",arr[len]); #endif return arr; } void wypisz_stanowiska(Pracownik* arr, int n) { int i,i2; int found=1; int curr=0; int* tmp; int* tmp2; tmp=malloc(sizeof(int)*1); tmp2=malloc(sizeof(int)*1); tmp[curr]=arr[curr].stanowisko; tmp2[curr]=1; #ifdef DEBUG printf("->tmp2[curr=%d]=%d; tmp[curr=%d]=%d\n",curr,tmp2[curr],curr,tmp[curr]); #endif curr++; for(i=1; i<n; i++) { #ifdef DEBUG printf("->%d: Przetwarzam %s %s... [curr=%d]\n",i, arr[i].imie, arr[i].nazwisko, curr); #endif if(znajdz(tmp,curr,arr[i].stanowisko)==-1) { printf("->Nie znaleziono.\n"); tmp=dodaj_do(tmp,curr,arr[i].stanowisko); tmp2=dodaj_do(tmp2,curr,1); curr++; } else { found=znajdz(tmp,curr,arr[i].stanowisko); #ifdef DEBUG printf("->tmp2[found=%d]=%d; tmp[found=%d]=%d\n",found,tmp2[found],found,tmp2[found]); #endif tmp2[found]++; } printf("POCZ\n"); for(i2=0; i2<=(curr-1); i2++) { printf("STANOWISKO [%d] %d: %d\n", i2, tmp[i2], tmp2[i2]); } printf("KONIEC\n"); } for(i=0; i<curr; i++) { printf("STANOWISKO [%d] %d: %d\n", i, tmp[i], tmp2[i]); } } int main() { int n,wybor; Pracownik* arr=NULL; Pracownik* tmp=NULL; time_t now = time ( NULL ); struct tm *date = localtime ( &now ); rok = 1900+date->tm_year; #ifdef DEBUG printf("Mamy rok %d.\n",rok); #endif #ifndef DEBUG printf("Podaj wielkosc tablicy: "); scanf("%d",&n); arr = malloc(sizeof(Pracownik)*n); #else Pracownik foo; int i=0; n=5; printf("Wypelniam tablice..."); arr = malloc(sizeof(Pracownik)*n); /* foo.imie="asd"; foo.nazwisko="asd"; foo.stanowisko=9; foo.staz=2; foo.rok_urodzenia=1990; foo.miejsce_urodzenia="Lodz"; arr[0]=foo; foo.imie="asd"; foo.nazwisko="asd"; foo.stanowisko=7; foo.staz=2; foo.rok_urodzenia=1991; foo.miejsce_urodzenia="Lodzz"; arr[1]=foo; */ foo.imie="jacek"; foo.nazwisko="wielemborek"; foo.stanowisko=666; foo.staz=20; foo.rok_urodzenia=1990; foo.miejsce_urodzenia="Lodz"; arr[i]=foo; i++; foo.imie="Fred"; foo.nazwisko="Durst"; foo.stanowisko=123; foo.staz=30; foo.rok_urodzenia=1980; foo.miejsce_urodzenia="Nowhere"; arr[i]=foo; i++; foo.imie="Trzeci"; foo.nazwisko="Wpis"; foo.stanowisko=123; foo.staz=20; foo.rok_urodzenia=1995; foo.miejsce_urodzenia="Testowo"; arr[i]=foo; i++; foo.imie="Barack"; foo.nazwisko="Obama"; foo.stanowisko=231; foo.staz=123; foo.rok_urodzenia=1970; foo.miejsce_urodzenia="USA"; arr[i]=foo; i++; foo.imie="Jaroslaw"; foo.nazwisko="Kaczynski"; foo.stanowisko=9; foo.staz=3; foo.rok_urodzenia=1950; foo.miejsce_urodzenia="Polska"; arr[i]=foo; i++; #endif for(;;) { printf("1) Pobierz tablice\n"); printf("2) Wypisz tablice\n"); printf("3) Podaj sredni wiek\n"); printf("4) Podaj najwiekszy staz\n"); printf("5) Szukaj pracownikow na stanowisku\n"); printf("6) Sprawdz czy powtarzaja sie miasta\n"); printf("7) Wypisz stanowiska\n"); printf("0) Wyjdz\n"); printf("\nPodaj wybor: "); scanf("%d",&wybor); popraw=true; printf("\n"); switch(wybor) { case 0: free(arr); return 0; break; case 1: pobierz_tab(arr,n); break; case 2: wypisz_tab(arr,n); break; case 3: printf("\n\nSredni wiek w podanych danych to %f\n\n",sredni_wiek(arr,n)); break; case 4: printf("Najwiekszy staz to: "); wypisz(*najwiekszy_staz(arr,n)); break; case 5: printf("\nPodaj stanowisko: "); scanf("%d",&wybor); printf("\n"); na_stanowisku(arr,n,wybor); break; case 6: if(ur_w_tym_samym(arr,n)) printf("Tak.\n"); else printf("Nie.\n"); break; case 7: wypisz_stanowiska(arr,n); break; } } free(arr); return 0; }
C
#include <stdio.h> #include <time.h> #define MILLION 1000000L #define THOUSAND 1000 void function_to_time(void); int main(void) { long diftime; struct itimerspec nvalue, ovalue; timer_t timeid; if (timer_create(CLOCK_REALTIME, NULL, &timeid) == -1) { perror("Failed to create a timer based on CLOCK_REALTIME"); return 1; } ovalue.it_interval.tv_sec = 0; ovalue.it_interval.tv_nsec = 0; ovalue.it_value.tv_sec = MILLION; /* a large number */ ovalue.it_value.tv_nsec = 0; if (timer_settime(timeid, 0, &ovalue, NULL) == -1) { perror("Failed to set interval timer"); return 1; } function_to_time(); /* timed code goes here */ if (timer_gettime(timeid, &nvalue) == -1) { perror("Failed to get interval timer value"); return 1; } diftime = MILLION*(ovalue.it_value.tv_sec - nvalue.it_value.tv_sec) + (ovalue.it_value.tv_nsec - nvalue.it_value.tv_nsec)/THOUSAND; printf("The function_to_time took %ld microseconds or %f seconds.\n", diftime, diftime/(double)MILLION); return 0; }
C
#include<stdio.h> void main(){ printf("print prime numbers ranging between 1 to 50:\n"); int count,j; for(int i=2; i<=50; i++){ count=0; j=1; while(j<=i/2){ if(i%j==0) count++; j++; } if(count==1) printf("%d\t",i); } printf("\n"); }
C
#include <stdio.h> int main() { int n; printf("do koe chiso?: "); scanf("%d", &n); for(int i=0;i<=n;i+=2) printf("%d\n", i); return 0; }
C
#include <stdio.h> #include <sys/socket.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> const int PORT = 8080; const int BUFFER_SIZE = 131072; int main() { int sockfd, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[BUFFER_SIZE]; sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) { printf("error opening socket\n"); return 0; } else { printf("success opening socket\n"); } bzero((char *)&serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); serv_addr.sin_port = htons(PORT); if (connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("error connecting\n"); return 0; } else { printf("succes connecting\n"); } for (;;) { bzero(buffer, BUFFER_SIZE); printf("enter the operands:\n"); fgets(buffer, BUFFER_SIZE, stdin); if (strcmp(buffer, "exit\n") == 0) { printf("Exiting...\n"); break; } n = send(sockfd, buffer, strlen(buffer), 0); bzero(buffer, BUFFER_SIZE); printf("enter the operator:\n"); fgets(buffer, BUFFER_SIZE, stdin); n = send(sockfd, buffer, strlen(buffer), 0); if (n < 0) { printf("error writing to socket\n"); return 0; } bzero(buffer, BUFFER_SIZE); n = recv(sockfd, buffer, BUFFER_SIZE, 0); if (n < 0) { printf("error reading from socket\n"); } printf("Echoed from server: \"%s\"\n", buffer); } close(sockfd); return 0; }
C
// O(n^2) // Insert_Sort void print_arr(int *, int); void insert_sort(int *, int); int main(){ int arr[10]= {9,5,8,1,3,4,2,7,6,10}; printf("before insert sorting\n"); print_arr(arr, sizeof(arr)/sizeof(int)); insert_sort(arr, sizeof(arr)/ sizeof(int)); printf("after insert sorting\n"); print_arr(arr, sizeof(arr)/sizeof(int)); return 0; } void print_arr(int *arr, int size){ int i; for(i=0; i<size; i++){ printf("%d ",*(arr+i)); } printf("\n"); } void insert_sort(int *arr, int size){ int i,j,temp; for(i=1; i<size-1; i++){ if(arr[i-1] > arr[i]){ temp = arr[i]; for(j=i; j>0; j--){ if(arr[j-1] < temp)break; //when the value is small, loop stop arr[j] = arr[j-1]; } arr[j] = temp; } } }
C
#include <stdio.h> #include <stdlib.h> #include <SDL/SDL.h> #include "graphics/SDLCheck.h" #include "game/variableManagement.h" #include "graphics/game/graphicGame.h" #include "graphics/button.h" #include "game/game.h" Card_t graphicPlayerCardChoice(Card_t player_hand[8], Card_t table_cards[4], SDL_Surface *screen, SDL_Surface *background) { //We blit one time for the initialization of card_sprites(to get the good dimensions set in displayPlayerCards) SDL_BlitSurface(background, NULL, screen, NULL); graphicDisplayPlayerCards(player_hand, screen); int number_of_card_played = -1;//The variable we will return //Needed for the card to be considered as a button Sprite_t card_sprite[8]; for(int i = 0 ; i<8 ; i++) { card_sprite[i] = player_hand[i].card_sprite; } int looping = 1; while(looping) { number_of_card_played = buttonPressed(card_sprite, 8); //We will return the card played if there is one if( number_of_card_played != -1) { looping = 0; } //We make all the Blit SDL_BlitSurface(background, NULL, screen, NULL); graphicDisplayPlayerCards(player_hand, screen); graphicDisplayTableCards(table_cards, screen); SDL_Flip(screen); } return player_hand[number_of_card_played]; } void graphicDisplayPlayerCards(Card_t player_hand[8], SDL_Surface *screen) { for(int i = 0 ; i<8 ; i++) { if(player_hand[i].color != 0) { //The position player_hand[i].card_sprite.rect.y = 600; player_hand[i].card_sprite.rect.x = i*200 + 20; //We set the transparency SDL_SetColorKey(player_hand[i].card_sprite.bmp, SDL_SRCCOLORKEY, SDL_MapRGB(player_hand[i].card_sprite.bmp->format,0,255,0)); //We blit the surface SDL_BlitSurface(player_hand[i].card_sprite.bmp, NULL, screen, &player_hand[i].card_sprite.rect ); } } } void graphicDisplayTableCards(Card_t table_cards[4], SDL_Surface *screen) { for(int i = 0 ; i<4 ; i++) { if(table_cards[i].color != 0 ) { //The position table_cards[i].card_sprite.rect.y = 300; table_cards[i].card_sprite.rect.x = i*300 + 260; //We set the transparency SDL_SetColorKey(table_cards[i].card_sprite.bmp, SDL_SRCCOLORKEY, SDL_MapRGB(table_cards[i].card_sprite.bmp->format,0,255,0)); //We blit the surface SDL_BlitSurface(table_cards[i].card_sprite.bmp, NULL, screen, &table_cards[i].card_sprite.rect ); } } } void displayAfterPlayerChoice(Card_t player_hand[8], Card_t table_cards[4], SDL_Surface *screen, SDL_Surface *background) { SDL_Event event; int looping = 1; TTF_Font *font = NULL; font = TTF_OpenFont("assets/font/Minecraft.ttf", 60); checkFont(font); SDL_Color lightBrown = {99,92,92}; Sprite_t txt_space = {.bmp = TTF_RenderText_Solid(font, "Press space to continue", lightBrown)}; checkError(txt_space.bmp); //The loop will stop when the space bar is pressed while(looping) { SDL_WaitEvent(&event); if(event.key.keysym.sym == SDLK_SPACE) { looping = 0; } //We make all the Blit SDL_BlitSurface(background, NULL, screen, &(txt_space.rect)); SDL_BlitSurface(txt_space.bmp, NULL, screen, NULL); graphicDisplayPlayerCards(player_hand, screen); graphicDisplayTableCards(table_cards, screen); SDL_Flip(screen); } SDL_FreeSurface(txt_space.bmp); } void displayScores(SDL_Surface *screen, SDL_Surface *background, int score1, int score2) { TTF_Font *font = NULL; font = TTF_OpenFont("assets/font/Minecraft.ttf", 60); checkFont(font); SDL_Color lightBrown = {99,92,92}; //The text displayed Sprite_t txt_title; txt_title.rect.x = 220; txt_title.rect.y = 10; Sprite_t txt_score1; txt_score1.rect.x = 220; txt_score1.rect.y = 250; Sprite_t txt_score2; txt_score2.rect.x = 220; txt_score2.rect.y = 350; Sprite_t txt_space; txt_space.rect.x = 220; txt_space.rect.y = 450; Sprite_t spr_title; spr_title.rect.x = 220; spr_title.rect.y = 10; Sprite_t spr_score1; spr_score1.rect.x = 220; spr_score1.rect.y = 250; Sprite_t spr_score2; spr_score2.rect.x = 220; spr_score2.rect.y = 350; Sprite_t spr_space; spr_space.rect.x = 220; spr_space.rect.y = 450; char title[25]="Teams points"; char txt1[19]; char txt2[19]; char space[25]="Press space to continue"; //We set the surface for the text diplayed sprintf(txt1, "Your Team : %d", score1); sprintf(txt2, "AI's Team : %d", score2); txt_title.bmp = TTF_RenderText_Solid(font, title, lightBrown); txt_score1.bmp = TTF_RenderText_Solid(font, txt1, lightBrown); txt_score2.bmp = TTF_RenderText_Solid(font, txt2, lightBrown); txt_space.bmp = TTF_RenderText_Solid(font, space, lightBrown); spr_title.bmp = TTF_RenderText_Solid(font, title, lightBrown); spr_score1.bmp = TTF_RenderText_Solid(font, txt1, lightBrown); spr_score2.bmp = TTF_RenderText_Solid(font, txt2, lightBrown); spr_space.bmp = TTF_RenderText_Solid(font, space, lightBrown); //We Blit SDL_BlitSurface(background,NULL,screen,NULL); SDL_BlitSurface(txt_title.bmp,NULL,screen, &txt_title.rect); SDL_BlitSurface(txt_score1.bmp,NULL,screen, &txt_score1.rect); SDL_BlitSurface(txt_score2.bmp,NULL,screen, &txt_score2.rect); SDL_BlitSurface(txt_space.bmp,NULL,screen, &txt_space.rect); SDL_BlitSurface(spr_title.bmp,NULL,screen, &spr_title.rect); SDL_BlitSurface(spr_score1.bmp,NULL,screen, &spr_score1.rect); SDL_BlitSurface(spr_score2.bmp,NULL,screen, &spr_score2.rect); SDL_BlitSurface(spr_space.bmp,NULL,screen, &spr_space.rect); SDL_Flip(screen); SDL_Event event; int exit_loop = 0; while (exit_loop!=2) { SDL_WaitEvent(&event); if (event.key.keysym.sym==SDLK_SPACE) { exit_loop++; } } SDL_FreeSurface(txt_title.bmp); SDL_FreeSurface(txt_score1.bmp); SDL_FreeSurface(txt_score2.bmp); SDL_FreeSurface(txt_space.bmp); SDL_FreeSurface(spr_title.bmp); SDL_FreeSurface(spr_score1.bmp); SDL_FreeSurface(spr_score2.bmp); SDL_FreeSurface(spr_space.bmp); TTF_CloseFont(font); } void displayGameOver(SDL_Surface *screen, SDL_Surface *background, int win) { TTF_Font *font = NULL; font = TTF_OpenFont("assets/font/Minecraft.ttf", 60); checkFont(font); SDL_Color lightBrown = {99,92,92}; //The text displayed Sprite_t txt_title; txt_title.rect.x = 220; txt_title.rect.y = 10; Sprite_t txt_result; txt_result.rect.x = 220; txt_result.rect.y = 250; Sprite_t txt_space; txt_space.rect.x = 220; txt_space.rect.y = 450; Sprite_t spr_title; spr_title.rect.x = 220; spr_title.rect.y = 10; Sprite_t spr_result; spr_result.rect.x = 220; spr_result.rect.y = 250; Sprite_t spr_space; spr_space.rect.x = 220; spr_space.rect.y = 450; char title[25]="Game Over"; char result[19]; char space[25]="Press space to continue"; //We set the surface for the text diplayed if (win) { sprintf(result, "You won :D"); } else { sprintf(result, "You lose :'<"); } txt_title.bmp = TTF_RenderText_Solid(font, title, lightBrown); checkError(txt_title.bmp); spr_title.bmp = TTF_RenderText_Solid(font, title, lightBrown); checkError(spr_title.bmp); txt_result.bmp = TTF_RenderText_Solid(font, result, lightBrown); checkError(txt_result.bmp); spr_result.bmp = TTF_RenderText_Solid(font, result, lightBrown); checkError(spr_result.bmp); txt_space.bmp = TTF_RenderText_Solid(font, space, lightBrown); checkError(txt_space.bmp); spr_space.bmp = TTF_RenderText_Solid(font, space, lightBrown); checkError(spr_space.bmp); //We Blit SDL_BlitSurface(background,NULL,screen,NULL); SDL_BlitSurface(txt_title.bmp,NULL,screen, &txt_title.rect); SDL_BlitSurface(txt_result.bmp,NULL,screen, &txt_result.rect); SDL_BlitSurface(txt_space.bmp,NULL,screen, &txt_space.rect); SDL_BlitSurface(spr_title.bmp,NULL,screen, &spr_title.rect); SDL_BlitSurface(spr_result.bmp,NULL,screen, &spr_result.rect); SDL_BlitSurface(spr_space.bmp,NULL,screen, &spr_space.rect); SDL_Flip(screen); SDL_Event event; int exit_loop = 0; while (exit_loop!=2) { SDL_WaitEvent(&event); if (event.key.keysym.sym==SDLK_SPACE) { exit_loop++; } } SDL_FreeSurface(txt_title.bmp); SDL_FreeSurface(txt_result.bmp); SDL_FreeSurface(txt_space.bmp); SDL_FreeSurface(spr_title.bmp); SDL_FreeSurface(spr_result.bmp); SDL_FreeSurface(spr_space.bmp); TTF_CloseFont(font); } void displayPassesResult(SDL_Surface *screen, SDL_Surface *background, Player_t players[], char trump) { TTF_Font *font = NULL; font = TTF_OpenFont("assets/font/Minecraft.ttf", 60); checkFont(font); SDL_Color lightBrown = {99,92,92}; //The sprites displayed Sprite_t spr_bet; spr_bet.rect.x = 220; spr_bet.rect.y = 200; Sprite_t spr_trump; spr_trump.rect.x = 220; spr_trump.rect.y = 275; Sprite_t spr_space; spr_space.rect.x = 220; spr_space.rect.y = 450; //the texts displayed on the sprites char txt_bet[35]; char txt_trump[45]; char txt_space[25]="Press space to continue"; //logic to know what to display int bet = 0; int team_bet_id; int i; for (i = 0; i < 4; i++) { if(players[i].bet > bet) { bet = players[i].bet; team_bet_id = i % 2; } } if (team_bet_id==0)//user's team placed the bet { sprintf(txt_bet, "Your team placed a %d bet", bet); } else { sprintf(txt_bet, "The other team placed a %d bet", bet); } switch(trump) { case 'D' : sprintf(txt_trump, "This round is played with Diamond trump"); break; case 'C' : sprintf(txt_trump, "This round is played with Club trump"); break; case 'H' : sprintf(txt_trump, "This round is played with Heart trump"); break; case 'S' : sprintf(txt_trump, "This round is played with Spade trump"); break; case 'N' : sprintf(txt_trump, "This round is played with No trump"); break; case 'A' : sprintf(txt_trump, "This round is played with All trump"); break; default : sprintf(txt_trump, "Error : Trump not found"); sprintf(txt_trump, "error:Trump not available"); } //Render the txts on the sprites spr_bet.bmp = TTF_RenderText_Solid(font, txt_bet, lightBrown); checkError(spr_bet.bmp); spr_trump.bmp = TTF_RenderText_Solid(font, txt_trump, lightBrown); checkError(spr_trump.bmp); spr_space.bmp = TTF_RenderText_Solid(font, txt_space, lightBrown); checkError(spr_space.bmp); //We Blit SDL_BlitSurface(background,NULL,screen,NULL); SDL_BlitSurface(spr_bet.bmp,NULL,screen, &spr_bet.rect); SDL_BlitSurface(spr_trump.bmp,NULL,screen, &spr_trump.rect); SDL_BlitSurface(spr_space.bmp,NULL,screen, &spr_space.rect); SDL_Flip(screen); SDL_Event event; int exit_loop = 0; while (exit_loop!=1) { SDL_WaitEvent(&event); if (event.key.keysym.sym==SDLK_SPACE) { exit_loop++; } } //we free SDL_FreeSurface(spr_bet.bmp); SDL_FreeSurface(spr_trump.bmp); SDL_FreeSurface(spr_space.bmp); TTF_CloseFont(font); }
C
#include "holberton.h" /** * factorial - Textbook example of using recursion through factorials. * @n: Parameter of given number that is used for factoring. * * Description: Two base cases where if n is negative and n gets to 1. * Description (cont): Otherwise, keep getting the factorial. * * Return: -1, 1, n */ int factorial(int n) { if (n < 0) return (-1); if (n == 1) return (1); return (n * (factorial(n - 1))); }
C
#include <stdio.h> // old project from 2016 #define INCOMETAX .125 #define FEDERALTAX .25 #define STATETAX .10 #define RETIREMENT .08 void calculatePayroll(int *s, int *b); void printPayroll(int *x, int *y, float, float, float, float, float, float); int main() { int sales, bonus; fputs("Please enter the total sales for employee: ", stdout); scanf("%d", &sales); fputs("Now enter the bonus for the employee: ", stdout); scanf("%d", &bonus); calculatePayroll(&sales, &bonus); return 0; } void calculatePayroll(int *s, int *b) { float income, federalTax, stateTax, retirement, deductions, finalIncome; income = (*s + *b) * INCOMETAX; federalTax = income * FEDERALTAX; stateTax = income * STATETAX; retirement = income * RETIREMENT; deductions = (federalTax + stateTax + retirement); finalIncome = income - deductions; printPayroll(s, b, income, federalTax, stateTax, retirement, deductions, finalIncome); } void printPayroll(int *x, int *y, float inc, float fed, float state, float retire, float deduct, float finl) { printf("Sales: $%d\n Bonus: $%d\n Income: $%.2f\n Federal Tax: $%.2f\n State Tax: $%.2f\n Retirement: $%.2f\n Deductions: $%.2f\n Final Income: $%.2f\n", *x, *y, inc, fed, state, retire, deduct, finl); }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: Vitor * * Created on 3 de Julho de 2018, 14:10 */ /* * */ #include <stdio.h> #include <stdlib.h> #define TRUE 1 #define FALSE 0 #define max 10 FILE *arq; typedef struct registro{ int codigo; int quantidade; char descricao[30]; char data[10]; float custo; } tproduto; void inserir_produto(tproduto prod[max], int qtde) { } void excluir_produto() { } void busca_produto() { } void printar_produtos(tproduto prod[max], int qtde) { int i; for(i = 0; i < qtde; i++) { printf("\nIdentificação: %d\n",prod[i].codigo); printf("Quantidade de produtos: %d\n", prod[i].quantidade); printf("Descrição: %s\n", prod[i].descricao); printf("Data da compra: %s\n", prod[i].data); printf("Custo: %.2f\n", prod[i].custo); } } int main(int argc, char** argv) { tproduto prod[max]; int qtde=0, opcao; // abarindo arquivo para leitura arq = fopen("estoque.txt","r"); printf("\nArquivo aberto\n"); while (!feof(arq)) { //lendo informações do arquivo fscanf(arq," %d", &prod[qtde].codigo); fscanf(arq," %d", &prod[qtde].quantidade); fscanf(arq," %s", prod[qtde].descricao); fscanf(arq," %s", prod[qtde].data); fscanf(arq," %f", &prod[qtde].custo); qtde++; } fclose(arq); do { puts("-----------------------------"); puts("| Menu principal |"); puts("| [1] printar produtos |"); puts("| [2] Excluir um produto |"); puts("| [3] Buscar um produto |"); puts("| [4] Printar Produtos |"); puts("| [5] Sair |"); puts("-----------------------------"); scanf(" %d", &opcao); switch (opcao) { case 1: printf("Digite a identificação do novo produto: "); scanf(" %d", &prod[qtde].codigo); inserir_produto(prod, qtde); break; case 2: printf("Digite o produto que deseja excluir"); excluir_produto(); break; case 3: printf("Digite o produto que deseja buscar"); busca_produto(); break; case 4: printar_produtos(prod, qtde); break; case 5: printf("Fim\n"); break; default: printf("Opção inválida"); } }while (opcao != 5); return 0; }
C
/* -- IFJ project 2013 ------------------------------------------------------ ** ** Interpreter of IFJ2013 language ** 4.11.2013 - 15.12.2013 ** ** Team 13 (b/3/I): ** ** Bank Tomáš <[email protected]> ** Birger Mark <[email protected]> ** Botka Roland <[email protected]> ** +Brandejs Zdenko <[email protected]> ** +Khudiakov Daniil <[email protected]> ** ** Binary Search Tree implementation. ** ** -------------------------------------------------------------------------*/ /* -- Includes part --------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "ial.h" /* -- Functions for BST ----------------------------------------------------*/ void treeInit (typeNodePtr *Root) { (*Root) = NULL; } typeNodePtr * treeSearch (typeNodePtr * Root, string Key) { if ((*Root) != NULL) { int compareResult = strCompare(&(*Root)->key, &Key); if (compareResult == 0) { return Root; } else { if (compareResult > 0) { return treeSearch (&(*Root)->left, Key); } else { return treeSearch (&(*Root)->right, Key); } } } else { return NULL; //not founded } } int treeInsert (typeNodePtr * Root, string Key, typeData Data) { if ((*Root) == NULL) { // new node if(((*Root)=malloc(sizeof(struct typeNode)))==NULL) return ALLOC_FAIL; if (strCopy(&(*Root)->key, &Key)==STR_ERROR) return ALLOC_FAIL; (*Root)->data = Data; (*Root)->left = NULL; (*Root)->right = NULL; } else { int compareResult = strCompare(&(*Root)->key, &Key); if (compareResult > 0) { return treeInsert (&(*Root)->left, Key, Data); } else if (compareResult < 0) { return treeInsert (&(*Root)->right, Key, Data); } else { (*Root)->data = Data; } } return SUCCESS; } void treeDispose (typeNodePtr *Root) { if ((*Root) != NULL) { treeDispose(&(*Root)->left); treeDispose(&(*Root)->right); free(*Root); (*Root) = NULL; //empty tree after dispose } } /* -- Debug function for BST printing --------------------------------------*/ void treePrint (typeNodePtr *Root) { if ((*Root) != NULL) { printf("'%s' -> [%i , ", (*Root)->key.str,(*Root)->data.type); char val; switch ((*Root)->data.type) { case _NULL: printf("NULL"); break; case _LOGICAL: val = (*Root)->data.valueOf.type_LOGICAL; if (val==0) { printf("false"); } else { printf("true"); } break; case _INTEGER: printf("%i", (*Root)->data.valueOf.type_INTEGER); break; case _DOUBLE: printf("%f", (*Root)->data.valueOf.type_DOUBLE); break; case _STRING: printf("%s", strGetContent(&(*Root)->data.valueOf.type_STRING)); break; } printf("]\n"); treePrint(&(*Root)->left); treePrint(&(*Root)->right); } } /* -- Shell sort -----------------------------------------------------------*/ char *sort_string(char *string) { //shell sort serazeni znaku retezce podle ordinalni hodnoty int n = strlen(string); //zjistime delku stringu -> n //i, j == for cykly/indexy, tmp => pomocna promenna pro bubble, m == step int j,i,step,tmp; //opakuj porad kdyz bude step > 0 a step zmensuj o polovinu for(step = n/2; step > 0; step /= 2){ for(j = step; j < n; j++){ //cykl pro upravu ukazatele do pole for(i = j - step; i >= 0; i -= step){ if(string[i+step] >= string[i]) break; else { //nasledujici 3 radky prohozeni hodnot jako u Bubble tmp = string[i]; string[i] = string[i+step]; string[i+step] = tmp; } } } } return string; } /* -- Boyer-Mooruv ---------------------------------------------------------*/ int max(int a, int b) { //pomocna funkce pro vyhledani vetsi hodnoty return (a > b)? a: b; } //Funkce pro BMA , zpracuje pole nesouhlasnych znaku void nesouhlasZnakFce( char *str, int size, int badchar[zadnyZeZnaku]) { int i; //Vsechny vyskyty inicializovat na -1 for (i = 0; i < zadnyZeZnaku; i++) badchar[i] = -1; //Vyplni aktualni hodnotu posledniho vyskytu znaku for (i = 0; i < size; i++) badchar[(int) str[i]] = i; } int find_string(char *txt, char *pat) { // BMA vyhledavaci algoritmus int m = strlen(pat); int n = strlen(txt); int badchar[zadnyZeZnaku]; // Vyplni pole spatnych znaku volanim funkce nesouhlasZnakFce() // pro dany vzorek nesouhlasZnakFce(pat, m, badchar); //s je posun vzorku k textu int s = 0; while(s <= (n - m)) { int j = m-1; /* Redukovani indexu <j> ze vzorku (pattern) * DOKUD se znaky vzoru a textu shoduji po posunuti <s> */ while(j >= 0 && pat[j] == txt[s+j]) j--; /* Pokud se vzorek nachazi v soucasnem posunu, tak index j * se zmeni v -1 po dovrseni smycky */ if (j < 0){ //pokud jsem tedy nasel prvni vyskyt, koncim a vracim index return s; /* Posun vzoru tak, aby dalsi znak v textu byl zarovnan s jeho poslednim vyskytem ve vzoru. Podminka s + m < n je nutna, pro pripad, kdy se vzor vyskytuje na konci textu */ s += (s+m < n)? m-badchar[(unsigned char)txt[s+m]] : 1; } else{ /* Posun vzoru tak, aby spatny znak v textu byl zarovnan s jeho poslednim vyskytem ve vzoru. Fce max se pouzije, aby sme opravdu dostali co "nejvyhodnejsi" posun == nejvetsi. Muzeme dostat negativni posun v pripade, ze posledni vyskyt spatneho znaku ve vzoru je na prave strane soucasneho znaku.*/ s += max(1, j - badchar[(unsigned char)txt[s+j]]); } } //kdyz nedostanu prvni vyskyt viz vyse, vratim -1 return -1; }
C
/* ** EPITECH PROJECT, 2019 ** PSU_tetris_2019 ** File description: ** fct_flag.c */ #include "tetris.h" int key_left(key_p *key, char *str) { int new_key = recup_char_key(str); if (new_key == -1) { my_printf("Bad input for key left\n"); exit (84); } else key->left = new_key; return (0); } int key_right(key_p *key, char *str) { int new_key = recup_char_key(str); if (new_key == -1) { my_printf("Bad input for key right\n"); exit (84); } else key->right = new_key; return (0); } int key_turn(key_p *key, char *str) { int new_key = recup_char_key(str); if (new_key == -1) { my_printf("Bad input for key turn\n"); exit (84); } else key->turn = new_key; return (0); } int key_drop(key_p *key, char *str) { int new_key = recup_char_key(str); if (new_key == -1) { my_printf("Bad input for key drop\n"); exit (84); } else key->drop = new_key; return (0); } int key_quit(key_p *key, char *str) { int new_key = recup_char_key(str); if (new_key == -1) { my_printf("Bad input for key quit\n"); exit (84); } else key->quit = new_key; return (0); }
C
#include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <stdio.h> #include <fcntl.h> char name[] = "large.dat"; int main(int argc, char* argv[]) { int f; char data = (char)0; /* not null! 0s. */ /* create / write the file given */ f = open(name, O_CREAT | O_WRONLY, 0666); write(f, &data, 1); /* write a byte*/ lseek(f, 100000000, SEEK_SET); /* jump ahead 100mb into the file, will use this middle space later */ write(f, &data, 1); close(f); return(0); }
C
#include "main.h" extern unsigned char data[9]; unsigned char Reset_1_Wire() { unsigned char status; bis(_1_WIRE_DIR, DQ); bic(_1_WIRE_OUT, DQ); __delay_cycles(480); //obtain about 480us bic(_1_WIRE_DIR, DQ); //release about 60us __delay_cycles(60); //60us status = check_bit(_1_WIRE_IN, DQ); //DS18B20 response by pulling DQ down, status = 0 __delay_cycles(420); //420 us, wait to cycle end return status; } void Write_1_Byte_1_Wire(unsigned char data) { unsigned char i; for(i = 0; i < 8; i++) { //LSB is sent first if(check_bit(data, BIT0)) { //master write "1" slot bis(_1_WIRE_DIR, DQ); bic(_1_WIRE_OUT, DQ); __delay_cycles(1); //obtain about 10us bic(_1_WIRE_DIR, DQ); __delay_cycles(60); //delay 60us to wait cycle end } else { //master write "0" slot bis(_1_WIRE_DIR, DQ); bic(_1_WIRE_OUT, DQ); __delay_cycles(60); //obtain about 60us bic(_1_WIRE_DIR, DQ); __delay_cycles(1); //15us recovery between individual write slots } //shift right 1 bit data = data >> 1; } } unsigned char Read_1_Byte_1_Wire() { unsigned char data; unsigned char i; for(i = 0; i < 8; i++) { bis(_1_WIRE_DIR, DQ); bic(_1_WIRE_OUT, DQ); // __delay_cycles(1); //obtain about 10us bic(_1_WIRE_DIR, DQ); // __delay_cycles(1); if(check_bit(_1_WIRE_IN, DQ)) { //master read "1" slot data = (data >> 1)|0x80; } else { //master read "0" slot data = (data >> 1)|0x00; } __delay_cycles(60); //70us recovery time between slots } return data; } void DS18B20_Read_Multi_Byte(unsigned char *data, unsigned char number) { unsigned char i; if(Reset_1_Wire() == 0) { Write_1_Byte_1_Wire(0xCC); //send skip rom command Write_1_Byte_1_Wire(0xBE); //send command read scratchpad for(i = 0; i < number; i++) { *(data + i) = Read_1_Byte_1_Wire(); } } } void DS18B20_Write_Multi_Byte(unsigned char *data) { if(Reset_1_Wire() == 0) { Write_1_Byte_1_Wire(0xCC); //send skip rom command Write_1_Byte_1_Wire(0x4E); //send write scratchpad command //send data Write_1_Byte_1_Wire(data[2]); Write_1_Byte_1_Wire(data[3]); Write_1_Byte_1_Wire(data[4]); } } void DS18B20_Send_Function_Command(unsigned char command) { if(Reset_1_Wire() == 0) { Write_1_Byte_1_Wire(0xCC); //send skip rom command Write_1_Byte_1_Wire(command); //send command convert temperature if(command == 0x44) while(!check_bit(_1_WIRE_IN, DQ)); //check converting temperature complete } } void DS18B20_Temperature_Format_Transfer(unsigned char *data, unsigned int *result) { unsigned char Res; //Thermometer Resolution Configuration unsigned int temp; Res = (*(data + 4))>>5; //get value R0, R1 in Configuration Register //get sign if(check_bit(*(data + 1), BIT7)) { *(result + 0) = 0xFF; //result[0] = sign: 0x00 is +, 0xFF is - } else { *(result + 0) = 0x00; } //get value switch(Res) { case 0x00://9 bits resolution *(result + 1) = (*(data + 0)>>4)|((*(data + 1)&0x07)<<4); *(result + 2) = ((*(data + 0)&0x08)>>3)*5; break; case 0x01://10 bits resolution *(result + 1) = (*(data + 0)>>4)|((*(data + 1)&0x07)<<4); *(result + 2) = ((*(data + 0)&0x0C)>>2)*25; break; case 0x02://11 bits resolution *(result + 1) = (*(data + 0)>>4)|((*(data + 1)&0x07)<<4); *(result + 2) = ((*(data + 0)&0x0E)>>1)*125; break; case 0x03://12 bits resolution *(result + 1) = (*(data + 0)>>4)|((*(data + 1)&0x07)<<4) ; temp = (unsigned int)(*(data + 0)&0x0F)*625; *(result + 2) = (unsigned char)(temp/100); break; } } void DS18B20_Configuration_Register(unsigned char temp) { DS18B20_Read_Multi_Byte(data, 9); //luu du lieu trong DS18B20 vao RAM msp430 data[4] = temp<<5; DS18B20_Write_Multi_Byte(data); } void HEX_2_LCD(unsigned int hex) { unsigned char temp[4]; unsigned char i = 0; while(1) { temp[i] = hex%10; hex = hex/10; if(hex == 0) break; i++; } while(1) { Putchar_LCD(temp[i]|0x30); if(i == 0) break; i--; } } void Display_Temperature(unsigned int* result) { //display sign if(result[0] == 0x00) { Putchar_LCD('+'); } else { Putchar_LCD('-'); } //display Int HEX_2_LCD(result[1]); //Display dot Putchar_LCD('.'); //display Decimal HEX_2_LCD(result[2]); Putchar_LCD(0xDF); Print_LCD("C "); }
C
#ifndef STRING_H #define STRING_H #include "../DataStructureBase.h" typedef struct { char *ch; //储存字符串,使用动态分配 int len; //存储字符串长度 }HString; Status InitStr(HString *str); //初始化str为空串 Status DestroyStr(HString *str); //销毁串str Status StrAssign(HString *str1, char *str2); //生成一个其值等于str2的串str1 Status StrCopy(HString *str1, HString str2); //拷贝str2的副本到str1 int StrCompare(HString str1, HString str2); //按字典序比较两个串str1和str2,若相等返回0,若str1<str2,返回大于大于0的整数。若str1>str2,返回小于0的整数 int StrLength(HString str); //返回S的元素个数,即串的长度 Status StrEmpty(HString str); //判断串str是否是空串 Status ClearString(HString *str); //将串str清为空串 Status Concat(HString *str3, HString str1, HString str2); //用str3返回str1和str2连接而成的新串 Status SubString(HString *sub, HString str, int position, int length); //0<=position<str.len,len>=0,返回串的第position个字符起长度为length的子串 Status StrInsert(HString *str1, HString str2, int pos); //在串str1的pos位置插入串str2 Status StrDelete(HString *str1, int pos, int length); //删除串str2中[pos,pos+length)位置的字符 Status StrReplace(HString *str1, HString str2, int pos, int length); //替换串str1中[pos,length)位置的内容为str2 char At(HString str, int index); //返回串str某位置的字符,位置非法返回'\0' int Index(HString str, char c, int pos); //返回c在pos后第一次出现的位置,找不到或pos非法返回-1 void PrintStr(HString str); //打印串str的内容 void PrintStrWithLine(HString str); //打印串str的内容并换行 Status Next(HString str, int *next); //KMP模式匹配算法求改良版的next数组 int SubIndex(HString str, HString sub, int pos); //返回串sub在str中的位置,位置非法或找不到返回-1,采用KMP模式匹配 Status StrReplaceFirst(HString *str, HString sub, HString new, int pos); //替换串str第pos位置之后的第一个字符ch Status StrReplaceAll(HString *str, HString sub, HString new, int pos); //替换串str第pos位置之后的第一个字符ch char *ToCString(HString *str); //返回C语言风格的字符串 #endif
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "LinkedList.h" #include "pelicula.h" #include "parser.h" #include "utn.h" int controller_listExist(LinkedList* pArrayListeDominio) { int existe = -1; if(ll_len(pArrayListeDominio)>0) { existe = 1; } return existe; } int controller_loadFromText(char* path,LinkedList* pArrayListPelicula) { int retorno=-1; FILE* Pfile = fopen(path,"r"); if(Pfile!=NULL&& pArrayListPelicula !=NULL) { if(parser_moviesFromText(Pfile,pArrayListPelicula)) { retorno=1; } else { retorno =-1; } } else { retorno =-1; } fclose(Pfile); free(Pfile); return retorno; } int controller_ListPelicula(LinkedList* pArrayListePelicula) { ePelicula* auxPelicula = ePelicula_new(); int auxID; char auxNombre[50]; int auxAnio; char auxGenero[50]; int retorno=-1; int i; if(auxPelicula!=NULL && pArrayListePelicula!=NULL) { system("cls"); puts(" [ID]\t[TITULO]\t[ANIO]\t[GENERO]\n\n"); for(i=0; i < ll_len(pArrayListePelicula); i++) { auxPelicula = ll_get(pArrayListePelicula, i); ePelicula_getId(auxPelicula, &auxID); ePelicula_getNombre(auxPelicula,auxNombre); ePelicula_getAnio(auxPelicula,&auxAnio); ePelicula_getGenero(auxPelicula,auxGenero); printf("%1d %1s %3d %5s\n",auxID, auxNombre, auxAnio, auxGenero); } retorno=1; } else { retorno=-1; } printf("\n\n"); return retorno; } /*int controller_saveAsText(char* path, LinkedList* pArrayListeDominio) { int retorno=-1; int len; int idAuxiliar; char dominioAuxiliar[50]; int anioAuxiliar; char tipoAuxiliar; int i; FILE* Pfile = fopen(path,"w+"); eDominio* auxEdominio=eDominio_new(); if(Pfile != NULL && pArrayListeDominio != NULL && auxEdominio!=NULL ) { len=ll_len(pArrayListeDominio); fprintf(Pfile, "id,dominio,anio,tipo\n"); for(i=0; i<len; i++) { auxEdominio= ll_get(pArrayListeDominio,i); eDominio_getId(auxEdominio, &idAuxiliar); eDominio_getDominio(auxEdominio,dominioAuxiliar); eDominio_getAnio(auxEdominio,&anioAuxiliar); eDominio_getTipo(auxEdominio,&tipoAuxiliar); fprintf(Pfile,"%d,%s,%d,%c\n",idAuxiliar,dominioAuxiliar,anioAuxiliar,tipoAuxiliar); } retorno = 1; } else { retorno=-1; } fclose(Pfile); return retorno; }*/
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "symbol_table.h" table *tableptr; void push(char * name, char type) { table * last = NULL; // Assign identifier values to the new struct table * new = malloc(sizeof(table)); new -> id = name; new -> type = type; new -> next = NULL; if (type == 'i') new -> value.ival = 0; else new -> value.fval = 0.0; if (tableptr == NULL) tableptr = new; else { last = last_element(); last -> next = new; } } table * last_element() { if (tableptr == NULL) return NULL; if (tableptr -> next == NULL) return tableptr; table * head = tableptr; while(head -> next != NULL) { head = head -> next; } return head; } table * search(char * name) { if (!tableptr) return NULL; table * current = tableptr; while(current != NULL) { int compare = strcmp(current -> id, name); if (compare == 0) return current; current = current -> next; } return current; }
C
/* * extension.h * A GTK+ interpreter for the LOGO language * * Author: Kenneth Kam <[email protected]> * Username: kk4053 * Declaration: This code for COMSM1201 is the original work of Kenneth Kam. */ #include <gtk/gtk.h> // linked list of Logo inputs struct _input_items { Logo input; gchar *buffer; /* for use for re-reading history */ struct _input_items *next; }; typedef struct _input_items * InputItems; struct _draw_info { InputItems input_items; GtkWidget *drawing_area; GtkWidget *text_view; GtkWidget *window; GtkWidget *statusbar; GtkWidget *tree_view; int drag_on; /* dragging is on */ double x; /* coordinates to move to before draw */ double y; }; typedef struct _draw_info DInfo; // GUI int gui_main(int argc, char * argv[]); GtkWidget * create_window(DInfo *dinfo); GtkWidget * create_menu_bar(DInfo *dinfo, GtkWidget *window); GtkWidget * create_scrolled_window(GtkWidget *child); GtkWidget * create_drawing_area(void); GtkWidget * create_slider_box(DInfo *dinfo); GtkWidget * create_text_view(void); GtkWidget * create_tree_view(void); // Helper functions int draw(DInfo *dinfo); void draw_triangle(DInfo *dinfo, double x, double y); void paint_white(DInfo *dinfo); void remove_messages(DInfo *dinfo); void update_tree_view(DInfo *dinfo); void clear_text(DInfo *dinfo); void new_file(DInfo *dinfo); int open_file(DInfo *dinfo, char *filename); int process_text_view(DInfo * dinfo); Logo read_input(char * buffer, int count); int parse_items(InputItems input_items); int input_items_add(InputItems *input_items, Logo input, char *buffer); Logo input_items_pop(InputItems *input_items); void free_input_items(InputItems input_items); // GUI Interpreter Backend void gui_ipt_fd(Logo input, float op); void gui_ipt_lt(Logo input, float op); void gui_ipt_rt(Logo input, float op);
C
#include<stdio.h> #include<conio.h> #include<windows.h> #include<stdlib.h> void gotoxy(int x,int y) { COORD c; c.X=x; c.Y=y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE),c); } void main() { int h=0,m=0,s=0; int a=20,b=8; int ch; double i; system("color 1a"); printf("enter the HH MM and SE :\n"); scanf("%d%d%d",&h,&m,&s); label1: for(h;h<24;h++) { for(m;m<60;m++) { for(s;s<60;s++) { system("cls"); gotoxy(45,10); printf("\n *clock* \n"); printf("\n %d : %d : %d \n",h,m,s); for(i=0;i<69889989;i++) { i++; i--; } } s=0; } m=0; } h=0; goto label1; getch(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strncmp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: smun <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/01 18:09:35 by smun #+# #+# */ /* Updated: 2020/10/01 18:19:46 by smun ### ########.fr */ /* */ /* ************************************************************************** */ #include <libft.h> #include <stdio.h> #include <string.h> t_bool do_test(const char *s1, const char *s2, size_t len) { int r1; int r2; r1 = ft_strncmp(s1, s2, len); r2 = strncmp(s1, s2, len); if (!((r1 > 0 && r2 > 0) || (r1 == 0 && r2 == 0) || (r1 < 0 && r2 < 0))) { printf("[실패] s1=[%s] s2=[%s]\n", s1, s2); printf("Your=%d\n", r1); printf("CStdLib=%d\n", r2); return (FALSE); } return (TRUE); } int main(void) { if (!do_test("", "", 0)) return (1); if (!do_test("Hello", "", 0)) return (2); if (!do_test("", "Hello", 0)) return (3); if (!do_test("", "", 3)) return (4); if (!do_test("Hello", "", 4)) return (5); if (!do_test("", "Hello", 5)) return (6); if (!do_test("Hello World!", "Hello World!", 30)) return (7); if (!do_test("Hello World!!", "Hello WorId!!", 10)) return (8); if (!do_test("42 SEOUL Campus", "42 ", 4)) return (9); if (!do_test("42 SEOUL Campus", "42 SEOUL Campus", 50)) return (10); if (!do_test("42 SEOUL \0Campus", "42 SEOUL ", 30)) return (11); return (0); }
C
/* Macro to calculate offset of variable in a structure. Let the base address to be zero, then the member's addresses are exactly their offset in this structure. Tested on gcc. */ #include <stdio.h> #define offsetof(s, m) (size_t)(&(((s *)0)->m)) typedef struct _aa { int a; int b; int c; } aa; int main() { int offset = offsetof(aa, a); printf("%d\n", offset); offset = offsetof(aa, b); printf("%d\n", offset); offset = offsetof(aa, c); printf("%d\n", offset); }
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 */ typedef struct TYPE_6__ TYPE_2__ ; typedef struct TYPE_5__ TYPE_1__ ; /* Type definitions */ struct TYPE_5__ {int cursor; int scroll; int widthInChars; int /*<<< orphan*/ buffer; } ; typedef TYPE_1__ field_t ; struct TYPE_6__ {scalar_t__ down; } ; /* Variables and functions */ int /*<<< orphan*/ Field_Paste (TYPE_1__*) ; #define K_DEL 133 #define K_END 132 #define K_HOME 131 #define K_INS 130 int K_KP_INS ; #define K_LEFTARROW 129 #define K_RIGHTARROW 128 size_t K_SHIFT ; int key_overstrikeMode ; TYPE_2__* keys ; int /*<<< orphan*/ memmove (int /*<<< orphan*/ ,int /*<<< orphan*/ ,int) ; int strlen (int /*<<< orphan*/ ) ; int tolower (int) ; void Field_KeyDownEvent( field_t *edit, int key ) { int len; // shift-insert is paste if ( ( ( key == K_INS ) || ( key == K_KP_INS ) ) && keys[K_SHIFT].down ) { Field_Paste( edit ); return; } key = tolower( key ); len = strlen( edit->buffer ); switch ( key ) { case K_DEL: if ( edit->cursor < len ) { memmove( edit->buffer + edit->cursor, edit->buffer + edit->cursor + 1, len - edit->cursor ); } break; case K_RIGHTARROW: if ( edit->cursor < len ) { edit->cursor++; } break; case K_LEFTARROW: if ( edit->cursor > 0 ) { edit->cursor--; } break; case K_HOME: edit->cursor = 0; break; case K_END: edit->cursor = len; break; case K_INS: key_overstrikeMode = !key_overstrikeMode; break; default: break; } // Change scroll if cursor is no longer visible if ( edit->cursor < edit->scroll ) { edit->scroll = edit->cursor; } else if ( edit->cursor >= edit->scroll + edit->widthInChars && edit->cursor <= len ) { edit->scroll = edit->cursor - edit->widthInChars + 1; } }
C
/* * NxM Mixer * * * The algorithm inplements generic NxM mixer * * N * --- * \ * y[i] = > a[i][j] * x[j] * / * --- * j=1 * * i = 1,2,3,...,M */ #define BLOCK_SIZE 16 #define N 16 // max number of input channels #define M 16 // max number of output channels typedef struct { int enable; //non-zero to enable this function int n_input_channels; int m_output_channels; float output_gain; //amount of gain to apply to all output channels float gain_matrix[N][M]; // gain_controls } mixerNxM_data; void mixerNxM_processing(float** input, float** output, mixerNxM_data data) { int i = 0; int in = 0; int out = 0; int gain_index = 0; float temp = 0; float current_gain; float* brick_in; float* brick_out; /* bypass */ if(!(data.enable)) { for(out = 0; out < data.m_output_channels; out++) { brick_out = output[out]; brick_in = input[out]; for(i = 0; i < BLOCK_SIZE; i++) { /* if N < M, bypass N channels to output, other outputs set to zero*/ if(out >= data.n_input_channels) { brick_out[i] = 0; } else { brick_out[i] = brick_in[i]; } } } } /* processing */ else { for(out = 0; out < data.m_output_channels; out++) { brick_out = output[out]; /* clear old out values */ for(i = 0; i < BLOCK_SIZE; i++) { brick_out[i] = 0; } for(in = 0; in < data.n_input_channels; in++) { brick_in = input[in]; for(i = 0; i < BLOCK_SIZE; i++) { brick_out[i] += data.gain_matrix[in][out] * brick_in[i]; } } for(i = 0; i < BLOCK_SIZE; i++) { brick_out[i] = brick_out[i] * data.output_gain; } } } }
C
/************************************************************************** Copyright(C), 2016-2026, tao.jing All rights reserved ************************************************************************** File : dvl_data_process.c Author : tao.jing Date : 19-9-6 Brief : **************************************************************************/ #include <stdio.h> #include <string.h> #include "dvl_data_process.h" #include "dvl_env.h" dvl_process_func_t process_func_array[10] = { process_sa_data, process_ts_data, process_wi_data, process_ws_data, process_we_data, process_wd_data, process_bi_data, process_bs_data, process_be_data, process_bd_data, }; void process_sa_data(const char* _data_type, const char* _data, unsigned char data_count) { printf(" === process_sa_data === \n"); int ret = sscanf(_data, "%f,%f,%f", &g_dvl_sa.pitch_degree, &g_dvl_sa.roll_degree, &g_dvl_sa.heading_degree); if ( ret != 3 ) { printf("SA Error: sscanf data resolved count %d\n", ret); return; } printf("SA - Pitch: %f, Roll: %f, Head: %f\n", g_dvl_sa.pitch_degree, g_dvl_sa.roll_degree, g_dvl_sa.heading_degree); } void process_ts_data(const char* _data_type, const char* _data, unsigned char data_count) { printf(" === process_ts_data === \n"); if ( data_count < DVL_TIME_SEG_LEN + 1 ) { printf("Error: ts length error %s\n", _data); return; } char time[DVL_TIME_SEG_LEN + 1] = {0}; char data[DVL_DATA_SEG_MAX_LEN] = {0}; //Resolve time seg -- len : 14 for (unsigned char idx = 0; idx < DVL_TIME_SEG_LEN; idx ++) { if ( _data[idx] <= '9' && _data[idx] >= '0' ) { time[idx] = _data[idx]; } else { printf("Error: time seg resolve failed %s\n", _data); return; } } if ( _data[DVL_TIME_SEG_LEN] != ',' ) { printf("Error: time seg resolve failed %s\n", _data); } printf("TS - Time String : %s\n", time); //Resolve data seg strncpy(data, _data + DVL_TIME_SEG_LEN + 1, data_count - DVL_TIME_SEG_LEN - 1); int ret = sscanf(data, "%f,%f,%f,%f,%d", &g_dvl_ts.salinity_ppt, &g_dvl_ts.temperature_c, &g_dvl_ts.depth_trans_m, &g_dvl_ts.speed_sound_m_s, &g_dvl_ts.bbb); if ( ret != 5 ) { printf("TS Error: sscanf data resolved count %d\n", ret); return; } printf("TS - salinity_ppt: %f \n" " temperature_c: %f \n" " depth_trans_m: %f \n" " speed_sound_m_s: %f \n" " built-in-test: %d \n", g_dvl_ts.salinity_ppt, g_dvl_ts.temperature_c, g_dvl_ts.depth_trans_m, g_dvl_ts.speed_sound_m_s, g_dvl_ts.bbb); } void process_wi_data(const char* _data_type, const char* _data, unsigned char data_count) { printf("process_wi_data\n"); } void process_ws_data(const char* _data_type, const char* _data, unsigned char data_count) { printf("process_ws_data\n"); } void process_we_data(const char* _data_type, const char* _data, unsigned char data_count) { printf("process_we_data\n"); } void process_wd_data(const char* _data_type, const char* _data, unsigned char data_count) { printf("process_wd_data\n"); } void process_bi_data(const char* _data_type, const char* _data, unsigned char data_count) { printf(" === process_bi_data === \n"); int ret = sscanf(_data, "%d,%d,%d,%d,%c", &g_dvl_bi.vx_mm_s, &g_dvl_bi.vy_mm_s, &g_dvl_bi.vz_mm_s, &g_dvl_bi.ve_mm_s, &g_dvl_bi.status); if ( ret != 5 ) { printf("BI Error: sscanf data resolved count %d\n", ret); return; } printf("BI - Vx: %d, Vy: %d, Vz: %d, \n" "Ve: %d, Status: %c\n", g_dvl_bi.vx_mm_s, g_dvl_bi.vy_mm_s, g_dvl_bi.vz_mm_s, g_dvl_bi.ve_mm_s, g_dvl_bi.status); } void process_bs_data(const char* _data_type, const char* _data, unsigned char data_count) { printf(" === process_bs_data === \n"); int ret = sscanf(_data, "%d,%d,%d,%c", &g_dvl_bs.transverse_vel_mm_s, &g_dvl_bs.longitude_vel_mm_s, &g_dvl_bs.normal_vel_mm_s, &g_dvl_bs.status); if ( ret != 4 ) { printf("BS Error: sscanf data resolved count %d\n", ret); return; } printf("BS - TV: %d, LV: %d, NV: %d, Status: %c\n", g_dvl_bs.transverse_vel_mm_s, g_dvl_bs.longitude_vel_mm_s, g_dvl_bs.normal_vel_mm_s, g_dvl_bs.status); } void process_be_data(const char* _data_type, const char* _data, unsigned char data_count) { printf(" === process_be_data === \n"); int ret = sscanf(_data, "%d,%d,%d,%c", &g_dvl_be.east_vel_mm_s, &g_dvl_be.north_vel_mm_s, &g_dvl_be.upward_vel_mm_s, &g_dvl_be.status); if ( ret != 4 ) { printf("BE Error: sscanf data resolved count %d\n", ret); return; } printf("BS - EV: %d, NV: %d, UV: %d, Status: %c\n", g_dvl_be.east_vel_mm_s, g_dvl_be.north_vel_mm_s, g_dvl_be.upward_vel_mm_s, g_dvl_be.status); } void process_bd_data(const char* _data_type, const char* _data, unsigned char data_count) { printf(" === process_bd_data === \n"); int ret = sscanf(_data, "%f,%f,%f,%f,%f", &g_dvl_bd.east_dis_m, &g_dvl_bd.north_dis_m, &g_dvl_bd.upward_dis_m, &g_dvl_bd.range_to_center, &g_dvl_bd.time_to_last_good_vel_s); if ( ret != 5 ) { printf("BE Error: sscanf data resolved count %d\n", ret); return; } printf("BS - ED: %f, \n" " ND: %f, \n" " UD: %f, \n" " RC: %f, \n" " TL: %f, \n", g_dvl_bd.east_dis_m, g_dvl_bd.north_dis_m, g_dvl_bd.upward_dis_m, g_dvl_bd.range_to_center, g_dvl_bd.time_to_last_good_vel_s); }
C
/*=============== * 静态链表去重 * * 包含算法: 2.17 ================*/ #include "Difference.h" /* * ████████ 算法2.17 ████████ * * S = (A-B)∪(B-A) * * 对集合A和集合B进行(A-B)∪(B-A)计算,计算结果存入静态链表S * * *【备注】 * * 教材中默认从控制台读取数据。 * 这里为了方便测试,避免每次运行都手动输入数据, * 因而允许选择从预设的文件path中读取测试数据。 * * 如果需要从控制台读取数据,则path为NULL或者为空串, * 如果需要从文件中读取数据,则需要在path中填写文件名信息。 */ void difference(SLinkList space, int* S, char* path) { int m, n; // 集合A和集合B中元素数量 int j; // 循环计数器 int R; // 指向静态链表最后一个结点 int i, k, p; int b; // 临时存储从集合B中读到的数据 FILE* fp; int readFromConsole; // 是否从控制台读取数据 // 如果没有文件路径信息,则从控制台读取输入 readFromConsole = path == NULL || strcmp(path, "") == 0; // 初始化备用空间 InitSpace(space); // 获取静态链表头结点 *S = Malloc(space); // 让R执行静态链表最后的结点 R = *S; // 读取集合A和集合B的元素个数 if(readFromConsole) { printf("请输入集合A的元素个数:"); scanf("%d", &m); printf("请输入集合B的元素个数:"); scanf("%d", &n); } else { // 打开文件,准备读取测试数据 fp = fopen(path, "r"); if(fp == NULL) { exit(ERROR); } ReadData(fp, "%d%d", &m, &n); } if(readFromConsole) { printf("请输入 %d 个元素存入集合A:", m); } // 录入集合A的数据 for(j = 1; j <= m; ++j) { // 分配结点 i = Malloc(space); // 输入集合A的元素值 if(readFromConsole) { scanf("%d", &space[i].data); } else { ReadData(fp, "%d", &space[i].data); } // 将新结点插入到表尾 space[R].cur = i; R = i; } // 尾结点的指针置空 space[R].cur = 0; if(readFromConsole) { printf("请输入 %d 个元素存入集合B:", n); } // 录入集合B的数据 for(j = 1; j <= n; ++j) { // 输入集合B的元素值 if(readFromConsole) { scanf("%d", &b); } else { ReadData(fp, "%d", &b); } p = *S; // 指向静态链表头结点,后续总是指向k的前一个位置 k = space[*S].cur; // 指向静态链表中的首个元素 // 在当前静态链表中查找是否存在b元素 while(k != space[R].cur && space[k].data != b) { p = k; k = space[k].cur; } // 如果该元素不存在,则加入静态链表 if(k == space[R].cur) { i = Malloc(space); space[i].data = b; space[i].cur = space[R].cur; space[R].cur = i; // 如果该元素已存在,则需要移除 } else { space[p].cur = space[k].cur; Free(space, k); if(R == k) { R = p; } } } if(!readFromConsole) { fclose(fp); } }
C
#ifndef RYAN_CS_H_ #define RYAN_CS_H_ #include "ryan_s.c" #endif /* RYAN_CS_H_ */ #define MAX 1024 int main(int argc, char** argv) { int listenfd, connfd; char rev[100],sendline[MAX]; int max = 100, rev_len; if(argc < 2){ printf("usage: ./s <port>\n"); return 0; } listenfd = ryan_server_start(atoi(argv[1]), 10); while(1){//循环等待端链接 if(listenfd != -1){ connfd = ryan_server_accept(listenfd); } while(connfd > -1){//每一个链接接受多次发送 rev_len = ryan_server_recv(connfd, rev, max); if (rev_len < 1) { break; }else{ printf("Rev:%s", rev); printf("Send:"); fgets(sendline, MAX, stdin); ryan_server_send(connfd, sendline); } } } ryan_server_close(listenfd, connfd); return 0; } void ryan_server_listen_err(int err_no) { printf("listen error \n"); } void ryan_server_accept_error(int err_no) { printf("accept error\n"); } void ryan_server_before_accept(void) { printf("========Hello Im ready for you connect=========\n"); } void ryan_server_after_accept(int listenfd) { printf("welcome!\n"); }