language
large_string
text
string
C
#ifndef __PI_BITSUPPORT_H__ #define __PI_BITSUPPORT_H__ // some simple bit manipulation functions: helps make code clearer. // set x[bit]=0 (leave the rest unaltered) and return the value static inline uint32_t bit_clr(uint32_t x, unsigned bit) { assert(bit<32); return x & ~(1<<bit); } // set x[bit]=1 (leave the rest unaltered) and return the value static inline uint32_t bit_set(uint32_t x, unsigned bit) { assert(bit<32); return x | (1<<bit); } // is x[bit] == 1? static inline unsigned bit_isset(uint32_t x, unsigned bit) { assert(bit<32); return (x >> bit) & 1; } // extract bits [lb:ub] (inclusive) static inline uint32_t bits_get(uint32_t x, unsigned lb, unsigned ub) { assert(lb <= ub); assert(ub < 32); unsigned n = ub-lb+1; return ((x >> lb) & ((1<<n)-1)); } // set bits[off:n]=0, leave the rest unchanged. static inline uint32_t bits_clr(uint32_t x, unsigned lb, unsigned ub) { assert(lb <= ub); assert(ub < 32); unsigned n = ub-lb+1; unsigned mask = (1 << n) - 1; return x & ~(mask << lb); } // set bits [lb:ub] to v (inclusive) static inline uint32_t bits_set(uint32_t x, unsigned lb, unsigned ub, uint32_t v) { assert(lb <= ub); assert(ub < 32); unsigned n = ub-lb+1; assert((v >> n) == 0); return bits_clr(x, lb, ub) | (v << lb); } // bits [lb:ub] == <val? static inline unsigned bits_eq(uint32_t x, unsigned lb, unsigned ub, uint32_t val) { assert(lb <= ub); assert(ub < 32); unsigned n = ub-lb+1; assert(val < (1ULL<<n)); return bits_get(x, lb, ub) == val; } #endif
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* main.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: mintran <[email protected]> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2018/07/18 16:44:11 by mintran #+# ## ## #+# */ /* Updated: 2018/07/18 21:10:08 by mintran ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include <stdio.h> #include "../ex00/ft_create_elem.c" #include "../ex02/ft_list_push_front.c" #include "ft_list_clear.c" #include "ft_list.h" int main(void) { t_list *list; int x; int y; x = 101; y = 42; list = ft_create_elem(&x); ft_list_push_front(&list, &y); ft_list_push_front(&list, &x); ft_list_push_front(&list, &y); printf("%p = [%d\t| %p]\n", list, *(int*)(list->data), list->next); list = list->next; printf("%p = [%d\t| %p]\n", list, *(int*)(list->data), list->next); list = list->next; printf("%p = [%d\t| %p]\n", list, *(int*)(list->data), list->next); ft_list_push_front(&list, 0); ft_list_push_front(0, &y); ft_list_push_front(0, 0); ft_list_clear(&list); //printf("%p = [%d\t| %p]\n", list, *(int*)(list->data), list->next); list = list->next; //printf("%p = [%d\t| %p]\n", list, *(int*)(list->data), list->next); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "libtime.h" #include "liberrmsg.h" static char HMSG[]= {"\ Description: Calculate dt for {D T - F Y}, return value is in seconds.\n\ Usage: %-6s (-Dyyyy/mm/dd | -Jyyyy/ddd)\n\ (-Thh:mm:ss.sss)\n\ (-Fyyyy/mm/dd | -Kyyyy/ddd)\n\ (-Yhh:mm:ss.sss)\n\ [-H]\n\ \n\ (-D|-J) Date1\n\ (-T) Time1\n\ (-F|-K) Date1\n\ (-Y) Time1\n\ [-H] Display this message.\n\ \n\ NOTE: Return value is t1 - t2. \n\ "}; int main(int argc, char const *argv[]) { Time t1,t2; int i; int kt1d = NO, kt1jd = NO, kt1t = NO; int kt2d = NO, kt2jd = NO, kt2t = NO; float Dt; long long int dSecs; int dMsec; memset(t1.KDATE,0,16); memset(t1.KTIME,0,16); memset(t1.KJD ,0,16); memset(t2.KDATE,0,16); memset(t2.KTIME,0,16); memset(t2.KJD ,0,16); for(i = 1; i < argc; ++i) { if (argv[i][0] == '-') { switch(argv[i][1]) { case 'D': memcpy(t1.KDATE,argv[i]+2,15); kt1d = YES; break; case 'J': memcpy(t1.KJD,argv[i]+2,15); kt1jd = YES; break; case 'T': memcpy(t1.KTIME,argv[i]+2,15); kt1t = YES; break; /// case 'F': memcpy(t2.KDATE,argv[i]+2,15); kt2d = YES; break; case 'K': memcpy(t2.KJD,argv[i]+2,15); kt2jd = YES; break; case 'Y': memcpy(t2.KTIME,argv[i]+2,15); kt2t = YES; break; /// case 'H': fprintf(stderr, HMSG, argv[0]); exit(0); default: break; } } } if( ( (kt1d + kt1jd) != YES ) || kt1t != YES || ( (kt2d + kt2jd) != YES ) || kt2t != YES ) { perrmsg("",ERR_MORE_ARGS); fprintf(stderr, HMSG, argv[0]); exit(0); } //Read Date and Time if(kt1d == YES) rtime(&t1); else if(kt1jd == YES) rtimej(&t1); if(kt2d == YES) rtime(&t2); else if(kt2jd == YES) rtimej(&t2); if(!judge(&t1) || !judge(&t2)) { exit(1); } Dt = dt(&t1,&t2, &dSecs, &dMsec); if(Dt < 0) printf("%lld sec %d msec\n", dSecs, dMsec); else printf("%lld sec %d msec\n", dSecs, dMsec); return 0; }
C
void triangulo (int n); int main () { int n; triangulo (n); return 0; }
C
#include<stdio.h> int main() { int number1, number2; int flag; //ƴϢ char ch; scanf("%d", &number1); flag = 1; while ((ch = getchar()) != '=') { scanf("%d", &number2); switch (ch) { case '+': number1 += number2; break; case '-': number1 -= number2; break; case '*': number1 *= number2; break; case '/': if (number2 == 0) //Ϊ0޸flagΪ0switch { flag = 0; break; } else { number1 /= number2; break; } default: flag = 0; break; //switch } } if (flag == 0) { printf("ERROR"); } else { printf("%d", number1); } return 0; }
C
#include <stdio.h> #include <stdbool.h> #include <stdlib.h> // Ķͷ ־ ڿ const ־ϴ. Ϸ ڿ ؼ ϼ. bool solution(const char* s) { bool answer = true; int len = strlen(s); if (len != 4 && len != 6) return false; for (int i = 0; i < len; i++) { if (s[i] >= '0' && s[i] <= '9') { continue; } else answer = false; break; } return answer; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* init_pages.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sbres <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2014/04/18 16:03:14 by sbres #+# #+# */ /* Updated: 2014/04/20 19:36:34 by sbres ### ########.fr */ /* */ /* ************************************************************************** */ #include "malloc.h" #include <unistd.h> #include <sys/mman.h> static void define_zones(int *tiny_page, int *medium_page) { int page_size; page_size = getpagesize(); *tiny_page = page_size * 2; *medium_page = page_size * 8; } void init_pages(void) { void *tiny_ptr; void *medium_ptr; define_zones(&pages.tiny_page_size, &pages.medium_page_size); tiny_ptr = mmap(NULL, pages.tiny_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); medium_ptr = mmap(NULL, pages.medium_page_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); pages.tiny = NULL; pages.medium = NULL; pages.big = NULL; new_block(pages.tiny_page_size, tiny_ptr, 1, &pages.tiny); new_block(pages.medium_page_size, medium_ptr, 1, &pages.medium); }
C
#include "libft.h" void ft_vecresize(t_vector *vec) { char *tmp; if (!vec || !(tmp = (char*)malloc(vec->max * 2 + 1))) return ; ft_memmove(tmp, vec->arr, vec->len); *(tmp + vec->len + 1) = 0; free(vec->arr); vec->arr = tmp; vec->max *= 2; }
C
#include <stdlib.h> #include <time.h> #include <stdio.h> /* more headers goes there */ /** *main-use print *Return: print ten numbers from zero */ /* betty style doc for function main goes there */ int main(void) { int count; /* your code goes there */ for (count = 0; count < 10; count++) { printf("%d", count); } printf("\n"); return (0); }
C
#include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include "Constraint.c" #include <string.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> void writeToFile(char text[]){ FILE *fptr; fptr = fopen("placer.txt","w"); if(fptr == NULL) { printf("Error!"); exit(1); } fprintf(fptr,"%s",text); fclose(fptr); } char *str_replace(char *orig, char *rep, char *with) { char *result; char *ins; char *tmp; int len_rep; int len_with; int len_front; int count; if (!orig || !rep) return NULL; len_rep = strlen(rep); if (len_rep == 0) return NULL; if (!with) with = ""; len_with = strlen(with); ins = orig; for (count = 0; tmp = strstr(ins, rep); ++count) { ins = tmp + len_rep; } tmp = result = malloc(strlen(orig) + (len_with - len_rep) * count + 1); if (!result) return NULL; ins = strstr(orig, rep); len_front = ins - orig; tmp = strncpy(tmp, orig, len_front) + len_front; tmp = strcpy(tmp, with) + len_with; orig += len_front + len_rep; strcpy(tmp, orig); return result; } int main(){ FILE *fptr; fptr = fopen("placer.txt","w"); fclose(fptr); int fd; char text[BUFF]; int wordCount , sentenceCount; mkfifo(FIFO_PLACER_PATH, 0666); fd = open(FIFO_PLACER_PATH, O_RDONLY); read(fd, &wordCount, sizeof(int)); char words[wordCount][BUFF]; for (int i = 0; i < wordCount; ++i) { read(fd,words[i], sizeof(words[i])); } mkfifo(FIFO_PLACER_PATH_MP, 0666); fd = open(FIFO_PLACER_PATH_MP, O_RDONLY); char sentence[BUFF]; read(fd,sentence, sizeof(sentence)); char * str; int j = 0; while ((str = strstr(sentence,"$"))){ memcpy(sentence,str_replace(sentence,"$",words[j++]) , sizeof(sentence)); } writeToFile(sentence); close(fd); mkfifo(FIFO_PLACER_PATH_MP, 0666); fd = open(FIFO_PLACER_PATH_MP, O_WRONLY); write(fd,sentence,sizeof(sentence)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <math.h> /* The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? */ //http://www.puzzles9.com/how-to-find-prime-numbers-how-to-check-if-a-number-is-prime/ int is_prime(long number) { long sqrt_num = (long) ceil(sqrtl((long double) number)); for (long i=2; i<= sqrt_num; i++) { if (number % i == 0) { return 0; } } return 1; } // This ends up searching double, since it finds the answer value in 'i' first, but it's // only checking the output value. Naive solution needs much improvement, look into sqrt method void compute(void) { long ans = 0; long large_num = 600851475143; printf("Starting at %ld\n", large_num); for (double i=2.0; i < large_num/2; i++) { double output = large_num / i; if (output == (long) output) { printf("Factors at %f and %f\n", output, i); if (is_prime((long) output)) { printf("Found prime\n"); ans = (long) output; break; } } } printf("Answer is %ld\n", ans); } int main(int argc, char* argv[]) { time_t start = time(NULL); compute(); time_t end = time(NULL); printf("Finished in %ld seconds\n", (end -start)); return 0; }
C
#include <stdlib.h> #include <string.h> #include <stdio.h> #include "Interface.h" int main(void) { FILE *fp = fopen("out.txt", "w"); struct Interface *pInterfaceA = 0, *pInterfaceB = 0; struct Interface *pInterfaceA_2 = 0, *pInterfaceB_2 = 0; printf("This is OO-like C program test\n"); if (!fp) { printf("Error opening .txt file!\n"); system("pause"); } //#define LOG(str, ...) printf(str, __VA_ARGS__) #define LOG(str, ...) fprintf(fp, str, __VA_ARGS__) printf("====================visual function and abstract class in C===================\n" "=== create-on-demand version ===\n"); pInterfaceA = createInterface(EImpType_A); pInterfaceB = createInterface(EImpType_B); pInterfaceA_2 = createInterface(EImpType_A); pInterfaceB_2 = createInterface(EImpType_B); pInterfaceA->enter(pInterfaceA, 65); pInterfaceA->execute(pInterfaceA, "A is here!"); pInterfaceA->exit(pInterfaceA); pInterfaceB->enter(pInterfaceB, 66); pInterfaceB->execute(pInterfaceB, "B is here!"); pInterfaceB->exit(pInterfaceB); destroyInterface(&pInterfaceA, EImpType_A); destroyInterface(&pInterfaceB, EImpType_B); destroyInterface(&pInterfaceA_2, EImpType_A); destroyInterface(&pInterfaceB_2, EImpType_B); printf("\n\n=== static version (Singleton) ===\n"); pInterfaceA = initStaticInterface(EImpType_A); pInterfaceB = initStaticInterface(EImpType_B); pInterfaceA->enter(pInterfaceA, 65); pInterfaceA->execute(pInterfaceA, "A is here!"); pInterfaceA->exit(pInterfaceA); pInterfaceB->enter(pInterfaceB, 66); pInterfaceB->execute(pInterfaceB, "B is here!"); pInterfaceB->exit(pInterfaceB); uninitStaticInterface(&pInterfaceA, EImpType_A); uninitStaticInterface(&pInterfaceB, EImpType_B); printf("\n\n\n"); fclose(fp); getchar(); return 0; }
C
#include <stdio.h> #include<string.h> int main() { int length,i,j; scanf("%d",&length); char str[length+1]; scanf("\n%[^\n]s",str); for(i=0;str[i];i++){ if(str[i]=='a' ||str[i]=='e'||str[i]=='i'||str[i]=='o'||str[i]=='u'){ for(j=i+1;str[j];j++){ str[j-1]=str[j]; } str[j-1]='\0'; } } length=strlen(str); j=length-1; for(i=0;i<j;i++){ char tmp=str[i]; str[i]=str[j]; str[j]=tmp; j--; } printf("%s\n",str); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fork_execve.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mdambrev <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/26 18:47:27 by mdambrev #+# #+# */ /* Updated: 2018/10/29 16:09:59 by mdambrev ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "includes/libft.h" #include <stdio.h> #include <sys/types.h> #include <sys/time.h> #include <sys/resource.h> #include <sys/wait.h> int get_fork(char *bin_path, char **cmd_tab) { pid_t pid; int status; struct rusage *rusage; pid = fork(); if(pid > 0) wait4(0, &status, 0, rusage); else execv(bin_path, cmd_tab); return(0); } int fork_execv(char *cmd) { char **cmd_tab; char *tab[5]; char *bin_path; tab[0] = "ls"; tab[1] = "mkdir"; tab[2] = "pwd"; tab[3] = NULL; cmd_tab = ft_strsplit(cmd, ' '); if(if_exist_in_tab(tab, cmd_tab[0])) bin_path = ft_strjoin("/bin/", cmd_tab[0]); else return(-1); get_fork(bin_path, cmd_tab); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #include "lift.h" #include "si_ui.h" // Unfortunately the rand() function is not thread-safe. However, the // rand_r() function is thread-safe, but need a pointer to an int to // store the current state of the pseudo-random generator. This // pointer needs to be unique for every thread that might call // rand_r() simultaneously. The functions below are wrappers around // rand_r() which should work in the environment encountered in // assignment 3. // static unsigned int rand_r_state[MAX_N_PERSONS]; // Get a random value between 0 and maximum_value. The passenger_id // parameter is used to ensure that the rand_r() function is called in // a thread-safe manner. sem_t init_passenger; static int get_random_value(int passenger_id, int maximum_value) { return rand_r(&rand_r_state[passenger_id]) % (maximum_value + 1); } static lift_type Lift; // Initialize the random seeds used by the get_random_value() function // above. static void init_random(void) { int i; for(i=0; i < MAX_N_PERSONS; i++){ // Use this statement if the same random number sequence // shall be used for every execution of the program. rand_r_state[i] = i; // Use this statement if the random number sequence // shall differ between different runs of the // program. (As the current time (as measured in // seconds) is used as a seed.) //rand_r_state[i] = i+time(NULL); } } static void *lift_thread(void *unused) { int floor_init = 0; int direction_init = 0; int* next_floor = &floor_init; int* change_direction = &direction_init; while(1){ lift_next_floor(Lift, next_floor, change_direction); lift_move(Lift, *next_floor, *change_direction); lift_has_arrived(Lift); } return NULL; } static void *passenger_thread(void *idptr) { // Code that reads the passenger ID from the idptr pointer // (due to the way pthread_create works we need to first cast // the void pointer to an int pointer). int *tmp = (int *) idptr; int id = *tmp; sem_post(&init_passenger); int to_floor=0, from_floor=0; while(1){ // * Select random floors to_floor = get_random_value(id, N_FLOORS-1); from_floor = get_random_value(id, N_FLOORS-1); if(to_floor != from_floor) { if(enter_floor(Lift,id,from_floor)){ // * Travel between these floors lift_travel(Lift,id,from_floor,to_floor); } // * Wait a little while usleep(5000000); } } return NULL; } static void *user_thread(void *unused) { int init_id = 0; int* current_passenger_id = &init_id; char message[SI_UI_MAX_MESSAGE_SIZE]; pthread_t thread_handle[MAX_N_PERSONS]; si_ui_set_size(670, 700); sem_init(&init_passenger,0,0); while(1){ // Read a message from the GUI si_ui_receive(message); if(!strcmp(message, "new")){ // create a new passenger if possible, else // use si_ui_show_error() to show an error // message if too many passengers have been // created. Make sure that each passenger gets // a unique ID between 0 and MAX_N_PERSONS-1. if(*current_passenger_id != MAX_N_PERSONS-1) { pthread_create(&thread_handle[*current_passenger_id], NULL, passenger_thread,(void*)current_passenger_id); sem_wait(&init_passenger); (*current_passenger_id)++; } else { si_ui_show_error("To many persons!"); } }else if(!strcmp(message, "exit")){ lift_delete(Lift); exit(0); } } return NULL; } int main(int argc, char **argv) { si_ui_init(); init_random(); Lift = lift_create(); pthread_t lift_thread_handle; pthread_t user_thread_handle; pthread_create(&lift_thread_handle, NULL, lift_thread, 0); pthread_create(&user_thread_handle, NULL, user_thread, 0); pthread_join(lift_thread_handle, NULL); pthread_join(user_thread_handle, NULL); //int i; //for(i=0; i<MAX_N_PERSONS; i++) // { // pthread_join(thread_handle[i], NULL); //} return 0; }
C
#include <iostream> using namespace std; int main() { char ch; while(true) { cin.get(ch); if(!cin) break; cout << ch; } return 0; }
C
/***************************************************** * * * spin button * * * * GTK+ 3 * * Versao: 1.0 * * Samuel Eleuterio 2015 * * * *****************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <gtk/gtk.h> GtkWidget *entry1, *spin1, *label1; gboolean func_button1 (GtkWidget *w , gpointer data ) { gdouble x1 ; gchar str1[16] ; x1 = gtk_spin_button_get_value (GTK_SPIN_BUTTON(spin1)); sprintf (str1, "%.2lf", x1); gtk_label_set_text (GTK_LABEL(label1), str1); return FALSE; } GtkWidget * create_spin_button (void) { GtkWidget *spinButton ; GtkAdjustment *adj1 ; adj1 = (GtkAdjustment *) gtk_adjustment_new (1.0, -10.0, 31.0, 0.5, 5.0, 0); spinButton = gtk_spin_button_new (adj1, 0, 0); gtk_spin_button_set_numeric (GTK_SPIN_BUTTON(spinButton), TRUE); gtk_spin_button_set_digits (GTK_SPIN_BUTTON(spinButton), 2); gtk_widget_set_size_request (spinButton, 150, 30); return spinButton; } int main (int argc, char **argv) { GtkWidget *window, *vbox, *hbox0, *hbox1, *hbox2, *button1, *label0 ; gtk_init (&argc, &argv); window = gtk_window_new (GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size (GTK_WINDOW(window), 450, 300); gtk_widget_set_size_request (window, 400, 250); gtk_window_set_title (GTK_WINDOW(window), "GTK3-Ex: SpinButtun"); gtk_window_set_position (GTK_WINDOW(window), GTK_WIN_POS_CENTER); g_signal_connect_swapped (G_OBJECT(window), "destroy", G_CALLBACK(gtk_main_quit), NULL); vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 0); gtk_container_add (GTK_CONTAINER(window), vbox); /* label, button */ //label0 = gtk_label_new ("Spin Button\nSe carregar usando a tecla do meio\nAvança de 'page_increment'"); label0 = gtk_label_new ("Spin Button"); gtk_box_pack_start (GTK_BOX (vbox), label0, FALSE, TRUE, 10); label0 = gtk_label_new ("Teclas do rato a usar:"); gtk_box_pack_start (GTK_BOX (vbox), label0, FALSE, TRUE, 0); label0 = gtk_label_new ("Esquerda: Recua/Avança normal"); gtk_box_pack_start (GTK_BOX (vbox), label0, FALSE, TRUE, 0); label0 = gtk_label_new ("Central: Recua/Avança uma página"); gtk_box_pack_start (GTK_BOX (vbox), label0, FALSE, TRUE, 0); label0 = gtk_label_new ("Direita: Início/Fim "); gtk_box_pack_start (GTK_BOX (vbox), label0, FALSE, TRUE, 0); hbox0 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_set_homogeneous (GTK_BOX(hbox0), TRUE); gtk_box_pack_start (GTK_BOX (vbox), hbox0, FALSE, TRUE, 50); spin1 = create_spin_button (); gtk_box_pack_start (GTK_BOX (hbox0), spin1, TRUE, FALSE, 10); hbox2 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 0); gtk_box_set_homogeneous (GTK_BOX(hbox2), TRUE); gtk_box_pack_end (GTK_BOX (vbox), hbox2, FALSE, TRUE, 20); label1 = gtk_label_new ("Value"); gtk_box_pack_start (GTK_BOX (hbox2), label1, FALSE, TRUE, 20); hbox1 = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 20); gtk_box_set_homogeneous (GTK_BOX(hbox1), TRUE); gtk_box_pack_end (GTK_BOX (vbox), hbox1, FALSE, TRUE, 10); button1 = gtk_button_new_with_label ("Spin Value"); gtk_widget_set_size_request (button1, 150, 30); g_signal_connect (button1, "clicked", G_CALLBACK (func_button1), NULL); gtk_box_pack_start (GTK_BOX (hbox1), button1, TRUE, FALSE, 10); gtk_widget_show_all (window); gtk_main (); return 0; }
C
#include "MDR_HSRPRP_ProxyTable.h" #include <MDR_Ethernet_FrameDefs.h> #include "MDR_HSRPRP_Config.h" typedef union { uint32_t loMAC32; uint16_t hiMAC16; uint16_t busy; uint32_t timeRX; } MDR_ProxyItemMAC; MDR_ProxyItemMAC _TableMAC[HSR_ProxyNodeTableMaxEntries]; bool MDR_ProxyTable_HasMAC(uint8_t *MAC, uint32_t timeRX) { uint32_t i; uint32_t loMAC32 = *(uint32_t *)MAC; uint16_t hiMAC16 = *(uint16_t *)&MAC[4]; for (i = 0; i < HSR_ProxyNodeTableMaxEntries; ++i) if (_TableMAC[i].busy) if ((loMAC32 == _TableMAC[i].loMAC32) && (hiMAC16 == _TableMAC[i].hiMAC16)) { _TableMAC[i].timeRX = timeRX; return true; } return false; } bool MDR_ProxyTable_AddMac(uint8_t *MAC, uint32_t timeRX) { uint32_t i; for (i = 0; i < HSR_ProxyNodeTableMaxEntries; ++i) if (!_TableMAC[i].busy) { _TableMAC[i].loMAC32 = *(uint32_t *)MAC; _TableMAC[i].hiMAC16 = *(uint16_t *)&MAC[4]; _TableMAC[i].timeRX = timeRX; _TableMAC[i].busy = true; return true; } return false; } void MDR_ProxyTable_ProcessForget(uint32_t timeNow, uint32_t forgetTime) { uint32_t i; for (i = 0; i < HSR_ProxyNodeTableMaxEntries; ++i) if (_TableMAC[i].busy && (timeNow - _TableMAC[i].timeRX) > forgetTime) _TableMAC[i].busy = false; }
C
#include<stdio.h> #include<math.h> #define tol .0001 float g(float x) { return 1/(sqrt(1+x)); } int main() { int i=1; float x,x1,x2; printf("Enter the value of x1\n"); scanf("%f", &x1); printf("x1\t\t x2\t\t g1\n"); do{ x2=x1; x1=g(x1); i++; printf("%f\t %f\t %f\n",x2,x1,g(x1)); } while(fabs(x1-x2)<tol); printf("i=%d\n x1=%f",i,x1); return 0; }
C
#ifndef __FT_PRINTF_H # define __FT_PRINTF_H # include "libft.h" # include <stdarg.h> # include <stdlib.h> # include <stdbool.h> # include <limits.h> # define error -1 # define BUFFER_SIZE 4096 typedef struct s_flags { bool flag_plus; bool flag_less; bool flag_space; bool flag_zero; bool flag_sharp; } t_flags; typedef struct s_modifier { bool hh; bool h; bool l; bool ll; bool j; bool z; } t_modifier; typedef struct s_type { bool s; bool big_s; bool p; bool d; bool big_d; bool i; bool o; bool big_o; bool u; bool big_u; bool x; bool big_x; bool c; bool big_c; } t_type; typedef struct s_core { char buffer[BUFFER_SIZE]; int padding; int precision; int fd; struct s_flags *t_flags; struct s_modifier *t_modifier; struct s_type *t_type; } t_core; /* ** MODIFIER function */ void ft_jump_i_to_next(t_core *core, int *i); bool ft_is_a_modifier(char *str, t_core *core, int i); void ft_modifier(char *str, int *i, t_core *core); /* ** PRECISION function */ int ft_return_rank(int nb); void ft_precision(char *str, int *i, t_core *core); /* ** FLAGS function */ void ft_flag(char *str, int *i, t_core *core); /* ** CORE function */ void ft_core(t_core *core, char *str); void reset_buffer(t_core *core, size_t len); /* ** printf & dprinf function */ int ft_printf(const char *str, ...); int ft_dprintf(int fd, const char *str, ...); #endif
C
#include<stdio.h> void main() { int i,j,k,n,count = 0; char ch = 'a'; printf("enter the number of rows to print\n"); scanf("%d",&n); for(i = 1 ; i <= n ; i++) { for(j = 1 ; j <= n-i ; j++) { printf(" "); } for(k = 1 ; k <= i ; k++) { printf("*"); if(i>1 && count<i) { printf("%c",ch++); count++; } } ch = 'a'; // this line used when you want to print every row from alphabet 'a' printf("\n"); count = 1; } }
C
/* I used this program to brute force the 5/8 voltage divider */ /* needed by the i2c chip as my hand-attempts never worked right */ #include <stdio.h> #include <math.h> #define NUMBER 48 double values[NUMBER]={ 100.0,110.0,120.0,130.0,150.0,160.0,180.0, 200.0,220.0,240.0,270.0, 300.0,330.0,360.0,390.0, 430.0,470.0, 510.0,560.0, 620.0,680.0, 750.0, 820.0, 910.0, 1000.0,1100.0,1200.0,1300.0,1500.0,1600.0,1800.0, 2000.0,2200.0,2400.0,2700.0, 3000.0,3300.0,3600.0, 4300.0,4700.0, 5100.0,5600.0, 6200.0,6800.0, 7500.0, 8200.0, 9100.0, 10000.0, }; int main(int argc, char **argv) { int i,j; double divide; for(i=0;i<NUMBER;i++) { for(j=0;j<NUMBER;j++) { divide=values[i]/(values[i]+values[j]); if (fabs(divide-(5.0/8.0))<0.01) { printf("%lf = %lf (%lf %lf)\n",(5.0/8.0), divide,values[i],values[j]); } } } return 0; }
C
#include "decls.h" #include <stdbool.h> #define LEFT_SHIFT 16 /** * Handler para el timer (IRQ0). Escribe un carácter cada segundo. */ static const uint8_t hz_ratio = 18; // Default IRQ0 freq (18.222 Hz). void timer() { static char chars[81]; static unsigned ticks; static int8_t line = 20; static uint8_t idx = 0; if (++ticks % hz_ratio == 0) { chars[idx] = '.'; chars[++idx] = '\0'; vga_write(chars, line, 0x07); } if (idx >= sizeof(chars)) { line++; idx = 0; } } /** * Mapa de "scancodes" a caracteres ASCII en un teclado QWERTY. */ /* KBDUS means US Keyboard Layout. This is a scancode table * used to layout a standard US keyboard. I have left some * comments in to give you an idea of what key is what, even * though I set it's array index to 0. You can change that to * whatever you want using a macro, if you wish! */ unsigned char kbdus[180] = { 0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */ '9', '0', '-', '=', '\b', /* Backspace */ '\t', /* Tab */ 'q', 'w', 'e', 'r', /* 19 */ 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', /* Enter key */ 0, /* 29 - Control */ 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */ '\'', '`', LEFT_SHIFT, /* Left shift */ '\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */ 'm', ',', '.', '/', 0, /* Right shift */ '*', 0, /* Alt */ ' ', /* Space bar */ 0, /* Caps lock */ 0, /* 59 - F1 key ... > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, /* < ... F10 */ 0, /* 69 - Num lock*/ 0, /* Scroll Lock */ 0, /* Home key */ 0, /* Up Arrow */ 0, /* Page Up */ '-', 0, /* Left Arrow */ 0, 0, /* Right Arrow */ '+', 0, /* 79 - End key*/ 0, /* Down Arrow */ 0, /* Page Down */ 0, /* Insert Key */ 0, /* Delete Key */ 0, 0, 0, 0, /* F11 Key */ 0, /* F12 Key */ 0, /* All other keys are undefined */ 0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */ // Chars when shift is being held '9', '0', '-', '=', '\b', /* Backspace */ '\t', /* Tab */ 'Q', 'W', 'E', 'R', /* 19 */ 'T','Y','U','I','O','P', '[', ']', '\n', /* Enter key */ 0, /* 29 - Control */ 'A','S','D','F','G','H','J','K','L', ';', /* 39 */ '\'', '`', LEFT_SHIFT, /* Left shift */ '\\', 'Z','X','C','V','B','N', 'M', ',', '.', '/', 0, /* Right shift */ '*', 0, /* Alt */ ' ', /* Space bar */ 0, /* Caps lock */ 0, /* 59 - F1 key ... > */ 0, 0, 0, 0, 0, 0, 0, 0, 0, /* < ... F10 */ 0, /* 69 - Num lock*/ 0, /* Scroll Lock */ 0, /* Home key */ 0, /* Up Arrow */ 0, /* Page Up */ '-', 0, /* Left Arrow */ 0, 0, /* Right Arrow */ '+', 0, /* 79 - End key*/ 0, /* Down Arrow */ 0, /* Page Down */ 0, /* Insert Key */ 0, /* Delete Key */ 0, 0, 0, 0, /* F11 Key */ 0, /* F12 Key */ 0, /* All other keys are undefined */ }; static const uint8_t KBD_PORT = 0x60; /** * Handler para el teclado (IRQ1). * * Imprime la letra correspondiente por pantalla. */ static bool shift_pressed = false; void keyboard() { uint8_t code; static char chars[81]; static uint8_t idx = 0; asm volatile("inb %1,%0" : "=a"(code) : "n"(KBD_PORT)); /* If the top bit of the byte we read from the keyboard is * set, that means that a key has just been released */ if (code & 0x80) { // key released code = code & 0x7F; // turn off bit 7 if (kbdus[code] == LEFT_SHIFT) { shift_pressed = false; } } else { // key pressed if (idx == 80) { while (idx--) chars[idx] = ' '; } if (kbdus[code] == LEFT_SHIFT) { shift_pressed = true; return; } if (shift_pressed) { code += 90; // go to uppercase, there are 180 chars on kdbus, 90 without shift and 90 with shift held } chars[idx++] = kbdus[code]; vga_write(chars, 19, 0x0A); } }
C
#include <sys/socket.h> /* socket definitions */ #include <sys/types.h> /* socket types */ #include <arpa/inet.h> /* inet (3) funtions */ #include <netdb.h> //gethostbyname, ecc #include <stdio.h> //input-output printf #include <string.h> //operazioni sulle stringhe (strcmp) #include <stdlib.h> //exit #include <unistd.h> //misc unix - esempio close #include <signal.h> //per segnali #include "struttura.h" #include "mappa.h" #define DIM (1000) //Variabili Globali char *porta; //porta server char *indirizzo; //indirizzo server //Prototipi void analisiArgomenti(int argc, char *argv[]); void messaggioTerminazione(int sig); void messPipe(int sig); int main(int argc, char *argv[]) { //Variabili int conn_sock; //socket connessione struct sockaddr_in serv_addr; //indirizzo server struct hostent *hp; //per risoluzione indirizzo char buff[DIM]; //buffer per lettura int opzione; //opzione MENU int numeroPosti; posto p; //per cicli posto *lista; //lista posti dinamica int i; //contatore char *map; //contenitore mappa int codice; //codice prenotazione int nonValido; int responso; //responso server hp=NULL; //nullo per gethostbyname lista=NULL; //nullo per realloc struct sigaction signal_terminazione, signal_pipe; sigfillset(&signal_terminazione.sa_mask); signal_terminazione.sa_handler=messaggioTerminazione; signal_terminazione.sa_flags=0; sigfillset(&signal_pipe.sa_mask); signal_pipe.sa_handler=messPipe; signal_pipe.sa_flags=0; //SEGNALI - Principali Segnali di terminazione e SIGPIPE if (sigaction(SIGINT, &signal_terminazione, NULL) == -1) {printf("Errore sigaction\n"); exit(1);} if (sigaction(SIGHUP, &signal_terminazione, NULL) == -1) {printf("Errore sigaction\n"); exit(1);} if (sigaction(SIGTERM, &signal_terminazione, NULL) == -1) {printf("Errore sigaction\n"); exit(1);} if (sigaction(SIGQUIT, &signal_terminazione, NULL) == -1) {printf("Errore sigaction\n"); exit(1);} if (sigaction(SIGABRT, &signal_terminazione, NULL) == -1) {printf("Errore sigaction\n"); exit(1);} if (sigaction(SIGPIPE, &signal_pipe, NULL) == -1) {printf("Errore sigaction\n"); exit(1);} //Start analisiArgomenti(argc, argv); printf("Connessione al server %s sulla porta %s\n", indirizzo, porta); //Socket if ((conn_sock=socket(AF_INET, SOCK_STREAM,0)) < 0) { printf("Errore nella creazione del socket\n"); exit(1); } //Indirizzo memset(&serv_addr, 0, sizeof(serv_addr)); //Settaggio tutti i byte a zero serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(atoi(porta)); if ( inet_aton(indirizzo, &serv_addr.sin_addr) <= 0 ) //IP o risoluzione { printf("client: indirizzo IP non valido.\nclient: risoluzione nome..."); if ((hp=gethostbyname(indirizzo)) == NULL) { printf("fallita.\n"); exit(1); } printf("riuscita.\n"); serv_addr.sin_addr = *((struct in_addr *)hp->h_addr); } printf("indirizzo server: %s\n", inet_ntoa(serv_addr.sin_addr)); //Connessione if (connect(conn_sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { printf("Errore durante la connessione\n"); exit(1); } printf("\n\nBENVENUTO"); //CICLO MENU while(1) { printf("\n\nSeleziona l'operazione\n\n"); printf("1 - Mostra mappa dei posti disponibili\n"); printf("2 - Effettua una prenotazione\n"); printf("3 - Disdici una prenotazione conoscendo il codice\n"); printf("4 - Esci dal programma\n\n"); printf("Inserisci il numero corrispondente all'operazione scelta: "); //AZZERAMENTO VARIABILI numeroPosti=0; opzione=0; responso=0; codice=0; nonValido=0; lista=NULL; memset(&p,0, sizeof(posto)); memset(buff, 0, sizeof(buff)); //LETTURA OPZIONE fgets(buff, DIM, stdin); buff[strlen(buff)-1]=0; opzione=atoi(buff); //SWITCH SU OPZIONE switch (opzione) { case 1: //MOSTRA MAPPA map=genMappa(); writeIntero(conn_sock, &opzione); //INVIO SELEZIONE readIntero(conn_sock, &responso); if (responso != 333) { printf("\n******Errore durante la ricezione dei dati. Riprovare...******\n\n"); break; } readIntero(conn_sock, &numeroPosti); lista=(posto*)malloc(numeroPosti*sizeof(posto)); readListaPosti(conn_sock, lista, numeroPosti); //CONTROLLLO VALIDITA for (i=0; i<numeroPosti; i++) { if (!isPostoValido(&lista[i])) { nonValido=1; break; } } if (nonValido) { printf("\n******Errore nei dati ricevuti******\n"); free(lista); break; } printf("\n******Ricezione dati sala completata******\n"); for (i=0; i<numeroPosti; i++) { marcaPosto(map, lista[i]); } printf("%s", map); free(lista); free(map); break; case 2: //PRENOTA writeIntero(conn_sock, &opzione); //INVIO SELEZIONE //LEGGI DA TASTIERA POSTI E CREA LISTA printf("Inserire il posto che si desidera prenotare\n"); while (1) { memset(buff, 0, sizeof(buff)); fgets(buff, DIM, stdin); buff[strlen(buff)-1]=0; if (strcmp(buff, "prenota") ==0 || strcmp(buff, "PRENOTA") ==0) { if (lista != NULL) break; //TEST LISTA VUOTA else { printf("La lista è vuota, inserire almeno un posto che si desidera prenotare\n"); continue; } } p.fila=buff[0]; p.numero=atoi(buff+1); if (!isPostoValido(&p)) //TESTA VALIDITA' POSTO { printf("Posto non riconosciuto, inserire un altro posto o digitare PRENOTA per inviare\n"); continue; } if (isPostoInLista(p, lista, numeroPosti)) //TEST DOPPIONE { printf("Hai già selezionato questo posto, inserire un altro posto o digitare PRENOTA per inviare\n"); continue; } numeroPosti++; lista=(posto *)realloc(lista, (numeroPosti*sizeof(posto))); lista[numeroPosti-1]=p; printf("Aggiungere un altro posto o digitare PRENOTA per inviare\n"); } //INVIA LISTA writeIntero(conn_sock, &numeroPosti); writeListaPosti(conn_sock, lista, numeroPosti); free(lista); readIntero(conn_sock, &responso); switch (responso) { case 333: readIntero(conn_sock, &responso); printf("\n******Prenotazione effettuata.******\n******Codice prenotazione: %d ******\n", responso); break; case 999: printf("\n******Qualche posto è gia occupato. Riprovare...******\n"); break; case 555: printf("\n******Qualche posto indicato non era valido. Riprovare...******\n"); break; default: printf("\n******Errore durante l'operazione. Riprovare...******\n"); break; } break; case 3: //DISDICI writeIntero(conn_sock, &opzione); //INVIO SELEZIONE //LETTURA CODICE printf("\nInserire il codice della prenotazione che si vuole annullare: "); fgets(buff, DIM, stdin); buff[strlen(buff)]=0; codice=atoi(buff); writeIntero(conn_sock, &codice); //INVIO CODICE readIntero(conn_sock, &responso); //LETTURA RESPONSO switch (responso) { case 333: printf("\n******Prenotazione annullata******\n"); break; case 999: printf("\n******Nessuna prenotazione corrispondente trovata******\n"); break; default: printf("\n******Errore durante l'operazione. Riprovare...\n******"); break; } break; case 4: //ESCI writeIntero(conn_sock, &opzione); //INVIO SELEZIONE close(conn_sock); exit(0); default: printf("Opzione non riconosciuta. Riprovare..."); break; } } exit(0); } void analisiArgomenti(int argc, char *argv[]) { int n=1; while (n<argc) { if (!strncmp(argv[n], "-p", 2)) porta = argv[n+1]; else if (!strncmp(argv[n], "-a", 2)) indirizzo = argv[n+1]; else if (!strncmp(argv[n], "-h", 2)) { printf("Sintassi:\n\n"); printf(" client -a (indirizzo remoto) -p (porta remota) [-h].\n\n"); exit(0); } n++; } if (argc!=5) { printf("Sintassi:\n\n"); printf(" client -a (indirizzo remoto) -p (porta remota) [-h].\n\n"); exit(1); } } void messPipe(int sig) { printf("\nErrore durante la comunicazione con il server. Il processo è stato terminato\n"); exit(1); } void messaggioTerminazione(int sig) { printf("\nProcesso terminato a causa di un segnale di terminazione\n"); exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include "ctype.h" // for basic socket communication #include <sys/socket.h> #include "error.h" #include "system.h" #include "network.h" #include "config.h" #include "hashtable.h" #include "network-utils.h" size_t parse_kv_pairs(const char *in_msg, ssize_t length, size_t starting_index, kv_list_t *kv_list); void print_kv_pair_list(kv_list_t kv_pair_list); /** * @brief Takes the four first bytes of a char array and converts them into a 32-bit unsigned char * @param in_msg to parse, in big-endian * @return 32-bit unsigned int */ size_t parse_nbr_kv_pair(const char *in_msg) { size_t nbr = 0; memcpy(&nbr, in_msg, 4); return (size_t) ntohl((uint32_t) nbr); } /** * @brief Dump content of given node (ip, port) * As follows : pps-dump-node <IP> <Port> * @return 0 on normal exit, -1 otherwise */ int main(int argc, char *argv[]) { /* Client initialization and parsing optionnal arguments */ client_t client; client_init_args_t client_i; client_i.client = &client; client_i.argv = &argv; client_i.required = 2; client_i.optionnal = 0; client_i.size_args = argc; error_code error_init = client_init(client_i); if (error_init != ERR_NONE) { printf("FAIL\n"); return -1; } char *ip; uint16_t port; /* parse ip and port */ if (argv[0] != NULL && argv[1] != NULL) { ip = argv[0]; port = (uint16_t) strtol(argv[1], NULL, 10); } else { client_end(&client); printf("FAIL\n"); return -1; } /* Set up socket */ int s = get_socket(1); node_t node; node_init(&node, ip, port, 0); /* Send packet to node */ if (send_packet(s, "\0", 1, node) != ERR_NONE) { client_end(&client); //error handling printf("FAIL\n"); return -1; } /* Wait to receive the response */ char in_msg[MAX_MSG_SIZE]; ssize_t in_msg_len = recv(s, in_msg, MAX_MSG_SIZE, 0); if (in_msg_len == -1) { client_end(&client); printf("FAIL\n"); return -1; } kv_list_t *kv_list = malloc(sizeof(kv_list_t)); kv_list->list = calloc(MAX_MSG_SIZE, sizeof(kv_pair_t)); kv_list->size = parse_nbr_kv_pair(in_msg); /* 4 is the size (in bytes) of a 32-bit unsigned integer */ size_t parsed_kv_pairs = parse_kv_pairs(&in_msg[4], in_msg_len - 4, 0, kv_list); if ((int) parsed_kv_pairs == -1) { kv_list_free(kv_list); client_end(&client); printf("FAIL\n"); return -1; } /* More packets handling */ while (parsed_kv_pairs < kv_list->size) { size_t startingIndex = parsed_kv_pairs; in_msg_len = recv(s, in_msg, MAX_MSG_SIZE, 0); size_t more_kv_pairs = parse_kv_pairs(in_msg, in_msg_len, startingIndex, kv_list); if (more_kv_pairs == (size_t) -1) { printf("FAIL\n"); return -1; } parsed_kv_pairs += more_kv_pairs; if (in_msg_len == -1 && parsed_kv_pairs != kv_list->size) { printf("FAIL\n"); return -1; } } if (parsed_kv_pairs != kv_list->size) { printf("FAIL\n"); return -1; } print_kv_pair_list(*kv_list); kv_list_free(kv_list); client_end(&client); return 0; } /** * @brief Iterate over a list of key_value and prints its content * @param kv_pair_list to print */ void print_kv_pair_list(kv_list_t kv_pair_list) { for (size_t i = 0; i < kv_pair_list.size; i++) { printf("%s = %s\n", kv_pair_list.list[i].key, kv_pair_list.list[i].value); } } /** * @brief Parse an incoming message to a list of key_value pairs * @param in_msg message to parse * @param length of the message * @param starting_index to insert elements in @param kv_list * @param kv_list pointer to a kv_list * @return the number of key_value pairs parsed, -1 (unsigned) if parsing failed */ size_t parse_kv_pairs(const char *in_msg, ssize_t length, size_t starting_index, kv_list_t *kv_list) { char key[MAX_MSG_SIZE]; int key_index = 0; char value[MAX_MSG_SIZE]; int value_index = 0; size_t list_index = starting_index; int parsing_key = 1; char iterator; for (ssize_t i = 0; i < length; i++) { iterator = in_msg[i]; if (parsing_key && iterator != '\0') { key[key_index] = iterator; key_index++; } else if (parsing_key && iterator == '\0') { parsing_key = 0; key[key_index] = '\0'; key_index = 0; } else if (!parsing_key && iterator != '\0') { value[value_index] = iterator; value_index++; } else if (!parsing_key && iterator == '\0') { value[value_index] = '\0'; kv_list->list[list_index] = create_kv_pair(key, value); list_index++; if (list_index >= kv_list->size) { return (size_t) -1; } parsing_key = 1; value_index = 0; } } value[value_index] = '\0'; kv_list->list[list_index] = create_kv_pair(key, value); return list_index + 1; }
C
/** *@brief DHCP server *@author ayakatakuriko *@date 2018/12/14 * */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <inttypes.h> #include "server.h" #include "utility.h" #include "dhcp.h" /** * @biref クライアントを双方向リストの最後に入れる * @param head * @param target * */ void insert_client(struct client *head, struct client *target) { target->fp = head; target->bp = head->bp; head->bp->fp = target; head->bp = target; } /** * @brief 特定のクライアントを双方向リストから取り除く * @param head 双方向リストの先頭 * @param target 消去したいクライアント * @return 消去したクライアントへのアドレス.targetが無かったらNULLを返す。 * */ struct client *rm_client(struct client *head, struct client *target) { struct client *p; if (target == NULL) return NULL; for (p = head->fp; p != head; p = p->fp) { if (p->id.s_addr == target->id.s_addr) { p->bp->fp = p->fp; p->fp->bp = p->bp; p->fp = p->bp = NULL; return p; } } return NULL; } /** * @brief IPアドレスをリストの最後に挿入する。 * @param head * @param target **/ void insert_ip(struct served_ip *head, struct served_ip *target) { target->fp = head; target->bp = head->bp; head->bp->fp = target; head->bp = target; } /** * @brief リストの先頭のIPアドレスを取り除く。 **/ struct served_ip *rm_ip(struct served_ip *head) { struct served_ip *target = head->fp; target->bp->fp = target->fp; target->fp->bp = target->bp; target->fp = target->bp = NULL; return target; } /** * @brief configファイルからデータを読み込む * @param head * @return 読み込んだIPとネットマスクの組数 **/ int perser(struct served_ip *head, char *fname) { FILE *fd; uint16_t ttl; struct served_ip *temp; char ip[STR_LEN], netmask[STR_LEN]; int count = 0; int check; // ファイルを開く file_open(fd, fname, "r", 1); // TTLを読み込む if ((check = fscanf(fd, "%" PRIu16, &(head->ttl))) == EOF) { fprintf(stderr, "Error: Invalid config file\n"); fclose(fd); return count; } while ((check = fscanf(fd, "%s %s", ip, netmask)) != EOF) { // 保存先のserved_ipのメモリを確保 mem_alloc(temp, struct served_ip, sizeof(struct served_ip), 1); // IPとネットマスクの表示形式を変換 inet_aton(ip, &(temp->ip)); inet_aton(netmask, &(temp->netmask)); temp->ttl = head->ttl; insert_ip(head, temp); temp = NULL; count++; } fclose(fd); return count; } /** * @brief コンフィグファイルの内容を出力 * @param head */ void print_config(struct served_ip *head) { struct served_ip *p; if (head == NULL) { // エラーチェック fprintf(stderr, "IP list is NULL\n"); return; } printf("\n---------- config-file information ----------\n\n"); printf("TTL: %" PRIu16 "\n", head->ttl); printf(" ----- Served IP and Netmask -----\n"); for (p = head->fp; p != head; p = p->fp) { printf("%s ", inet_ntoa(p->ip)); printf("%s\n", inet_ntoa(p->netmask)); } printf("-------------------- end --------------------\n\n"); } /** * @brief タイムアウトしたクライアントを返す * @param chead [description] * @return タイムアウトしたクライアント */ struct client *timeout_client(struct client *chead, struct served_ip *phead) { struct client *p; struct served_ip *target; for (p = chead->fp; p != chead; p = p->fp) { if (p->ttlcounter <= 0) { return p; } } return NULL; } /** * @brief idをもとにクライアントを探索する * @param head 双方向リストの先頭 * @param id 探したいid. ネットワークバイトオーダー。 * @return 見つけたクライアントへのアドレス.targetが無かったらNULLを返す。 * */ struct client *find_client(struct client *head, in_addr_t id) { struct client *p; for (p = head->fp; p != head; p = p->fp) { if (p->id.s_addr == id) return p; } return NULL; } /** * @brief リストの先頭にあるIPアドレスを読む * @param head [description] * @return [description] */ struct served_ip *get_ip(struct served_ip *head) { return head->fp; } /** * @brif クライアントリストのttlカウンターをデクリメント * @param head クライアントリストの先頭 */ void decriment_ttl(struct client *head) { struct client *p; for (p = head->fp; p != head; p = p->fp) { if (p->ttlcounter > 0) p->ttlcounter--; if (p->stat == STAT_IN_USE) { printf("TTL %s(", inet_ntoa(p->addr)); printf("%s): %" PRIu16 " sec\n", inet_ntoa(p->id), p->ttlcounter); } } }
C
#include <stdio.h> main() { float fahr,celsius; int lower,upper,step; lower = 0; //温度表的下限 upper = 300; //温度表的上线 step = 20; //步长 printf("Celsius Fahr\n"); celsius = lower; while(celsius <= upper){ fahr = (9.0 * celsius) / 5.0 + 32.0; printf("%3.0f\t%6.1f\n",celsius,fahr); celsius = celsius + step; } }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main(void) { //Ask the user for amount of change (only positive) float change; do { change = get_float("Change owed: "); } while (change < 0); // change dollars for cents int cents = round(change * 100); // define the coins that can be used int penys = 1; int nickels = 5; int dimes = 10; int quarters = 25; int rounds = 0; // number of quarters while (cents >= 25) { cents = cents - quarters; rounds++; } // number of dimes while (cents >= 10) { cents = cents - dimes; rounds++; } // number of nickels while (cents >= 5) { cents = cents - nickels; rounds++; } // number of penys while (cents > 0) { cents = cents - penys; rounds++; } printf("%i \n", rounds); }
C
#include <stdio.h> #define N 1000 void swap(int * x, int * y); int main(){ int i, n, a[N], k; scanf("%d", &n); for (i=0;i<n;i++) { scanf("%d", &a[i]); } for (i=0;i<n;i++) { for (k=0;k<n;k++) { if (a[i] == a[k] && i!=k) a[i] = -100000000; } } for (i=0; i<n ; i++) for(k=i+1; k<n ; k++) if (a[i] > a[k]) swap(&a[i], &a[k]); for (i=0;i<n;i++) if (a[i] != -100000000) printf("%d\n", a[i]); return 0; } void swap(int * x, int * y){ int temp; temp = *y; *y = *x; *x = temp; }
C
#include "led.h" #include "stm32f10x.h" #include "delay.h" void LED_Init() { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOB, ENABLE); //ʹ PB ˿ʱ //nled GPIO_InitStructure.GPIO_Pin = GPIO_Pin_14; // pin10 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //IO ת 50MHz GPIO_Init(GPIOB, &GPIO_InitStructure); GPIO_SetBits(GPIOB,GPIO_Pin_14); } void ledon() { GPIO_ResetBits(GPIOB,GPIO_Pin_14); } void ledoff() { GPIO_SetBits(GPIOB,GPIO_Pin_14); } void ledon_fast(u16 time) { u16 i; i=10*time; while(i>0) { ledon(); delay_ms(100); ledoff(); delay_ms(100); i-=2; } } void ledon_slow(u16 time) { u16 i; i=10*time; while(i>0) { ledon(); delay_ms(1000); ledoff(); delay_ms(1000); i-=20; } }
C
#include<stdio.h> typedef struct date { int year; int month; int day; }DATE; typedef struct student { long studentID; char studentName[10]; char stdentSex; DATE birthday; int score[4]; }STUDENT; int main() { STUDENT stu1 = {100310121, "",'M', {1991,5,19},{72,38,90,82}}; STUDENT stu2; stu2 = stu1; printf("stu2:%101d%8s%3c%6d/ %02d/ %02d%4d%4d%4d%4d\n", stu2.studentID,stu2.studentName,stu2.stdentSex, stu2.birthday.year,stu2.birthday.month,stu2.birthday.day, stu2.score[0],stu2.score[1],stu2.score[2],stu2.score[3]); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* for_wchar.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sprotsen <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/02/16 21:08:48 by sprotsen #+# #+# */ /* Updated: 2017/02/22 20:23:07 by sprotsen ### ########.fr */ /* */ /* ************************************************************************** */ #include "printhead.h" int ft_sizeof_wchar(wchar_t s) { int i; i = 0; if (s <= 0x7F) i += 1; else if (s <= 0x7FF) i += 2; else if (s <= 0xFFFF) i += 3; else if (s <= 0x10FFFF) i += 4; return (i); } void pr_symb(wchar_t *str, int *fl, size_t *res, int i) { size_t k; k = *res; while (*str) { if (fl[6] > 0 && (int)(*res - k) >= fl[6]) break ; ft_putwchar(*str, res); str++; if (fl[6] > 0 && (int)((*res - k) + ft_sizeof_wchar(*str)) > fl[6]) break ; } if (i) pr_space_null(fl[5] - (*res - k), res, ' '); } int find_i(wchar_t *str, int *fl) { wchar_t *row; int i; i = 0; row = str; while ((int)i <= fl[6]) { i += ft_sizeof_wchar(*row); row++; } row--; i -= ft_sizeof_wchar(*row); return (i); } void for_wchar_next(wchar_t *str, size_t *res, int *fl, size_t len) { int pr; if (fl[5] > 0 && fl[3] == 0) { pr = fl[5] - (((fl[6] < (int)len) && fl[6] != 0) ? find_i(str, fl) : (int)len); fl[4] == 1 ? PSN(pr, res, '0') : PSN(pr, res, ' '); pr_symb(str, fl, res, 0); } else if ((fl[5] > (int)len && fl[3] == 1)) { pr_symb(str, fl, res, 0); pr = fl[5] - (((fl[6] < (int)len) && fl[6] != 0) ? find_i(str, fl) : (int)len); fl[4] == 1 ? pr_space_null(pr, res, '0') : pr_space_null(pr, res, ' '); } else pr_symb(str, fl, res, 1); } void for_wchar(wchar_t *str, size_t *res, int *fl) { size_t len; wchar_t *row; len = 0; row = str; if ((char*)str == NULL) { pr_null(res, fl); return ; } if (fl[6] < 0) { fl[4] == 1 ? PSN(fl[5], res, '0') : PSN(fl[5], res, ' '); return ; } while (*row) { len += ft_sizeof_wchar(*row); row++; } for_wchar_next(str, res, fl, len); }
C
#include <sys/types.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> /*Задание: напишите программу, создающую процесс-зомби. Выведите на экран его pid и посмотрите в другом окне терминала, как обозначается данный процесс при вызове команды просмотра состояния процессов (ко- манда ps)*/ int main() { printf("Лабораторная работа №3.3 \n"); printf("Управление процессами \n"); printf("Выполнил студент группы ИСТбд-22 Каяшов П.А.\n"); printf("Пример создания процесса-зомби \n"); pid_t id, pid, ppid;///Тип данных pid_t является синонимом для одного из целочисленных типов языка C. id = fork();///При успешном создании нового процесса с этого места псевдопараллельно ///начинают работать два процесса: старый и новый pid = getpid();/// получение значения идентификатора текущего процесса ppid = getppid();///получение начения идентификатора родительского процесса для текущего процесса if (id > 0) { printf("Zombie-process\n"); sleep(10);///режим сна 10 секунд } else { printf("PID - %d; PPID - %d\n", pid, ppid); exit(0);///состояние "закончил исполнение" } printf("PID - %d; PPID - %d\n", pid, ppid); return 0; }
C
/* * Airown - utility functions * * Copyright (C) 2010 sh0 <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Int inc #include "ao_config.h" #include "ao_util.h" // Hex dump void dumphex(guint8* data, guint32 len) { uint32_t i; uint32_t done = 0; while (len > done) { // Hex uint32_t cur = 0; printf("| "); while ((cur < 16) && (len >= done + cur)) { printf("%02x ", data[done + cur]); cur++; } for (i = 0; i < (16-cur); i++) printf(" "); // String printf("| "); cur = 0; while ((cur < 16) && (len >= done + cur)) { char ch = data[done + cur]; if ((ch >= 32) && (ch <= 126)) printf("%c", data[done + cur]); else printf("."); cur++; } for (i = 0; i < (16-cur); i++) printf(" "); printf(" |\n"); // Next done += cur; } } // Compare addresses gboolean cmp_ipv4(struct in_addr* a, struct in_addr* b) { if (*((guint32*)a) != *((guint32*)b)) return FALSE; return TRUE; } gboolean cmp_ipv6(struct libnet_in6_addr* a, struct libnet_in6_addr* b) { gint i; for (i=0; i<8; i++) { if (a->__u6_addr.__u6_addr16[i] != b->__u6_addr.__u6_addr16[i]) return FALSE; } return TRUE; } gboolean cmp_ipv4_mask(struct in_addr* a, struct in_addr* b, struct in_addr* mask) { guint32 am = *((guint32*)a) & *((guint32*)mask); guint32 bm = *((guint32*)b) & *((guint32*)mask); if (am != bm) return FALSE; return TRUE; } gboolean cmp_ipv6_mask(struct libnet_in6_addr* a, struct libnet_in6_addr* b, struct libnet_in6_addr* mask) { gint i; for (i=0; i<8; i++) { if ((a->__u6_addr.__u6_addr16[i] & mask->__u6_addr.__u6_addr16[i]) != (b->__u6_addr.__u6_addr16[i] & mask->__u6_addr.__u6_addr16[i])) return FALSE; } return TRUE; } // Copy addresses void cpy_ipv4(struct in_addr* dst, struct in_addr* src) { g_memmove(dst, src, sizeof(struct in_addr)); } void cpy_ipv6(struct libnet_in6_addr* dst, struct libnet_in6_addr* src) { g_memmove(dst, src, sizeof(struct libnet_in6_addr)); }
C
// Implementation of cprintf console output for user environments, // based on printfmt() and cputs(). // // cprintf is a debugging facility, not a generic output facility. // It is very important that it always go to the console, especially when // debugging file descriptor code! #include <types.h> /* #include <spinlock.h> */ #include <stdarg.h> #include <console.h> #include <stdio.h> // Collect up to CONSBUFSIZE-1 characters into a buffer // and perform ONE system call to print all of them, // in order to make the lines output to the console atomic // and prevent interrupts from causing context switches // in the middle of a console output line and such. struct printbuf { int idx; // current buffer index int cnt; // total bytes printed so far char buf[CONSBUFSIZE]; }; static void putch(int ch, struct printbuf *b) { b->buf[b->idx++] = ch; if (b->idx == CONSBUFSIZE-1) { b->buf[b->idx] = 0; cputs(b->buf); b->idx = 0; } b->cnt++; } int vcprintf(const char *fmt, va_list ap) { struct printbuf b; b.idx = 0; b.cnt = 0; vprintfmt((void*)putch, &b, fmt, ap); b.buf[b.idx] = 0; cputs(b.buf); return b.cnt; } /* volatile spinlock print_lock = 0; */ int cprintf(const char *fmt, ...) { va_list ap; int cnt; /* spinlock_acquire(&print_lock); */ va_start(ap, fmt); cnt = vcprintf(fmt, ap); va_end(ap); /* spinlock_release(&print_lock); */ return cnt; }
C
#include "common.h" #include <stdarg.h> FILE *log_fp = NULL; void init_log(const char *log_file) { if (log_file == NULL) return; log_fp = fopen(log_file, "w"); Assert(log_fp, "Can not open '%s'", log_file); } char log_bytebuf[80] = {}; char log_asmbuf[80] = {}; static char tempbuf[256] = {}; void strcatf(char *buf, const char *fmt, ...) { va_list ap; va_start(ap, fmt); vsnprintf(tempbuf, sizeof(tempbuf), fmt, ap); va_end(ap); strcat(buf, tempbuf); } void asm_print(vaddr_t ori_pc, int instr_len, bool print_flag) { snprintf(tempbuf, sizeof(tempbuf), "%8x: %s%*.s%s", ori_pc, log_bytebuf, 50 - (12 + 3 * instr_len), "", log_asmbuf); log_write("%s\n", tempbuf); if (print_flag) { puts(tempbuf); } } void log_clearbuf(void) { log_bytebuf[0] = '\0'; log_asmbuf[0] = '\0'; }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #define COMBINE_STRING_LITERAL(x, y) x##y #define PREPARE_COMBINE_STRING(x, y) COMBINE_STRING_LITERAL(x, y) #define STRING_IN_QUOTES(a) #a #define PREPARE_STRING_IN_QUOTES(a) STRING_IN_QUOTES(a) #define BUFF_SIZE 64 /********************************************************************* / AUTHOR: Joseph Burns *********************************************************************/ int main(void) { char myArray[BUFF_SIZE] = PREPARE_STRING_IN_QUOTES(PREPARE_COMBINE_STRING(Joseph, Burns)); printf("%s", myArray); return 0; }
C
//Nome: Rafael Daily Santos Martins //Matrcula: 11721EEL001 #include <stdio.h> int a (int m, int n) { if(m==0) return n+1; else if(m>0 && n==0) return a(m-1, 1); else if(m>0 && n>0) return a(m-1, a(m, n-1)); } int main () { int m, n; printf("Digite m: "); scanf("%d", &m); printf("\nDigite n: "); scanf("%d", &n); printf("%d", a(m, n)); return 0; }
C
#include<conio.h> #include<stdio.h> void main() { clrscr(); as(); getch(); } int as() { int b=2,h=3,area; area=b*h; printf("The Area of Parallelogram is :-%d",area); }
C
/* * lab_design.h * * Created on: May 28, 2015 * Author: shaunpur */ #ifndef LAB_DESIGN_H_ #define LAB_DESIGN_H_ /* includes */ #include <inttypes.h> #define BLUE_MASK 0x000000FF #define GREEN_MASK 0x0000FF00 #define RED_MASK 0x00FF0000 // pull out the color component and return as a value between 0 and 255 #define getBlue(colorPixel) (colorPixel & BLUE_MASK) #define getGreen(colorPixel) (colorPixel & GREEN_MASK) >> 8 #define getRed(colorPixel) (colorPixel & RED_MASK) >> 16 #define setBlue(existingPixel,blueComponent) ((existingPixel & ~BLUE_MASK) | blueComponent) #define setGreen(existingPixel,greenComponent) ((existingPixel & ~GREEN_MASK) | (greenComponent << 8)) #define setRed(existingPixel,redComponent) ((existingPixel & ~RED_MASK) | (redComponent << 16)) /* define types and structures */ #define FRAME_WIDTH 1920 #define FRAME_HEIGHT 1080 #define WIDOW_WIDTH 3 #define WIDOW_HEIGHT 3 #define COLOR_CHANNEL_RED 0 #define COLOR_CHANNEL_GREEN 1 #define COLOR_CHANNEL_BLUE 2 #define COLOR_CHANNELS 3 typedef union pixel { struct { uint8_t red; uint8_t green; uint8_t blue; }; struct { uint8_t gray; }; } pixel_t; typedef struct frame { uint32_t height; uint32_t width; uint8_t *colorFrame; //Multiply by COLOR_CHANNELS for each color channel, RGB uint8_t *grayFrame; } frame_t; #endif /* LAB_DESIGN_H_ */
C
#include <stdio.h> int main() { char a[40]; char b[40]; printf("a="); scanf("%s",a); printf("b="); scanf("%s",b); int i=0; for(i=0;a[i]!='\0' && b[i]!='\0';i++) { if(a[i]!=b[i]) { break; } else { continue; } } if(a[i]=='\0' && b[i]=='\0') { printf("相等\n"); } else { printf("不相等\n"); } return 0; }
C
#include<stdio.h> #include<conio.h> #include<math.h> #include<stdlib.h> struct HeapNode{ int* Array; int count; int index; }; typedef struct HeapNode HNode; HNode* NewNode(int count){ HNode* newNode=(HNode*)malloc(sizeof(HNode)); newNode->index=0; newNode->count=count; newNode->Array=(int*)malloc(sizeof(int)*newNode->count); return newNode; } int LeftChild(int i){ return 2*i+1; } int RightChild(int i){ return 2*i+2; } int RunETL(HNode** heapArray,int n){ int i; int height=ceil(log2(n)); for(i=(int)pow(2,height)-2;i>=0;i--){ //printf("\nEntering here\n"); if(heapArray[LeftChild(i)]->index==heapArray[LeftChild(i)]->count){ heapArray[i]=heapArray[RightChild(i)]; } else if(heapArray[RightChild(i)]->index==heapArray[RightChild(i)]->count){ heapArray[i]=heapArray[LeftChild(i)]; } else if(heapArray[LeftChild(i)]->index<heapArray[LeftChild(i)]->count && heapArray[RightChild(i)]->index<heapArray[RightChild(i)]->count){ /* int left=LeftChild(i); int right=RightChild(i); printf("\n%d %d",left,right); printf("\n\n Data fetching : left child %d",heapArray[left]->Array[heapArray[right]->index]); printf("\n\n Data fetching : right child %d",heapArray[right]->Array[heapArray[right]->index]); */ if(heapArray[LeftChild(i)]->Array[heapArray[LeftChild(i)]->index] < heapArray[RightChild(i)]->Array[heapArray[RightChild(i)]->index]){ heapArray[i]=heapArray[LeftChild(i)]; }else{ heapArray[i]=heapArray[RightChild(i)]; } } } int result=heapArray[0]->Array[heapArray[0]->index]; heapArray[0]->index++; return result; } int main(){ int n; printf("\nEnter the number of teams participating : \n"); scanf("%d",&n); int height=ceil(log2(n)); //printf("\nHeight is : %d",height); HNode** heapArray=(HNode**)malloc(sizeof(HNode*)*2*n); int i; int count; int j=0; int k; for(i=(int)pow(2,height)-1;i<2*n-1;i++){ printf("\nHere we create %d sorted array to participat in tournament \n",j++); printf("\nEnter the number of memebers in this team : "); scanf("%d",&count); heapArray[i]=NewNode(count); //printf("\n\nIndex of new allocated node : %d",heapArray[i]->index); printf("\nEnter elements of this array :\n"); for(k=0;k<heapArray[i]->count;k++){ scanf("%d",&heapArray[i]->Array[k]); } printf("\n\nData entered \n\n"); getch(); } for(i=0;i<(int)pow(2,height)-1;i++){ heapArray[i]=(HNode*)malloc(sizeof(HNode)); } /* printf("\n\nGetting data \n\n"); getch(); for(i=pow(2,height)-1;i<2*n-1;i++){ printf("\nelements of this array :\n"); for(k=0;k<heapArray[i]->count;k++){ printf("%d ",heapArray[i]->Array[k]); } getch(); } */ printf("\nEnter which samllest u want to see : "); scanf("%d",&j); int result; for(i=0;i<j;i++){ result=RunETL(heapArray,n); /* for(k=(int)pow(2,height)-2;k>=0;k--){ printf("\n K is : %d",k); getch(); int left=LeftChild(k); int right=RightChild(k); printf("\n\n Data fetching : left child %d",heapArray[left]->Array[heapArray[right]->index]); printf("\n\n Data fetching : right child %d",heapArray[right]->Array[heapArray[right]->index]); getch(); if(heapArray[LeftChild(k)]->Array[heapArray[LeftChild(k)]->index]< heapArray[RightChild(k)]->Array[heapArray[RightChild(k)]->index]){ heapArray[k]=heapArray[LeftChild(k)]; }else{ heapArray[k]=heapArray[RightChild(k)]; } } result=heapArray[0]->Array[heapArray[0]->index]; heapArray[0]->index++; */ //printf("\n\n%dth samllest element is : %d",i,result); //getch(); } printf("\n\n%dth samllest element is : %d",j,result); getch(); return 0; }
C
/* * Przykadowy program dla kursu "POSIX Threads" z wikibooks.pl * * Temat: priorytety wtkw * * Autor: Wojciech Mua * Ostatnia zmiana: 2010-03-xx */ #define _XOPEN_SOURCE 500 #include <stdlib.h> #include <stdio.h> #include <pthread.h> #include <sched.h> #include <errno.h> #include <unistd.h> #define test_errno(msg) do{if (errno) {perror(msg); exit(EXIT_FAILURE);}} while(0) typedef struct { int licznik; char przerwij; int priorytet; } Arg; /* funkcja wykonywana w wtku - zwiksza licznik */ void* watek(void* _arg) { Arg *arg = (Arg*)_arg; arg->licznik = 0; while (!arg->przerwij) { arg->licznik += 1; usleep(10); } return NULL; } //------------------------------------------------------------------------ #define N 4 /* liczba wtkw */ int main(int argc, char* argv[]) { pthread_t id[N]; pthread_attr_t attr; Arg arg[N]; int pmin, pmax; int i, sched_policy; struct sched_param sp; sched_policy = SCHED_OTHER; if (argc > 1) switch (atoi(argv[1])) { case 0: sched_policy = SCHED_OTHER; break; case 1: sched_policy = SCHED_RR; break; case 2: sched_policy = SCHED_FIFO; break; } else { puts("program [0|1|2]"); return EXIT_FAILURE; } pmin = sched_get_priority_min(sched_policy); pmax = sched_get_priority_max(sched_policy); switch (sched_policy) { case SCHED_OTHER: printf("SCHED_OTHER: priorytety w zakresie %d ... %d\n", pmin, pmax); break; case SCHED_RR: printf("SCHED_RR: priorytety w zakresie %d ... %d\n", pmin, pmax); break; case SCHED_FIFO: printf("SCHED_FIFO: priorytety w zakresie %d ... %d\n", pmin, pmax); break; } errno = pthread_attr_init(&attr); test_errno("pthread_attr_init"); /* parametry szeregowania odczytywane z atrybutw */ errno = pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED); test_errno("pthread_attr_setinheritsched"); /* wybr podanego algorytmu szeregowania */ errno = pthread_attr_setschedpolicy(&attr, sched_policy); test_errno("pthread_attr_setschedpolicy"); /* utworzenie kilku wtkw wtku z rnymi priorytetami */ for (i=0; i < N; i++) { /* kolejne wtki maj coraz wysze priorytety */ sp.sched_priority = pmin + (pmax-pmin) * i/(float)(N-1); arg[i].przerwij = 0; arg[i].licznik = 0; arg[i].priorytet = sp.sched_priority; /* ustawienie priorytetu */ errno = pthread_attr_setschedparam(&attr, &sp); test_errno("pthread_attr_setschedparam"); /* uruchomienie wtku */ errno = pthread_create(&id[i], &attr, watek, &arg[i]); test_errno("pthread_create"); printf("utworzono wtek #%d o priorytecie %d\n", i, arg[i].priorytet); } errno = pthread_attr_destroy(&attr); test_errno("pthread_attr_destroy"); /* oczekiwanie */ sleep(2); /* ustawienie flagi zakoczenia pracy, ktr testuj funkcje wtkw oraz odczyt ich biecych licznikw */ for (i=0; i < N; i++) { arg[i].przerwij = 1; printf("wtek #%d (priorytet %3d): licznik = %d\n", i, arg[i].priorytet, arg[i].licznik ); } /* teraz oczekiwanie na ich zakoczenie */ for (i=0; i < N; i++) { errno = pthread_join(id[i], NULL); test_errno("pthread_join"); } return EXIT_SUCCESS; } //------------------------------------------------------------------------
C
#include <stdio.h> #include <stdlib.h> #define ARRAY_SIZE 13 int linear_search (int array[], int n, int key) { int i; for (i = 0; i < n; i++) { if (array[i] == key) { return i; } } return -1; } void print_array(int array[], int n) { int i; for (i = 0; i < n; i++) { printf("%d ", array[i]); } printf("\n"); } int main () { int index, key; int arrary[ARRAY_SIZE] = { 900, 990, 210, 50, 80, 150, 330, 470, 510, 530, 800, 250, 280, }; key = 800; print_array(arrary, ARRAY_SIZE); index = linear_search(arrary, ARRAY_SIZE, key); if (index != -1) { printf("Found %d\n (Index: %d)\n", key, index); } else { printf("Not Found %d\n", key); } }
C
#include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <pthread.h> char buf1[1024]; char buf2[1024]; int fd; void *thr_rtn(void *arg) { int n; if ((n = pread(fd, buf1, 1024, 3)) < 0) { printf("thread 1: pread error: %s\n", strerror(errno)); return (void *)1; } printf("thread 1: pread: buf1: %s", buf1); return (void *)0; } void *thr_rtn2(void *arg) { int n; if ((n = pread(fd, buf2, 1024, 10)) < 0) { printf("thread 2: pread error: %s\n", strerror(errno)); return (void *)1; } printf("thread 2: pread: buf2: %s", buf2); return (void *)0; } /* 书中第12.10小节提到,多线程环境下要使用pread(),pwrite()函数,而不要用 * read(),write()函数.因为pread()和pwrite()函数不会改变文件偏移指针,避免 * 多线程调度时,文件偏移指针发生改变,导致读写的位置不如预期. * 编译的时候,要添加 -D_XOPEN_SOURCE=500选项,否则会报警: * warning: implicit declaration of function ‘pread’ */ int main(void) { pthread_t tid1, tid2; int err; if ((fd = open("today", O_RDWR)) < 0) { printf("open file 'today' error: %s\n", strerror(errno)); return 1; } err = pthread_create(&tid1, NULL, thr_rtn, NULL); if (err != 0) { printf("pthread_create: thread 1: error: %s\n", strerror(err)); return 1; } err = pthread_create(&tid2, NULL, thr_rtn2, NULL); if (err != 0) { printf("pthread_create: thread 2: error: %s\n", strerror(err)); return 1; } err = pthread_join(tid1, NULL); if (err != 0) { printf("pthread_join: thread 1: error: %s\n", strerror(err)); return 1; } err = pthread_join(tid2, NULL); if (err != 0) { printf("pthread_join: thread 2: error: %s\n", strerror(err)); return 1; } return 0; }
C
#include "libft.h" /*This function applies the parameter function f to each character of a string * also passed in it's parameter at at precisely that character's index string * position. Each character that is passed into the function f is modified if * necessary.*/ void ft_striteri(char *s, void (*f)(unsigned int, char *)) { /*We start by creating our counter variable i as an unsigned variable to * compensate for the possibilty of a long string.*/ unsigned int i; /*We then start at the beginning of our string and work our way until the * end, applying the function f to each character. When our loop reaches * the of the string the function is finished.*/ i = 0; while (s[i] != '\0') { f(i, s + i); i++; } }
C
#include <stdio.h> int a[1005]; void puzyr(int n) { int i,j,t; for (i=1; i<=n-1; i++) for (j=1; j<=n-i; j++) if (a[j]<a[j+1]) { t=a[j]; a[j]=a[j+1]; a[j+1]=t; } return; } int main() { int n,k; int s=0; scanf("%d",&n); for (k=1; k<=n; k++) scanf("%d",&a[k]); puzyr(n); for (k=1; k<=n; k+=3) s+=a[k]+a[k+1]; printf("%d\n",s); }
C
#include<stdio.h> //#include<conio.h> int main() { float tim; //clrscr(); printf("Enter the Time taken by the Worker to Complete the Work(In Hrs): "); scanf("%f", &tim); if(tim>=2 && tim<3) printf("You are a Highly Efficient Worker"); else if(tim>=3 && tim<4) printf("You must Improve your Speed"); else if(tim>=4 && tim<5) printf("Immediately Go and Practice for your Speed"); else printf("Leave the Job NOW"); //getch(); return 0; }
C
/* ### * IP: GHIDRA * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "pcode_test.h" u1 u1_complexLogic(u1 a, u1 b, u1 c, u1 d, u1 e, u1 f) { u1 ret = 0; if (a > b && b > c || d < e && f < e) { ret += 1; } if (a != b || a != c && d != e || f != e) { ret += 2; } if (a && b && c || d && e && f) { ret += 4; } if (a || b || c && d || e || f) { ret += 8; } return ret; } i1 i1_complexLogic(i1 a, i1 b, i1 c, i1 d, i1 e, i1 f) { i1 ret = 0; if (a > b && b > c || d < e && f < e) { ret += 1; } if (a != b || a != c && d != e || f != e) { ret += 2; } if (a && b && c || d && e && f) { ret += 4; } if (a || b || c && d || e || f) { ret += 8; } return ret; } u1 u1_compareLogic(u1 lhs, u1 rhs) { if (lhs < rhs) lhs += 2; if (lhs > rhs) lhs += 4; if (lhs == 0) lhs += 8; if (lhs != rhs) lhs += 16; return lhs; } i1 i1_compareLogic(i1 lhs, i1 rhs) { if (lhs < 0) lhs += 2; if (lhs > 0) lhs += 4; if (lhs == 0) lhs += 8; if (lhs != rhs) lhs += 16; return lhs; } /* Comparison operators */ u1 u1_greaterThan(u1 lhs, u1 rhs) { u1 z; z = lhs > rhs; return z; } u1 u1_greaterThanEquals(u1 lhs, u1 rhs) { u1 z; z = lhs >= rhs; return z; } u1 u1_lessThan(u1 lhs, u1 rhs) { u1 z; z = lhs < rhs; return z; } u1 u1_lessThanEquals(u1 lhs, u1 rhs) { u1 z; z = lhs <= rhs; return z; } u1 u1_equals(u1 lhs, u1 rhs) { u1 z; z = lhs == rhs; return z; } u1 u1_notEquals(u1 lhs, u1 rhs) { u1 z; z = lhs != rhs; return z; } i1 i1_greaterThan(i1 lhs, i1 rhs) { i1 z; z = lhs > rhs; return z; } i1 i1_greaterThanEquals(i1 lhs, i1 rhs) { i1 z; z = lhs >= rhs; return z; } i1 i1_lessThan(i1 lhs, i1 rhs) { i1 z; z = lhs < rhs; return z; } i1 i1_lessThanEquals(i1 lhs, i1 rhs) { i1 z; z = lhs <= rhs; return z; } i1 i1_equals(i1 lhs, i1 rhs) { i1 z; z = lhs == rhs; return z; } i1 i1_notEquals(i1 lhs, i1 rhs) { i1 z; z = lhs != rhs; return z; } /* Bitwise operators */ u1 u1_bitwiseAnd(u1 lhs, u1 rhs) { u1 z; z = lhs & rhs; return z; } u1 u1_bitwiseOr(u1 lhs, u1 rhs) { u1 z; z = lhs | rhs; return z; } u1 u1_bitwiseXor(u1 lhs, u1 rhs) { u1 z; z = lhs ^ rhs; return z; } i1 i1_bitwiseAnd(i1 lhs, i1 rhs) { i1 z; z = lhs & rhs; return z; } i1 i1_bitwiseOr(i1 lhs, i1 rhs) { i1 z; z = lhs | rhs; return z; } i1 i1_bitwiseXor(i1 lhs, i1 rhs) { i1 z; z = lhs ^ rhs; return z; } /* Logical operators */ u1 u1_logicalAnd(u1 lhs, u1 rhs) { u1 z; z = lhs && rhs; return z; } u1 u1_logicalOr(u1 lhs, u1 rhs) { u1 z; z = lhs || rhs; return z; } u1 u1_logicalNot(u1 lhs) { u1 z; z = !lhs; return z; } i1 i1_logicalAnd(i1 lhs, i1 rhs) { i1 z; z = lhs && rhs; return z; } i1 i1_logicalOr(i1 lhs, i1 rhs) { i1 z; z = lhs || rhs; return z; } i1 i1_logicalNot(i1 lhs) { i1 z; z = !lhs; return z; } /* Shift operators */ u1 u1_shiftLeft(u1 lhs, u1 rhs) { u1 z; z = lhs << rhs; return z; } u1 u1_shiftRight(u1 lhs, u1 rhs) { u1 z; z = lhs >> rhs; return z; } i1 i1_shiftLeft(i1 lhs, i1 rhs) { i1 z; z = lhs << rhs; return z; } i1 i1_shiftRight(i1 lhs, i1 rhs) { i1 z; z = lhs >> rhs; return z; } /* Arithmetic operators */ u1 u1_unaryPlus(u1 lhs) { u1 z; z = +lhs; return z; } u1 u1_addition(u1 lhs, u1 rhs) { u1 z; z = lhs + rhs; return z; } u1 u1_subtract(u1 lhs, u1 rhs) { u1 z; z = lhs - rhs; return z; } u1 u1_multiply(u1 lhs, u1 rhs) { u1 z; z = lhs * rhs; return z; } i1 u1_divide(u1 lhs, u1 rhs) { i1 z; z = lhs / rhs; return z; } u1 u1_remainder(u1 lhs, u1 rhs) { u1 z; z = lhs % rhs; return z; } i1 i1_unaryMinus(i1 lhs) { i1 z; z = -lhs; return z; } i1 i1_unaryPlus(i1 lhs) { i1 z; z = +lhs; return z; } i1 i1_addition(i1 lhs, i1 rhs) { i1 z; z = lhs + rhs; return z; } i1 i1_subtract(i1 lhs, i1 rhs) { i1 z; z = lhs - rhs; return z; } i1 i1_multiply(i1 lhs, i1 rhs) { i1 z; z = lhs * rhs; return z; } i1 i1_divide(i1 lhs, i1 rhs) { i1 z; z = lhs / rhs; return z; } i1 i1_remainder(i1 lhs, i1 rhs) { i1 z; z = lhs % rhs; return z; }
C
/* * Copyright (c) 2015-2019 Intel Corporation. * All rights reserved. * * SPDX-License-Identifier: Apache-2.0 * */ #ifndef _SPRINTF_H_ #define _SPRINTF_H_ #include "vmm_base.h" /* maximum string length */ #define MAX_STR_LEN 0x1000 /* The strnlen_s function computes the length of the string pointed to by str */ uint32_t strnlen_s (const char *str, uint32_t maxlen); /* The strstr_s function locates the first occurrence of the substring pointed * by str2 which would be located in the string pointed by str1 */ const char *strstr_s (const char *str1, uint32_t maxlen1, const char *str2, uint32_t maxlen2); /* The str2uint() function convert a string to an unsigned integer */ uint32_t str2uint(const char *str, uint32_t maxlen, const char **endptr, uint32_t base); #ifdef __GNUC__ #define va_list __builtin_va_list #define va_start(ap,v) __builtin_va_start((ap),v) #define va_arg(ap,t) __builtin_va_arg(ap,t) #define va_end(ap) __builtin_va_end(ap) #else /* * find size of parameter aligned on the native integer size */ //#define VA_ARG_SIZE(type) ALIGN_F(sizeof(type), sizeof(uint64_t)) /* it is always 8 for int,char,long,longlong,pointer type */ #define VA_ARG_SIZE(type) 8 typedef char *va_list; #define va_start(ap,v) (ap = (va_list)&(v) + VA_ARG_SIZE(v)) #define va_arg(ap,t) (*(t *)((ap += VA_ARG_SIZE(t)) - VA_ARG_SIZE(t))) #define va_end(ap) (ap = (va_list)0) #endif /* #ifdef __GNUC__ */ /*------------------------- interface ------------------------------------- */ /* ++ * Routine Description: * vsprintf_s function to process format and place the * results in Buffer. Since a va_list is used this rountine allows the nesting * of Vararg routines. Thus this is the main print working routine * Arguments: * buffer_start - buffer to print the results of the parsing of Format * into. * buffer_size - Maximum number of characters to put into buffer * (including the terminating null). * format - Format string see file header for more details. * argptr - Vararg list consumed by processing format. * Returns: * Number of characters printed. * Notes: * Format specification * * Types: * %X - hex uppercase unsigned integer * %x - hex lowercase unsigned integer * %P - hex uppercase unsigned integer, 32bit on x86 and 64bit on em64t * default width - 10 chars, starting with '0x' prefix and including * leading zeroes * %p - hex lowercase unsigned integer, 32bit on x86 and 64bit on em64t * default width - 10 chars, starting with '0x' prefix and including * leading zeroes * %u - unsigned decimal * %d - signed decimal * %s - ascii string * %c - ascii char * %% - % * * Width and flags: * 'l' - 64bit integer, ex: "%lx" * '0' - print leading zeroes * positive_number - field width * * Width and flags\types %X/%x %P/%p %u %d %s %c %% * 'l' o x o o x x x * '0' o o o o x x x * positive_number o o o o o x x * sample: * ("%016lx", 0x1000): 0000000000001000 * ("%06d", -1000): -01000 * ("%016p", 0x1000): 0x00000000001000 * ("%5s", "strings"): strin * ("%8x", 0x1000): ' '' '' '' '1000 *--------------------------------------------------------------------------- */ uint32_t vmm_vsprintf_s(char *buffer_start, uint32_t buffer_size, const char *format, va_list argptr); uint32_t vmm_sprintf_s(char *buffer_start, uint32_t buffer_size, const char *format, ...); #endif
C
//gcc -Wall -march=haswell -std=c11 -O2 -o a.out source_file.c //clang -std=c11 -mavx avxvec.c -o avxvec #include <x86intrin.h> #include <stdio.h> #include <stdlib.h> #include <time.h> void clear_array(float *array, int size) { for (int i = 0; i < size; i++) array[i] = 0; } void fill_from_to(float *array, int from, int to) { for (int i = from; i < to; i++) array[i - from] = i; } void print_first_n(float * array, int n) { for (int i = 0; i < n; i++) printf("%f ", array[i]); printf("\n"); } void print_last_n(float * array, int size, int n) { for (int i = size - 1; i > size - 1 - n; i--) printf("%f ", array[i]); printf("\n"); } void benchmark_common_scalar_product(float * array, int size, float value) { double t0 = clock(); for (int i = 4; i < size; i++) array[i] *= value; double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_scalar_product_256_set(float * array, int size, float value) { double t0 = clock(); __m256 v2 = _mm256_set_ps(value, value, value, value, value, value, value, value); for (int i = 4; i <= size - 8; i+=8) { __m256 v = _mm256_set_ps(array[i+7], array[i+6], array[i+5], array[i+4], array[i+3], array[i+2], array[i+1], array[i]); __m256 sq = _mm256_mul_ps(v, v2); _mm256_store_ps(array + i, sq); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_scalar_product_256_load(float * array, int size, float value) { double t0 = clock(); __m256 v2 = _mm256_set1_ps(value); for (int i = 4; i <= size - 8; i+=8) { __m256 v = _mm256_load_ps(&array[i]); __m256 sq = _mm256_mul_ps(v, v2); _mm256_store_ps(array + i, sq); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_scalar_product_set_128(float * array, int size, float value) { double t0 = clock(); __m128 v2 = _mm_load_ps1(&value); for (int i = 4; i <= size - 4; i+=4) { __m128 v = _mm_set_ps(array[i+3], array[i+2], array[i+1], array[i]); __m128 sq = _mm_mul_ps(v, v2); _mm_store_ps(array + i, sq); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_scalar_product_load_128(float * array, int size, float value) { double t0 = clock(); __m128 v2 = _mm_load_ps1(&value); for (int i = 4; i <= size - 4; i+=4) { __m128 v = _mm_load_ps(&array[i]); __m128 sq = _mm_mul_ps(v, v2); _mm_store_ps(&array[i], sq); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_common_arrays_sum(float * array1, float * array2, int size) { double t0 = clock(); for (int i = 4; i < size; i++) array1[i] += array2[i]; double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_arrays_sum_set_256(float * array1, float * array2, int size) { double t0 = clock(); for (int i = 4; i <= size - 8; i+=8) { __m256 v1 = _mm256_set_ps(array1[i+7], array1[i+6], array1[i+5], array1[i+4], array1[i+3], array1[i+2], array1[i+1], array1[i]); __m256 v2 = _mm256_set_ps(array2[i+7], array2[i+6], array2[i+5], array2[i+4], array2[i+3], array2[i+2], array2[i+1], array2[i]); __m256 result =_mm256_add_ps(v1, v2); _mm256_store_ps(array1 + i, result); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_arrays_sum_load_256(float * array1, float * array2, int size) { double t0 = clock(); for (int i = 4; i <= size - 8; i+=8) { __m256 v1 = _mm256_load_ps(&array1[i]); __m256 v2 = _mm256_load_ps(&array2[i]); __m256 result =_mm256_add_ps(v1, v2); _mm256_store_ps(array1 + i, result); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_common_arrays_fma(float * array1, float * array2, float * array3, int size) { double t0 = clock(); for (int i = 4; i < size; i++) array1[i] += array1[i] * array2[i] + array3[i]; double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_arrays_fma_256(float * array1, float * array2, float * array3, int size) { double t0 = clock(); for (int i = 4; i <= size - 8; i+=8) { __m256 v1 = _mm256_load_ps(&array1[i]); __m256 v2 = _mm256_load_ps(&array2[i]); __m256 v3 = _mm256_load_ps(&array3[i]); __m256 result =_mm256_fmadd_ps(v1, v2, v3); _mm256_store_ps(array1 + i, result); } double t1 = clock(); printf("%f\n", t1 - t0); } void benchmark_intrinsic_arrays_fma_128(float * array1, float * array2, float * array3, int size) { double t0 = clock(); for (int i = 4; i <= size - 4; i+=4) { __m128 v1 = _mm_load_ps(&array1[i]); __m128 v2 = _mm_load_ps(&array2[i]); __m128 v3 = _mm_load_ps(&array3[i]); __m128 result =_mm_fmadd_ps(v1, v2, v3); _mm_store_ps(array1 + i, result); } double t1 = clock(); printf("%f\n", t1 - t0); } void matrices_product(float *matrix1, int rows1, int columns1, float *matrix2, int rows2, int columns2, float *matrix3) { for (int row = 0; row < rows1; row++) for (int col = 0; col < columns2; col++) for (int i = 0; i < columns1; i++) matrix3[row*col] += matrix1[row*i] * matrix2[i*columns1]; } void benchmark_matrices_product() { const int size1 = 192, size2 = 108; float *m1 = malloc(sizeof(float) * size1 * size2); float *m2 = malloc(sizeof(float) * size2 * size1); float *m3 = malloc(sizeof(float) * size1 * size1); fill_from_to(m1, 0, size1 * size2); fill_from_to(m2, 0, size2 * size1); clear_array(m3, size1 * size1); double t0 = clock(); matrices_product(m1, size1, size2, m2, size2, size1, m3); double t1 = clock(); printf("%f\n", m3[53]); free(m1); free(m2); free(m3); printf("%f\n", t1 - t0); } //see https://software.intel.com/sites/landingpage/IntrinsicsGuide/#techs=AVX int main() { const int ARRAY_SIZE = 100000004; const int SCALAR_VALUE = 3; float *array = malloc(sizeof(float) * ARRAY_SIZE); printf("---------------------------------------------------------------------------\n"); //conventional scalar product printf("common scalar product:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_common_scalar_product(array, ARRAY_SIZE, SCALAR_VALUE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic scalar product 256 printf("AVX2 scalar product set:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_scalar_product_256_set(array, ARRAY_SIZE, SCALAR_VALUE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic scalar product 256 printf("AVX2 scalar product load:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_scalar_product_256_load(array, ARRAY_SIZE, SCALAR_VALUE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic scalar product 128 set printf("SSE scalar product set:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_scalar_product_set_128(array, ARRAY_SIZE, SCALAR_VALUE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic scalar product 128 load printf("SSE scalar product load:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_scalar_product_load_128(array, ARRAY_SIZE, SCALAR_VALUE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //conventional sum printf("common sum:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_common_arrays_sum(array, array, ARRAY_SIZE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic sum 256 set printf("AVX2 sum set:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_arrays_sum_set_256(array, array, ARRAY_SIZE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic sum 256 load printf("AVX2 sum load:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_arrays_sum_load_256(array, array, ARRAY_SIZE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //common fma printf("common fma:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_common_arrays_fma(array, array, array, ARRAY_SIZE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic fma printf("intrinsic fma 256:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_arrays_fma_256(array, array, array, ARRAY_SIZE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); //intrinsic fma printf("intrinsic fma 128:\n"); clear_array(array, ARRAY_SIZE); fill_from_to(array, 0, ARRAY_SIZE); benchmark_intrinsic_arrays_fma_128(array, array, array, ARRAY_SIZE); print_first_n(array, 10); print_last_n(array, ARRAY_SIZE, 10); free(array); //matrices product printf("common matrices product:\n"); benchmark_matrices_product(); printf("---------------------------------------------------------------------------\n"); //printf("%f\n", array[5]); //__m256d v = _mm256_load_pd(array); //__m256d v = _mm256_set_pd(1, 2, 5, 4); // (e3, e2, e1, e1); //__m256d sq = _mm256_mul_pd(v, v); //__m256 v2 = _mm256_set_ps(1, 2, 3, 4, 5, 6, 7, 8); // (e3, e2, e1, e1); //_mm256_store_pd(array, sq); return 0; }
C
#include <stdio.h> #include <string.h> #include "file_reader.h" #include "line_reader.h" enum file_phase_t { INPUT_PHASE, OUTPUT_PHASE, NODES_PHASE }; typedef enum file_phase_t File_phase; Logical_circuit* read_logical_circuit_file(char* filepath) { FILE *file; File_phase file_phase = INPUT_PHASE; file = fopen(filepath, "r"); if (file == NULL) { printf("Nie można otworzyć pliku %s.\n", filepath); return NULL; } Logical_circuit* logical_circuit = create_empty_logical_circuit(); Node *tmp_node = NULL; char *line; int failed = 0; do { line = read_one_line_from_file(file); if (line != NULL) { if (file_phase == INPUT_PHASE) { logical_circuit->nodes = create_input_nodes_from_line_of_text(line); if (logical_circuit->nodes == NULL) { failed = 1; } file_phase = OUTPUT_PHASE; } else if (file_phase == OUTPUT_PHASE) { logical_circuit->output_id = read_output_id_from_line_of_text(line); if (logical_circuit->output_id == -1) { failed = 1; break; } file_phase = NODES_PHASE; } else if (file_phase == NODES_PHASE) { if (tmp_node == NULL) { tmp_node = logical_circuit->nodes; } while (tmp_node->next != NULL) { tmp_node = tmp_node->next; } tmp_node->next = create_node_from_line_of_text(line); if (tmp_node->next == NULL) { failed = 1; break; } tmp_node = tmp_node->next; } } else { break; } } while (line != NULL); fclose(file); if (failed) { printf("Wystapil problem z przeczytaniem lini - '%s' z pliku '%s'", line, filepath); free_logical_circuit_from_memory(logical_circuit); return NULL; } return logical_circuit; } Input_state_change* read_input_state_file(char* filepath) { FILE *file; file = fopen(filepath, "r"); if (file == NULL) { printf("Nie można otworzyć pliku %s.\n", filepath); return NULL; } Input_state_change *input_state_change = create_empty_input_state_change(); Input_state_change *tmp_input_state_change = input_state_change; char *line; int failed = 0; do { line = read_one_line_from_file(file); if (line == NULL) { break; } if (input_state_change->input_state == NULL) { input_state_change->input_state = read_input_state_from_line_of_text(line); if (input_state_change->input_state == NULL) { failed = 1; break; } } else { if (tmp_input_state_change->next == NULL) { tmp_input_state_change->next = create_empty_input_state_change(); } tmp_input_state_change->next->input_state = read_input_state_from_line_of_text(line); if (tmp_input_state_change->next->input_state == NULL) { failed = 1; break; } tmp_input_state_change = tmp_input_state_change->next; } } while (line != NULL); fclose(file); if (failed) { printf("Wystapil problem z przeczytaniem lini - '%s' z pliku '%s'", line, filepath); free_input_state_change_from_memory(input_state_change); return NULL; } return input_state_change; }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* ft_paths_better_eval.c :+: :+: */ /* +:+ */ /* By: ayundina <[email protected]> +#+ */ /* +#+ */ /* Created: 2019/09/17 15:46:30 by ayundina #+# #+# */ /* Updated: 2019/09/17 15:46:32 by ayundina ######## odam.nl */ /* */ /* ************************************************************************** */ #include "lem_in.h" /* ** ft_paths_better_eval() function counts the number of steps it will take to ** lead the given number of ants through the given paths. ** First it counts the number of ants per path where paths[0][0]->path_row ** refers to the number of given paths. ** paths[row][0]->path_col refers to the length of the path. ** In a while loop the function counts the sum of steps through all the paths, ** and ft_count_steps counts the final number of steps. ** If the new number of steps is less or equal to previous and the number ** of rooms in last added path is less or equal to the number of steps ** a new evaluation of steps replaces the previous ** ** Param 1: t_room ***paths is an array of paths, where one path is an array ** of rooms. ** ** Param 2: int num_ants is the number of ants given to lead through the graph. ** ** Returns: 1 if the new combination of paths gives smaller or same number of ** steps comparing to the previous combination, 0 otherwise. */ int ft_paths_better_eval(t_room ***paths, int num_ants) { int row; int steps; int ants_per_path; int ants_per_path_remain; row = 0; ants_per_path = num_ants / (paths[0][0]->path_row + 1); ants_per_path_remain = num_ants % (paths[0][0]->path_row + 1); steps = paths[row][0]->path_col + ants_per_path + ants_per_path_remain - 2; while (paths[row + 1] != NULL && paths[row + 1][1] != NULL) { row++; steps += paths[row][0]->path_col + ants_per_path - 2; } steps = ft_count_steps_per_path(steps, paths[0][0]->path_row + 1); if ((steps <= paths[0][0]->combo_eval && steps >= paths[paths[0][0]->path_row][0]->path_col) || paths[0][0]->combo_eval == 0) { paths[0][0]->combo_eval = steps; return (1); } return (0); }
C
/* ** EPITECH PROJECT, 2017 ** switch.c ** File description: ** each carac on a string */ #include "../include/included.h" int get_line(char **map) { int x = 0; while (map[x] != NULL) x++; return (x); } void my_sw(int **map) { for(int y = 0; map[y]; y++) { for(int x = 0; map[y][x] != -1; x++) { if (map[y][x] == '.') map[y][x] = 1; if (map[y][x] == 'o') map[y][x] = 0; } } } int get_min(int **map, int y, int x) { int min = 10000000; if (x > 0 && map[y][x - 1] < min) min = map[y][x - 1]; if (x > 0 && y > 0 && map[y - 1][x - 1] < min) min = map[y - 1][x - 1]; if (y > 0 && map[y - 1][x] < min) min = map[y - 1][x]; return (min); } void my_algo(int **map) { int y; int x; y = 1; while (map[y]) { x = 1; while (map[y][x] != -1) { if (map[y][x] != 0) map[y][x] = get_min(map, y, x) + 1; x++; } y++; } } int search_big(int **map, int *xptr, int *yptr) { int max; int x; int y; max = 0; *yptr = 0; *xptr = 0; y = 0; while (map[y]) { x = 0; while (map[y][x] != -1) { if (map[y][x] > max) { max = map[y][x]; *xptr = x; *yptr = y; } x++; } y++; } return (max); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msymkany <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/03/25 17:55:52 by msymkany #+# #+# */ /* Updated: 2017/04/13 20:34:03 by msymkany ### ########.fr */ /* */ /* ************************************************************************** */ #include "push.h" int visualize(int *stack, int length, t_op *op) { t_stack *a; t_stack *b; int num; num = 0; b = NULL; a = push_to_list(stack, length); while (op) { print_stack_a_b(a, b); read(0, NULL, 1); ft_printf("%s\n", op->op); commands(op->op, &a, &b); op = op->next; num++; } print_stack_a_b(a, b); del_stack(a); return (num); } void sort_print(int *stack, int length, int wrong, char flag) { t_stack *list; t_op *op; t_op *ptr; int num; num = 0; list = push_to_list(stack, length); (flag & 2) ? print_stack_a_b(list, NULL) : 0; op = sort_it(&list, length, wrong); ptr = op; if (flag & 1) num = visualize(stack, length, op); else while (ptr) { if ((flag & 7) == 0) ft_printf("%s\n", ptr->op); ptr = ptr->next; num++; } (flag & 4) ? print_stack_a_b(list, NULL) : 0; if (flag & 8) ft_printf("Number of operations: %d\n", num); del_stack(list); del_op(op); } int main(int ar, char **av) { int *stack; int wrong; char flag; int count_flag; wrong = 0; flag = 0; count_flag = 0; stack = 0; if (ar == 1) ft_usage(av[0]); else { count_flag = get_flags(ar, av, &flag); stack = (read_stack(ar, av, &wrong, count_flag)); if (wrong == 0) exit(0); else sort_print(stack, ar - count_flag, wrong, flag); } free(stack); return (0); }
C
/* getLine.c * Implements the getLine function for CS 3 Lab 2 * Alex Lew * 11/8/15 */ #include <stdlib.h> #include <stdio.h> #define DEFAULT_ALLOC_SIZE 10 /* Read the next line of the standard input into a newly allocated * buffer. Returns a pointer to that buffer if successful. If unable * to allocate memory, or if STDIN has ended (getchar() == EOF), * getLine will return NULL. It is the caller's responsiblity to free * the allocated memory when it is no longer needed. */ char *getLine() { int size = DEFAULT_ALLOC_SIZE; char *str = malloc(size); if (!str) return NULL; int i = 0; char c; while ((c = getchar()) != '\n' && c != EOF) { if (i == size - 2) { size = size * 2; char *temp = realloc(str, size); if (!temp) { str[i] = '\0'; return str; } else { str = temp; } } str[i] = c; i++; } if (c == '\n') { str[i++] = '\n'; } str[i] = '\0'; if (i == 0) { free(str); str = NULL; } return str; }
C
#include <stdio.h> #include <stdlib.h> int main(int ac, char **av) { int input; int startc; int endc; int start; int end; int current; scanf("%d%d", &start, &end); scanf("%d", &input); current = 0; while (input--) { scanf("%d%d", &startc, &endc); if (startc <= end && endc >= start) current++; } printf("%d\n", current); ac = ac; av = av; return (0); }
C
#include <unistd.h> #include <fcntl.h> #include <stdio.h> int main(int argc, char **argv) { char buf[2]; char file[] = "/tmp/httpXXXXXX"; int filedesc = mkstemp(file); printf("%s\n", file); /*int filedesc = open(file, O_RDWR);*/ if(filedesc < 0) { return 1; } write(filedesc,"This will be output to testfile.txt\n", 36); close(filedesc); filedesc = open(file, O_RDWR); while(read(filedesc, buf, sizeof(buf))) { printf("%s", buf); } return 0; }
C
/********************************************************************************************** Filename: buffer.h Compiler: Visual Studio Premium 2012 Author: Amaury Diaz Diaz, 040-738-985 Course: CST8152 Compilers, Lab Section: 012 Assignment: Assignment 1 - The Buffer Date: September 28, 2015 Professor: Svillen Ranev Purpose: Building a Buffer Data structure capable of storing and retrieving characters. Function list: b_create(), b_addc(), b_reset(), b_destroy(), b_isfull(), b_size(), b_capacity(), b_setmark(), b_mark(), b_mode(), b_inc_factor(), b_load(), b_isempty(), b_eob(), b_getc(), b_print(), b_pack(), b_rflag(), b_retract(), b_retract_to_mark(), b_getc_offset() *********************************************************************************************/ #ifndef BUFFER_H_ #define BUFFER_H_ /*#pragma warning(1:4001) *//*to enforce C89 type comments - to make //comments an warning */ /*#pragma warning(error:4001)*//* to enforce C89 comments - to make // comments an error */ /* standard header files */ #include <stdio.h> /* standard input/output */ #include <malloc.h> /* for dynamic memory allocation*/ #include <limits.h> /* implementation-defined data type ranges and limits */ /* constant definitions */ /* You may add your own constant definitions here */ #define R_FAIL_1 -1 /* fail return value */ #define R_FAIL_2 -2 /* fail return value */ #define LOAD_FAIL -2 /* load fail error */ #define SET_R_FLAG 1 /* realloc flag set value */ #define FIX_M 0 /*fixed mode*/ #define ADD_M 1 /*additive mode*/ #define MULT_M -1 /*multiplicative mode*/ #define MAXIMUM_BUFFER_SIZE SHRT_MAX /*maximum buffer size(defined by the data type of the capacity)*/ #define INC_FACTOR_FAIL 256 /*Value returned if the Increment factor is invalid*/ #define R_SUCCESS_1 1 /*Value returned if the buffer was reset correctly*/ #define B_EMPTY 1 /*Value returned if the buffer is empty*/ #define B_NON_EMPTY 0 /*Value returned if the buffer is not empty*/ #define B_FULL 1 /*Value returned if the buffer is full*/ #define B_NON_FULL 0 /*Value returned if the buffer is not full*/ #define SET_DEFAULT 0 /*Set the members of the buffer structure to its default value*/ #define INC_ADDCOFFSET 1 /*Increment the addc_offset by 1*/ #define EOB_REACHED 1 /*Value given if the end of buffer is reached*/ /* user data type declarations */ typedef struct BufferDescriptor { char *cb_head; /* pointer to the beginning of character array (character buffer) */ short capacity; /* current dynamic memory size (in bytes) allocated to character buffer */ short addc_offset; /* the offset (in chars) to the add-character location */ short getc_offset; /* the offset (in chars) to the get-character location */ short mark_offset; /* the offset (in chars) to the mark location */ char inc_factor; /* character array increment factor */ char r_flag; /* character array reallocation flag */ char mode; /* operational mode indicator*/ int eob; /* end-of-buffer reached flag */ } Buffer, *pBuffer; /*typedef Buffer *pBuffer;*/ /* function declarations */ Buffer * b_create(short,char,char); pBuffer b_addc(pBuffer const,char); int b_reset(Buffer*const); void b_destroy(Buffer*const); int b_isfull(Buffer*const); short b_size(Buffer *const); short b_capacity(Buffer *const); char * b_setmark(Buffer*const,short); short b_mark(Buffer*const); int b_mode(Buffer*const); size_t b_inc_factor(Buffer*const); int b_load(FILE *const, Buffer*const); int b_isempty(Buffer*const); int b_eob(Buffer*const); char b_getc(Buffer*const); int b_print(Buffer*const); Buffer*b_pack(Buffer*const); char b_rflag(Buffer*const); short b_retract(Buffer*const); short b_retract_to_mark(Buffer*const); short b_getc_offset(Buffer*const); #endif
C
#include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <string.h> #include <signal.h> #define ERR_EXIT(m)\ do\ {\ perror(m);\ exit(EXIT_FAILURE);\ }while(0) int globale = 100; int main() { signal(SIGCHLD,SIG_IGN); printf("before fokk pid = %d\n",getpid()); pid_t pid = fork(); if(-1 == pid) ERR_EXIT("fork"); if(pid > 0) { sleep(1); globale += 50; printf("this is parent ,globale = %d\n",globale); sleep(3); } else { globale -= 50; printf("this is child ,globale = %d\n",globale); } return 0; }
C
#if USE_UART //----------------------------------Инициализация UART---------------------------------- void dataChannelInit(void) //инициализация UART { PRR &= ~(0x01 << 1); //включаем питание UART UBRR0 = (F_CPU / (8UL * UART_BAUND)) - 1; //устанавливаем битрейт UCSR0A = (0x01 << U2X0); //устанавливаем удвоение скорости UCSR0B = ((0x01 << TXEN0)); //разрешаем передачу UCSR0C = ((0x01 << UCSZ01) | (0x01 << UCSZ00)); //длинна пакета 8бит } //----------------------------------Выключение UART---------------------------------- void dataChannelEnd(void) //выключение UART { UCSR0B = 0; //выключаем UART PRR |= (0x01 << 1); //включаем питание UART } //----------------------------------Отправка команды---------------------------------- void sendNumI(uint32_t num) //отправка команды { char buf[15]; uint8_t c = 0; buf[c++] = '\n'; //перевод строки buf[c++] = '\r'; //установка курсора в начало строки buf[c++] = '\0'; //конец строки if (num) { while (num > 0) { buf[c++] = 48 + (num % 10); num = (num - (num % 10)) / 10; } } else buf[c++] = 48; while (c) { while (!(UCSR0A & (1 << UDRE0))); UDR0 = buf[--c]; } } #endif
C
#include <stdio.h> #include <math.h> int win(char c[]){ if(c[0]==c[1] && c[1]==c[2] && c[0]!='\0') return 1; else if(c[3]==c[4] && c[4]==c[5] && c[3]!='\0') return 1; else if(c[6]==c[7] && c[7]==c[8] && c[6]!='\0') return 1; else if(c[0]==c[3] && c[3]==c[6] && c[0]!='\0') return 1; else if(c[1]==c[4] && c[4]==c[7] && c[1]!='\0') return 1; else if(c[2]==c[5] && c[5]==c[8] && c[2]!='\0') return 1; else if(c[0]==c[4] && c[4]==c[8] && c[4]!='\0') return 1; else if(c[2]==c[4] && c[4]==c[6] && c[4]!='\0') return 1; return 0; } int main(){ int counter = 0 , input; char tabel_xo[9]={'\0'}; while(counter < 9){ if(counter%2 == 0){ printf("Player X: \n"); scanf("%d" ,&input); if(tabel_xo[input-1] == '\0') tabel_xo[input-1] = 'X'; else counter--; } else{ printf("Player O: \n"); scanf("%d" ,&input); if(tabel_xo[input-1] == '\0') tabel_xo[input-1] = 'O'; else counter--; } printf("%c | %c | %c\n" ,tabel_xo[0],tabel_xo[1],tabel_xo[2]); printf("%c | %c | %c\n" ,tabel_xo[3],tabel_xo[4],tabel_xo[5]); printf("%c | %c | %c\n" ,tabel_xo[6],tabel_xo[7],tabel_xo[8]); if(win(tabel_xo)==1) break; counter++; } if(counter%2 == 0) printf("Player X has won the game \n"); else printf("Player O has won the game \n"); }
C
/** * @file board.h * @author Berki Tamás - PDRE31 * @date 2017. 11. 01. */ #ifndef BOARD_H #define BOARD_H #define BOARD_BG "\e[0m" ///< A táblában használt háttérszín (fehér) #define BOARD_FG "\e[0m\e[7m" ///< A táblában használt előtérszín (fekete) #define BOARD_EMPTY "\e[38;5;252m" ///< Az üres elem előtérszíne (szürke) #define BOARD_P1 "\e[38;5;160m" ///< Az első játékos előtérszíne (piros) #define BOARD_P2 "\e[38;5;38m" ///< A második játékos előtérszíne (kék) #define BOARD_SELECT "\e[38;5;241m" ///< A kijelölt elem előtérszíne (sötétszürke) #define BOARD_BLOCK_BG " " ///< A blokk megjelenítésére használt karakter (háttér) #define BOARD_BLOCK_FG " " ///< A blokk megjelenítésére használt karakter (előtér) #define BOARD_BLOCK_SELECT "[]" ///< A kijelölt blokk megjelenítésére használt karakter #define BOARD_BLOCK_MOVING "@@" ///< A mozgatandó blokk megjelenítésére használt karakter #define BLINK_TIME 500 ///< A táblában lévő animáció intervalluma miliszekundumban /** * @brief Irányt leíró enum * * Mozgásnál használjuk, pl board_move_cursor() * */ typedef enum Direction { D_UP, ///< Fel D_RIGHT,///< Jobbra D_DOWN,///< Le D_LEFT///< Balra } dir_t; /** * @brief A játékosok enumja */ enum Player { PLAYER_1, ///< Első játékos PLAYER_2 ///< Második játékos }; /** * @brief A játszma részei */ enum BoardStage { STAGE_PLACE, ///< Bábuk lerakása STAGE_MOVE ///< Bábuk mozgatása }; /** * @brief A tábla tulajdonságai */ struct Board { bool win; ///< Nyert-e valaki? enum Player winner; ///< Ki nyert? enum BoardStage stage; ///< A malom játéknak 2 része van, itt tároljuk, hogy melyik az aktuális bool remove_mode; ///< Akkor true, ha valaki malmot rakott ki, és az ellenfél bábuját akarja levenni bool move_mode; ///< A második részben az az állapot, amikor a játékos kijelölte a mozgatni kívánt bábut bool paused; ///< Le van-e állítva a játék? element_t *selected_element; ///< A kiválaszott elem element_t *moving_element; ///< A mozgatni kívánt elem /** * Az játék első felében létrejöhet az az eset, hogy egyszerre két malmot rak ki a játékos * Ebben az esetben annyi bábut vehet le, ahány malmot kirakott * Ez a speciális eset csak az első részben lehetséges, és kettőnél több malom nem rakható ki egyszerre */ int removable_pieces; ///< A malom kirakása során levehető bábuk száma /** * Ezt azért kell külön eltárolni, mert már az első részben fennállhat az az eset, hogy * valaki malmot rak ki, és levesz az ellenfél bábui közül egyet, szóval kevesebb bábu * lesz a táblán, mint 9+9, de attól még 9+9 bábut tettek le a játékosok. */ int placed_pieces; ///< Az első részben lerakott bábuk száma enum Player current_player; ///< A jelenlegi játékos }; /** * @brief A tábla inicializálása */ void board_init(); /** * @brief A tábla frissítése * * @param[in] input Input * @param running Cikluskilépéshez átadjuk a pointert */ void board_update(input_t input, bool *running); void board_debug(); /** * @brief Rendereli a táblát */ void board_render(); /** * @brief Továbbítja a győztest * * @return Győztes játékos */ enum Player board_winner(); /** * @brief Leellenőrzi, hogy van-e nyertes * * Ez az eljárás el is végzi a szükséges teendőket, ha valamelyik játékos nyert * * @param running Cikluskilépéshez átadjuk a pointert */ void board_check_win(bool *running); /** * @brief Megnézi az összes ugyanolyan státuszú bábuk számát * * @param[in] p Az ellenőrizendő bábu státusza * * @return Az ugyanolyan státuszú bábuk száma */ int count_pieces_with_status(enum PieceStatus p); /** * @brief Leellenőrzi, hogy megadott bábu tud-e mozogni a megadott pontra * * @param from A mozgatandó bábu * @param to A cél * * @return Mozgatható-e oda? */ bool piece_can_move_here(struct Piece *from, struct Piece *to); /** * @brief Leellenőrzi, hogy a megadott bábu tud-e mozogni * * @param p Az ellenőrizendő bábu * * @return Tud-e mozogni? */ bool piece_can_move(struct Piece *p); /** * @brief Megnézi, hogy a megadott játékos összes bábuja malomban van-e * * @param[in] player Az ellenőrizendő játékos * * @return Malomban van-e az összes bábu? */ bool board_check_all_mill_player(enum Player player); /** * @brief Megnézi, hogy az adott bábu malomban van-e * * Muszáj visszaadni, hogy hány malom alakult ki. (ld. Board::removable_pieces) * * @param p A bábu * * @return Malomban van-e? */ int board_check_mill(struct Piece *p); /** * @brief A kijelölt bábu lehelyezése a táblára */ void board_place_piece(); /** * @brief A kurzor mozgatása a táblán * * @param[in] d A mozgatás iránya */ void board_move_cursor(enum Direction d); /** * @brief Megteremti a logikai kapcsolatot az elemek és a bábuk között */ void set_piece_element_relation(); /** * @brief Egy elemet rajzol ki, a makrókban meghatározottak alapján * * @param output A kimenő string pointere * @param[in] row Az elem sora * @param[in] col Az elem oszlopa */ void draw_element(char *output, int row, int col); /** * @brief Egy sort rajzol ki, a draw_element() függvény alapján * * @param output A kimenő string pointere * @param[in] row A kirajzolandó sor */ void draw_row(char *output, int row); #endif
C
#define __ELEMENT_NODE__ // 这个头文件必须在fifo前,才能使用ElementNode,否则fifo会调用内部自定义的结构体。 typedef struct { char * lpBuffer; int nLoc; int nSize; int bUsed; }MemoryBuffer,*ElementNode; #include "fifo.h" #ifndef __MEMORY_H__ #define __MEMORY_H__ // 分配MemoryBuffer内存,释放MemoryBuffer内存 MemoryBuffer * memory_new_data(int size); void memory_delete_data(MemoryBuffer * mem); //打印数据 void memory_print_data(FIFO * li); // 得到内部数据的个数,不是fifo中ElementNode的个数。 int memory_get_data_size(FIFO * li); // 把li中的数据复制到output中,output的尺寸最大是outsize个字节。 int memory_output_data(char * output,int outsize,FIFO * li); // 把input中的数据复制到li中,input中的数据个数是insize个字节。 int memory_input_data(const char * input,int insize,FIFO * li); #endif
C
#include "csapp.h" #include "bit.h" typedef unsigned float_bits; /* Return the position of leftmost one. The position starts at 1. When x = 0, return 0 */ int leftmost_one_pos(unsigned x) { int high = 31; int low = 0; int middle; int result; int length = high - low; while (length >= 0) { middle = (low + high) / 2; result = x >> middle; if (result == 0x1) return middle + 1; else if (result > 0x1) low = middle + 1; else high = middle - 1; length = high - low; } return 0; } /* Compute (float) i */ float_bits float_i2f(int i) { //unsigned sign = f >> 31; //unsigned exp = f >> 23 & 0xff; //unsigned frac = f & 0x7fffff; unsigned sign; unsigned exp;; unsigned frac; unsigned round_to_even; int pos; //convert negative to positive if (i == INT_MIN) { return 0xcf000000; } else if (i < 0) { sign = 1; i = -i; } else sign = 0; //Compute the the position of leftmost one of bit pattern of i pos = leftmost_one_pos(i); exp = pos + 126; if (pos == 0) return 0x0; else if (pos <= 24) { frac = (i & lower_ones(pos - 1)) << (24 - pos); } else if (pos > 24) { frac = ((i >> (pos - 24)) & lower_ones(23)); unsigned lsb_frac = 0x1 & frac; unsigned round_off = i & lower_ones(pos - 24); if (lsb_frac == 0x0) { if (round_off > (1 << (pos - 25))) { frac += 1; } } else { if (round_off >= (1u << (pos - 25))) { if (frac == 0x7fffff) { frac = 0; exp = pos + 127; } else { frac += 1; } } } } return (sign << 31) | (exp << 23) | frac; } int main() { int i = INT_MIN; do { printf("%d\n", i); unsigned u = float_i2f(i); if (isnan(u2f(u))) { if (!isnan((float) i)) printf("The test failed when integer i = %d\n", i); return -1; } else if (u2f(u) != (float) i) { printf("The test failed when integer i = %d\n", i); return 1; } } while (++i != INT_MIN); printf("All test passed\n"); }
C
#include <stdio.h> int main() { int x; int one, two, five; scanf("%d", &x); for(one=0;one<=x*10;one++) { for(two=0;two<=x*5;two++) { for(five=0;five<=x*2;five++){ if(one+two*2+five*5==x*10){ printf("%d , %d and %d get %d .\n", one, two, five, x); break; } } break; } break; } return 0; }
C
#include <stdio.h> int main() { int n; scanf_s("%d", &n); if (n < 0) { printf(" µ %d Դϴ\n", n); } else { printf(" µ %d Դϴ\n", n); } return 0; }
C
/* POINTERS */ // Pointers are very important in C programming because they allow you // to easily work with memory locations. // They are fundamental to arrays, strings, and other data structures and // algorithms. // A pointer is a variable that contains the address of another variable. // In other words, it "points" to the location assigned to a variable and // can indirectly access the variable. // Pointers are declared using the * symbol and take the form: // pointer_type *identifier // ointer_type is the type of data the pointer // Asterisk * declares a pointer and should appear next to the // identifier used for the pointer variable. #include <stdio.h> void swap (int *num1, int *num2); int main() { int j = 63; // Pointers should be initialized to NULL until they are assigned a valid location. int *p = NULL; p = &j; printf("The address of j is %x\n", &j); printf("p contains address %x\n", p); printf("The value of j is %d\n", j); printf("p is pointing to the value %d\n", *p); // Some algorithms use a pointer to a pointer int a = 12; int *p1 = NULL; int **ptr = NULL; p1 = &a; ptr = &p1; // Pointers and Arrays int x[5] = {22, 33, 44, 55, 66}; int *ptr_x = NULL; int i; ptr_x = x; // atribuir o pointer a array for (i = 0; i < 5; i++) { // pointing each element --> using address arithmetic to transverse the intere array printf("%d ", *(ptr_x + i)); printf("\n"); } // Besides using + and – to refer to the next and previous memory // locations, you can use the assignment operators to change the address // the pointer contains. printf("%d %x\n", *ptr_x, ptr_x); /* 22 */ ptr_x++; printf("%d %x\n", *ptr_x, ptr_x); /* 33 */ ptr_x += 3; printf("%d %x\n", *ptr_x, ptr_x); /* 66 */ ptr_x--; printf("%d %x\n", *ptr_x, ptr_x); /* 55 */ ptr_x -= 2; printf("%d %x\n", *ptr_x, ptr_x); /* 33 */ // Pointer and Functions int z = 25; int y = 100; printf("x is %d, y is %d\n", z, y); swap(&z, &y); printf("x is %d, y is %d\n", z, y); return 0; } void swap (int *num1, int *num2) { int temp; temp = *num1; *num1 = *num2; *num2 = temp; }
C
#ifndef _STRUTIL_H #define _STRUTIL_H 1 #include <string.h> #include "banking.h" int strcmp(const char* a, const char* b); int strcmpi(const char* a, const char* b); int str_equals(char* a, char* b); int indexof(const char* str, int c); int lindexof(const char* str, int c, int start); int str_startswith(const char* str, const char* prefix); int str_endswith(const char* str, const char* suffix); int basicToCstr(const char* str, char* buf); char* strtok(char *str, int delim); char* strtokpeek(char* str, int delim); void strset(char* buffer, int value, int limit); char* strcat(char* dst, const char* add); char* strncpy(char* dest, char* src, int limit); void strpad(char* dest, int limit, int pad); int htoi(char* s); extern char *lasts; static inline void setstrtok(char *str) { lasts = str; } // string constants in ROM cannot be passed directly.. use this utility to hoist them to ram first. extern char str2ram_buf[128]; static inline char* str2ram(const char* str) { memcpy(str2ram_buf, str, 128); return str2ram_buf; } DECLARE_BANKED(strcmp, BANK(1), int, bk_strcmp, (const char *a, const char *b), (a, b)) DECLARE_BANKED(strcmpi, BANK(1), int, bk_strcmpi, (const char *a, const char *b), (a, b)) DECLARE_BANKED(str_equals, BANK(1), int, bk_str_equals, (const char *a, const char *b), (a, b)) DECLARE_BANKED(indexof, BANK(1), int, bk_indexof, (const char *str, int c), (str, c)) DECLARE_BANKED(lindexof, BANK(1), int, bk_lindexof, (const char *str, int c, int start), (str, c, start)) DECLARE_BANKED(str_startswith, BANK(1), int, bk_str_startswith, (const char *str, const char *prefix), (str, prefix)) DECLARE_BANKED(str_endswith, BANK(1), int, bk_str_endswith, (const char *str, const char *suffix), (str, suffix)) DECLARE_BANKED(basicToCstr, BANK(1), int, bk_basicToCstr, (const char *str, char *buf), (str, buf)) DECLARE_BANKED(strtok, BANK(1), char *, bk_strtok, (char *str, int delim), (str, delim)) DECLARE_BANKED(strtokpeek, BANK(1), char *, bk_strtokpeek, (char *str, int delim), (str, delim)) DECLARE_BANKED_VOID(strset, BANK(1), bk_strset, (char *buffer, int value, int limit), (buffer, value, limit)) DECLARE_BANKED(strcat, BANK(1), char *, bk_strcat, (char *dst, const char *add), (dst, add)) DECLARE_BANKED(strncpy, BANK(1), char *, bk_strncpy, (char *dest, char *src, int limit), (dest, src, limit)) DECLARE_BANKED_VOID(strpad, BANK(1), bk_strpad, (char *dest, int limit, int pad), (dest, limit, pad)) DECLARE_BANKED(htoi, BANK(1), int, bk_htoi, (char* s), (s)) #endif
C
#include<stdio.h> #include<math.h> void hello(); void add(); void subtract(); void Multi(); void div(); void mod(); void cal(); void prime(); void rev1(); void count(); void count1(); void armstrong(); void strong1(); void cuber(); void squarer(); void cube(); void square(); void npow(); void evechck(); void oddchck(); void halfpyramids(); void halfpyramidn(); void floydtrian(); void invertedfloy(); void invertedhalfs(); void invertedhalfn(); void leftpys(); void leftpyn(); void inleftpys(); void fact(); void butter(); void displayarr(); void sumofarr(); void sumofeve(); void sumofodd(); void sumofelementateve(); void sumofelementatedd(); void encrypt(); void multiele(); void multieveele(); void multioddel(); void averageofarr(); void reverseofarr(); void palindromearr(); void dispevenel(); void dispoddel(); void rightshift(); void leftshift(); void alphabet(){ char ch; printf("Enter the alphabet"); scanf("%c",&ch); if((ch>='A' && ch<='z')||(ch>='a' && ch<='z')){ switch(ch) { case 'A': case 'I': case 'E': case 'O': case 'U': case 'a': case 'i': case 'e': case 'o': case 'u': printf("Character is vowel"); break; default : printf("Character is Constant"); } } else { printf("%c is not an alphabet.\n",ch); } } void series() { int i,n,sume=0,sumo=0,sum = 0; printf("Till where you want:"); scanf("%d",&n); for(i=1;i<=n;i++){ if(i%2==0){ sume= sume + i; } else { sumo= sumo-i; } } sum = sume + sumo; printf("sum of series is : %d",sum); } void power() { int c,x,y; printf("Enter the value of x and y"); scanf("%d%d",&x,&y); c=pow(x,y); printf("%d",c); } void hcflcm() { int n; printf("Enter the value of n :"); scanf("%d",&n); } void datatype(){ char ch; int a; float b; double c; scanf("%c%d%f%lf",&ch,&a,&b,&c); printf("%c %d %f %lf",ch,a,b,c); } void salary() { float da,hra,ta,gs,tax,bs; printf("Enter basic salary"); scanf("%f",&bs); da = (bs*0.15); hra =( bs*10)/100; ta = (bs*5)/100; gs =bs +da+hra+ta; printf("\n Basic salary \t = %f",bs); printf("\n da \t = %f",da); printf("\n hra \t = %f",hra); printf("\n ta \t = %f",ta); printf("\n Gross salary \t = %f",gs); } void strong() { int num,i,f,r,sum=0,temp; printf("Enter a number: "); scanf("%d",&num); temp=num; while(num) { i=1,f=1; r=num%10; while(i<=r) { f=f*i; i++; } sum=sum+f; num=num/10; } if(sum==temp) printf("%d is a strong number",temp); else printf("%d is not a strong number",temp); } void paliendrome() { int i,flag=0,len; char str[20]; printf("enter the string"); fflush(stdin); gets(str); for(i=0;str[i]!=NULL;i++); len=i; for(i=0;i<(len-1)/2;i++) { if(str[i]!=str[len-1-i]){ flag=1; break; } } if(flag==0){ printf("str is palindrome",str[20]); } else{ printf("str is not palindrome",str[20]); } } void svowel() { int i,ctr=0; char str[20]; printf("enter the string"); fflush(stdin); gets(str); printf("%s \n",str); for(i=0;str[i]!=NULL;i++) { if((str[i]=='a')||(str[i]=='A')||(str[i]=='e')||(str[i]=='E')||(str[i]=='i')||(str[i]=='I')||(str[i]=='o')||(str[i]=='O')||(str[i]=='u')||(str[i]=='U')) { printf("%c",str[i]); ctr++; } } printf("%d \n",ctr); } void srev() { int i,j; char str[20]; printf("Enter the string\n"); fflush(stdin); gets(str); j=strrev(str); printf("%s",j); } void capital() { int i,ctr; char str[20]; printf("enter the string \n"); fflush(stdin); gets(str); for(i=0;str[i]!=NULL;i++) { if(str[i]>=65 && str[i]<=90){ str[i]=str[i]+32; } if(str[i]>=97 && str[i]<=122){ str[i]=str[i]-32; } printf("%s",str); } } void slast() { int i,k=0; char str[20],str1[20]; printf("enter the string\n"); fflush(stdin); gets(str); for(i=0;str[i]!=NULL;i++) ; for(i=i-1;i>=0;i--) { str[k+1]=str[i]; } str1[i]=NULL; printf("%s",str); } void slength() { char str[20]; int i; printf("enter the string\n"); fflush(stdin); gets(str); for (i = 0; str[i] != '\0'; i++); printf("Length of the string: %d", i); } void concat() { int i, j; char str[20],str1[20]; printf("Enter the String: \n"); fflush(stdin); gets(str); printf("Enter the String 1: \n"); gets(str1); for (i = 0; str[i] != '\0'; i++) { printf("i = %d\n", i); } for (j = 0; str1[j] != '\0'; j++,i++) { str[i] = str1[j]; } str[i] = '\0'; printf("After concatenation: "); puts(str); } void copy() { char s1[100], s2[100], i; printf("Enter string s1: "); fflush(stdin); gets(s1); for (i = 0; s1[i] != '\0';i++) { s2[i] = s1[i]; } s2[i] = '\0'; printf("String s2: %s", s2); } void substring() { char string[1000], sub[1000]; int position, length, c = 0; printf("Input a string\n"); fflush(stdin); gets(string); printf("Enter the position and length of substring\n"); scanf("%d%d", &position, &length); while (c < length) { sub[c] = string[position+c-1]; c++; } sub[c] = '\0'; printf("Required substring is \"%s\"\n", sub); } void strword() { int i,j,d,x=0; char str[20]; printf("Enter the string: "); fflush(stdin); gets(str); for (i = 0; str[i] != '\0';i++) { if(str[i]==' ') { x++; for (j=x,d=i; str[d] != '\0';j++,d++) { str[j]=str[d]; } str[j]=NULL; i=x+1; x++; } } printf("%s",str); } void sname() { char name[10]; int age; printf("Enter your first name and age: \n"); scanf("%s %d", name, &age); printf("You entered: %s %d",name,age); } void sswap() { char s1[100]; char s2[100]; char ch; printf(" Enter the string :"); fflush(stdin); gets(s1); printf(" Enter the string :"); fflush(stdin); gets(s2); int i = 0; printf("Before Swapping - \n"); printf("Value of s1 - %s \n", s1); printf("Value of s2 - %s \n", s2); while(s1[i] != '\0') { ch = s1[i]; s1[i] = s2[i]; s2[i] = ch; i++; } printf("After Swapping - \n"); printf("Value of s1 - %s \n", s1); printf("Value of s2 - %s \n", s2); } void maxmin(){ int i,n,arr[n],max=0,min=0; scanf("%d",&n); for(i=0;i<n;i++){ scanf("%d",&n); } max = arr[0]; for(i=0;i<n;i++){ if(min > arr[i]) { min = arr[i];} if(min<arr[i]){ max = arr[i]; } printf("Min: %d Max :%d",min,max); } } void digit(){ int i,n,arr[20]; printf("Enter the number"); scanf("%d",&n); if(n<9 && n>0){ printf("Single digit"); } else { printf("not a single digit"); } } void binary() { int n,r,i=1,binary =0; printf("Enter the decimal number :"); scanf("%d",&n); while(n!=0){ r=n%2; n=n/2; binary =binary + (r*i); i = i*10; } printf("Binary is %d",binary); } void perfect() { int i,n,sum=0; printf("Enter the number"); scanf("%d",&n); for(i=1;i<=n/2;i++) { if(n%i==0){ sum = sum +i; } if(sum==n) { printf("Number is perfect"); } else { printf("Number is not perfect"); } } } void asciialpha() { int ch; printf("Enter the alphabet :"); scanf("%d",&ch); if(ch>=65 && ch<=90) { printf("%c",ch); } if(ch>=97 && ch<=122) { printf("%c",ch); } } void factor() { int num, i; printf("Enter a positive integer: "); scanf("%d", &num); printf("Factors of %d are: ", num); for (i = 1; i <= num; ++i) { if (num % i == 0) { printf("%d ", i); } } } void factsum() { int i,n,fact=1,sum=0,dig ,dig1; printf("Enter the number :"); scanf("%d",&n); for(i=1;i<=n;i++) { if(n%2==0) { fact*= i ; } printf("%d",fact); } while(n) { sum += n % 10; n /= 10 ; } printf("%d",sum); } void matrixmult() { int first[10][10], second[10][10], mult[10][10], r1, c1, r2, c2; printf("Enter rows and column for the first matrix: "); scanf("%d %d", &r1, &c1); printf("Enter rows and column for the second matrix: "); scanf("%d %d", &r2, &c2); while (c1 != r2) { printf("Error! Enter rows and columns again.\n"); printf("Enter rows and columns for the first matrix: "); scanf("%d%d", &r1, &c1); printf("Enter rows and columns for the second matrix: "); scanf("%d%d", &r2, &c2); } enterData(first, second, r1, c1, r2, c2); multiplyMatrices(first, second, mult, r1, c1, r2, c2); display(mult, r1, c2); return 0; } void enterData(int first[][10], int second[][10], int r1, int c1, int r2, int c2) { printf("\nEnter elements of matrix 1:\n"); for (int i = 0; i < r1; ++i) { for (int j = 0; j < c1; ++j) { printf("Enter a%d%d: ", i + 1, j + 1); scanf("%d", &first[i][j]); } } printf("\nEnter elements of matrix 2:\n"); for (int i = 0; i < r2; ++i) { for (int j = 0; j < c2; ++j) { printf("Enter b%d%d: ", i + 1, j + 1); scanf("%d", &second[i][j]); } } } void multiplyMatrices(int first[][10], int second[][10], int mult[][10], int r1, int c1, int r2, int c2) { for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { mult[i][j] = 0; } } for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { for (int k = 0; k < c1; ++k) { mult[i][j] += first[i][k] * second[k][j]; } } } } void display(int mult[][10], int r1, int c2) { printf("\nOutput Matrix:\n"); for (int i = 0; i < r1; ++i) { for (int j = 0; j < c2; ++j) { printf("%d ", mult[i][j]); if (j == c2 - 1) printf("\n"); } } } void num_cha() { int n,sum=0,r; printf("enter the number "); scanf("%ld",&n); while(n>0) { r=n%10; sum=sum*10+r; n=n/10; } n=sum; while(n>0) { r=n%10; switch(r) { case 1: printf("one "); break; case 2: printf("two "); break; case 3: printf("three "); break; case 4: printf("four "); break; case 5: printf("five "); break; case 6: printf("six "); break; case 7: printf("seven "); break; case 8: printf("eight "); break; case 9: printf("nine "); break; case 0: printf("zero "); break; default: printf("tttt"); break; } n=n/10; } } void transpose() { int a[10][10], transpose[10][10], r, c, i, j; printf("Enter rows and columns: "); scanf("%d %d", &r, &c); printf("\nEnter matrix elements:\n"); for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) { printf("Enter element a%d%d: ", i + 1, j + 1); scanf("%d", &a[i][j]); } printf("\nEntered matrix: \n"); for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) { printf("%d ", a[i][j]); if (j == c - 1) printf("\n"); } for (i = 0; i < r; ++i) for (j = 0; j < c; ++j) { transpose[j][i] = a[i][j]; } printf("\nTranspose of the matrix:\n"); for (i = 0; i < c; ++i) for (j = 0; j < r; ++j) { printf("%d ", transpose[i][j]); if (j == r - 1) printf("\n"); } } void frequencyword() { int freq,l; char str[1000], ch; int count = 0; printf("Enter a string: \n"); fflush(stdin); scanf("%d",str); gets(str); l=strlen(str); printf("Enter a character to find its frequency: "); scanf("%c", &ch); for (int i = 0; i<l; i++) { if (ch == str[i]) count++; } printf("Frequency of %c = %d", ch,count); } void frequencynumber() { int arr[100], freq[100]; int size, i, j, count; printf("Enter size of array: "); scanf("%d", &size); printf("Enter elements in array: "); for(i=0; i<size; i++) { scanf("%d", &arr[i]); freq[i] = -1; } for(i=0; i<size; i++) { count = 1; for(j=i+1; j<size; j++) { if(arr[i]==arr[j]) { count++; freq[j] = 0; } } if(freq[i] != 0) { freq[i] = count; } } printf("\nFrequency of all elements of array : \n"); for(i=0; i<size; i++) { if(freq[i] != 0) { printf("%d occurs %d times\n", arr[i], freq[i]); } } } void stringlength() { int i,ctr=0; char str []= "hello"; //printf("Enter the string : "); //gets(str); for(i=0;str[i]!='\0';i++) { ctr++; } printf("%d",ctr); } void leapyear() { int y; printf("Enter year: "); scanf("%d",&y); if(y % 4 == 0) { if( y % 100 == 0) { if ( y % 400 == 0) printf("%d is a Leap Year", y); else printf("%d is not a Leap Year", y); } else printf("%d is a Leap Year", y ); } else printf("%d is not a Leap Year", y); } void greatestofthree() { int num1,num2,num3; printf("\nEnter value of num1, num2 and num3:"); scanf("%d %d %d",&num1,&num2,&num3); if((num1>num2)&&(num1>num3)) printf("\n Number1 is greatest"); else if((num2>num3)&&(num2>num1)) printf("\n Number2 is greatest"); else printf("\n Number3 is greatest"); } void naturalsum() { int n, count, sum = 0; printf("Enter the value of n(positive integer): "); scanf("%d",&n); for(count=1; count <= n; count++) { sum = sum + count; } printf("Sum of first %d natural numbers is: %d",n, sum); } void rev() { int n, rev = 0, remainder; printf("Enter an integer: "); scanf("%d", &n); while (n != 0) { remainder = n % 10; rev = rev * 10 + remainder; n /= 10; } printf("Reversed number = %d", rev); } void avg() { int n, i; float sum = 0, x; printf("Enter number of elements: "); scanf("%d", &n); printf("\n\n\nEnter %d elements\n\n", n); for(i = 0; i < n; i++) { scanf("%f", &x); sum += x; } printf("\n\n\nAverage of the entered numbers is = %f", (sum/n)); } void multtable() { int n,i; printf("Enter an integer you need to print the table of: "); scanf("%d", &n); printf("\n\n\n"); for(i = 1; i <= 10; i++) { printf("\n\t\t\t%d * %d = %d \n", n, i, n*i); } } void revarray() { int c, d, n, a[100], b[100]; printf("\n\nEnter number of elements in array :"); scanf("%d", &n); printf("\n\nEnter %d elements\n", n); for(c = 0; c < n; c++) scanf("%d", &a[c]); for(c = n-1, d = 0; c >= 0; c--, d++) b[d] = a[c]; for(c = 0; c < n; c++) a[c] = b[c]; printf("\n\n Resultant array is: "); for(c = 0; c < n; c++) printf("%d", a[c]); } void determinant() { int a[2][2], i, j; long determinant; printf("\n\nEnter the 4 elements of the array\n"); for(i = 0; i < 2; i++) for(j = 0; j < 2; j++) scanf("%d", &a[i][j]); printf("\n\nThe entered matrix is: \n\n"); for(i = 0; i < 2; i++) { for(j = 0; j < 2; j++) { printf("%d\t", a[i][j]); } printf("\n"); } determinant = a[0][0]*a[1][1] - a[1][0]*a[0][1]; printf("\n\nDeterminant of 2x2 matrix is : %d - %d = %d", a[0][0]*a[1][1], a[1][0]*a[0][1], determinant); } void compare(){ char arr1[200], arr2[200]; printf("Please enter the 1st string\n"); fflush(stdin); gets(arr1); printf("Please enter the 2nd string\n"); fflush(stdin); gets(arr2); printf("Entered strings are\narr1 = %s \narr2 = %s", arr1, arr2); if( strcmp(arr1,arr2) == 0 ) printf("\nEntered strings are equal.\n"); else printf("\nEntered strings are not equal.\n"); } void duplicate() { int arr1[100]; int arr2[100]; int arr3[100]; int n,mm=1,ctr=0; int i, j; printf("Input the number of elements to be stored in the array :"); scanf("%d",&n); printf("Input %d elements in the array :\n",n); for(i=0;i<n;i++) { scanf("%d",&arr1[i]); } for(i=0;i<n; i++) { arr2[i]=arr1[i]; arr3[i]=0; } for(i=0;i<n; i++) { for(j=0;j<n;j++) { if(arr1[i]==arr2[j]) { arr3[j]=mm; mm++; } } mm=1; } for(i=0; i<n; i++) { if(arr3[i]==2) { ctr++; } } printf("The total number of duplicate elements found in the array is: %d ", ctr); } int main(){ int x; //---------------------------------------------------------------------------------------output----------------------- label: printf("\t\t\t\t\t\t\t\t\tWELCOME TO 100 CODES\n"); printf("---------------------------------------------------------------------------------------------------------------------------------------------------------------------\n"); printf("1. About 2.Source Code\n"); printf("\t\t\t------------IF ELSE STATEMENTS--------------\n"); printf("\t\t\tPress 1 for Hello World\n"); printf("\t\t\tPress 2 for Addition\n"); printf("\t\t\tPress 3 for Subtraction\n"); printf("\t\t\tPress 4 for Multiplication\n"); printf("\t\t\tPress 5 for Division \n"); printf("\t\t\tPress 6 for Modulo\n"); printf("\t\t\tPress 7 for Calculator\n"); printf("\t\t\t------------LOOPS--------------\n"); printf("\t\t\tPress 8 for Prime Number\n"); printf("\t\t\tPress 9 for Reversing a Number\n"); printf("\t\t\tPress 10 for Counting Digits in a Number\n"); printf("\t\t\tPress 11 for Counting Specific Digit in a Number\n"); printf("\t\t\tPress 12 to Check a number is Armstrong\n"); printf("\t\t\tPress 13 to Check a Number is Strong\n"); printf("\t\t\tPress 14 for Cube root of Number\n"); printf("\t\t\tPress 15 for Square root of a number\n"); printf("\t\t\tPress 16 for Cube of a number\n"); printf("\t\t\tPress 17 for Square of a number\n"); printf("\t\t\tPress 18 for Calculating Nth power of a number \n"); printf("\t\t\tPress 19 to Check a number is Even \n"); printf("\t\t\tPress 20 to Check a number is Odd\n"); printf("\t\t\t------------PATTERNS--------------\n"); printf("\t\t\tPress 21 for half pyramid using star\n"); printf("\t\t\tPress 22 for half pyramid using numbers\n"); printf("\t\t\tPress 23 for Floyd triangle\n"); printf("\t\t\tPress 24 for Inverted Floyd triangle\n"); printf("\t\t\tPress 25 for Inverted half pyramid using star\n"); printf("\t\t\tPress 26 for Inverted half pyramid using numbers\n"); printf("\t\t\tPress 27 for left half pyramid using stars\n"); printf("\t\t\tPress 28 for left half pyramid using Numbers\n"); printf("\t\t\tPress 29 for Inverted left half pyramid using stars\n"); printf("\t\t\tPress 30 for Inverted left half pyramid using numbers\n"); printf("\t\t\tPress 31 for Pyramid using stars\n"); printf("\t\t\tPress 32 for factorial\n"); printf("\t\t\tPress 33 for Butterfly pattern\n"); printf("\t\t\t------------ARRAYS--------------\n"); printf("\t\t\tPress 34 for Displaying an Array\n"); printf("\t\t\tPress 35 for Sum of a Array Elements\n"); printf("\t\t\tPress 36 for Sum of even Elements in an Array\n"); printf("\t\t\tPress 37 for Sum of odd Elements in an Array\n"); printf("\t\t\tPress 38 for Sum of elements at odd index in an Array \n"); printf("\t\t\tPress 39 for Sum of elements at even index in an Array\n"); printf("\t\t\tPress 40 for Encrypting an array by a number n\n"); printf("\t\t\tPress 41 for Multiplication of elements in an Array\n"); printf("\t\t\tPress 42 for Multiplication of even elements in an Array\n"); printf("\t\t\tPress 43 for Multiplication of odd elements in an Array\n"); printf("\t\t\tPress 44 for Average of elements of an Array \n"); printf("\t\t\tPress 45 for Reversing an array\n"); printf("\t\t\tPress 46 for Checking whether array is palindrome\n"); printf("\t\t\tPress 47 for Displaying Even elements of an array\n"); printf("\t\t\tPress 48 for Displaying Odd elements of an array\n"); printf("\t\t\tPress 49 for Right shift of array elements\n"); printf("\t\t\tPress 50 for Left shift of array elements\n"); printf("\t\t\t------------MISCS--------------\n"); printf("\n\t\t\t 51: alphabet \n\t\t\t 52: power \n\t\t\t 53: hcflcm \n\t\t\t 54: datatype \n\t\t\t 55: salary "); printf("\n\t\t\t 56: to check strong number \n\t\t\t 57: paliendrome \n\t\t\t 58: vowel in a string \n\t\t\t 59: reverse of a string \n\t\t\t 60: capital becomes small and small becomes capital in a string \n\t\t\t 61: last string was printed as a character \n\t\t\t 62: length of a string \n\t\t\t 63: concatenate of string \n\t\t\t 64: copy a string \n\t\t\t 65: substring of a string \n\t\t\t 66: short the name through string \n\t\t\t 67: enter your first name and age \n\t\t\t 68: swapping of a string"); printf("\n\t\t\t 69: print max and min \n\t\t\t 70: print single digit or not \n\t\t\t 71: print binary or not \n\t\t\t 72: print perfect number \n\t\t\t 73: print ascii alphabet \n\t\t\t 74: print factor of a number \n\t\t\t 75: print factorial of even number and sum of digits of odd number \n\t\t\t 76: to convert number into character"); printf("\n\t\t\t 77 : Print Transpose of a matrix \t\t\t------------STRINGS--------------\n \n\t\t\t 78 : Print Frequency of word \n\t\t\t 79 : Print Frequency of a each number \n\t\t\t 90 : Print String Length \n\t\t\t 91 : Print Leap year \n\t\t\t 92 : Print Greatest of three number \n\t\t\t 93 : Print Sum of first n natural number \n\t\t\t 94 : Print reverse of a number \n\t\t\t 95 : Print average of a number \n\t\t\t 96 : Print Multiplication table \n\t\t\t 97: Print reverse of an array \n\t\t\t 98 : Print Determinant of a matrix \n\t\t\t 99 : Print Compare two strings \n\t\t\t 100 : Count total number of duplicate elements in an array "); //-----------------------------------------------------input---------------------------------- printf("\n---------------------------------------------------------------------------\n\t\tENTER YOUR CHOICE"); scanf("%d",&x); switch(x){ case 1: hello(); break; case 2: add(); break; case 3: subtract(); break; case 4: Multi(); break; case 5: div(); break; case 6: mod(); break; case 7: cal(); break; case 8: prime(); break; case 9: rev1(); break; case 10: count(); break; case 11: count1(); break; case 12: armstrong(); break; case 13: strong1(); break; case 14: cuber(); break; case 15: squarer(); break; case 16: cube(); break; case 17: square(); break; case 18: npow(); break; case 19: evechck(); break; case 20: oddchck(); break; case 21: halfpyramids(); break; case 22: halfpyramidn(); break; case 23: floydtrian(); break; case 24: invertedfloy(); break; case 25: invertedhalfs(); break; case 26: invertedhalfn(); break; case 27: leftpys(); break; case 28: leftpyn(); break; case 30: inleftpys(); break; case 31: fact(); break; case 32: butter(); break; case 34: displayarr(); break; case 35: sumofarr(); break; case 36: sumfofeve(); break; case 37: sumofodd(); break; case 38: sumofelementateve(); break; case 39: sumofelementatodd(); break; case 40: encrypt(); break; case 41: multiele(); break; case 42: multieveele(); break; case 43: multioddel(); break; case 44: averageofarr(); break; case 45: reverseofarr(); break; case 46: palindromearr(); break; case 47: dispevenel(); break; case 48: dispoddel(); break; case 49: rightshift(); break; case 50: leftshfit(); break; case 51 : alphabet(); break; case 52 : power(); break; case 53 : hcflcm(); break; case 54 : datatype(); break; case 55 : salary(); break; case 56 : strong(); break; case 57 : paliendrome(); break; case 58 : svowel(); break; case 59 : srev(); break; case 60 : capital(); break; case 61 : slast(); break; case 62 : slength(); break; case 63 : concat(); break; case 64 : copy(); break; case 65 : substring(); break; case 66 : strword(); break; case 67 : sname(); break; case 68 : sswap(); break; case 69 : maxmin(); break; case 70 : digit(); break; case 71 : binary(); break; case 72 : perfect(); break; case 73 : asciialpha(); break; case 74 : factor(); break; case 75 : factsum(); break; case 76 : num_cha(); break; case 77 : transpose(); break; case 78 : frequencyword(); break; case 79 : frequencynumber(); break; case 90 : stringlength(); break; case 91 : leapyear(); break; case 92 : greatestofthree(); break; case 93 : naturalsum(); break; case 94 : rev(); break; case 95 : avg(); break; case 96 : multtable(); break; case 97 : revarray(); break; case 98 : determinant(); break; case 99 : compare(); break; case 100 : duplicate(); break; default : ("wrong choice"); } char a; printf("\n\t\t1WANT TO RETURN TO MAIN MENU(Y/N)\n"); scanf("%s",&a); if(a=='Y') goto label; else return 0; } void hello() { printf("Hello World"); } void add() { int x,y; printf("Enter two numbers\n"); scanf("%d %d",&x,&y); printf("%d",x+y); } void subtract() { int x,y; printf("Enter two numbers\n"); scanf("%d %d",&x,&y); printf("%d",x-y); } void Multi() { int x,y; printf("Enter two numbers\n"); scanf("%d %d",&x,&y); printf("%d",x*y); } void div() { int x,y; printf("Enter two numbers\n"); scanf("%d %d",&x,&y); printf("%d",x/y); } void mod() { int x,y; printf("Enter two numbers\n"); scanf("%d %d",&x,&y); printf("%d",x%y); } void cal() { int n,x,y; printf("Press 1 for addition\n"); printf("Press 2 for Subtraction\n"); printf("Press 3 for division\n"); printf("Press 4 for multiplication\n"); printf("Press 5 for mod\n"); scanf("%d",&n); printf("Enter two numbers\n"); scanf("%d %d",&x,&y); switch(n) { case 1: printf("%d",x+y); break; case 2: printf("%d",x-y); break; case 3: printf("%d",x/y); break; case 4: printf("%d",x*y); break; case 5: printf("%d",x%y); break; default: printf("Wrong Choice"); } } void prime() { int n,flag; printf("Enter the number"); scanf("%d",&n); for(int i=2;i<n;i++) { if(n%i==0) { flag=1; break; } } if(flag==1) printf("NON-PRIME"); else printf("Prime"); } void rev1() { int n,rev=0,digi; printf("Enter the number"); scanf("%d",&n); while(n!=0) { digi=n%10; rev=rev*10+digi; n=n/10; } printf("Reverse number is %d",rev); } void count() { int n,digi=0; printf("Enter the number"); scanf("%d",&n); while(n!=0) { n=n/10; ++digi; } printf("The number of digits are %d",digi); } void count1() { int n,i,digi,c=0; printf("Enter the number"); scanf("%d",&n); printf("Enter the digit to be counted"); scanf("%d",&i); while(n!=0) { digi=n%10; if(i==digi) ++c; } printf("The number of %d in %d are %d",i,n,c); } void armstrong() { int n,temp,result,digi; printf("Enter a three digit number"); n=temp; while(temp!=0) { digi=temp%10; result=digi*digi*digi; temp=temp/10; } if(n==result) printf("Armstrong"); else printf("Not armstrong"); } void strong1() { int i, originalNum, num, lastDigit, sum; long fact; printf("Enter any number to check Strong number: "); scanf("%d", &num); originalNum = num; sum = 0; while(num > 0) { lastDigit = num % 10; fact = 1; for(i=1; i<=lastDigit; i++) { fact = fact * i; } sum = sum + fact; num = num / 10; } if(sum == originalNum) printf("%d is STRONG NUMBER", originalNum); else printf("%d is NOT STRONG NUMBER", originalNum); } void cuber() { int x; printf("Enter the number"); scanf("%d",&x); x=cbrt(x); printf("%d",x); } void squarer() { int x; printf("Enter the number"); scanf("%d",&x); x=sqrt(x); printf("%d",x); } void cube() { int x; printf("Enter the number"); scanf("%d",&x); x=x*x*x; printf("%d",x); } void square() { int x; printf("Enter the number"); scanf("%d",&x); x=x*x; printf("%d",x); } void npow() { int x,n; printf("Enter the number and power"); scanf("%d %d",&x,&n); x=pow(x,n); printf("%d",x); } void evechck() { int x; printf("Enter the number"); scanf("%d",&x); if(x%2==0) printf("Even"); else printf("Not even"); } void oddchck() { int x; printf("Enter the number"); scanf("%d",&x); if(x%2==0) printf("Even"); else printf("Not even"); } void halfpyramids() { int n,i,j; printf("Enter the number of lines you want"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i<=j) printf("*"); else printf(" "); } printf("\n"); } } void halfpyramidn() { int n,i,j,k=1; printf("Enter the number of lines you want"); scanf("%d",&n); for(i=0;i<n;i++) { k=1; for(j=0;j<n;j++) { if(i<=j) printf("%d",k++); else printf(" "); } printf("\n"); } } void floydtrian() { int n,i,j,k=1; printf("Enter the number of lines you want"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i<=j) printf("%d",k); else printf(" "); } ++k; printf("\n"); } } void invertedfloy() { int n,i,j,k; printf("Enter the number of lines you want"); scanf("%d",&n); k=n; for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(j>=i) printf("%d",k); else printf(" "); } ++k; printf("\n"); } } void invertedhalfs() { int n,i,j,k=1; printf("Enter the number of lines you want"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(j>=i) printf("*"); else printf(" "); } printf("\n"); } } void invertedhalfn() { int n,i,j,k=1; printf("Enter the number of lines you want"); scanf("%d",&n); for(i=0;i<n;i++) { k=1; for(j=0;j<n;j++) { if(j>=i) printf("%d",k++); else printf(" "); } ++k; printf("\n"); } } void leftpyn() { int n,i,j,k=1; printf("Enter the number of lines"); scanf("%d",&n); for(i=0;i<n;i++) { k=1; for(j=0;j<n;j++) { if(i+j>=n-1) printf("%d",k++); else printf(" "); } printf("\n"); } } void leftpys() { int n,i,j; printf("Enter the number of lines you want"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i+j<=n-1) printf("*"); else printf(" "); } printf("\n"); } return 0; } void inleftpys() { int n,i,j,k=1; printf("Enter the no of lines"); scanf("%d",&n); for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(i+j<=n-1) printf("*"); else printf(" "); } printf("\n"); } } void butter() { int i,j,n; for (i=1; i<=n; i++) { for (j=1; j<=(2*n); j++) { if (i<j) printf(" "); else printf("*"); if (i<=((2*n)-j)) printf(" "); else printf("*"); } printf("\n"); } for (i=1; i<=n; i++) { for (j=1;j<=(2*n);j++) { if (i>(n-j+1)) printf(" "); else printf("*"); if ((i+n)>j) printf(" "); else printf("*"); } printf("\n"); } } void displayarr() { int n; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) scanf("%d",&a[i]); printf("The elements of array"); for(int i=0;i<n;i++) printf("%d ",a[i]); } void sumofarr() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); sum+=a[i]; } printf("The sum is %d",sum); } void sumfofeve() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(a[i]%2==0) sum+=a[i]; } printf("The sum of even elements are %d",sum); } void sumofodd() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(a[i]%2!=0) sum+=a[i]; } printf("The sum of odd elements are %d",sum); } void sumofelementatodd() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(i%2!=0) sum+=a[i]; } printf("The sum of elements at odd %d",sum); } void sumofelementateve() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(i%2==0) sum+=a[i]; } printf("The sum of elements at even %d",sum); } void encrypt() { int n,s,k; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } printf("the encrypt code"); scanf("%d",&k); for(int i=0;i<n;i++) { a[i]=a[i]+k; } printf("The encrypted array"); for(int i=0;i<n;i++) printf("%d",a[i]); } void multiele() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); sum*=a[i]; } printf("The multiplications of elements %d",sum); } void multieveele() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(i%2==0) sum*=a[i]; } printf("The multiplication of elements at even %d",sum); } void multioddel() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(i%2!=0) sum*=a[i]; } printf("The multi of elements at odd %d",sum); } void averageofarr() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); sum+=a[i]; } printf("The average of elements at %d",sum/n); } void reverseofarr() { int n,temp; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } for(int i=0;i<n;i++) { temp=a[i]; a[i]=a[n-i-1]; a[n-i-1]=temp; } } void palindromearr() { int n,flag; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } for(int i=0;i<n;i++) { if(a[i]!=a[n-i-1]) { flag=1; break; } } if(flag==1) printf("Not palindrome"); else printf("Palindrome"); } void dispevenel() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } printf("The even elements"); for(int i=0;i<n;i++) if(a[i]%2==0) printf("%d",a[i]); } void dispoddel() { int n,sum=0; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(int i=0;i<n;i++) { scanf("%d",&a[i]); } printf("The even elements"); for(int i=0;i<n;i++) if(a[i]%2!=0) printf("%d",a[i]); } void rightshift() { int n,temp,i; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for(i=0;i<n;i++) { scanf("%d",&a[i]); } printf("The right shift"); temp=a[0]; for(i=1;i<n-1;i++) { a[i]=a[i+1]; } a[i]=temp; for(int i=0;i<n;i++) printf("%d",a[i]); } void leftshfit() { int n,temp,i; printf("enter the no of elements of array"); scanf("%d",&n); int a[n]; for( i=0;i<n;i++) { scanf("%d",&a[i]); } printf("The right shift"); temp=a[0]; for(i=0;i<n-1;i++) { a[i]=a[i+1]; } a[i]=temp; for(i=0;i<n;i++) printf("%d",a[i]); } void fact() { int i,f=1,n; printf("Enter n"); scanf("%d",&n); for(i=1;i<=n;i++) f=f*i; printf("%d",f); }
C
/* ============================================================================ Name : client.c Author : Gonzalo Sinnott Segura Version : Copyright : Description : Library client.c ============================================================================ */ #include <stdio_ext.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "client.h" #include "utn.h" static int client_generateNewId(void); static int client_checkFirstEmptyIndex(Client* client_list, int client_len, int *emptyIndex); static int client_getForm(char *client_name, char *client_lastName, char *client_cuit); static int client_addData(Client* client_list,int client_len,int client_id,char *client_name, char *client_lastName, char *client_cuit); static int client_findIndexById(Client* client_list, int client_len,int id); static int client_modify(Client* client_list, int client_len,int id); /** * \brief client_addHardcode: Adds Hardcoded data for testing purposes * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty * \return (-1) Error / (0) Ok */ int client_addHardcode(Client* client_list, int client_len, int *client_firstLoad) { int retorno = -1; if(client_list != NULL && client_len >0) { int client_id[]={50,60,70,80,100}; char client_name[][LEN_NAME]={"Juan Carlos", "Marcos", "Anabel", "Ricardo", "Florencia"}; char client_lastName[][LEN_NAME]={"Gomez", "Sanchez", "Pereira Iraola", "Guzman", "Bianchi"}; char client_cuit[][LEN_FORMATEDCUIT]={"23-34797474-9", "26-24935994-7", "21-45045347-5", "27-10364926-4", "21-36983457-6"}; for(int i = 0; i < 5; i++) { client_addData(client_list, client_len, client_id[i], client_name[i], client_lastName[i], client_cuit[i]); } *client_firstLoad = TRUE; } return retorno; } /** * \brief client_initArray: To indicate that all positions in the array are empty, * \this function puts the flag (client_isEmpty) in TRUE in all position of the array * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \return (-1) Error / (0) Ok */ int client_initArray(Client* client_list, int client_len) { int retorno = -1; if(client_list != NULL && client_len > 0) { for(int i=0;i<client_len;i++) { client_list[i].client_isEmpty = TRUE; } retorno = 0; } return retorno; } /** * \brief client_add: Asks the user for the client data * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty * \return (-1) Error / (0) Ok */ int client_add(Client* client_list,int client_len, int *client_firstLoad) { int retorno = -1; int client_id; char client_name[LEN_NAME]; char client_lastName[LEN_NAME]; char client_cuit[LEN_FORMATEDCUIT]; int index; if(client_list != NULL && client_len > 0 && client_checkFirstEmptyIndex(client_list, client_len, &index)==0) { if(client_getForm(client_name, client_lastName, client_cuit)== 0) { client_id=client_generateNewId(); if(client_addData(client_list, client_len, client_id, client_name, client_lastName, client_cuit)==0) { client_printById(client_list, client_len, client_id); *client_firstLoad = TRUE; retorno=0; } } else { printf("\nERROR EN LA CARGA DEL EMPLEADO.\n"); } } else { printf("\nNO SE PUEDEN CARGAR MAS REGISTROS.\n"); } return retorno; } /** * \brief client_checkFirstEmptyIndex: Checks first empty index in the array * \this function search the array for the first index with the value TRUE in the client_isEmpty variable * \param Client* client_list: Pointer to array of clients * \param int client_len: Client Array length * \param int *EmptyIndex: Pointer to position of first empty index. * \return (-1) Error / (0) Ok */ static int client_checkFirstEmptyIndex(Client* client_list, int client_len, int *emptyIndex) { int retorno = -1; if(client_list != NULL && client_len >0 && emptyIndex != NULL) { for(int i = 0; i < client_len; i++) { if(client_list[i].client_isEmpty == TRUE) { *emptyIndex = i; retorno = 0; break; } } } return retorno; } /** * \brief client_getForm: Brings up a menu for the user to complete with the client info * \param char *client_name: Pointer to place to store client_name * \param char *lastName: Pointer to place to store last client_name * \param float *salary: Pointer to place to store salary * \param int *sector: Pointer to place to store sector * \return (-1) Error / (0) Ok */ static int client_getForm(char *client_name, char *client_lastName, char *client_cuit) { int retorno = -1; if(client_name != NULL && client_lastName != NULL && client_cuit != NULL ) { if((utn_getString("Ingrese Apellido:", "Error. ", client_lastName, 3, LEN_NAME)==0) && (utn_getString("Ingrese Nombre:", "Error. ", client_name, 3, LEN_NAME)==0) && (utn_getCuit("Ingrese CUIT(SIN GUIONES):", "Error. ", client_cuit, 3, LEN_CUIT)==0)) { retorno = 0; } } return retorno; } /** * \brief client_generateNewId: Generates a new ID that's +1 from previous loaded ID. */ static int client_generateNewId(void) { static int id; id = id+1; return id; } /** * \brief client_addData: add in a existing list of clients the values received as parameters in the first empty position. * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_id: id generated by client_generateNewId() function * \param char client_name[]: Input by user from client_getForm * \param char lastName[]: Input by user from client_getForm * \param float salary: Input by user from client_getForm * \param int sector: Input by user from client_getForm * \return (-1) Error / (0) Ok */ static int client_addData(Client* client_list,int client_len,int client_id,char *client_name, char *client_lastName, char *client_cuit) { int retorno = -1; int emptyIndex; if(client_list != NULL && client_len >0 && client_id > 0 && client_name != NULL && client_lastName != NULL && client_cuit != NULL ) { if(client_findByCuit(client_list, client_len, client_cuit)!=0) { if(client_checkFirstEmptyIndex(client_list, client_len, &emptyIndex)==0) { client_list[emptyIndex].client_id=client_id; client_list[emptyIndex].client_isEmpty=FALSE; strncpy(client_list[emptyIndex].client_name,client_name,LEN_NAME); strncpy(client_list[emptyIndex].client_lastName,client_lastName,LEN_NAME); strncpy(client_list[emptyIndex].client_cuit,client_cuit,LEN_FORMATEDCUIT); retorno=0; } } else { printf("\nERROR, EL CUIT INGRESADO PERTENECE A OTRO CLIENTE.\n"); } } return retorno; } /** * \brief client_findIndexById: find a Client by Id then returns the index position in array. * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int id: id to search * \return Return employee index position or (-1) if ERROR */ static int client_findIndexById(Client* client_list, int client_len,int id) { int retorno = -1; if (client_list != NULL && client_len > 0 && id > 0) { for (int i = 0; i < client_len; i++) { if(client_list[i].client_isEmpty == FALSE && client_list[i].client_id == id ) { retorno = i; break; } } } return retorno; } /** * \brief client_findByCuit: find a client by CUIT and returns 0 if CUIT is found * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int cuit: cuit to search * \return Return 0 if cuit exists or (-1) if ERROR */ int client_findByCuit(Client* client_list, int client_len,char *cuit) { int retorno = -1; if (client_list != NULL && client_len > 0 && cuit > 0) { for (int i = 0; i < client_len; i++) { if(client_list[i].client_isEmpty == FALSE && strcmp(client_list[i].client_cuit,cuit) == 0) { retorno = 0; break; } } } return retorno;; } /** * \brief client_findById: find a client by Id and returns 0 if ID is found * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int id: id to search * \return Return 0 if ID exists or (-1) if ERROR */ int client_findById(Client* client_list, int client_len,int id) { int retorno = -1; if (client_list != NULL && client_len > 0 && id > 0) { for (int i = 0; i < client_len; i++) { if(client_list[i].client_isEmpty == FALSE && client_list[i].client_id == id ) { retorno = 0; break; } } } return retorno;; } /** * \brief client_modifyMenu: Ask the user for an ID and Modifies the data of an client by given Id. * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty * \return (-1) Error / (0) Ok */ int client_modifyMenu(Client* client_list, int client_len, int client_firstLoad) { int retorno = -1; int idToSearch; if(client_list != NULL && client_len > 0) { if(client_firstLoad == FALSE) { printf("\nERROR. NO HAY DATOS INGRESADOS.\n"); } else { client_printAll(client_list, client_len, client_firstLoad); if(utn_getIntNumber("Ingrese el ID a modificar:","Error, no es un ID valido. ",&idToSearch,3,INT_MAX,1)==0 && client_findById(client_list, client_len, idToSearch)== 0) { if(client_modify(client_list,client_len,idToSearch)==0) { printf("\nREGISTRO DE CLIENTE MODIFICADO CON EXITO.\n"); retorno = 0; } } else { printf("\nERROR, ID INEXISTENTE.\n"); } } } return retorno; } /** * \brief client_modify: Modifies the data of an Employee by given Id. * Allows to modify individual fields of the employee by a switch * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty * \return (-1) Error / (0) Ok */ static int client_modify(Client* client_list, int client_len,int id) { int retorno = -1; int choosenOption; int answer; int indexToModify; Client bufferClient; if(client_list != NULL && client_len > 0 && id > 0) { indexToModify = client_findIndexById(client_list, client_len, id); if(client_list != NULL && client_len>0 && id > 0 && indexToModify > -1) { do { client_printById(client_list, client_len, id); if(utn_getIntNumber("\nQue campo desea modificar:" "\n 1-Apellido." "\n 2-Nombre." "\n 3-CUIT:" "\n 4-Salir" "\nOpcion:", "\nError.", &choosenOption, 3, 4, 1)==0) { switch(choosenOption) { case 1: if(utn_getString("\nIngrese Apellido:","\nError. ",bufferClient.client_lastName,2,LEN_NAME)==0) { strncpy(client_list[indexToModify].client_lastName,bufferClient.client_lastName,LEN_NAME); } break; case 2: if(utn_getString("\nIngrese Nombre:","\nError. ",bufferClient.client_name,2,LEN_NAME)==0) { strncpy(client_list[indexToModify].client_name,bufferClient.client_name,LEN_NAME); } break; case 3: if(utn_getCuit("\nIngrese CUIT (SIN GUIONES):","\nError. ", bufferClient.client_cuit,2,LEN_CUIT)==0 && client_findByCuit(client_list, client_len, bufferClient.client_cuit) !=0) { strncpy(client_list[indexToModify].client_cuit,bufferClient.client_cuit,LEN_FORMATEDCUIT); } else { printf("\nERROR, EL CUIT INGRESADO PERTENECE A OTRO CLIENTE.\n"); } break; case 4: answer = 'N'; break; } } if(choosenOption!=4) { utn_getIntNumber("\n¿Desea seguir modificando este ID?(1-SI/2-NO):", "Error. ", &answer, 3, 2, 1); } }while(answer==1); retorno = 0; } } return retorno; } /** * \brief client_removeMenu: Asks the user for an ID and removes the client associated to said Id (put client_isEmpty Flag in TRUE) * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty and * \safeguard to prevent errors if all data is erased * \return (-1) Error / (0) Ok */ int client_removeMenu(Client* client_list, int client_len,int *client_firstLoad) { int retorno = -1; int idToSearch; if(client_list != NULL && client_len) { if(*client_firstLoad == FALSE) { printf("\nERROR. NO HAY DATOS INGRESADOS.\n"); } else { if(utn_getIntNumber("Ingrese el ID a eliminar:","Error, no es un ID valido. ",&idToSearch,3,INT_MAX,1)==0 && client_findById(client_list, client_len, idToSearch)== 0 && client_remove(client_list,client_len,idToSearch)== 0) { for(int i = 0; i < client_len; i++) { if(client_list[i].client_isEmpty == TRUE) { *client_firstLoad = FALSE; } else { *client_firstLoad = TRUE; break; } } retorno = 0; } } } return retorno; } /** * \brief client_remove: Remove a Employee by Id (put client_isEmpty Flag in TRUE) * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int id: id value of client to remove * \return (-1) Error / (0) Ok */ int client_remove(Client* client_list, int client_len,int id) { int retorno = -1; int indexToModify; int answer; if(client_list != NULL && client_len > 0 && id > 0) { indexToModify = client_findIndexById(client_list, client_len, id); if(client_list != NULL && client_len>0 && id > 0 && indexToModify > -1) { utn_getIntNumber("\n¿Desea eliminar este ID y sus publicaciones asociadas?(1-SI/2-NO):", "Error. ", &answer, 3, 2, 1); switch(answer) { case 1: client_list[indexToModify].client_isEmpty = TRUE; printf("\nREGISTRO DE CLIENTE BORRADO CON EXITO.\n"); break; case 2: printf("\nREGISTRO NO BORRADO\n"); break; default: printf("\nERROR, INGRESE 'Y' PARA BORRAR EL REGISTRO.\n"); } retorno = 0; } } return retorno; } /** * \brief client_printAll: print the content of clients array * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty * \return (-1) Error / (0) Ok* */ int client_printAll(Client* client_list, int client_len, int client_firstLoad) { int retorno = -1; if(client_list != NULL && client_len > 0) { if(client_firstLoad == FALSE) { printf("\nERROR. NO HAY DATOS INGRESADOS.\n"); } else { if(client_list != NULL && client_len > 0) { printf("-------------------------------------------------------------\n"); printf("| LISTADO DE CLIENTES |\n"); printf("-------------------------------------------------------------\n"); printf("| APELLIDO | NOMBRE | CUIT | ID |\n"); printf("-------------------------------------------------------------\n"); for(int i=0;i< client_len ;i++) { if(client_list[i].client_isEmpty == FALSE) { printf("| %-16s| %-16s| %-16s| %-3d |\n", client_list[i].client_lastName, client_list[i].client_name, client_list[i].client_cuit, client_list[i].client_id); printf("-------------------------------------------------------------\n"); } } retorno = 0; } } } return retorno; } /** * \brief client_printById: print the client associated to the id given * \param Client* client_list: Pointer to array of clients * \param int client_len: Array length * \param int client_firstLoad: Pointer to space in memory where is the variable to indicate if clients array is empty * \param int idClient: Value to search and print associated info * \return (-1) Error / (0) Ok* */ int client_printById(Client* client_list, int client_len, int idClient) { int retorno = -1; if(client_list != NULL && client_len > 0 && idClient > 0) { for(int i=0;i< client_len ;i++) { if(client_list[i].client_isEmpty == FALSE && client_list[i].client_id == idClient) { printf("-------------------------------------------------------\n"); printf("| DATOS DEL CLIENTE ID: %-4d |\n",idClient); printf("-------------------------------------------------------\n"); printf("| APELLIDO | NOMBRE | CUIT |\n"); printf("-------------------------------------------------------\n"); printf("| %-16s| %-16s| %-16s|\n", client_list[i].client_lastName, client_list[i].client_name, client_list[i].client_cuit); printf("-------------------------------------------------------\n"); retorno = 0; } } } return retorno; }
C
#include<stdio.h> int is_permutation(long long m, long long n) { int m_d[10],i; for(i=0;i<10;i++) m_d[i] = 0; while(m!=0) { m_d[m%10]++; m=m/10; } while(n!=0) { m_d[n%10]--; n=n/10; } for(i=0;i<10;i++) if(m_d[i] !=0) return 1; return 0; } int main() { char primes[1000000]; long long i,j; float lx,cx; long long m; lx = 10.0; m = 2; for(i=0;i<1000*1000;i++) primes[i] = '0'; for(i=2;i<1000;i++) if(primes[i] == '0') for(j=i*i;j<1000*1000;j=j+i) primes[j] = '1'; for(j=1000*10;j>1;j--) { if(primes[j] == '0') { for(i=j-1;i>1;i--) { if(primes[i] == '0') { if(i*j <= (1000*10000)) { if(is_permutation(i*j, (i-1)*(j-1)) == 0) { cx = ((double) (i*j) / ((double) ((i-1)*(j-1)))); m = lx > cx ? i*j : m; lx = lx > cx ? cx : lx; printf("%lld : %lld : %f\n", i*j, (i-1)*(j-1), cx); } } } } } } printf("Ans : %lld : %f\n", m, lx); return 0; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { for (int i = 1; i < 10; i++){ for (int j = i; j > 0; j--){ printf("%i ", j); } printf("\n"); } return 0; }
C
#include "selectsort.h" #include "qsort.h" void selectsort(int data[], int N){ int i, j, tmp, m; for(i=0;i<N;i++){ tmp = data[i]; m = i; for(j=i+1;j<N;j++){ if(data[j] < tmp){ tmp = data[j]; m = j; } } swap(data, i, m); } }
C
//#include "Fonctions.h" #include <stdio.h> int copierFichier(char const * const, char const * const); int TmpMain(int argc, char **argv) { char fichierS[] = "dataTest"; char fichierD[] = "dataTest2."; copierFichier(fichierS, fichierD); getchar(); } int copierFichier(char const * const nomfichierSource, char const * const nomfichierDestination) { //cration des pointeurs fichiers FILE* fSource = NULL; FILE* fDest = NULL; char buffer[512] = { 0 }; int nbLus = 0; // ouverture du fichier source en lecture binaire if ((fSource = fopen(nomfichierSource,"rb")) == NULL) { fprintf(stderr,"impossible d'ouvrir le fichier source"); return 1; } //ouverture du fichier destination en ecriture binaire if ((fDest = fopen(nomfichierDestination,"wb")) == NULL) { fclose(fSource); fprintf(stderr, "impossible d'ouvrir un fichier destination\n"); return 2; } while ((nbLus = fread(buffer, 1, 512, fSource)) != 0) fwrite(buffer, 1, nbLus, fDest); fclose(fDest); fclose(fSource); fprintf(stdout, "copie termine\n"); return 0; }
C
#include <stdint.h> #ifndef UTILS_H #define UTILS_H /* To avoid the bug of the compilers */ double int2double(signed int i); typedef struct { char *data; uint32_t front, rear; uint16_t count, max_size; } char_queue; int init_char_queue(char_queue *p, char buf[], uint16_t max_size); int in_char_queue(char_queue *p, char c); int out_char_queue(char_queue *p, char *c); #endif
C
// 3. Obter o MDC entre dois números inteiros. #include <stdio.h> #include <stdlib.h> int main() { int n, n1, m, m1, aux, resto = 1; printf("Informe n: "); scanf("%i", &n); printf("Informe m: "); scanf("%i", &m); // Guarda valores iniciais m1 = m; n1 = n; while (resto != 0) { if (n > m) { aux = n; n = m; m = aux; } if (m % n == 0) { resto = 0; printf("%i %i %i", n1, m1, n); } else { m -= n; resto = m % n; } } return 0; }
C
//Vallery Salomon //Lecture 5 Lab 2 //EEGR 409 C Programming Applications //September 30, 2016 #include <stdio.h> int main() { //Declare Variables char c; char c2; int i = 0; printf("Enter some text\n"); //Function do { scanf_s("%c", &c); printf("%c", c); if (c >= 'a' && c <= 'z') c2 -= 32; printf("%c", c2); } while (c != '\n'); getchar(); getchar(); return 0; }
C
int putchar (int c); int main () { int n = 0; while (n < 26) { putchar(65 + n); n = n + 1; } return 0; }
C
#include <linux/kernel.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/unistd.h> #include <linux/init.h> /* * For the current (process) structure, we need * this to know who the current user is. */ #include <linux/sched.h> #include <asm/uaccess.h> #include <asm/cacheflush.h> static unsigned long **sys_call_table; unsigned long* find_sys_call_table(void) { struct { unsigned short limit; unsigned int base; } __attribute__ ( ( packed ) ) idtr; struct { unsigned short offset_low; unsigned short segment_select; unsigned char reserved, flags; unsigned short offset_high; } __attribute__ ( ( packed ) ) * idt; unsigned long system_call = 0; // x80中断处理程序system_call 地址 char *call_hex = "\xff\x14\x85"; // call 指令 char *code_ptr = NULL; char *p = NULL; unsigned long sct = 0x0; int i = 0; __asm__ ( "sidt %0": "=m" ( idtr ) ); idt = ( void * ) ( idtr.base + 8 * 0x80 ); system_call = ( idt->offset_high << 16 ) | idt->offset_low; code_ptr = (char *)system_call; for(i = 0;i < ( 100 - 2 ); i++) { if(code_ptr[i] == call_hex[0] && code_ptr[i+1] == call_hex[1] && code_ptr[i+2] == call_hex[2] ) { p = &code_ptr[i] + 3; break; } } if ( p ){ sct = *(unsigned long*)p; } return (unsigned long*)sct; } /* FUNCTION TO DISABLE WRITE PROTECT BIT IN CPU */ static void disable_wp(void) { unsigned int cr0_value; asm volatile ("movl %%cr0, %0" : "=r" (cr0_value)); /* Disable WP */ cr0_value &= ~(1 << 16); asm volatile ("movl %0, %%cr0" :: "r" (cr0_value)); } /* FUNCTION TO RE-ENABLE WRITE PROTECT BIT IN CPU */ static void enable_wp(void) { unsigned int cr0_value; asm volatile ("movl %%cr0, %0" : "=r" (cr0_value)); /* Enable WP */ cr0_value |= (1 << 16); asm volatile ("movl %0, %%cr0" :: "r" (cr0_value)); } /* * UID we want to spy on - will be filled from the * command line */ static int uid; module_param(uid, int, 0644); asmlinkage int (*original_call) (const char *, int, int); asmlinkage int our_sys_open(const char *filename, int flags, int mode) { int i = 0; char ch; /* * Check if this is the user we're spying on */ if (uid == current->cred->uid) { //2.6.35 中current->cred->uid printk("Opened file by %d: ", uid); do { get_user(ch, filename + i); i++; printk("%c", ch); } while (ch != 0); printk("\n"); } /* * Call the original sys_open - otherwise, we lose * the ability to open files */ return original_call(filename, flags, mode); } /* * Initialize the module - replace the system call */ unsigned int cr0; int init_module() { sys_call_table=find_sys_call_table(); disable_wp(); original_call=sys_call_table[__NR_open]; sys_call_table[__NR_open] = (long*)our_sys_open; printk("Spying on UID:%d\n", uid); return 0; } /* * Cleanup - unregister the appropriate file from /proc */ void cleanup_module() { sys_call_table[__NR_open] = (long *)original_call; enable_wp(); } MODULE_LICENSE("GPL");
C
#include <stdio.h> int main() { unsigned long long n; int i; unsigned long long test; while(scanf("%llu", &n) != EOF) { int count = 0; for(i = 0;i < 64;i++) { test = (n >> i); if(test & 1) { count++; } } printf("%d\n", count); } return 0; }
C
/* Scrivere una funzione che dato un array di interi e un valore x cerca il valore x nell’array. Se il valore x è presente allora restituirà la posizione altrimenti un codice di errore 404. */ #include <stdio.h> int find(int* A, int n){ size_t lenght = sizeof(A); //Permette di conoscere il numero di elementi dell'array for(int i=0;i<lenght;i++){ if(A[i]==n){ return i; // Se abbiamo trovato n nell'array ritorniamo la posizione } } return 404; } int main(){ int arr[] = {2,56,42,21,987,222,9}; int x; printf("Inserisci numero da ricercare: "); scanf("%d",&x); int res = find(arr,x); printf("\n Risultato della ricerca: %d\n",res); return 0; }
C
#include <stdio.h> #include "ll.h" typedef struct { uint8_t age; char name[32]; } person_t; #define PERSONS_LL_SIZE 16 void print_person(void * person_p){ person_t * person = (person_t *) person_p; printf("Name: %s, Age: %d\n", person->name, person->age); } void print2(ll_t * pll){ ll_node_t * curr; ll_node_t * next; person_t * p; ll_get_next(pll, NULL, &next); while (next != NULL){ p = next->data; printf("Name: %s, Age: %d\n", p->name, p->age); curr = next; ll_get_next(pll, &curr, &next); } } void delete_under(ll_t * pll, uint8_t age){ ll_node_t * curr = NULL; ll_node_t * next; person_t * p; ll_get_next(pll, NULL, &next); while (next != NULL){ p = next->data; printf("%s is %d\n", p->name, p->age); if (p->age < age){ ll_delete_next(pll, curr); } else { curr = next; } if (curr == NULL){ ll_get_next(pll, NULL, &next); } else { ll_get_next(pll, &curr, &next); } } } int16_t main(){ stack_t persons_ll_s; person_t persons_ll_a[PERSONS_LL_SIZE]; ll_node_t * persons_ll_sa[PERSONS_LL_SIZE]; ll_node_t persons_ll_na[PERSONS_LL_SIZE]; ll_t persons_ll; person_t person_db[16] = { {12, "John"}, {15, "Jenny"}, {11, "Dan"}, {10, "Steve"}, {14, "Anne"}, {19, "Tom"}, {12, "Joe"}, {14, "Julie"}, {12, "Cris"}, {21, "Meg"}, {16, "Sam"}, {14, "Alex"}, {12, "Con"}, {21, "Alf"}, {10, "Mary"}, {22, "Alex"} }; ll_init(&persons_ll, persons_ll_na, &persons_ll_a, &persons_ll_s, persons_ll_sa, PERSONS_LL_SIZE, sizeof(person_t)); ll_print(&persons_ll); ll_push(&persons_ll, &person_db[0]); ll_push(&persons_ll, &person_db[1]); ll_push(&persons_ll, &person_db[4]); ll_push(&persons_ll, &person_db[5]); ll_push(&persons_ll, &person_db[8]); ll_push(&persons_ll, &person_db[10]); ll_print(&persons_ll); ll_traverse(&persons_ll, print_person); printf("*****\n"); delete_under(&persons_ll,15); printf("*****\n"); print2(&persons_ll); return 0; }
C
/* FUNCTION <<abort>>---abnormal termination of a program INDEX abort SYNOPSIS #include <stdlib.h> void abort(void); DESCRIPTION Use <<abort>> to signal that your program has detected a condition it cannot deal with. Normally, <<abort>> ends your program's execution. In general implementation, <<abort>> raises the exception <<SIGABRT>>. But for nds32 target, currently it is not necessary for MCU platform. We can just call <<_exit>> to terminate program. RETURNS <<abort>> does not return to its caller. PORTABILITY ANSI C requires <<abort>>. Supporting OS subroutines required: <<_exit>>. */ #include <unistd.h> void abort (void) { while (1) { _exit (1); } }
C
/* ** EPITECH PROJECT, 2019 ** CPool_infinadd_2019 ** File description: ** infinadd */ #include <unistd.h> #include <stdlib.h> #include "./include/my.h" char *add(char *s1, char *s2) { int i = 0, rest = 0, len = 0, lena = my_strlen(s1), lenb = my_strlen(s2); char *poi = (char *)malloc(len + 1); if (lena >= lenb) len = lena + 1; else if (lenb > lena) len = lenb + 1; poi[0] = '0'; poi[len] = 0; while (i < lena || i < lenb || rest){ if (i >= lena && i >= lenb){ poi[len - i - 1] = rest % 10 + '0'; rest = rest / 10; } else if (i >= lena){ poi[len - i - 1] = (rest + s2[lenb - i - 1] - '0') % 10 + '0'; rest = (rest + s2[lenb - i - 1] - '0') / 10; } else if (i >= lenb){ poi[len - i - 1] = (rest + s1[lena - i - 1] - '0') % 10 + '0'; rest = (rest + s1[lena - i - 1] - '0') / 10; } else{ poi[len - i - 1] = (rest + s1[lena - i - 1] - '0' + s2[lenb - i - 1] - '0') % 10 + '0'; rest = (rest + s1[lena - i - 1] - '0' + s2[lenb - i - 1] - '0')/ 10; } i++; } return (poi + len - i); } int compare(char *s1, char *s2) { int i = 0, lena = my_strlen(s1), lenb = my_strlen(s2); if (lena > lenb) return (1); else if (lenb > lena) return (-1); while (i < lena){ if (s1[i] > s2[i]) return (1); if (s2[i] > s1[i]) return (-1); i++; } return (0); } char *substract(char *s1, char *s2) { int i = 0, rest = 0, len = 0, lena = my_strlen(s1), lenb = my_strlen(s2); char *poi = (char *)malloc(len + 1); if (lena >= lenb) len = lena; else if (lenb > lena) len = lenb; poi[len] = 0; while (i < lena || i < lenb){ if (i >= lena){ poi[len - i - 1] = ((s2[lenb - i - 1] - '0') - rest + 10) % 10 +'0'; rest = (s2[lenb - i - 1] - '0' - rest) < 0; } else if (i >= lenb){ poi[len - i - 1] = ((s1[lena - i - 1] - '0') - rest + 10) % 10 +'0'; rest = (s1[lena - i - 1] - '0' - rest) < 0; } else{ poi[len - i - 1] = ((s1[lena - i - 1] - '0') - (s2[lenb - i - 1] - '0') - rest + 10) % 10 + '0'; rest = ((s1[lena - i - 1] - '0') - (s2[lenb - i - 1] - '0') - rest) < 0; } i++; } poi = poi + len - i; while (poi[0] == '0') poi++; return (poi); } int main(int argc, char **argv) { char *res; int comp; if (argc != 3) return (0); if (argv[1][0] != '-' && argv[2][0] != '-') res = add(argv[1], argv[2]); else if (argv[1][0] == '-' && argv[2][0] == '-'){ write(1, "-", 1); res = add(argv[1] + 1, argv[2] + 1); } else{ if (argv[1][0] == '-'){ comp = compare(argv[1] + 1, argv[2]); if (comp > 0){ write(1, "-", 1); res = substract(argv[1] + 1, argv[2]); } else if (comp < 0) res = substract(argv[2], argv[1] + 1); else res = "0"; } else{ comp = compare(argv[1], argv[2] + 1); if (comp > 0) res = substract(argv[1], argv[2] + 1); else if (comp < 0){ write(1, "-", 1); res = substract(argv[2] + 1, argv[1]); } else res = "0"; } } write(1, res, my_strlen(res)); write(1, "\n", 1); return (0); }
C
#include <stdio.h> int main() { int start = 1; int end = 100; int stop = 555; int sum = 0; int lastAddition = 0; for(int i = start; i <= end; i++) { sum = sum + i; lastAddition = i; if(sum >= stop){ break; } else{ continue; } } printf("With max. sum %d, the integers from %d to %d sum up to %d\n", stop, start, lastAddition, sum); return 0; }
C
#include "big2.h" /** O estado joga_straight é aquele que faz com que o bot jogue um straight. Após todas as validações da sua mão, ele adiciona cartas para jogar, removendo-as da sua mão. Posto isto, mostra as cartas no tabuleiro, e é a vez de outro jogador. @param e O estado actual. @returns O novo estado. */ ESTADO joga_straight(ESTADO e) { long long int m=0, n=0; int v1,v2,v3,v4,v5,n1,n2,n3,n4,n5,p1,p2,p3,p4,p5; p1 = maior_carta_straight_bots (e.mao[e.actual_jogador]); p2 = codifica((maior_carta_straight_bots(e.mao[e.actual_jogador]))-1); p3 = codifica((maior_carta_straight_bots(e.mao[e.actual_jogador]))-2); p4 = codifica((maior_carta_straight_bots(e.mao[e.actual_jogador]))-3); p5 = codifica((maior_carta_straight_bots(e.mao[e.actual_jogador]))-4); v1 = p1; v2 = descodifica_straight(p2); v3 = descodifica_straight(p3); v4 = descodifica_straight(p4); v5 = descodifica_straight(p5); n1 = maior_naipe_straight_bots((e.mao[e.actual_jogador]),v1); n2 = maior_naipe_straight_bots((e.mao[e.actual_jogador]),v2); n3 = maior_naipe_straight_bots((e.mao[e.actual_jogador]),v3); n4 = maior_naipe_straight_bots((e.mao[e.actual_jogador]),v4); n5 = maior_naipe_straight_bots((e.mao[e.actual_jogador]),v5); m = add_carta(0,n1,v1); m = add_carta(m,n2,v2); m = add_carta(m,n3,v3); m = add_carta(m,n4,v4); m = add_carta(m,n5,v5); n = rem_carta((e.mao[e.actual_jogador]),n1,v1); n = rem_carta(n,n2,v2); n = rem_carta(n,n3,v3); n = rem_carta(n,n4,v4); n = rem_carta(n,n5,v5); e.cartas[e.actual_jogador] = (e.cartas[e.actual_jogador]) - 5; e.ultima_jogada = m; e.cartas_bots[e.actual_jogador] = m; e.mao[e.actual_jogador] = n; e.ultimo_jogador = e.actual_jogador; e.actual_jogador = incrementa_jogador(e); e.card = 0; return e; } /** O estado joga_flush é aquele que faz com que o bot jogue um flush. Após todas as validações da sua mão, ele adiciona cartas para jogar, removendo-as da sua mão. Posto isto, mostra as cartas no tabuleiro, e é a vez de outro jogador. @param e O estado actual. @returns O novo estado. */ ESTADO joga_flush(ESTADO e) { long long int m=0, n=0; int flag1,flag2,flag3,flag4,v1,v2,v3,v4,v5,p1=0,p2=0,p3=0,p4=0,p5=0,n1; n1 = valida_flush(e.mao[e.actual_jogador]); v1 = maior_carta_flush_bots(e.mao[e.actual_jogador], n1); flag1 = 0; p1 = v1; for(v2 = (v1 - 1); v2 >= 0 && flag1 != 1; --v2) { if (carta_existe(e.mao[e.actual_jogador],n1,v2)) { p2 = v2; flag1 = 1; } } flag2 = 0; for (v3 = v2; v3 >= 0 && flag2 != 1; --v3) { if (carta_existe(e.mao[e.actual_jogador],n1,v3)) { p3 = v3; flag2 = 1; } } flag3 = 0; for (v4 = v3; v4 >= 0 && flag3 != 1; --v4) { if (carta_existe(e.mao[e.actual_jogador],n1,v4)) { p4 = v4; flag3 = 1; } } flag4 = 0; for (v5 = v4; v5 >= 0 && flag4 != 1; --v5) { if (carta_existe(e.mao[e.actual_jogador],n1,v5)) { p5 = v5; flag4 = 1; } } m = add_carta(0,n1,p1); m = add_carta(m,n1,p2); m = add_carta(m,n1,p3); m = add_carta(m,n1,p4); m = add_carta(m,n1,p5); n = rem_carta((e.mao[e.actual_jogador]),n1,p1); n = rem_carta(n,n1,p2); n = rem_carta(n,n1,p3); n = rem_carta(n,n1,p4); n = rem_carta(n,n1,p5); e.cartas[e.actual_jogador] = (e.cartas[e.actual_jogador]) - 5; e.ultima_jogada = m; e.cartas_bots[e.actual_jogador] = m; e.mao[e.actual_jogador] = n; e.ultimo_jogador = e.actual_jogador; e.actual_jogador = incrementa_jogador(e); e.card = 0; return e; } /** O estado joga_fullhouse é aquele que faz com que o bot jogue um full house. Após todas as validações da sua mão, ele adiciona cartas para jogar, removendo-as da sua mão. Posto isto, mostra as cartas no tabuleiro, e é a vez de outro jogador. @param e O estado actual. @returns O novo estado. */ ESTADO joga_fullhouse(ESTADO e) { long long int m=0, f=0; int v1=0,n=0,n3=0,n2=0,n1=0,p=0,p1=0,p2=0,p3=0,np1=0,np2=0,flag,flag1,flag2,flag3,flag4; v1 = valida_fullhouse(e.mao[e.actual_jogador]); flag = 0; for (n = 3; n >= 0 && flag != 1; --n) { if(carta_existe(e.mao[e.actual_jogador], n, v1)) { n1 = n; flag = 1; } } flag1 = 0; p1 = n1-1; for (n = p1; n >= 0 && flag1 != 1; --n) { if(carta_existe(e.mao[e.actual_jogador], n, v1)) { n2 = n; flag1 = 1; } } flag2 = 0; p2 = n2-1; for (n = p2; n >= 0 && flag2 != 1; --n) { if (carta_existe(e.mao[e.actual_jogador], n, v1)) { n3 = n; flag2 = 1; } } f = rem_carta((e.mao[e.actual_jogador]),n1,v1); f = rem_carta(f,n2,v1); f = rem_carta(f,n3,v1); p = maior_carta_par_fullhouse(f); /* valor do par */ flag3 = 0; for (n = 3; n >= 0 && flag3 != 1; --n) { if (carta_existe(e.mao[e.actual_jogador], n, p)) { np1 = n; flag3 = 1; } } flag4 = 0; p3 = n; for (n = p3; n >= 0 && flag4 != 1; --n) { if (carta_existe(e.mao[e.actual_jogador], n, p)) { np2 = n; flag4 = 1; } } m = add_carta(0,n1,v1); m = add_carta(m,n2,v1); m = add_carta(m,n3,v1); m = add_carta(m,np1,p); m = add_carta(m,np2,p); f = rem_carta(f,np1,p); f = rem_carta(f,np2,p); e.cartas[e.actual_jogador] = (e.cartas[e.actual_jogador]) - 5; e.ultima_jogada = m; e.cartas_bots[e.actual_jogador] = m; e.mao[e.actual_jogador] = f; e.ultimo_jogador = e.actual_jogador; e.actual_jogador = incrementa_jogador(e); e.card = 0; return e; } /** O estado joga_fourkind é aquele que faz com que o bot jogue um four of a kind. Após todas as validações da sua mão, ele adiciona cartas para jogar, removendo-as da sua mão. Posto isto, mostra as cartas no tabuleiro, e é a vez de outro jogador. @param e O estado actual. @returns O novo estado. */ ESTADO joga_fourkind(ESTADO e) { long long int m=0, n=0; int v1=0,n2=0,n1=0,p=0; v1 = maior_carta_fourkind(e.mao[e.actual_jogador]); p = da_carta_fourkind(e.mao[e.actual_jogador]); for (n1 = 3; n1 >= 0; --n1) { if (carta_existe(e.mao[e.actual_jogador],n1,p)) { n2 = n1; } } /* os v's são todos iguais, exceto v5 */ m = add_carta(0,0,v1); m = add_carta(m,1,v1); m = add_carta(m,2,v1); m = add_carta(m,3,v1); m = add_carta(m,n2,p); n = rem_carta((e.mao[e.actual_jogador]),0,v1); n = rem_carta(n,1,v1); n = rem_carta(n,2,v1); n = rem_carta(n,3,v1); n = rem_carta(n,n2,p); e.cartas[e.actual_jogador] = (e.cartas[e.actual_jogador]) - 5; e.ultima_jogada = m; e.cartas_bots[e.actual_jogador] = m; e.mao[e.actual_jogador] = n; e.ultimo_jogador = e.actual_jogador; e.actual_jogador = incrementa_jogador(e); e.card = 0; return e; } /** O estado joga_straightflush é aquele que faz com que o bot jogue um straight flush. Após todas as validações da sua mão, ele adiciona cartas para jogar, removendo-as da sua mão. Posto isto, mostra as cartas no tabuleiro, e é a vez de outro jogador. @param e O estado actual. @returns O novo estado. */ ESTADO joga_straightflush(ESTADO e) { long long int m=0, n=0; int v1,v2,v3,v4,v5,n1,n2,n3,n4,n5,p2,p3,p4,p5; v1 = maior_carta_straightflush_bots (e.mao[e.actual_jogador]); p2 = codifica ((maior_carta_straightflush_bots(e.mao[e.actual_jogador]))-1); p3 = codifica ((maior_carta_straightflush_bots(e.mao[e.actual_jogador]))-2); p4 = codifica ((maior_carta_straightflush_bots(e.mao[e.actual_jogador]))-3); p5 = codifica ((maior_carta_straightflush_bots(e.mao[e.actual_jogador]))-4); v2 = descodifica_straight(p2); v3 = descodifica_straight(p3); v4 = descodifica_straight(p4); v5 = descodifica_straight(p5); /* os ns sao todos iguais */ n1 = maior_naipeCarta_straightflush_bots((e.mao[e.actual_jogador])); n2 = maior_naipeCarta_straightflush_bots((e.mao[e.actual_jogador])); n3 = maior_naipeCarta_straightflush_bots((e.mao[e.actual_jogador])); n4 = maior_naipeCarta_straightflush_bots((e.mao[e.actual_jogador])); n5 = maior_naipeCarta_straightflush_bots((e.mao[e.actual_jogador])); m = add_carta(0,n1,v1); m = add_carta(m,n2,v2); m = add_carta(m,n3,v3); m = add_carta(m,n4,v4); m = add_carta(m,n5,v5); n = rem_carta((e.mao[e.actual_jogador]),n1,v1); n = rem_carta(n,n2,v2); n = rem_carta(n,n3,v3); n = rem_carta(n,n4,v4); n = rem_carta(n,n5,v5); e.cartas[e.actual_jogador] = (e.cartas[e.actual_jogador]) - 5; e.ultima_jogada = m; e.cartas_bots[e.actual_jogador] = m; e.mao[e.actual_jogador] = n; e.ultimo_jogador = e.actual_jogador; e.actual_jogador = incrementa_jogador(e); e.card = 0; return e; }
C
#include<stdio.h> #include<stdlib.h> struct node{ int info; struct node *next; }; typedef struct node node1; void initlist(node1 **list) { *list=NULL; } void pushdynamic(node1 **list,int x) { node1 *l; l=(node1*)(malloc(sizeof(node1))); l->info=x; l->next=*list; *list=l; } void popdynamic(node1 **list,int *x) { node1 *p; p=*list; *x=p->info; *list=p->next; free(p); } int emptystack(node1 *list) { if (list==NULL) return 1; else return 0; } int main() { node1 *list; int choice,v,i; initlist(&list); do{ printf("1. Push value in stack\n"); printf("2. Pop a value from stack\n"); printf("3. EXIT\n"); printf("Enter your choice:"); scanf("%d",&choice); switch(choice) { case 1: printf("Give value to enter: "); scanf("%d",&v); pushdynamic(&list,v); break; case 2: if (emptystack(list)==0) { popdynamic(&list,&v); printf("Popped value=%d\n",v); } else printf("Stack empty, cannot delete\n"); break; case 3: printf("Thank you, BYE\n"); break; default: printf("invalid choice, enter again\n"); } } while(choice!=3); }
C
#include <stdio.h> #include <stdlib.h> int main () { long t, a, b, a2, b2; scanf("%ld %ld %ld", &t, &a, &b); a2 = a; b2 = b; while (abs(a - b) != t) { if (a < b) { a = a + a2; } else { b = b + b2; } } if (a < b) { printf("%ld\n", b); } else { printf("%ld\n", a); } return 0; }
C
#include "ush.h" static void sort_vars(char **vars) { char *temp; int p = 1; while (p == 1) { p = 0; for (int i = 0; vars[i + 1]; i++) { if (strcmp(vars[i], vars[i + 1]) > 0) { temp = vars[i]; vars[i] = vars[i + 1]; vars[i + 1] = temp; p = 1; } } } } static void env_var_handler(t_shell *shell, char **result, char *var) { char *var_value = NULL; if (strcmp(var, "$") == 0) { pid_t curr_id = getpid(); var_value = mx_itoa(curr_id); } else if (strcmp(var, "?") == 0) { var_value = mx_itoa(shell->exit_code); } else { var_value = strdup(getenv(var)); } mx_strdel(&var); if (!var_value) return; *result = mx_strrejoin(*result, var_value); mx_strdel(&var_value); } void mx_export(t_shell *shell) { char **words = mx_strsplit(shell->command_now, ' '); bool fp = false; char p[2]; if (words[1]) { if (words[1][0] == '-') { if (words[1][1] == 'p' && !words[1][2]) { fp = true; } else { fprintf(stderr, "export: bad option: %s\n", words[1]); mx_free_words(words); shell->exit_code = EXIT_FAILURE; return; } } else { char *var = NULL; char *val = NULL; int quote = 0; int eq = 0; int skip_spaces = 0; for (int a = 1; words[a] && quote % 2 == 0; a++) { if (quote % 2 == 0) { for (int j = 0; words[a][j]; j++) { if (words[a][j] == '=') { eq = j + 1; break; } MX_C_TO_P(words[a][j], p); var = mx_strrejoin(var, p); } } if (eq > 0 && words[a][eq]) { char *sequenses = "abfnrtv"; char *escapes = "\a\b\f\n\r\t\v"; int backslash = 0; int brace1 = 0; int brace2 = 0; int bracket1 = 0; int bracket2 = 0; bool dollar = false; char *dollar_sequense = NULL; for (int i = a; words[i]; i++) { if (i > a) eq = 0; for (int j = eq; words[i][j]; j++) { if (backslash == 2) { bool correct = false; for (int k = 0; sequenses[k]; k++) { if (words[i][j] == sequenses[k]) { MX_C_TO_P(escapes[k], p); val = mx_strrejoin(val, p); backslash = 0; correct = true; break; } } if (!correct) { val = mx_strrejoin(val, "\\"); MX_C_TO_P(words[i][j], p); val = mx_strrejoin(val, p); backslash = 0; } continue; } if (words[i][j] == '"' || words[i][j] == '\'') { if (backslash == 1) { MX_C_TO_P(words[i][j], p); val = mx_strrejoin(val, p); backslash = 0; continue; } else { quote++; continue; } } if (words[i][j] == '$') { if (!dollar) { dollar = true; continue; } else { dollar = false; continue; } } if (dollar) { if (words[i][j] == '{') { brace1++; continue; } else if (words[i][j] == '(') { bracket1++; continue; } else if (words[i][j] == '}') { brace2++; if (brace1 != brace2 && words[i][j + 1] != '}') { fprintf(stderr, "ush: bad substitution\n"); mx_strdel(&dollar_sequense); mx_strdel(&var); mx_strdel(&val); mx_free_words(words); shell->exit_code = EXIT_FAILURE; return; } else if (words[i][j + 1] != '}') { dollar = false; env_var_handler(shell, &val, dollar_sequense); } continue; } else if (words[i][j] == ')') { bracket2++; if (bracket1 != bracket2 && words[i][j + 1] != ')') { fprintf(stderr, "ush: parse error near `)'\n"); mx_strdel(&dollar_sequense); mx_strdel(&var); mx_strdel(&val); mx_free_words(words); shell->exit_code = EXIT_FAILURE; return; } else { mx_strdel(&shell->line); shell->line = strdup(dollar_sequense); shell->new_line = false; mx_command_handler(shell); shell->new_line = true; mx_strdel(&dollar_sequense); dollar = false; } } else { MX_C_TO_P(words[i][j], p); dollar_sequense = mx_strrejoin(dollar_sequense, p); if (!words[i][j + 1]) { dollar = false; env_var_handler(shell, &val, dollar_sequense); } continue; } } MX_C_TO_P(words[i][j], p); val = mx_strrejoin(val, p); } if (quote % 2 == 0) { break; } if (words[i + 1]) { val = mx_strrejoin(val, " "); skip_spaces++; } } } if (quote % 2 == 0) { // printf("%s -> %s\n", var, val); // for test if (!val) val = strdup(""); setenv(var, val, 1); mx_strdel(&var); mx_strdel(&val); a += skip_spaces; skip_spaces = 0; } } if (quote % 2 != 0) { fprintf(stderr, "Odd number of quotes.\n"); mx_free_words(words); shell->exit_code = EXIT_FAILURE; return; } } } if (!words[1] || fp) { extern char **environ; int env_len = 0; for (; environ[env_len]; env_len++); char **vars = malloc(sizeof(char*) * env_len + 1); int k = 0; for (int i = 0; environ[i]; i++) { if (!(environ[i][0] == '_' && environ[i][1] == '=')) // exclude '_=/last/command' vars[k++] = strdup(environ[i]); } vars[k] = NULL; sort_vars(vars); for (int i = 0; vars[i]; i++) { if (fp) printf("export "); printf("%s\n", vars[i]); } mx_free_words(vars); } mx_free_words(words); shell->exit_code = EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "funcoes.h" #define NUM 20 int main() { int i = 0; int nums[NUM]; int maior = 0; for( i=0; i < NUM; i++ ) { printf("Insira um numero [%d/20] \n", i+1); scanf("%d", &nums[i]); } maior = calc_maior(nums,NUM); printf("O maior numero e %d \n", maior); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* dir_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: apelykh <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/09/09 12:50:16 by apelykh #+# #+# */ /* Updated: 2017/09/09 12:50:17 by apelykh ### ########.fr */ /* */ /* ************************************************************************** */ #include "../libft/includes/libft.h" #include "../includes/minishell.h" #include <sys/stat.h> #include <unistd.h> static char *append_homepath(char *path, char **env) { char *homedir; char *upd_path; homedir = ft_getenv("HOME", env); if (homedir) { upd_path = ft_strnew(ft_strlen(homedir) + ft_strlen(path) - 1); ft_strcat(upd_path, homedir); ft_strcat(upd_path, &path[1]); ft_strdel(&homedir); } else upd_path = ft_strdup(path); return (upd_path); } static int check_dir_rights(char *dir_path) { struct stat dir_stat; if (!lstat(dir_path, &dir_stat)) { if ((dir_stat.st_mode & S_IXUSR) && (dir_stat.st_mode & S_IXGRP) && (dir_stat.st_mode & S_IXOTH)) return (1); handle_error(dir_path, NO_EXEC_PERM); return (0); } handle_error(dir_path, NO_WD_CHANGE); return (0); } static void set_cur_wd(char *old_wd, char ***env) { char *cur_wd; cur_wd = ft_strnew(MAX_PATH); getcwd(cur_wd, MAX_PATH); ft_setenv(env, "OLDPWD", old_wd, 1); ft_setenv(env, "PWD", cur_wd, 1); ft_strdel(&cur_wd); } static int change_wd(char *path, char ***env) { char *old_wd; int status; int to_free_path; to_free_path = (path[0] == '~'); if (path[0] == '~') path = append_homepath(path, *env); old_wd = ft_strnew(MAX_PATH); getcwd(old_wd, MAX_PATH); if ((status = chdir(path)) == 0) { set_cur_wd(old_wd, env); ft_strdel(&old_wd); if (to_free_path) ft_strdel(&path); return (0); } check_dir_rights(path); ft_strdel(&old_wd); if (to_free_path) ft_strdel(&path); return (-1); } void handle_cd(char **args, char ***env) { char *tgt_dir; tgt_dir = NULL; if (ft_arrlen(args) > 2) { handle_error("cd", INVAL_ARGS_NUM); ft_putendl("usage: cd dir"); return ; } if (ft_arrlen(args) == 1 || (args[1] && !ft_strcmp(args[1], "~"))) tgt_dir = ft_getenv("HOME", *env); else if (args[1] && !ft_strcmp(args[1], "-")) tgt_dir = ft_getenv("OLDPWD", *env); if (tgt_dir) { change_wd(tgt_dir, env); ft_strdel(&tgt_dir); } else change_wd(args[1], env); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> int main() { const char * const str = "hello"; printf("%s\n",str); char const * ptr = "we"; printf("%s\n",ptr); ptr = "omg"; printf("%s\n",ptr); return 0; }
C
// Jeu de la vie avec sauvegarde de quelques itérations // compiler avec gcc -O3 -march=native (et -fopenmp si OpenMP souhaité) #include <stdio.h> #include <stdlib.h> #include <time.h> #include <sys/time.h> #include <mpi.h> // hauteur et largeur de la matrice #define HM 1200 #define LM 800 // nombre total d'itérations #define ITER 10001 // multiple d'itérations à sauvegarder #define SAUV 1000 #define DIFFTEMPS(a,b) \ (((b).tv_sec - (a).tv_sec) + ((b).tv_usec - (a).tv_usec)/1000000.) /* tableau de cellules */ typedef char Tab[HM][LM]; // initialisation du tableau de cellules void init(Tab); // calcule une nouveau tableau de cellules à partir de l'ancien // - paramètres : ancien, nouveau void calcnouv(Tab, Tab); // variables globales : pas de débordement de pile Tab t1, t2; Tab tsauvegarde[1+ITER/SAUV]; int rank,size; MPI_Request requestRecv, requestSend, requestRecvBis, requestSendBis; MPI_Status status, statusBis; int main( int argc, char **argv ) { struct timeval tv_init, tv_beg, tv_end, tv_save; MPI_Init(&argc,&argv); int root; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); gettimeofday( &tv_init, NULL); if (rank == 0) init(t1); MPI_Scatter(t1, HM*LM/size, MPI_CHAR, t1[HM/size*rank], HM*LM/size, MPI_CHAR, 0, MPI_COMM_WORLD); gettimeofday( &tv_beg, NULL); for(int i=0 ; i<ITER ; i++) { if( i%2 == 0) { calcnouv(t1, t2); } else { calcnouv(t2, t1); } if(i%SAUV == 0) { // Utile pour les sauvegardes MPI_Gather(t1[HM/size*rank], HM*LM/size, MPI_CHAR, t1, HM*LM/size, MPI_CHAR, 0, MPI_COMM_WORLD); if (rank==0) { printf("sauvegarde (%d)\n", i); // copie t1 dans tsauvegarde[i/SAUV] for(int x=0 ; x<HM ; x++) for(int y=0 ; y<LM ; y++) tsauvegarde[i/SAUV][x][y] = t1[x][y]; } } } gettimeofday( &tv_end, NULL); if (rank==0) { FILE *f = fopen("jdlv.out", "w"); for(int i=0 ; i<ITER ; i+=SAUV) { fprintf(f, "------------------ sauvegarde %d ------------------\n", i); for(int x=0 ; x<HM ; x++) { for(int y=0 ; y<LM ; y++) fprintf(f, tsauvegarde[i/SAUV][x][y]?"*":" "); fprintf(f, "\n"); } } fclose(f); } gettimeofday( &tv_save, NULL); printf("init : %lf s,", DIFFTEMPS(tv_init, tv_beg)); printf(" calcul : %lf s,", DIFFTEMPS(tv_beg, tv_end)); printf(" sauvegarde : %lf s\n", DIFFTEMPS(tv_end, tv_save)); MPI_Finalize(); return( 0 ); } void init(Tab t) { srand(time(0)); for(int i=0 ; i<HM ; i++) for(int j=0 ; j<LM ; j++ ) { // t[i][j] = rand()%2; // t[i][j] = ((i+j)%3==0)?1:0; // t[i][j] = (i==0||j==0||i==h-1||j==l-1)?0:1; t[i][j] = 0; } t[10][10] = 1; t[10][11] = 1; t[10][12] = 1; t[9][12] = 1; t[8][11] = 1; t[55][50] = 1; t[54][51] = 1; t[54][52] = 1; t[55][53] = 1; t[56][50] = 1; t[56][51] = 1; t[56][52] = 1; } int nbvois(Tab t, int i, int j) { int n=0; if( i>0 ) { /* i-1 */ if( j>0 ) if( t[i-1][j-1] ) n++; if( t[i-1][j] ) n++; if( j<LM-1 ) if( t[i-1][j+1] ) n++; } if( j>0 ) if( t[i][j-1] ) n++; if( j<LM-1 ) if( t[i][j+1] ) n++; if( i<HM-1 ) { /* i+1 */ if( j>0 ) if( t[i+1][j-1] ) n++; if( t[i+1][j] ) n++; if( j<LM-1 ) if( t[i+1][j+1] ) n++; } return( n ); } void calcnouv(Tab t, Tab n) { if (size > 1) { if (rank != size-1 ) { MPI_Issend(t[(HM/size)*(rank+1)-1], LM, MPI_CHAR, rank+1, 0, MPI_COMM_WORLD, &requestSend); MPI_Irecv(t[(HM/size)*(rank+1)], LM, MPI_CHAR, rank+1, MPI_ANY_TAG, MPI_COMM_WORLD, &requestRecv); } if (rank != 0) { MPI_Issend(t[(HM/size)*rank], LM, MPI_CHAR, rank-1, 0, MPI_COMM_WORLD, &requestSendBis); MPI_Irecv(t[(HM/size)*rank-1], LM, MPI_CHAR, rank-1, MPI_ANY_TAG, MPI_COMM_WORLD, &requestRecvBis); } } #pragma omp parallel for for(int i=(HM/size)*rank; i<((HM/size)*(rank+1)); i++) { if (size>1) { if (rank != (size-1) && i == (HM/size)*(rank+1)-1) { MPI_Wait(&requestRecv,&status); } else if (rank != 0 && i == ((HM/size)*rank)){ i++; } } for(int j=0 ; j<LM ; j++) { int v = nbvois(t, i, j); if(v==3) n[i][j] = 1; else if(v==2) n[i][j] = t[i][j]; else n[i][j] = 0; } } if (rank != 0) { MPI_Wait(&requestRecvBis,&statusBis); for(int j=0 ; j<LM ; j++) { int v = nbvois(t, HM/size*rank, j); if(v==3) n[HM/size*rank][j] = 1; else if(v==2) n[HM/size*rank][j] = t[HM/size*rank][j]; else n[HM/size*rank][j] = 0; } } }
C
// // Created by Ming Hu on 4/9/17. // #include "weather.h" char * get_weather_json() { // Curl string declaration curl_string str_buffer; str_buffer.memory = malloc(1); str_buffer.size = 0; // Curl declaration CURL * curl; CURLcode curl_response_code; // Curl init curl = curl_easy_init(); // Detect if it successfully initialized if(curl == NULL) { printf("[ERROR] libcurl init failed!\n"); exit(1); } #ifdef YWEATHER_DEBUG_CURL // Set debug mode curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L); #endif // Set Curl parameters // Set URL curl_easy_setopt(curl, CURLOPT_URL, YWEATHER_MAIN_API_ENDPOINT); // Set write function pointer (see libcurl's example) curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, save_response_to_string); // Write to string curl_easy_setopt(curl, CURLOPT_WRITEDATA, &str_buffer); // Perform request curl_response_code = curl_easy_perform(curl); if(curl_response_code != CURLE_OK) { fprintf(stderr, "[ERROR] CURL Perform failed, result is: %s", curl_easy_strerror(curl_response_code)); // Clean up curl instance curl_easy_cleanup(curl); free(str_buffer.memory); curl_global_cleanup(); return NULL; } else { printf("[INFO] API data fetch successful\n"); // Declare a new string and copy it from curl string buffer char * return_str = malloc(str_buffer.size); strcpy(return_str, str_buffer.memory); // Clean up curl instance curl_easy_cleanup(curl); free(str_buffer.memory); curl_global_cleanup(); return return_str; } } weather_result_t * get_weather_result(char * weather_str) { // Declare weather result weather_result_t * weather_result = malloc(sizeof(weather_result_t)); struct tm * utc_time_struct = malloc(sizeof(struct tm)); // Parse JSON JSON_Value * weather_value = json_parse_string(weather_str); JSON_Object * weather_root = json_value_get_object(weather_value); weather_result->humidity = (uint8_t)strtol( json_object_dotget_string(weather_root, "query.results.channel.atmosphere.humidity") , NULL, 10); weather_result->status_code = (uint16_t)strtol( json_object_dotget_string(weather_root, "query.results.channel.item.condition.code") , NULL, 10); weather_result->temp = (uint8_t)strtol( json_object_dotget_string(weather_root, "query.results.channel.item.condition.temp") , NULL, 10); weather_result->pressure = strtof( json_object_dotget_string(weather_root, "query.results.channel.atmosphere.pressure"), NULL); // Parse time to string first then covert to time struct strptime(json_object_dotget_string(weather_root, "query.created"), "%FT%T%z", utc_time_struct); // Force set to UTC first in order to let it understand it's a damn UTC time source... char * tz_env = getenv("TZ"); setenv("TZ", "UTC", 1); weather_result->current_time = mktime(utc_time_struct); tz_env == NULL ? unsetenv("TZ") : setenv("TZ", tz_env, 1); // Clean up and return free(utc_time_struct); json_value_free(weather_value); return weather_result; } static size_t save_response_to_string(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; curl_string *mem = (curl_string*)userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if(mem->memory == NULL) { /* out of memory! */ fprintf(stderr, "[ERROR] Not enough memory (realloc returned NULL)\n"); return 0; } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; }
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 */ struct stat {int st_mode; } ; typedef int mode_t ; typedef int /*<<< orphan*/ lua_State ; /* Variables and functions */ int S_IFMT ; scalar_t__ S_ISBLK (int) ; scalar_t__ S_ISCHR (int) ; scalar_t__ S_ISDIR (int) ; scalar_t__ S_ISFIFO (int) ; scalar_t__ S_ISLNK (int) ; scalar_t__ S_ISREG (int) ; scalar_t__ S_ISSOCK (int) ; int /*<<< orphan*/ lua_pushstring (int /*<<< orphan*/ *,char const*) ; __attribute__((used)) static void push_st_mode(lua_State *L, struct stat *sb) { const char *mode_s; mode_t mode; mode = (sb->st_mode & S_IFMT); if (S_ISREG(mode)) mode_s = "file"; else if (S_ISDIR(mode)) mode_s = "directory"; else if (S_ISLNK(mode)) mode_s = "link"; else if (S_ISSOCK(mode)) mode_s = "socket"; else if (S_ISFIFO(mode)) mode_s = "fifo"; else if (S_ISCHR(mode)) mode_s = "char device"; else if (S_ISBLK(mode)) mode_s = "block device"; else mode_s = "other"; lua_pushstring(L, mode_s); }
C
/************************************************************************* > File Name: fork_path.c > Author: liyijia > Mail: [email protected] > Created Time: 2019年10月13日 星期日 14时18分44秒 ************************************************************************/ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <sys/wait.h> int main() { char *patharg; patharg = getenv("PATH"); printf(" a.out %s\n", patharg); if (fork() == 0) { execlp("./b.out", NULL); } wait(NULL); return 0; }
C
#include "../header/decoder.h" #include "../header/matrixMan.h" #include<stdio.h> #include<stdlib.h> void writePPM_P6(const char *filename, struct PPMImage *img) { FILE *fp; //open file for output fp = fopen(filename, "wb"); if (!fp) { fprintf(stderr, "Unable to open file '%s'\n", filename); exit(1); } //write the header file //image format fprintf(fp, "P6\n"); //comments fprintf(fp, "# Created by %s\n",CREATOR); //image size fprintf(fp, "%d %d\n",img->x,img->y); // rgb component depth fprintf(fp, "%d\n",RGB_COMPONENT_COLOR); // pixel data fwrite(img->data, 3 * img->x, img->y, fp); fclose(fp); } void writePPM_P3(const char *filename, struct PPMImage *img) { FILE *fp; //open file for output fp = fopen(filename, "w"); if (!fp) { fprintf(stderr, "Unable to open file '%s'\n", filename); exit(1); } //write the header file //image format fprintf(fp, "P3\n"); //comments fprintf(fp, "# Created by %s\n",CREATOR); //image size fprintf(fp, "%d %d\n",img->x,img->y); // rgb component depth fprintf(fp, "%d\n",RGB_COMPONENT_COLOR); for (int i = 0; i < img->y * img->x; i++) { fprintf(fp,"%d\n%d\n%d\n", img->data[i].red, img->data[i].green, img->data[i].blue); } fclose(fp); } void writePPM(const char* filename, struct PPMImage* img) { if ( img->format == '3' ) writePPM_P3(filename, img); else writePPM_P6(filename, img); } struct PPMImage* convertMatrixesToArray(struct Pixels* img) { struct PPMImage* ppm = (struct PPMImage*)malloc(sizeof(struct PPMImage)); ppm->x = img->width; ppm->y = img->height; ppm->format = img->format; ppm->data = (struct PPMPixel*)malloc(sizeof(struct PPMPixel) * img->width * img->height); int k = 0; for (int i = 0; i < img->height; i++) for (int j = 0; j < img->width; j++) { struct PPMPixel data; data.red = img->a[i][j]; data.green = img->b[i][j]; data.blue = img->c[i][j]; ppm->data[k] = data; k++; } return ppm; } struct Pixels* convertFromYUVtoRGB(struct Pixels* yuv) { struct Pixels* rgb = (struct Pixels*)malloc(sizeof(struct Pixels)); rgb->width = yuv->width; rgb->height = yuv->height; rgb->format = yuv->format; int width = yuv->width; int height = yuv->height; rgb->a = matrixMalloc(width, height); rgb->b = matrixMalloc(width, height); rgb->c = matrixMalloc(width, height); for (int i = 0; i < height; i++) for (int j = 0; j < width; j++) { int Y = yuv->a[i][j]; int Cb = yuv->b[i][j] - 128; int Cr = yuv->c[i][j] - 128; // rgb->a[i][j] = clampTo8Bit(Y + Cr + (Cr >> 2) + (Cr >> 3) + (Cr >> 5)); // rgb->b[i][j] = clampTo8Bit(Y - ((Cb >> 2) + (Cb >> 4) + (Cb >> 5)) - ((Cr >> 1) + (Cr >> 3) + (Cr >> 4) + (Cr >> 5))); // rgb->c[i][j] = clampTo8Bit(Y - Cb + (Cb >> 1) + (Cb >> 2) + (Cb >> 6)); rgb->a[i][j] = clampTo8Bit(Y + 1.402 * Cr); rgb->b[i][j] = clampTo8Bit(Y - 0.344136 * Cb - 0.714136 * Cr); rgb->c[i][j] = clampTo8Bit(Y + 0.1772 * Cb); } return rgb; } void printMatrix(const char* filename, struct EncodedMatrix* matrix, int length) { FILE *fp; //open file for output fp = fopen(filename, "w"); if (!fp) { fprintf(stderr, "Unable to open file '%s'\n", filename); exit(1); } for (size_t i = 0; i < length; i++) { for (size_t j = 0; j < matrix[i].size; j++) { for (size_t k = 0; k < matrix[i].size; k++) { fprintf(fp, "%d ", matrix[i].matrix[j][k]); } fprintf(fp, "\n"); } fprintf(fp, "\n\n"); } fclose(fp); } unsigned int** compressMatrixes(int width, int height, struct EncodedMatrix* matrixes, int blockSize) { unsigned int** matrix = matrixMalloc(width, height); int length = (width * height) / (blockSize * blockSize); for (size_t k = 0; k < length; k++) { int poz_i = matrixes[k].i; int poz_j = matrixes[k].j; for (size_t i = 0; i < blockSize; i++) for (size_t j = 0; j < blockSize; j++) matrix[i + poz_i][j + poz_j] = matrixes[k].matrix[i][j]; } return matrix; } struct EncodedMatrix expandAverage(struct EncodedMatrix matrix) { struct EncodedMatrix submat; submat.i = matrix.i; submat.j = matrix.j; submat.size = 8; submat.matrix = matrixMalloc(8, 8); int ii = 0; int jj = 0; for(int i = 0; i < 8; i += 2) { for(int j = 0; j < 8; j += 2) { if(jj == 4) jj = 0; submat.matrix[i][j] = matrix.matrix[ii][jj]; submat.matrix[i+1][j] = matrix.matrix[ii][jj]; submat.matrix[i][j+1] = matrix.matrix[ii][jj]; submat.matrix[i+1][j+1] = matrix.matrix[ii][jj]; jj++; } ii++; } return submat; } struct EncodedMatrix* expandBlocks(struct EncodedMatrix* matrixes, int length) { struct EncodedMatrix* blocks = (struct EncodedMatrix*)malloc(sizeof(struct EncodedMatrix) * length); for (int k = 0; k < length; k++) blocks[k] = expandAverage(matrixes[0]); return blocks; } struct Pixels* createFullMatrix(struct BlocksImg* block) { struct Pixels* pi = (struct Pixels*)malloc(sizeof(struct Pixels)); pi->width = block->width; pi->height = block->height; pi->format = block->format; int length = block->width * block->height / 64; struct EncodedMatrix* u = expandBlocks(block->b, length); struct EncodedMatrix* v = expandBlocks(block->c, length); pi->a = compressMatrixes(block->width, block->height, block->a, 8); pi->b = compressMatrixes(block->width, block->height, u, 8); pi->c = compressMatrixes(block->width, block->height, v, 8); return pi; } void decode_ppm(struct BlocksImg* block, const char* filename) { int length = block->width * block->height / 64; printMatrix("./output/yBlock", block->a, length); printMatrix("./output/uBlock", block->b, length); printMatrix("./output/vBlock", block->c, length); struct Pixels* pi = createFullMatrix(block); pi = convertFromYUVtoRGB(pi); struct PPMImage* img = convertMatrixesToArray(pi); writePPM(filename, img); }
C
#include <stdio.h> #include "RobotArmManager.h" #include "Action.h" int main(int argc, char const *argv[]) { int x,y,z,t; RobotArmManager* me = RobotArmManager_Create(); x=1; y=2; z=3; t=4; RobotArmManager_computeTrajectory(me, x, y, z, t); x=5; y=6; z=7; t=8; RobotArmManager_graspAt(me, x, y, z, t); // struct Action // { // int rotatingArmJoint1; // int rotatingArmJoint2; // int rotatingArmJoint3; // int rotatingArmJoint4; // int slidingArmJoint1; // int slidingArmJoint2; // int manipulatorForce; // int manipulatorOpen; // }; Action* action = (Action*)malloc(sizeof(Action)); action->rotatingArmJoint1 = 11; action->rotatingArmJoint2 = 11; action->rotatingArmJoint3 = 11; action->rotatingArmJoint4 = 11; action->slidingArmJoint1 = 11; action->slidingArmJoint2 = 11; action->manipulatorForce = 11; action->manipulatorOpen = 11; RobotArmManager_addItsAction(me, action); RotatingArmJoint* p_RotatingArmJoint = (RotatingArmJoint*)malloc(sizeof(RotatingArmJoint)); RobotArmManager_addItsRotatingArmJoint(me, p_RotatingArmJoint); RobotArmManager_executeStep(me); RobotArmManager_Destroy(me); return 0; }
C
#include <stdio.h> int main(){ printf("\tCalculator\n\n"); while(1){ float num1, num2, total; int oper; printf("................\n"); printf("1 for sum\n"); printf("2 for sub\n"); printf("3 for mul\n"); printf("4 for div\n"); printf("5 for exit\n"); printf("................\n"); printf("choice:"); scanf("%d", &oper); if(oper == 5){ break; } printf("................\n"); printf("1st number: "); scanf("%f", &num1); printf("2nd number: "); scanf("%f", &num2); printf("................\n"); if(oper == 1){ printf(" Output: %.2f\n", num1+num2); } else if(oper == 2){ printf(" %.2f\n", num1-num2); } else if(oper == 3){ printf("Output: %.2f\n", num1*num2); } else if(oper == 4){ printf("Output: %.2f\n", num1/num2); } } }