language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> int main(){ int cont; cont = 0; while(cont <= 10){ printf("Contador é igual a %d\n", cont); cont++; } return 0; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #define SLEN 20 char * s_gets(char *st, int n); int cal_ch(char ch, FILE *fp); int main(int argc, char *argv[]) { char ch; FILE *fp; int count; if (argc < 2) { fprintf(stderr, "Usage: %s char [filename] or printf.\n", argv[0]); exit(EXIT_FAILURE); } ch = argv[1][0]; if (argc == 2) { char filename[SLEN]; printf("Enter the filename: "); while (s_gets(filename, SLEN) != NULL && filename[0] != '\0') { if ((fp = fopen(filename, "r")) == NULL) { fprintf(stderr, "Cant't open %s.\n", filename); printf("Enter the filename: "); continue; }else { count = cal_ch(ch, fp); printf("The %s file has appear %d -%c\n", filename, count, ch); printf("Enter the filename: "); } } } if (argc == 3) { if ((fp = fopen(argv[2], "r")) == NULL) { fprintf(stderr, "Can't open %s.\n", argv[2]); exit(EXIT_FAILURE); } count = cal_ch(ch, fp); printf("The %s file has appear %d -%c\n", argv[2], count, ch); } fclose(fp); return 0; } char * s_gets(char *st, int n) { char *ret_val, *find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); if (find){ *find = '\0'; }else { while (getchar() != '\n') { continue; } } } return ret_val; } int cal_ch(char ch, FILE *fp) { char fch; int i = 0; while ((fch = getc(fp)) != EOF) { if (ch == fch) { i++; } } return i; }
C
#include<stdio.h> int main() { double etox = 1, n,x,i,j,k; scanf("%lf %lf", &x,&n); if (n<0) { printf("error"); } else { for(i=1;i<=n;i++) { double po=1,m=1; for(j = i;j>0;j--) { po = po*j; } for(k=0;k<i;k++) { m=m*x; } etox+=m/po; }printf("%lf",etox); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #ifndef PORT #define PORT 30000 #endif #define MAX_BACKLOG 5 #define MAX_CONNECTIONS 12 #define BUF_SIZE 128 struct sockname { int sock_fd; char *username; int type; char *buf; }; /* Accept a connection. Note that a new file descriptor is created for * communication with the client. The initial socket descriptor is used * to accept connections, but the new socket is used to communicate. * Return the new client's file descriptor or -1 on error. */ int accept_connection(int fd, struct sockname *usernames) { int user_index = 0; while (user_index < MAX_CONNECTIONS && usernames[user_index].sock_fd != -1) { user_index++; } if (user_index == MAX_CONNECTIONS) { fprintf(stderr, "server: max concurrent connections\n"); return -1; } int client_fd = accept(fd, NULL, NULL); if (client_fd < 0) { perror("server: accept"); close(fd); exit(1); } // instruction dprintf(client_fd, "Welcome to the Help Centre, what is your name?\r\n"); usernames[user_index].sock_fd = client_fd; usernames[user_index].username = NULL; return client_fd; } /* * Search the first n characters of buf for a network newline (\r\n). * Return one plus the index of the '\n' of the first network newline, * or -1 if no network newline is found. * Definitely do not use strchr or other string functions to search here. (Why not?) */ int find_network_newline(const char *buf, int n) { int i = 0; while (i + 1 < n){ if (buf[i] == '\r' && buf[i+1] == '\n') { return i + 2; } i++; } return -1; } int read_line(char *buf, int *fd_ptr){ // length of holding int inbuf = strlen(buf); // length of remaining int room = BUF_SIZE - inbuf; // cursor char *after = &buf[inbuf]; // position of network newline int where = -1; int nbytes; while ((nbytes = read(*fd_ptr, after, room)) > 0) { inbuf += nbytes; while ((where = find_network_newline(buf, inbuf)) > 0) { // replace network newline with null terminator buf[where - 2] = '\0'; // save the rest and clean inbuf = inbuf - where; return inbuf; } // no newline: continue room = sizeof(buf) - inbuf; after = &buf[inbuf]; } // exit condition: closed *fd_ptr = -1; return -1; } void clean_buf(char *buf, int len_next){ int i = 0; while (i < len_next) { buf[i] = buf[strlen(buf) + 2 + i]; i ++; } while (i < BUF_SIZE) { buf[i] = '\0'; i ++; } } /* Read a message from client_index and echo it back to all clients. * Return the fd if it has been closed or 0 otherwise. */ int read_from(int* hc_fd, int client_index, struct sockname *usernames, fd_set *listen_fds) { int fd = usernames[client_index].sock_fd; // Receive messages char *buf = usernames[client_index].buf; int len_next = -1; if ((len_next = read_line(buf, &(usernames[client_index].sock_fd))) < 0){ // closed return fd; } else { // check buf content int c1 = strcmp("stats", buf); int c2 = usernames[client_index].type; int c3 = strcmp("next", buf); if (c2 < 1) { perror("wrong type of client"); } if (c2 == 1 && c3 == 0){ dprintf(hc_fd[1], "next"); } else if (c1 == 0) { //TODO: write to Help Centre pipe if (c2 == 1){ dprintf(hc_fd[1], "print_full_queue"); } else if (c2 == 2){ dprintf(hc_fd[1], "print_currently_serving"); } //TODO: read from Help Centre char output[BUF_SIZE]; int num_read = read(hc_fd[0], &output, BUF_SIZE); buf[num_read] = '\0'; if (num_read == 0) { perror("read from helpcentre"); } //TODO: output to client if (write(fd, output, strlen(buf)) != strlen(buf)){ // closed return fd; } } else { dprintf(fd, "wrong syntax\r\n"); } // prepare for next line clean_buf(buf, len_next); return 0; } } /* Read the username from client_index, and modified the structaccordingly. * Return the fd if it is closed or 0 otherwise. */ int read_name(int client_index, struct sockname *usernames) { // check if (usernames[client_index].username != NULL){ perror("client already named."); exit(1); } // set up int fd = usernames[client_index].sock_fd; // read name char *buf = usernames[client_index].buf; // first time // length of holding int inbuf = 0; // length of remaining int room = sizeof(buf); // cursor char *after = buf; // position of network newline int where = -1; int nbytes; while ((nbytes = read(fd, after, room)) > 0) { inbuf += nbytes; while ((where = find_network_newline(buf, inbuf)) > 0) { // replace network newline with null terminator buf[where - 2] = '\0'; char* name = malloc(sizeof(char)*strlen(buf)); strncpy(name, buf, strlen(buf)); usernames[client_index].username = name; // instruction dprintf(fd, "Hello, %s. Are you a TA or a Student? (enter T or S)\r\n", usernames[client_index].username); // save the rest and clean inbuf = inbuf - where; int i = 0; while (i < inbuf) { buf[i] = buf[where + i]; i ++; } while (i < BUF_SIZE) { buf[i] = '\0'; i ++; } return 0; } // no newline: continue room = sizeof(buf) - inbuf; after = &buf[inbuf]; } // exit condition: closed usernames[client_index].sock_fd = -1; return fd; } /* Read the type from client_index, and modified the struct accordingly and write to help_centre. * Return the fd if it is closed or 0 otherwise. */ int read_type(int* hc_fd, int client_index, struct sockname *usernames) { // check if (usernames[client_index].username == NULL) { perror("client unnamed."); exit(1); } if (usernames[client_index].type != -1){ perror("client already typed."); exit(1); } //fd int fd = usernames[client_index].sock_fd; char *buf = usernames[client_index].buf; int len_next = -1; if ((len_next = read_line(buf, &(usernames[client_index].sock_fd))) < 0){ // closed return fd; } else { if (strlen(buf) != 1) { dprintf(fd, "Invalid role (enter T or S)\r\n"); } else if (buf[0] == 'T') { usernames[client_index].type = 1; dprintf(hc_fd[1], "add_ta %s", usernames[client_index].username); dprintf(fd, "Valid commands for TA:\r\n stats\r\n next\r\n (or usr Ctrl-C to leave)\r\n"); } else if (buf[0] == 'S') { usernames[client_index].type = 0; dprintf(fd, "Valid courses: CSC108, CSC148, CSC209\nWhich course are you asking about?\r\n"); } else { dprintf(fd, "Invalid role (enter T or S)\r\n"); } // prepare for next line clean_buf(buf, len_next); return 0; } } /* Read the type from client_index, and modified the struct accordingly and write to help_centre. * Return the fd if it is closed or 0 otherwise. */ int read_course(int *hc_fd, int client_index, struct sockname *usernames) { // check if (usernames[client_index].username == NULL) { perror("client unnamed."); exit(1); } if (usernames[client_index].type != 0){ perror("client not student."); exit(1); } // set up int fd = usernames[client_index].sock_fd; char *buf = usernames[client_index].buf; int len_next = -1; if ((len_next = read_line(buf, &(usernames[client_index].sock_fd))) < 0){ // closed return fd; } else { if (strlen(buf) != 6){ dprintf(fd, "This is not a valid course.\r\n"); } else if ((strncmp("CSC108", buf, 6) == 0) || (strncmp("CSC148", buf, 6)) == 0 || (strncmp("CSC209", buf, 6) == 0)) { usernames[client_index].type = 2; dprintf(hc_fd[1], "add_student %s %s", usernames[client_index].username, buf); // instruction dprintf(fd, "%s, you have been entered into the queue. While you wait, you can use the command stats to see which TAs are currently serving students.\r\n", usernames[client_index].username); } else { dprintf(fd, "This is not a valid course.\r\n"); } // prepare for next line clean_buf(buf, len_next); return 0; } } int main(void) { int hc_fd[2]; int pid; // create pipe if (pipe(hc_fd) == -1){ perror("help centre pipe"); exit(1); } // open helpcentre if ((pid = fork()) == 0){ // reset stdin if ((dup2(hc_fd[0], fileno(stdin))) == -1) { //assert perror("helpcentre reset stdin"); exit(1); } // reset stdout if ((dup2(hc_fd[1], fileno(stdout))) == -1) { // assert perror("helpcentre reset stdout"); exit(1); } // close fd[0] close(hc_fd[0]); // start helpcentre execl("./helpcentre", "helpcentre", (char *)NULL); perror("exec helpcentre"); exit(1); } else if (pid > 0) { // server set up struct sockname usernames[MAX_CONNECTIONS]; for (int index = 0; index < MAX_CONNECTIONS; index++) { usernames[index].sock_fd = -1; usernames[index].username = NULL; usernames[index].type = -1; usernames[index].buf = malloc(sizeof(char)*BUF_SIZE); } // Create the socket FD. int sock_fd = socket(AF_INET, SOCK_STREAM, 0); if (sock_fd < 0) { perror("server: socket"); exit(1); } // Set information about the port (and IP) we want to be connected to. struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(PORT); server.sin_addr.s_addr = INADDR_ANY; // This should always be zero. On some systems, it won't error if you // forget, but on others, you'll get mysterious errors. So zero it. memset(&server.sin_zero, 0, 8); // Bind the selected port to the socket. if (bind(sock_fd, (struct sockaddr *)&server, sizeof(server)) < 0) { perror("server: bind"); close(sock_fd); exit(1); } // Announce willingness to accept connections on this socket. if (listen(sock_fd, MAX_BACKLOG) < 0) { perror("server: listen"); close(sock_fd); exit(1); } // The client accept - message accept loop. First, we prepare to listen to multiple // file descriptors by initializing a set of file descriptors. int max_fd = sock_fd; fd_set all_fds; FD_ZERO(&all_fds); FD_SET(sock_fd, &all_fds); while (1) { // select updates the fd_set it receives, so we always use a copy and retain the original. fd_set listen_fds = all_fds; int nready = select(max_fd + 1, &listen_fds, NULL, NULL, NULL); if (nready == -1) { perror("server: select"); exit(1); } // Is it the original socket? Create a new connection ... if (FD_ISSET(sock_fd, &listen_fds)) { int client_fd = accept_connection(sock_fd, usernames); if (client_fd > max_fd) { max_fd = client_fd; } FD_SET(client_fd, &all_fds); printf("Accepted connection\n"); } // Next, check the clients. // NOTE: We could do some tricks with nready to terminate this loop early. for (int index = 0; index < MAX_CONNECTIONS; index++) { if (usernames[index].sock_fd > -1 && FD_ISSET(usernames[index].sock_fd, &listen_fds)) { // New client if (usernames[index].username == NULL){ // Name read_name(index, usernames); } else if (usernames[index].type == -1){ // TA / Student read_type(hc_fd, index, usernames); } else if (usernames[index].type == 0){ // Student course read_course(hc_fd, index, usernames); } else { // Note: never reduces max_fd int client_closed = read_from(hc_fd, index, usernames, &listen_fds); if (client_closed > 0) { FD_CLR(client_closed, &all_fds); printf("%s: Client %d disconnected\n", usernames[index].username, client_closed); } else { printf("%s: Answering request to %d client %d\n", usernames[index].username, usernames[index].type, usernames[index].sock_fd); } } } } } // Should never get here. return 1; } }
C
#include <stdio.h> #include <ncurses.h> #include "vkb.h" #define WIDTH 30 #define HEIGHT 10 WINDOW *mainwin; int startx = 0; int starty = 0; void vkb_init(){ initscr(); clear(); noecho(); cbreak(); startx = (80 - WIDTH) / 2; starty = (24 - HEIGHT ) / 2; mainwin = newwin(WIDTH,HEIGHT,startx,starty); keypad(mainwin,TRUE); refresh(); } void *vkb_runthread( void *arg ){ int curkey = -1; while(1){ curkey = wgetch(mainwin); if( curkey < 130 && keyfreq[curkey] != 0 ){ mvprintw(24, 0, "'%c' => %fHz", curkey, keyfreq[curkey]); refresh(); } } } int main(int argc, char *argv[]){ vkb_init(); vkb_runthread(NULL); }
C
#include <stdio.h> int add(void *a,void *b){ int result=0; result= *(int*)a + *(int *)b; return result; } int main(int argc, char *argv[]) { int a=100; int b=15; void *p=&a; //void * ָκ printf("a=%d\n",*(int *)p); int res=add(&a,&b); printf("res=%d\n",res); return 0; }
C
/********************************************************** * Author : 梁金荣 * Email : Liangjinrong111@163.com * Last modified : 2019-09-14 13:00 * Filename : exnum.c * Description : 模块初始化函数中求最大数(使用内核中的代码) * *******************************************************/ //必要的头文件 #include<linux/kernel.h> #include<linux/module.h> #include<linux/init.h> //模块的初始化函数,模块的入口函数,加载模块,需超级用户权限 static int __init lk_exnum(void) { int x = 1, y = 2; printk("The module is starting here!\n"); printk("x = %d, y = %d\n", x, y); printk("max=%d\n", max(x++, y++)); printk("x = %d, y = %d\n", x, y); printk("min=%d\n", min(x++, y++)); return 0; } //出口函数,卸载模块,需超级用户权限 static void __exit lk_exit(void) { printk("The maxnum moudle has exited!\n"); } module_init(lk_exnum); //内核入口点,调用初始化函数,包含在module.h中 module_exit(lk_exit); //出口点 MODULE_LICENSE("GPL"); //许可证 MODULE_AUTHOR("ljr"); //作者(非必须) MODULE_DESCRIPTION("max and min number"); //模块描述(非必须)
C
/* Program 7.11 A dynamic prime program */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main(void) { unsigned long *prime = NULL; unsigned long trial = 0; bool found = false; size_t total = 300; size_t count = 0; prime = malloc(total * sizeof(int)); *prime = 2; *(prime+1) = 3; *(prime+2) = 5; count = 3; trial = 5; while ( count < total ) { trial += 2; for(size_t i = 0; i < count ; i++) { if(!(found = (trial % *(prime+i)))) { break; } } if(found) { *(prime+count++) = trial; } } for(size_t i=0; i < count; i++) { if(!(i%10)) printf("\n"); printf("%d\t", *(prime+i)); } return 0; } /* `12345 67890[] {} ',.py fgcrl /= ?+ aoeui dhtns -\ _| ;qjkx bmwvz */
C
// C Primer Plus // Chapter 16 Exercise 4: // The ANSI library features a clock() function with this description: // #include <time.h> clock_t clock (void); // Here, clock_t is a type defined in time.h. The function returns the // processor time, which is given in some implementation-dependent units. (If // the processor time is unavailable or cannot be represented, the function // returns a value of -1.) However, CLOCKS_PER_SEC, also defined in time.h, is // the number of processor time units per second. Therefore, dividing the // difference between two return values of clock() by CLOCKS_PER_SEC gives you // the number of seconds elapsed between the two calls. Typecasting the values // to double before division enables you to get fractions of a second. Write a // function that takes a double argument representing a desired time delay and // then runs a loop until that amount of time has passed. Write a simple // program that tests the function. #include <stdio.h> #include <time.h> void timeout(double time); int main(void) { double time; printf("Enter desired time delay in seconds: "); while(scanf("%lf", &time) == 1) { puts("Starting."); timeout(time); printf("It is now %2f seconds later!\n", time); printf("Enter desired time delay in seconds: "); } puts("Bye."); } void timeout(double time) { clock_t start, end; start = clock(); while (((end = clock()) - start) / (double) CLOCKS_PER_SEC < time) continue; return; }
C
#include <stdlib.h> #include <sys/types.h> #include <math.h> #include "slm.h" #include "ehmm.h" long double llog10(long double x) { if (x < FLOOR_VALUE) return LOG_FLOOR_VALUE; return (long double)log10((double)x); } SLMEHMMState *SLMAllocEHMMState(int n_state,int n_vocab) { int i; long double *sprobs, *eprobs; SLMEHMMState *State; State = New_N(SLMEHMMState, n_state); sprobs = New_N(long double,n_state*n_state); eprobs = New_N(long double,n_state*n_vocab); for (i = 0; i < n_state; i++) { State[i].trans_probs = &sprobs[i*n_state]; State[i].emit_probs = &eprobs[i*n_vocab]; } return State; } void SLMDumpEHMM(FILEHANDLE f, SLMEHMMState *st, int n_state, int n_vocab) { int i,j; z_printf(f,"%d %d\n",n_state, n_vocab); for (i = 0; i < n_state; i++,st++) { for (j = 0; j < n_state; j++) { z_printf(f,"%Lg ",llog10(st->trans_probs[j])); } z_printf(f,"\n"); for (j = 0; j < n_vocab; j++) { z_printf(f,"%Lg ",llog10(st->emit_probs[j])); } z_printf(f,"\n"); } } static void z_getnum(char *file, FILEHANDLE f, void *ptr, int (*in_rout)(FILEHANDLE,void*)) { if (in_rout(f,ptr) < 0) { fprintf(stderr,"File format error in %s\n",file); exit(1); } } #define GETINT(file,f,p) z_getnum(file,f,(void*)p,(int(*)(FILEHANDLE,void*))z_getint) #define GETFLOAT(file,f,p) z_getnum(file,f,(void*)p,(int(*)(FILEHANDLE,void*))z_getdouble) SLMEHMMState * SLMReadEHMM(char *file, int *n_state, int *n_vocab) { FILEHANDLE f; int i,j; SLMEHMMState *st; double r; f = z_open(file,"r"); GETINT(file,f,n_state); GETINT(file,f,n_vocab); st = SLMAllocEHMMState(*n_state, *n_vocab); for (i = 0; i < *n_state; i++) { for (j = 0; j < *n_state; j++) { GETFLOAT(file,f,&r); st[i].trans_probs[j] = pow(10.0,r); } for (j = 0; j < *n_vocab; j++) { GETFLOAT(file,f,&r); st[i].emit_probs[j] = pow(10.0,r); } } z_close(f); return st; }
C
#include"global.h" #include"posix_api.h" void main(int argc,char **argv) { int n = 0; int fd; char *path; char buf[BUFSIZ]; if(argc != 2){ printf("invalid argument!\n"); exit(1); } path = argv[1]; fd = _OpenFile(path,O_RDONLY); printf("readfile fd -- %d\n",fd); if(fd != -1){ bzero(buf,BUFSIZ); n = _ReadFile(fd,buf,BUFSIZ,0); printf("read -- %s\n",buf); _CloseFile(fd); } exit(0); }
C
#include <stdio.h> #include <stdlib.h> struct fdQueue { struct Node* front; struct Node* rear; }; struct fdNode { int data; struct Node* next; }; // To Enqueue a node void fdEnqueue(struct fdQueue *queue, int number) { struct fdNode* temp = malloc(sizeof(struct fdNode)); temp->data = number; temp->next = NULL; if(queue->front == NULL && queue->rear == NULL){ queue->front = queue->rear = temp; return; } queue->rear->next = temp; queue->rear = temp; } // To Dequeue a node. int fdDequeue(struct fdQueue *queue) { struct fdNode* temp = queue->front; if(queue->front == NULL) { return -1; } if(queue->front == queue->rear) { queue->front = queue->rear = NULL; return temp->data; } else { queue->front = queue->front->next; return temp->data; } }
C
#include <stdio.h> #include <stdlib.h> int main() { int N,*X,i; scanf("%d",&N); X = (int*)malloc(sizeof(int)); for(i=0;i<N;i++) { scanf("%d",&X[i]); }for(i=0;i<N;i++){ if(X[i]%2==0 && X[i]>0){ printf("EVEN POSITIVE\n"); }else if(X[i]%2!=0 && X[i]>0){ printf("ODD POSITIVE\n"); }else if(X[i]%2!=0 && X[i]<0){ printf("ODD NEGATIVE\n"); }else if(X[i]%2==0 && X[i]<0){ printf("EVEN NEGATIVE\n"); }else if(X[i]==0){ printf("NULL\n"); } } }
C
#include<stdio.h> #include "9.4header.h" // 显示菜单,并返回操作选项 int menu(void) { int ret, status; printf("\n%s%s\n", STAR, STAR); printf("Please enter the option of the desired hotel:\n"); printf("1.Ximalay Hotel\t\t2.Hiberton Hotel\n"); printf("3.LA Hotel\t\t4.Seven Eleven Hotel\n"); printf("5.Quit\n"); // 处理异常输入 while((ret = scanf("%d", &status))!=1 || (status >5 || status <1)) { if(ret != 1) // 处理非整数 { scanf("%*s"); } printf("Please enter an integer from 1 to 5\n"); } // printf("ret = %d, status = %d\n", ret, status); return status; printf("%s%s\n", STAR, STAR); } // 获取入住天数 int getNights(void) { int nights; printf("How many nights are needed?\n"); while(scanf("%d", &nights) !=1) { scanf("%*s"); printf("Please enter an integer!\n"); } printf("nights = %d\n", nights); return nights; } // 显示入住酒店每天需要支付的金额 void showPrice(double rate, int nights) { double totalBill = 0; double factor = 1.0; for(int i = 0; i<nights;i++) { totalBill += rate*factor; factor *= DISCOUNT; } printf("The total cost will be $%.2f. \n", totalBill); }
C
#include <gtk/gtk.h> #define NAME "hepan" #define PWD "693640" void init_login_widget(); void enroll(GtkWidget *widget,gpointer data); void login(GtkWidget *widget,gpointer data); void gtk_win_destroy(GtkWidget *widget,gpointer data); void make_dialog(); void gtk_dialog_destroy(GtkWidget *widget, gpointer data); void gtk_win_chat(GtkWidget *widget, gpointer data); //将登陆窗体独立成一个结构体 struct login_widget{ GtkWidget *window; //主窗体 GtkWidget *label_tips; //用于信息提示的标签 GtkWidget *button_login; //两个按钮,一个点击后登录,一个点击后退出 GtkWidget *button_enroll; GtkWidget *entry_username; //两个文本框,用于输入用户名和密码 GtkWidget *entry_pwd; GtkWidget *label_username; //两个标签用于显示username文本框和password文本框提示 GtkWidget *label_pwd; GtkWidget *label_pwd2; GtkWidget *vbox; //垂直布局盒子,包含以下三个水平布局盒子 GtkWidget *hbox_username; //包含用户名提示标签和用户名文本框,下面的HBOX作用类似 GtkWidget *hbox_pwd; GtkWidget *hbox_pwd2; GtkWidget *hbox_button; GtkWidget *verify_pwd; //确认密码 }wgt; void make_dialog() { GtkWidget *dialog; GtkWidget *label; GtkWidget *button1; GtkWidget *button2; GtkWidget *vbox; GtkWidget *hbox; dialog = gtk_dialog_new(); //向对话框中加入一个文本标签 vbox = GTK_DIALOG(dialog)->vbox; label = gtk_label_new("确认退出?"); gtk_box_pack_start(GTK_BOX(vbox),label,TRUE,TRUE,30); //向对话框中加入两个按钮 hbox = GTK_DIALOG(dialog)->action_area; button1 = gtk_button_new_with_label("是"); gtk_box_pack_start(GTK_BOX(hbox),button1,FALSE,FALSE,0); button2 = gtk_button_new_with_label("否"); gtk_box_pack_start(GTK_BOX(hbox),button2,FALSE,FALSE,0); gtk_widget_show_all(dialog); g_signal_connect(G_OBJECT(button1),"clicked",G_CALLBACK(gtk_main_quit),NULL); g_signal_connect(G_OBJECT(button2),"clicked",G_CALLBACK(gtk_dialog_destroy),(void *)dialog); } void gtk_win_chat(GtkWidget *widget, gpointer data) { wgt.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); wgt.label_tips = gtk_label_new("欢迎来到聊天室"); gtk_window_set_title(GTK_WINDOW(wgt.window),"聊天窗口"); } void gtk_dialog_destroy(GtkWidget *widget, gpointer data) { gtk_widget_destroy((GtkWidget *)data); } void gtk_win_destroy(GtkWidget *widget, gpointer data) { make_dialog(); } //登录验证函数,点击login按钮时调用 void login(GtkWidget *widget,gpointer data) { char *name; char *pwd; struct login_widget *wgt; wgt = (struct loging_widget *)data; //获取输入的信息 name = gtk_entry_get_text(GTK_ENTRY(wgt->entry_username)); pwd = gtk_entry_get_text(GTK_ENTRY(wgt->entry_pwd)); if((strcmp(name,NAME) == 0) && (strcmp(pwd,PWD) == 0)) { gtk_label_set_text(GTK_LABEL(wgt->label_tips),"欢迎来到聊天室"); //g_signal_connect(G_OBJECT(wgt.button_login),"clicked",G_CALLBACK(gtk_win_chat),NULL); } else { gtk_label_set_text(GTK_LABEL(wgt->label_tips),"用户名或密码错误"); } } void enroll(GtkWidget *widget,gpointer data) { GtkWidget *button_enroll2; wgt.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); wgt.label_tips = gtk_label_new("欢迎注册"); wgt.entry_username = gtk_entry_new_with_max_length(15); wgt.entry_pwd = gtk_entry_new_with_max_length(16); wgt.verify_pwd = gtk_entry_new_with_max_length(16); wgt.label_username = gtk_label_new("用户名"); wgt.label_pwd = gtk_label_new("密码"); wgt.label_pwd2 = gtk_label_new("确认密码"); wgt.vbox = gtk_vbox_new(FALSE,20); wgt.hbox_username = gtk_hbox_new(FALSE,20); wgt.hbox_pwd = gtk_hbox_new(FALSE,20); wgt.hbox_pwd2 = gtk_hbox_new(FALSE,20); button_enroll2 = gtk_button_new_with_label("提交"); gtk_window_set_title(GTK_WINDOW(wgt.window),"注册窗口"); gtk_window_set_resizable(GTK_WINDOW(wgt.window),FALSE); gtk_box_pack_start(GTK_BOX(wgt.hbox_username),wgt.label_username,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_username),wgt.entry_username,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_pwd),wgt.label_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_pwd),wgt.entry_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_pwd2),wgt.label_pwd2,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_pwd2),wgt.verify_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.label_tips,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.hbox_username,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.hbox_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.hbox_pwd2,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),button_enroll2,TRUE,FALSE,10); gtk_entry_set_visibility(GTK_ENTRY(wgt.verify_pwd),FALSE); gtk_entry_set_invisible_char(GTK_ENTRY(wgt.verify_pwd),'*'); gtk_entry_set_visibility(GTK_ENTRY(wgt.entry_pwd),FALSE); gtk_entry_set_invisible_char(GTK_ENTRY(wgt.entry_pwd),'*'); gtk_container_add(GTK_CONTAINER(wgt.window),wgt.vbox); gtk_widget_show_all(wgt.window); } void init_login_widget() { GtkWidget *image; GtkWidget *frame; image = gtk_image_new_from_file("qq1.jpg"); wgt.window = gtk_window_new(GTK_WINDOW_TOPLEVEL); //frame = gtk_frame_new(NULL); //gtk_container_add(GTK_CONTAINER(frame),image); //gtk_container_add(GTK_CONTAINER(wgt.window),frame); wgt.label_tips = gtk_label_new("欢迎登录聊天室"); wgt.button_login = gtk_button_new_with_label("登录"); wgt.button_enroll = gtk_button_new_with_label("注册"); wgt.entry_username = gtk_entry_new_with_max_length(15); wgt.entry_pwd = gtk_entry_new_with_max_length(16); wgt.label_username = gtk_label_new("用户名"); wgt.label_pwd = gtk_label_new("密码"); wgt.vbox = gtk_vbox_new(FALSE,20); wgt.hbox_username = gtk_hbox_new(FALSE,20); wgt.hbox_pwd = gtk_hbox_new(FALSE,20); wgt.hbox_button = gtk_hbox_new(FALSE,20); //设置窗体 gtk_window_set_title(GTK_WINDOW(wgt.window),"登录窗口"); gtk_window_set_resizable(GTK_WINDOW(wgt.window),FALSE); //设置布局盒子 gtk_box_pack_start(GTK_BOX(wgt.hbox_username),wgt.label_username,TRUE,FALSE,10); //gtk_box_pack_start(GTK_BOX(wgt.hbox_username),image,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_username),wgt.entry_username,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_pwd),wgt.label_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_pwd),wgt.entry_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_button),wgt.button_login,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.hbox_button),wgt.button_enroll,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.label_tips,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.hbox_username,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.hbox_pwd,TRUE,FALSE,10); gtk_box_pack_start(GTK_BOX(wgt.vbox),wgt.hbox_button,TRUE,FALSE,10); //设置密码框不可见,用户输入时显示“*” gtk_entry_set_visibility(GTK_ENTRY(wgt.entry_pwd),FALSE); gtk_entry_set_invisible_char(GTK_ENTRY(wgt.entry_pwd),'*'); g_signal_connect(GTK_OBJECT(wgt.button_login),"clicked",GTK_SIGNAL_FUNC(login),&wgt); g_signal_connect(GTK_OBJECT(wgt.window),"delete_event",GTK_SIGNAL_FUNC(gtk_win_destroy),NULL); g_signal_connect(GTK_OBJECT(wgt.button_enroll),"clicked",GTK_SIGNAL_FUNC(enroll),NULL); gtk_container_add(GTK_CONTAINER(wgt.window),wgt.vbox); gtk_widget_show_all(wgt.window); } int main(int argc,char *argv[]) { gtk_init(&argc,&argv); init_login_widget(); gtk_main(); return 0; }
C
#include <stdbool.h> #include <stdio.h> #include <sys/time.h> #include <math.h> static double CurrentTimeInSeconds() { struct timeval tv; gettimeofday(&tv, NULL); return tv.tv_sec + tv.tv_usec / 1000000.0; } bool CalcTime(int * times, double * start) { if(*times == 0) { *start = CurrentTimeInSeconds(); } else { double elapsed = CurrentTimeInSeconds() - *start; if(elapsed > 0.1f) { *start = elapsed / *times; return false; } } (*times)++; return true; } // call the convolution //void my_convolution(double (*gettime)(),int argc, char* argv[]); void testsize(int M, int N, int K) { double mytime; int times = 0; while(CalcTime(&times,&mytime)) { //my_convolution(CurrentTimeInSeconds,argc,argv); } double logmytime = log(M) + log(N) + log(K) + log(2) + log(1e-9) - log(mytime); printf("%d %d %d %f \n",M,K,N,logmytime); } int main() { int NB = 48; // for(int i = NB; i < 3000; i += 3*NB) { // testsize(i,i,i); // } testsize(256, 256, 5); return 0; }
C
////nota!! in problema sa cere sa folosim fct chmod! #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<pwd.h> #include<string.h> #include<errno.h> #include<fcntl.h> #include <sys/stat.h> struct stat fs; void permisiunile_sunt(struct stat x){ printf( (x.st_mode & S_IRUSR) ? "r" : "-"); printf( (x.st_mode & S_IWUSR) ? "w" : "-"); printf( (x.st_mode & S_IXUSR) ? "x" : "-"); printf( (x.st_mode & S_IRGRP) ? "r" : "-"); printf( (x.st_mode & S_IWGRP) ? "w" : "-"); printf( (x.st_mode & S_IXGRP) ? "x" : "-"); printf( (x.st_mode & S_IROTH) ? "r" : "-"); printf( (x.st_mode & S_IWOTH) ? "w" : "-"); printf( (x.st_mode & S_IXOTH) ? "x" : "-"); } int main (int argc, char* argv[]) { char fis1[500]; char a,b; //int x,z; if(argc>2) { perror("prea multe arg citite"); exit(1); } else if(argc == 1) { printf("dati fisier:"); scanf("%s",fis1); printf("Pentru a oferi perm proprietar apasati 1;\n"); printf("Pentru a oferi perm grup apasati 2;\n"); printf("Pentru a oferi perm altii apasati 3;\n"); scanf("%c",&a); scanf("%c",&a); printf("Dati numarul corespunzator permisiunii(1-x,2-w,4-r)\n"); scanf("%c",&b); scanf("%c",&b); //printf("%c",a); //printf("%c",b); } else if(argc == 2) { strcpy(fis1, argv[1]); printf("Pentru a oferi perm proprietar apasati 1;\n"); printf("Pentru a oferi perm grup apasati 2;\n"); printf("Pentru a oferi perm altii apasati 3;\n"); scanf("%c",&a); scanf("%c",&a); printf("Dati numarul corespunzator permisiunii(1-x,2-w,4-r)\n"); scanf("%c",&b); scanf("%c",&b); } stat(fis1,&fs); permisiunile_sunt(fs); printf("\n"); ///chmod imi schimba in true r,w sau x doar pe una si pe restul le face 0 //printf("Pentru a oferi perm tuturor apasati 3;"); if(a=='1'){ //printf("am intrat"); if(b=='4'){ if(chmod(fis1,S_IRUSR)==-1){printf("Nu s-a putut efectua modificarea");exit(0);}} else if(b=='2'){ if(chmod(fis1,S_IWUSR)==-1){printf("Nu s-a putut efectua modificarea");exit(0);}} else if(b=='1') if(chmod(fis1,S_IXUSR)==-1){printf("Nu s-a putut efectua modificarea");exit(0);} //acces(fis1,b*100+x); } if(a=='2'){ if(b=='4'){ if(chmod(fis1,S_IRGRP)==-1){printf("Nu s-a putut efectua modificarea");exit(0);} } else if(b=='2'){ if(chmod(fis1,S_IWGRP)==-1){printf("Nu s-a putut efectua modificarea");exit(0);}} else if(b=='1'){ if(chmod(fis1,S_IXGRP)==-1){printf("Nu s-a putut efectua modificarea");exit(0);}} } if(a=='3'){ if(b=='4'){ if(chmod(fis1,S_IROTH)==-1){printf("Nu s-a putut efectua modificarea");exit(0);} } else if(b=='2'){ if(chmod(fis1,S_IWOTH)==-1){printf("Nu s-a putut efectua modificarea");exit(0);}} else if(b=='1'){ if(chmod(fis1,S_IXOTH)==-1){printf("Nu s-a putut efectua modificarea");exit(0);}} } close(fis1); stat(fis1,&fs); permisiunile_sunt(fs); printf("\n"); return 0; }
C
#include "listg.h" int main(int argc, char **argv) { List *list = (List *)malloc(sizeof(List)); printf("%d\n",empty(list)); /* putList(list ,1,5); putList(list ,1,6); putList(list ,2,7); putList(list ,3,8); putList(list ,1,9); putList(list ,2,10);*/ for(int i =1; i<11;i++){ putList(list,i,i); } dispList(list); printf("%d,%d\n",list->tail->data,list->head->data); /* printf("the 2th data:%d\n",getData(list , 2)); deleNode(list, 1); deleNode(list,4); dispList(list); printf("%d\n",empty(list));*/ return 0; }
C
/*********************************** Trabalho : T3F4 Objectivo : Introducao a programacao em C Funcionamento : Programa para leitura de ADC e transmissão de dados via USART0 Linguagem : C Ficheiro ASM : getadc.asm Ano : 2015/2016 Unidade Cur. : Sistemas Digitais 2 Semestre : 3 Autor : Luís Silva E-mail : 1101420@isep.ipp.pt ************************************/ #include <avr/io.h> #include <avr/interrupt.h> #include <stdio.h> char transmit_buffer[10]; uint16_t a; volatile uint8_t t; uint8_t LeituraH, LeituraL; void init(void); int getadc(void); void send_message(char *buffer); int main() { init(); while(1) { if (t==1) { sprintf(transmit_buffer,"%d\r\n",getadc()); send_message(transmit_buffer); t=0; } } } void send_message(char * buffer) { uint8_t i=0; while(buffer[i]!='\0') { while((UCSR0A & 1<<UDRE0)==0); UDR0=buffer[i]; i++; } } void init(void) { OCR0 = 156; TCCR0 = (1<<WGM01) | (1<<CS02) | (1<<CS01) | (1<<CS00); // 0b00001111; // TIMSK = (1<<OCIE0); //0b00000010; // UBRR0H=0; UBRR0L=51; UCSR0A =0; UCSR0B = (1<<TXEN0); UCSR0C = (1<<UCSZ01) | (1<<UCSZ00); ADMUX = (1<<REFS0); // 0b00000010; // ADCSRA = (1<<ADEN) | (1<<ADPS2) | (1<<ADPS1) | (1<<ADPS0); // 0b10000111; // sei(); } ISR(TIMER0_COMP_vect) { t=1; }
C
#include<stdio.h> #include<stdlib.h> #include "string.h" typedef struct user{ int m_account_number; char m_phone_number[12]; char m_date[10]; char m_address[100]; char m_type_account[50]; char m_name[100]; int m_age; char m_country[50]; int m_id[9]; }user_t; typedef struct node{ int m_account_num; float m_money; char m_date_creation[10]; user_t *person; struct node *next; }node_t; node_t* search_in_list(node_t** head, int account_number); int menu() { int user_selection; printf("CUSTOMER ACCOUNT BANKING MANAGEMENT SYSTEM\n"); printf("*************** WELCOME TO THE MAIN MENU *************************\n"); printf("\n"); printf("1.Create new account\n2.Update information of existing account\n 3.For transactions\n4.Check the details of existing account\n5.Removing existing account\n6.View customer's list\n7.Exit\n\n\n Enter your choice:"); scanf("%d",&user_selection); return user_selection; } void CreateNewAcount( node_t** head) { user_t *person = NULL; person = malloc(sizeof(user_t)); if (person == NULL) return; float money_to_seposit; char* date_creation; printf("Enter today's date(mm/dd/yyyy):"); scanf("%s",&date_creation); printf("\nEnter the account number:"); scanf("%d",&(person->m_account_number)); printf("\nEnter the name:"); scanf("%s",person->m_name); printf("\nEnter the date of birth(mm/dd/yyyy):"); scanf("%s",person->m_date); printf("\nEnter the age:"); scanf("%d",&person->m_age); printf("\nEnter the address:"); scanf("%s",person->m_address); printf("\nEnter the ID number:"); scanf("%d",&person->m_id); printf("Enter amount of money you want to deposit:"); scanf("%f",&money_to_seposit); printf("\nEnter the phone number: "); scanf("%s",person->m_phone_number); push(head,person,&date_creation,money_to_seposit); } void UpdateAcountInfo(node_t** head) { int account_num,user_selection; printf("Enter the account no. of the customer whose info you want to change:\n"); scanf("%d",&account_num); node_t* account_to_edit = search_in_list(head,account_num); if (account_to_edit == NULL) { printf("There is no account with this number - back to menu\n"); return; } printf("\nWhich information do you want to change?\n1.Address\n2.Phone\n\nEnter your choice(1 for address and 2 for phone):"); scanf("%d",&user_selection); switch (user_selection) { case 1: { printf("Enter the new address:"); scanf("%s",account_to_edit->person->m_address); printf("Changes saved!"); break; } case 2: { printf("Enter the new phone number:"); scanf("%s",&account_to_edit->person->m_phone_number); printf("Changes saved!"); break; } default: { printf("there is no such option in menu, try again..:)"); break; } } } node_t* GetUserInput(node_t** head) { int account_num; printf("Enter the account no. of the customer:"); scanf("%d",&account_num); node_t* account_to_edit = search_in_list(head,account_num); if (account_to_edit == NULL) printf("There is no account with this number\n"); return account_to_edit; } void WithdrawORDepostingMoney(node_t** head) { int amount; int user_selection; node_t* account = GetUserInput(head); if (account == NULL) return; printf("Do you want to\n1.Deposit\n2.Withdraw?\n\nEnter your choice(1 for deposit and 2 for withdraw):"); scanf("%d",&user_selection); switch (user_selection) { case 1:{ printf("Enter the amount you want to deposit:$ "); scanf("%f",&amount); account->m_money += amount; printf("your money has been deposited into your bank acount"); break; } case 2:{ printf("Enter the amount you want to withdraw:$ "); scanf("%f",&amount); account->m_money -= amount; if(account->m_money < 0) printf("your account is in debit balance"); else printf("Money Withdrawal was successful"); break; } default: printf("there is no such option in menu, try again..:)"); break; } } void DeleteAcount(node_t** head) { int account_num; printf("Enter the account no. of the customer:"); scanf("%d",&account_num); Delete_node(head,account_num); } void ShowAcountTypeInfo(node_t** head) { node_t* user_account = GetUserInput(head); if (user_account == NULL) { return; } printf("Account Number: %d\n",user_account->m_account_num); printf("Name: %s\n",user_account->person->m_name); printf("Address: %s\n",user_account->person->m_address); printf("Phone Number: %s\n",user_account->person->m_phone_number); } /*********************************************************************** *Function Name:push *Function input:ptr to head of linked list, ptr to user struct *Function output:none *Function Action:the function push a new account to list.To iterate over * the linked list, we use a pointer "current" and set it to start from * the head and then in each step, we advance the pointer to the next * item in the list, until we reach the last item. ***********************************************************************/ void push(node_t** head, user_t* m_user, char* date, float money) { //user_t *usr=m_user; node_t *new_node= (node_t*)malloc(sizeof(node_t)); new_node->m_account_num=m_user->m_account_number; new_node->person=m_user; new_node->m_money=money; new_node->next=NULL; strcpy(new_node->m_date_creation,date); if(*head == NULL) { *head=new_node; return; } node_t* current = *head; while (current->next != NULL) { current = current->next; } current->next=new_node; return; } void PopNode(node_t** head) { node_t* new_head=NULL; if (*head == NULL) { printf("The list is empty\n"); return; } new_head = (*head)->next; free(*head); *head=new_head; } void Delete_node(node_t** head, int account_num) { node_t* current = *head; node_t* temp_node=NULL; if ((*head)->m_account_num == account_num) { PopNode(head); return; } while (current->next->m_account_num != account_num && current->next !=NULL) { current=current->next; } if(current->next == NULL) { printf("there is no account number\n"); return; } temp_node = current->next; current->next = temp_node->next; free(temp_node); } node_t* search_in_list(node_t** head, int account_number) { node_t* current = *head; while (current != NULL) { if(current->m_account_num == account_number) { return current; } current=current->next; } return current; } void Free_List(node_t** head) { node_t* temp_node=NULL; node_t* current = *head; while (current !=NULL) { temp_node = current; current=current->next; free(temp_node); } *head=NULL; } int main() { int user_selection=menu(); node_t *head=NULL; while (user_selection != 7) { switch (user_selection) { case 1: CreateNewAcount(&head); break; case 2: UpdateAcountInfo(&head); break; case 3: WithdrawORDepostingMoney(&head); break; case 4: ShowAcountTypeInfo(&head); break; case 5: DeleteAcount(&head); break; default: break; } user_selection = menu(); } Free_List(&head); return 0; }
C
#ifndef __STACK_LIST_H__ #define __STACK_LIST_H__ #include <stdlib.h> // a LIFO stack using linked list typedef struct StackNode { void* key; struct StackNode* next; } StackNode; typedef StackNode* StackList; // initialize stack void init_stack_list (StackList*); // pop the stack and return the last introduced element void* pop_stack_list (StackList*); // push an element in front of the stack void push_stack_list (StackList*, void*, size_t); // verify whether the stack is empty or not int empty_stack_list (StackList); // return the last element introduced in the stack without removing it void* peek_stack_list (StackList); // return a stack node StackNode* make_stack_node (void*, size_t); #endif
C
/* * Copyright (C) 2020 */ #include <stdio.h> #include <time.h> #include <stdlib.h> #include "util.h" int partition(int* arr,int beg, int end) { int pivot_element = arr[end]; int i = beg - 1; for(int j = beg; j != end; ++j) { if(arr[j] <= pivot_element) swap(&arr[++i], &arr[j]); } swap(&arr[++i], &arr[end]); return i; } void quick_sort(int* arr, int beg, int end) { if(beg < end) { int index = partition(arr, beg, end); quick_sort(arr, beg, index - 1); quick_sort(arr, index + 1, end); } } void tail_recursive_quick_sort(int arr[], int beg, int end) { while(beg < end) { int index = partition(arr, beg, end); tail_recursive_quick_sort(arr, beg, index - 1); beg = index + 1; } } //////---------------------------- int get_random(int beg, int end) { srand((unsigned)time(NULL)); return beg + (rand() % (end - beg + 1)); } int random_partition(int arr[], int beg, int end) { int random_index = get_random(beg, end); swap(&arr[end], &arr[random_index]); return partition(arr, beg, end); } void random_quick_sort(int arr[], int beg, int end) { if(beg < end) { int index = random_partition(arr, beg, end); random_quick_sort(arr, beg, index - 1); random_quick_sort(arr, index + 1, end); } } int main(int argc, char* argv[]) { int array[] = {13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11}; int len = ARRAY_LENGTH(array); print(array, len); quick_sort(array, 0, len - 1); print(array, len); int array1[] = {13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11}; print(array1, len); tail_recursive_quick_sort(array1, 0, len -1); print(array1, len); int array2[] = {13, 19, 9, 5, 12, 8, 7, 4, 21, 2, 6, 11}; print(array2, len); random_quick_sort(array2, 0, len - 1); print(array2, len); }
C
#include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> #include <unistd.h> unsigned make_seed() { time_t tt; struct tm ttt; ttt.tm_year = 2019 - 1900; // from nini2 in IDA Pro ttt.tm_mon = 8; // sep ttt.tm_wday = 3; // wed ttt.tm_mday = 11; // only correct solution ttt.tm_hour = 5; ttt.tm_min = 25; ttt.tm_sec = 14; tt = mktime(&ttt); return (unsigned)tt; } int rotate_R(unsigned int num, unsigned int rot_cnt){ unsigned int res = num >> rot_cnt; unsigned int shifted_away_bits = num << (32 - rot_cnt); res |= shifted_away_bits; return res; } int rotate_L(unsigned int num, unsigned int rot_cnt) { unsigned int res = num << rot_cnt; unsigned int shifted_away_bits = num >> (32 - rot_cnt); res |= shifted_away_bits; return res; } unsigned int reversed_1(unsigned int num){ return num ^ 0xFACEB00C; } unsigned int reversed_2(unsigned int num){ return num - 74628; } unsigned int reversed_3(unsigned int num){ return (rotate_R(num & 0xAAAAAAAA, 2) | rotate_L(num & 0x55555555, 4)); } unsigned int reversed_4(unsigned int num){ return reversed_1(reversed_2(reversed_3(num))); } int main(){ unsigned int seed = make_seed(); srand(seed); int fout = open("output.txt", O_RDONLY); int fin = open("input_new.txt", O_RDWR | O_CREAT, 0666); char buf[4] = {0}; // read 4 bytes for integer length at once int cnt = 0; while(read(fout, buf, 4) == 4){ int num = *(unsigned int *)(buf); // cast to unsigned int pointer and extract value int todo = random() % 4; int res = 0; if(todo == 0){ res = reversed_1(num); // printf("res %d \n", res); } else if(todo == 1){ res = reversed_2(num); // printf("res %d \n", res); } else if(todo == 2){ res = reversed_3(num); // printf("res %d \n", res); } else if(todo == 3){ res = reversed_4(num); // printf("res %d \n", res); } else{ exit(-1); } // getchar(); write(fin, (char *) &res, 4); } close(fin); close(fout); return 0; }
C
#include<stdio.h> void funcToCheckPtr(int *ptr){ printf("The pointer in funtion is %d\n",*ptr); } int main(){ int i=10; int *ptr = &i; funcToCheckPtr(ptr); printf("The pointer in main is %p\n",ptr); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "interface.h" #define MAX_BUFFER 1024 extern struct { char *token; int (*f)(State *, char **); } function_table[]; int main() { int tokens, i, j; char command[MAX_BUFFER]; char *args[MAX_BUFFER]; State s; state_init(&s); while (1) { printf("> "); if(fgets(command, MAX_BUFFER, stdin) != NULL) { i = 0; args[i++] = strtok(command, " "); while ((args[i++] = strtok(NULL, " "))); tokens = i - 1; for (i = 0; args[tokens - 1][i] != '\0'; i++); args[tokens - 1][i - 1] = '\0'; for (i = 0; i < tokens; i++) { for (j = 0; function_table[j].token != NULL; j++) { if (strcmp(args[i], function_table[j].token) == 0) { i += (function_table[j].f)(&s, args + i); break; } } if (function_table[j].token == NULL) { printf("%s: invalid command\n", args[i]); printf("type \"help\" to get the list of available commands\n"); break; } } } } return EXIT_SUCCESS; }
C
#pragma once #include <stddef.h> #include <stdlib.h> #include <stdio.h> #include <string.h> static inline void* memory_allocate(size_t number, size_t size) { void* m = calloc(number, size); if (m) return m; fprintf(stderr, "out of memory\n"); exit (EXIT_FAILURE); } static inline void* memory_resize(void* memory, size_t size) { void* m = realloc(memory, size); if (m) return m; fprintf(stderr, "out of memory\n"); exit (EXIT_FAILURE); } static inline void memory_copy(const void* src, void* dst, size_t size) { memcpy(dst, src, size); }
C
#include<stdio.h> int main () { int a,b; scanf("%d",&a); scanf("%d",&b); if(a==b*b) printf("%d*%d=%d",b,b,a); else if(b==a*a) printf("%d*%d=%d",a,a,b); else printf("none"); return 0; }
C
/************************************************************ * Test convolution * * author: blkaron * e-mail: tekla.makkan@yahoo.co.uk ************************************************************/ #include "conv.h" int main() { int i; int *s; int size_x; int size_y; int x[] = {1, 2, 3, 4, 10, 22, 8, 5, 9}; size_x = sizeof(x)/sizeof(x[0]); int y[] = {0, 1, 2,}; size_y = sizeof(y)/sizeof(y[0]); s = conv(x,y,size_x, size_y); for(i=0; i < size_x + size_y; i++) { printf("%d\t", s[i]); } printf("\n"); print_conv(x, y, s, size_x, size_y, size_x+size_y); return 1; }
C
/*Program to process data using a struct From notes Brian Willis 6/3/2013 */ #include <stdio.h> #include <stdlib.h> struct record { char last_name[20]; char first_name[15]; int age; float salary; }; void main() { typedef struct record person; person employee; char choice='y'; FILE *people; people=fopen("employee.dat", "ab"); if (people==NULL) { printf ("ERROR: Failed to open file!"); } else { while (choice=='y'||choice=='Y') { printf ("\nEnter surname: "); scanf ("%s", employee.last_name); flushall(); printf ("\nEnter first name: "); scanf ("%s", employee.first_name); flushall(); printf ("\nEnter age: "); scanf ("%d", &employee.age); flushall(); printf ("\nEnter salary: "); scanf ("%f", &employee.salary); fwrite (&employee, sizeof(employee), 1, people); printf ("\nAdd another record? (y/n): "); scanf ("%1s", &choice); }//end while }//end if fclose(people); }//end main
C
#include<stdio.h> #include<stdlib.h> main(){ float salario,salario_alm,altura,peso,imc; int op; do{ printf("\n********************MULTIFUNCIONAL********************"); printf("\n*********(1) calculo de IMC ***************"); printf("\n*********(2) Almento de 10% no salario ***************"); printf("\n*********(3) teste 1 ***************"); printf("\n*********(4) teste 2 ***************"); printf("\n*********(0) Sair ***************"); printf("\n******************************************************"); printf("\n\nDigite a sua opcao: "); scanf("%f",&op); if (op==1) { printf("\n\nDigite sua altura: "); scanf("%f",&altura); printf("\nDigite seu peso: "); scanf("%f",&peso); imc=(altura*altura)/peso; printf("\n\nSeu IMC e: %.2f",imc); }else if (op==2){ printf("\nDigite seu salario atual: "); scanf("%f",&salario); salario_alm=(salario/100)*10; printf("Seu salario com 10% de aumento e: %.2f",salario_alm); } } while (op!=0); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> // //int main() //{ // int n = 9; // // // //0 00000000 00000000000000000001001 // //(-1)^0 * 0.00000000000000000001001 * 2^-126 // // // float *pFloat = (float *)&n; // printf("nֵΪ%d\n", n);//9 // printf("*pFloatֵΪ%f\n", *pFloat);//0.000000 // // *pFloat = 9.0; // //1001.0 // //(-1)^0 * 1.001*2^3 // //S=0 // //M=1.001 // //E=3 +127 // //01000001000100000000000000000000 // // // printf("numֵΪ%d\n", n); // printf("*pFloatֵΪ%f\n", *pFloat);//9.0 // return 0; //} // // //9.5 //1001.1 //1.0011*2^3 //(-1)^0 * 1.0011 * 2^3 //S=0 //M=1.0011 //E=3 // //0.5 //0.1 - //1.0 * 2^-1 //(-1)^0 *1.0*2^-1 //S=0 //M=1.0 //E=-1 // //int main() //{ // int a = 10; // int* p = &a; // // return 0; //} //int main() //{ // char ch = 'a'; // char* pc = &ch; // // char* p = "abcdef";//ġabcdefһַ // //printf("%c\n", *p); // printf("%s\n", p); // char arr[] = "abcdef"; // printf("%s\n", arr); // return 0; //} #include <stdio.h> // //int main() //{ // char str1[] = "hello bit."; // char str2[] = "hello bit."; // char *str3 = "hello bit."; // char *str4 = "hello bit."; // // if (str1 == str2) // printf("str1 and str2 are same\n"); // else // printf("str1 and str2 are not same\n"); // // if (str3 == str4) // printf("str3 and str4 are same\n"); // else // printf("str3 and str4 are not same\n"); // // return 0; //} //int main() //{ // const char*p = "abcdef"; // // return 0; //} // //ָ - //ָ飬ָ // //int main() //{ // int* arr[10]; // char** ch[20]; // // return 0; //} // //ָ - ָ //ú - //ָ - ָεָ //int a = 10; //int* p = &a; //ַָ - ַָָ //ָ - ָָ // //int main() //{ // int a = 10; // int *p = &a; // char ch = 'w'; // char* pc = &ch; // // int arr[10] = {0}; // int (*pa)[10] = &arr;//ĵַ // //paһָָ - ָ // // char ch[5]; // char(*p3)[5] = &ch; // // // //&arr 飬ȡĵַ // //&arr arr Ա // return 0; //} //int main() //{ // int arr[10] = { 1, 2, 3, 4, 5 }; // int*p1 = arr;//Ԫصĵַ // int(*p2)[10] = &arr;//ĵַ // // printf("%p\n", p1); // printf("%p\n", p1+1); // // printf("%p\n", p2); // printf("%p\n", p2+1); // // // //& // //sizeof() // //2֮-Ԫصĵַ // // return 0; //} //int main() //{ // int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // int* p = arr; // int i = 0; // int sz = sizeof(arr) / sizeof(arr[0]); // for (i = 0; i < sz; i++) // { // printf("%d ", *(p + i)); // } // return 0; //} //int main() //{ // int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // int (*p)[10] = &arr; // // *p <==> arr; // int i = 0; // /*for (i = 0; i < 10; i++) // { // printf("%d ", (*p)[i]); // }*/ // for (i = 0; i < 10; i++) // { // printf("%d ", *((*p)+i)); // } // // return 0; //} //int main() //{ // int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; // int(*p)[10] = &arr; // // *p <==> arr; // int i = 0; // /*for (i = 0; i < 10; i++) // { // printf("%d ", (*p)[i]); // }*/ // for (i = 0; i < 10; i++) // { // printf("%d ", *((*p) + i)); // // //printf("%d ", p[0][i]); // //printf("%d ", *(*(p) + i)); // } // return 0; //} // //void print1(int arr[3][5], int r, int c) //{ // int i = 0; // for (i = 0; i < r; i++) // { // int j = 0; // for (j = 0; j < c; j++) // { // printf("%d ", arr[i][j]); // } // printf("\n"); // } //} //// //// //void print2(int(*p)[5], int r, int c) //{ // int i = 0; // for (i = 0; i < r; i++) // { // //*(p + i) - iУi0ʼ // int j = 0; // for (j = 0; j < c; j++) // { // printf("%d ", *(*(p + i) + j)); // } // printf("\n"); // } //} ////void print3(int*p, int sz) ////{ ////} //int main() //{ // int arr[3][5] = { { 1, 2, 3, 4, 5 }, { 2, 3, 4, 5, 6 }, { 3, 4, 5, 6, 7 } }; // //ά鴫ΣҲԪصĵַάԪǵһ // //ȥľǵһеĵַ // /*int a[5]; // print3(a, 5);*/ // // print1(arr, 3, 5); // print2(arr, 3, 5); // // return 0; //} // // //void test(int *p) //{ // //} // //int main() //{ // int a = 10; // int *pa = &a; // int arr[10] = {0}; // test(&a); // test(pa); // test(arr); // // return 0; //} //void test(int **p) //{ // //} //int main() //{ // int a = 10; // int*pa = &a; // int ** ppa = &pa; // int* arr[10]; // // test(&pa); // test(ppa); // test(arr); // // return 0; //}
C
#include<stdio.h> struct comp{ float real; float imag; }; struct comp comp1,comp2; struct comp sum_complex(struct comp complex1,struct comp complex2){ struct comp temp; temp.real = complex1.real + complex2.real; temp.imag = complex1.imag + complex2.imag; return temp; } int main(){ struct comp result; printf("Enter Complex Number 1: "); scanf("%f%f",&comp1.real, &comp1.imag); printf("Enter Complex Number 2: "); scanf("%f%f",&comp2.real,&comp2.imag); result = sum_complex(comp1,comp2); printf("The sum is %.2f +%.2f'i'\n\n", result.real,result.imag); return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct in_addr {void* s_addr; } ; struct hostent {scalar_t__ h_addrtype; int /*<<< orphan*/ h_length; int /*<<< orphan*/ h_addr; } ; /* Variables and functions */ scalar_t__ AF_INET ; void* INADDR_ANY ; void* INADDR_NONE ; struct hostent* gethostbyname (char const*) ; scalar_t__ inet_aton (char const*,struct in_addr*) ; int /*<<< orphan*/ isalnum (char const) ; int /*<<< orphan*/ memcpy (struct in_addr*,int /*<<< orphan*/ ,int /*<<< orphan*/ ) ; int /*<<< orphan*/ strcasecmp (char const*,char*) ; int /*<<< orphan*/ * strchr (char*,char const) ; struct in_addr GetIpAddr(const char *cp) { struct in_addr ipaddr; if (!strcasecmp(cp, "default")) ipaddr.s_addr = INADDR_ANY; else if (inet_aton(cp, &ipaddr) == 0) { const char *ptr; /* Any illegal characters ? */ for (ptr = cp; *ptr != '\0'; ptr++) if (!isalnum(*ptr) && strchr("-.", *ptr) == NULL) break; if (*ptr == '\0') { struct hostent *hp; hp = gethostbyname(cp); if (hp && hp->h_addrtype == AF_INET) memcpy(&ipaddr, hp->h_addr, hp->h_length); else ipaddr.s_addr = INADDR_NONE; } else ipaddr.s_addr = INADDR_NONE; } return ipaddr; }
C
#include <stdlib.h> #include <stdio.h> int funcao(int a, int b) { return a+b; } int main(int argc, char *argv[]) { int (*p)(int, int); p = &funcao; printf("%d\n", p(5,6)); return 0; }
C
#include <iostream> #include <fstream> #include "TFile.h" #include "TH1D.h" using namespace std; int main(int argc, char* argv[]){ string rmin = argv[1]; string rmax = argv[2]; cout << "Runs: " << rmin << " - " << rmax << endl; // read file with dst paths string fname = "livetime/dst_list" + rmin + "-" + rmax + ".list"; cout << "Reading from: " << fname << endl; ifstream f(fname.c_str()); // read livetime from each dst string dst; TH1D* hlive = new TH1D("livetime_tot", "livetime_tot", 30198, 5002.5, 35200.5); cout << "Adding histos..." << endl; while (f >> dst){ // get livetime histogram cout << dst << endl; TFile* fdst = TFile::Open(dst.c_str()); TH1D* h = (TH1D*) fdst->Get("live_time"); // add them all together hlive->Add(h); fdst->Close(); } f.close(); // loop over runs and save info cout << "Getting livetime..." << endl; int nbins = hlive->GetXaxis()->GetNbins(); fname = "livetime/livetime_run" + rmin + "-" + rmax + ".csv"; ofstream out(fname.c_str()); // header out << "RunNumber Livetime" << endl; for(int bin=1; bin < nbins + 1; bin++){ float lt = hlive->GetBinContent(bin); // save only runs with non-zero livetime if(lt) out << hlive->GetBinCenter(bin) << " " << lt << endl; } cout << "--> " << fname << endl << endl; }
C
// strspn_ex.c : strspn() example // ------------------------------------------------------------- #include <string.h> // int strspn( const char *s1, const char *s2 ); #include <stdio.h> int main() { char wordin[256]; double val; puts( "Enter a floating-point number, please:" ); scanf( "%s", wordin ); int index = strspn( wordin, "+-0123456789eE." ); if ( index < strlen( wordin ) ) printf( "Sorry, but the character %c is not permitted.\n", wordin[index] ); else { sscanf( wordin, "%lg", &val ); printf( "You entered the value %g\n", val ); } return 0; }
C
#include <stdarg.h> #include <stdio.h> #include "variadic_functions.h" /** * print_strings - prints strings * @separator: string pritns between numbers * @n: integers passed to the funtion **/ void print_strings(const char *separator, const unsigned int n, ...) { va_list arguments; unsigned int i = 0; char *palabra; va_start(arguments, n); for (i = 0; i < n; i++) { palabra = va_arg(arguments, char*); if (palabra == NULL) { printf("%s", "(nil)"); } else printf("%s", palabra); if (separator != NULL) { if (i != (n - 1)) printf("%s", separator); } } va_end(arguments); printf("\n"); }
C
#include <raykernel.h> #define MAX_TRIES 10 #define FAST_START 550 UINT32 MathSquareRoot(UINT32 value) { UINT8 tries; UINT32 sqr_est = FAST_START; for (tries = 0; tries < MAX_TRIES; tries++) { sqr_est = (sqr_est + value/sqr_est)>>1; } return sqr_est; }
C
/** lab28.h * =========================================================== * Name: Jim Wang, 03 November 2019 (I know it's late) * Section: M4A * Project: Programming Assessment 3 Practice * Documentation: None * =========================================================== */ #ifndef MYEXE_LAB28_H #define MYEXE_LAB28_H #define MAX_LENGTH 20 #define FILENAME "Employee_Recs.txt" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> typedef struct EmployeeBD_struct { char firstName[MAX_LENGTH]; char lastName[MAX_LENGTH]; char birthMonth[MAX_LENGTH]; int birthDate; } EmployeeBD; int numVowels(char *in); char *sortString(char *in); int readFile(char fileName[], EmployeeBD *empStruct, int numLines); int IDEmpBDMonth(EmployeeBD *empStruct, int numLines, int month); #endif //MYEXE_LAB28_H
C
/*----------------------------------------------------------------------------* * Copyright (c) 2006 Southeastern Universities Research Association, * * Thomas Jefferson National Accelerator Facility * * * * This software was developed under a United States Government license * * described in the NOTICE file included as part of this distribution. * * * * C. Timmer, 21-Mar-2004, Jefferson Lab * * * * Author: Carl Timmer * * timmer@jlab.org Jefferson Lab, MS-12B3 * * Phone: (757) 269-5130 12000 Jefferson Ave. * * Fax: (757) 269-5800 Newport News, VA 23606 * * * *----------------------------------------------------------------------------* * * This application is just to illustrate how to call the funcstions of the * dummy domain. The dummy domain itself is just an outline or example of how * to go about writing a domain in C that can be dynamically loaded. * *----------------------------------------------------------------------------*/ #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <sys/types.h> #include <unistd.h> #include <time.h> #include "cMsg.h" /******************************************************************/ static void callback(void *msg, void *arg) {} /* shutdown handler function */ static void shutdownHandler(void *arg) { printf("RAN SHUTDOWN HANDLER!!\n"); return; } /******************************************************************/ int main(int argc,char **argv) { char *myName = "Dumb Dumb"; char *myDescription = "Dummy consumer"; char *subject = "SUBJECT"; char *type = "TYPE"; char *UDL = "cMsG:DUmmY://localhost/cMsg/myNameSpace"; int err, debug = 1, response; cMsgSubscribeConfig *config; void *domainId, *domainId2, *msg; void *unSubHandle; printf("Running the Dummy consumer, \"%s\"\n", myName); /* connect to cMsg server */ err = cMsgConnect(UDL, myName, myDescription, &domainId); if (err != CMSG_OK) { if (debug) { printf("cMsgConnect: %s\n",cMsgPerror(err)); } exit(1); } printf(" connected to, %s\n", UDL); /* create message */ msg = cMsgCreateMessage(); cMsgSetSubject(msg, subject); cMsgSetType(msg, type); /* start receiving messages */ cMsgReceiveStart(domainId); cMsgReceiveStop(domainId); cMsgFlush(domainId, 0); /* set the subscribe configuration */ config = cMsgSubscribeConfigCreate(); cMsgSetDebugLevel(CMSG_DEBUG_INFO); /* subscribe */ cMsgSubscribe(domainId, subject, type, callback, NULL, config, &unSubHandle); /* unsubscribe */ cMsgUnSubscribe(domainId, unSubHandle); /* send */ cMsgSend(domainId, msg); /* syncSend */ cMsgSyncSend(domainId, msg, NULL, &response); /* subAndGet */ cMsgSubscribeAndGet(domainId, subject, type, NULL, &msg); /* sendAndGet */ cMsgSendAndGet(domainId, msg, NULL, &msg); /* set shutdown handler */ cMsgSetShutdownHandler(domainId, shutdownHandler, NULL); /* shutdown a client call "shutdowner" */ cMsgShutdownClients(domainId, "shutdowner", CMSG_SHUTDOWN_INCLUDE_ME); /* shutdown a server call "shutdowner" */ cMsgShutdownServers(domainId, "shutdowner", CMSG_SHUTDOWN_INCLUDE_ME); /* disconnect */ cMsgDisconnect(&domainId); return(0); }
C
/************************************************************************* FindCP.c - Change Point Detection Method ------------------- last modified : Mon Dec 19 2016 (NS) email : hawyang@princeton.edu, nsong@princeton.edu *************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <float.h> #include <stdio.h> #include <gsl/gsl_math.h> #include <gsl/gsl_sf_gamma.h> #include <gsl/gsl_sf_erf.h> #include "changepoint.h" #define MAX_X 10.0 #define DX 0.01 #define TOL 1.0e-8 // Functions for calculation of critical values double C_ac(); double Vostrikova(); struct changepoint* AddCPNode(); // Find a change point in traj with bounds cpl (left) and cpr (right), exclusive. // Type-I error of alpha and confidence interval of beta. Found change point added to // tree pointed to by cp. ca points to confidence region critical values. Na is length // of traj, rc indicates recursive tracing int FindCP(struct changepoint **cp, double *traj, int cpl, int cpr, double alpha, double beta, int * Ncp, double *ca, int Na, int rc ) { int n,i,k,k_max; //indices to iterate through traj int LB, RB; //left and right bounds of confidence region int cp2=0, cp1=0, cp_max; //largest change point in absolute index //Relevant variables for gaussian mean change point detection double kL, nL; // Double analogs in integers double x_old, dx, mean_dx, var_dx; // Used for calculation of log-likelihood double critical_region; // Critical value for specified alpha and N double llrt_max=0.0; // Maximum log-likelihood double *cumsum, *llrt; // Arrays to store values enum bool dummy_bool = false; // If applicable, denotes if found CP has been inserted n = cpr - cpl; LB = cpl; RB = cpr; cp_max = 0; if ( n > 1 ) { nL = (double) n; cumsum = (double *) malloc( (n+1) * sizeof(double) ); llrt = (double *) malloc( (n+1) * sizeof(double) ); // Calculate the critical region using Horvath's approximation critical_region = C_ac(alpha,n); if(cpl == 0) x_old = traj[1]; else x_old = traj[cpl]; cumsum[0] = 0; for (i=1, mean_dx=var_dx=0.0; i<n; i++) { // estimate Gaussian means at different k cumsum[i] = cumsum[i-1] + traj[cpl+i]; // estimate sample variance using gaussian difference dx = traj[cpl+i] - x_old; mean_dx += dx; var_dx += dx*dx; x_old = traj[cpl+i]; } var_dx = fabs(var_dx - mean_dx*mean_dx)/(nL-1.0); for ( k=1,k_max=0; k<n; k++ ) { kL = (double) k; // traditional Generalized Log-likelihood ratio test llrt[k] = cumsum[k] * cumsum[k] / kL + (cumsum[n-1]-cumsum[k]) * (cumsum[n-1]-cumsum[k]) / (nL-kL-1.0) - cumsum[n-1] * cumsum[n-1] / (nL-1.0); llrt[k] = 2.0*llrt[k] / var_dx; if ( llrt[k] > llrt_max ) { // find the maximum of the likelihood functions llrt_max = llrt[k]; k_max = k; } } // Compare maximum log likelihood ratio to critical region if ( llrt_max > critical_region ) { // Find the left-hand bound of critical region k = k_max; while ( (k>1) && (llrt_max - llrt[k-1] < ca[n]) ) k--; LB = k; // Find the right-hand bound of critical region k = k_max; while ( (k < n-1) && (llrt[k+1]+ca[n]-llrt_max > 0) ) k++; RB = k; cp_max = cpl + RB; // Add change point to current tree *cp = AddCPNode(k_max+cpl, LB+cpl, RB+cpl, *cp, Ncp, &dummy_bool); // No recursion for checking change points if(rc==3){ /********************* Free up used workspace *********************/ // Return index of change point found return k_max+cpl; } // Recursively find change points if((rc==1)||(rc==0)){ // Go to the left branch cp1 = FindCP(cp, traj, cpl, LB+cpl, alpha, beta, Ncp, ca, Na, 1); // Go to the right branch cp1 = FindCP(cp, traj, RB+cpl, cpr, alpha, beta, Ncp, ca, Na, 1); if (cp1 > cp_max ) cp_max = cp1; } } free(llrt); free(cumsum); } // Return maximum index of change point found return cp_max; }
C
/*------------------------------------------------------------------------ MCPY.C : ॢ ணࠬ SSP 믮 뭪 .. : 01.00 / 10.08.1997 / ------------------------------------------------------------------------*/ #include "ssp.h" /* ............................................................... SUBROUTINE MCPY PURPOSE COPY ENTIRE MATRIX USAGE mcpy(A,R,N,M,MS) DESCRIPTION OF PARAMETERS A - NAME OF INPUT MATRIX R - NAME OF OUTPUT MATRIX N - NUMBER OF ROWS IN A OR R M - NUMBER OF COLUMNS IN A OR R MS - ONE DIGIT NUMBER FOR STORAGE MODE OF MATRIX A (AND R) 0 - GENERAL 1 - SYMMETRIC 2 - DIAGONAL REMARKS NONE SUBROUTINES AND FUNCTION SUBPROGRAMS REQUIRED LOC METHOD EACH ELEMENT OF MATRIX A IS MOVED TO THE CORRESPONDING ELEMENT OF MATRIX R .................................................................. */ void mcpy(double a[], double r[], int n, int m, int ms) { int i, it; /* COMPUTE VECTOR LENGTH, IT */ loc( n-1, m-1, &it, n, m, ms ); /* COPY MATRIX */ for( i = 0; i <=it; i++ ) r[i] = a[i]; return; }
C
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // /*============================================================= ** ** Source: test5.c ** ** Purpose: Do more complex overlapping. Move a section of memory back so ** that it actually ends up overlapping itself. ** ** **============================================================*/ #include <palsuite.h> enum Memory { MEMORY_AMOUNT = 128 }; int __cdecl main(int argc, char *argv[]) { char* NewAddress; char* SectionToMove; char TheMemory[MEMORY_AMOUNT]; int i; if(PAL_Initialize(argc, argv)) { return FAIL; } NewAddress = TheMemory; SectionToMove = TheMemory+50; /* Put some data into the first 50 bytes */ memset(TheMemory, 'X', 50); /* Put some data into the rest of the memory */ memset(SectionToMove, 'Z', MEMORY_AMOUNT-50); /* Move the section in the middle of TheMemory back to the start of TheMemory -- but have it also overlap itself. (ie. the section to be move is overlapping itself) */ RtlMoveMemory(NewAddress, SectionToMove, MEMORY_AMOUNT-50); /* Check to ensure the moved data didn't get corrupted */ for(i=0; i<MEMORY_AMOUNT-50; ++i) { if(NewAddress[i] != 'Z') { Fail("ERROR: When the memory was moved to a new location, the " "data which was stored in it was somehow corrupted. " "Character %d should have been 'Z' but instead is %c.\n", i, NewAddress[i]); } } PAL_Terminate(); return PASS; }
C
#include <stdio.h> #include <string.h> #include <iostream> using namespace std; char m[4][4]; int iswin(char c) { int i,j; for(i=0; i<4; i++) { for(j=0; j<4; j++) if (!(m[i][j] == c || m[i][j] == 'T')) break; if (j >= 4) return 1; for(j=0; j<4; j++) if (!(m[j][i] == c || m[j][i] == 'T')) break; if (j >= 4) return 1; } for(i=0; i<4; i++) if (!(m[i][i] == c || m[i][i] == 'T')) break; if (i >= 4) return 1; for(i=0; i<4; i++) if (!(m[i][3-i] == c || m[i][3-i] == 'T')) break; if (i >= 4) return 1; return 0; } int main() { int i,j,k; int cc,ca; cin >> ca; for(cc=1; cc<=ca; cc++) { string s; for(i=0; i<4; i++) { cin >> s; for(j=0; j<4; j++) m[i][j] = s[j]; } if (iswin('X')) { printf("Case #%d: X won\n", cc); continue; } if (iswin('O')) { printf("Case #%d: O won\n", cc); continue; } k=0; for(i=0; i<4; i++) for(j=0; j<4; j++) if (m[i][j] == '.') k=1; if (k == 0) { printf("Case #%d: Draw\n", cc); continue; } printf("Case #%d: Game has not completed\n", cc); } }
C
#include <stdlib.h> #include <stdio.h> #define MAX 30 typedef struct Pile { int taille; char tab[MAX]; } Pile; // initialisation d'une pile void init(Pile *p) { p->taille=0; } void affichage(Pile *p) { int i; printf("Pile :"); for (i=0; i<p->taille; i++) { printf("%c", p->tab[i]); } printf("\n"); } // est_vide: retourne VRAI si la pile est vide et FAUX sinon int est_vide(Pile *p) { return p->taille==0; } // taille:renvoie le nombre d'lments dans la pile ; int taille(Pile *p) { return p->taille; } // empiler: ajoute un lment sur la pile void empiler(Pile *p, char c) { if (p->taille == MAX) return; p->tab[p->taille] = c; p->taille++; } // sommet: retourne l'lment de tte sans le dpiler char sommet(Pile *p) { char res = '_'; if (! est_vide(p)) { res = p->tab[p->taille-1]; } return res; } // dpiler: enlve un lment de la pile et le retourne char depiler(Pile *p) { char res = sommet(p); if (! est_vide(p)) { p->taille--; } return res; } int main() { Pile *p; char tmp; p = malloc(sizeof(Pile)); init(p); printf("taille : %d \n", p->taille); affichage(p); empiler(p, 'a'); affichage(p); empiler(p, 'b'); affichage(p); empiler(p, 'c'); affichage(p); tmp = depiler(p); printf("\t on depile : %c\n", tmp); affichage(p); tmp = depiler(p); printf("\t on depile : %c\n", tmp); affichage(p); tmp = depiler(p); printf("\t on depile : %c\n", tmp); affichage(p); free(p); return EXIT_SUCCESS; }
C
/* * File: dlist.h */ #include <stdio.h> #ifndef DLIST_H #define DLIST_H #ifdef __cplusplus extern "C" { #endif/*__cplusplus*/ typedef enum _DListRet { DLIST_RET_OK, DLIST_RET_OOM, DLIST_RET_STOP, DLIST_RET_INVALID_PARAMS, DLIST_RET_FAIL }DListRet; struct _DList; typedef struct _DList DList; typedef void (*DListDataDestroyFunc)(void* ctx, void* data); typedef int (*DListDataCompareFunc)(void* ctx, void* data); typedef DListRet (*DListDataVisitFunc)(void* ctx, void* data); DList* dlist_create(DListDataDestroyFunc data_destroy, void* data_destroy_ctx); DListRet dlist_insert(DList* thiz, size_t index, void* data); DListRet dlist_prepend(DList* thiz, void* data); DListRet dlist_append(DList* thiz, void* data); DListRet dlist_delete(DList* thiz, size_t index); DListRet dlist_get_by_index(DList* thiz, size_t index, void** data); DListRet dlist_set_by_index(DList* thiz, size_t index, void* data); size_t dlist_length(DList* thiz); int dlist_find(DList* thiz, DListDataCompareFunc cmp, void* ctx); DListRet dlist_foreach(DList* thiz, DListDataVisitFunc visit, void* ctx); void dlist_destroy(DList* thiz); #define return_if_fail(p) if(!(p)) \ {printf("%s:%d Warning: "#p" failed.\n", \ __func__, __LINE__); return;} #define return_val_if_fail(p, ret) if(!(p)) \ {printf("%s:%d Warning: "#p" failed.\n",\ __func__, __LINE__); return (ret);} #ifdef __cplusplus } #endif/*__cplusplus*/ #endif/*DLIST*/
C
/** ****************************************************************************** @file @author PavelB @version V1.0 @date 03-April-2017 @brief ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" #include "cmsis_os.h" #include "lcd_log.h" #include "cpu_utils.h" /* Private define ------------------------------------------------------------*/ /* Private typedef -----------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ RTC_HandleTypeDef hrtc; RTC_TimeTypeDef time; RTC_DateTypeDef date; float temperature; ADC_HandleTypeDef hadc1; uint32_t adcTempSensorValue = 0; /* Private function prototypes -----------------------------------------------*/ void MX_RTC_Init(void); void MX_ADC1_Init(void); /** @brief Timer callback that update RTC vars @param argument not used @retval None */ static void osRTCTimerCallback(void const *argument) { (void) argument; /*************************************************************************** every second update RTC vars ***************************************************************************/ HAL_RTC_GetTime(&hrtc, &time, RTC_FORMAT_BIN); HAL_RTC_GetDate(&hrtc, &date, RTC_FORMAT_BIN); /*************************************************************************** show on LCD ***************************************************************************/ char sFooter[50] = {0}; sprintf(sFooter, "Press BTN to switch | Load %02u% | T = %+.1f [C]\n", osGetCPUUsage(), temperature); LCD_LOG_SetFooter((uint8_t *)sFooter); } /** @brief Timer callback that update RTC vars @param argument not used @retval None */ static void osTemperatureTimerCallback(void const *argument) { (void) argument; /*************************************************************************** every second check chip temperature ***************************************************************************/ float Vsense = 0, V25 = 0.76, Avg_Slope = 0.0025; HAL_ADC_Start(&hadc1); HAL_ADC_PollForConversion(&hadc1, 10); /* Check if the continous conversion of regular channel is finished */ if (HAL_IS_BIT_SET(HAL_ADC_GetState(&hadc1), HAL_ADC_STATE_REG_EOC)) { /*##-5- Get the converted value of regular channel ########################*/ adcTempSensorValue = HAL_ADC_GetValue(&hadc1); } // formula from DS on stm32f42xx Vsense = 3.33 * ((float)adcTempSensorValue / 4096); temperature = ((Vsense - V25) / Avg_Slope) + 25; } /*----------------------------------------------------------------------------*/ void vStartTimers() { LCD_UsrLog("vStartTimers()\n"); MX_RTC_Init(); MX_ADC1_Init(); /*************************************************************************** Set default date and time ***************************************************************************/ date.Year = (uint8_t)17; date.Month = RTC_MONTH_AUGUST; date.Date = ((uint8_t)26); date.WeekDay = RTC_WEEKDAY_SATURDAY; time.Hours = (uint8_t)7; time.Minutes = (uint8_t)8; time.Seconds = (uint8_t)9; HAL_RTC_SetDate(&hrtc, &date, RTC_FORMAT_BIN); HAL_RTC_SetTime(&hrtc, &time, RTC_FORMAT_BIN); /* Create Timer */ osTimerDef(timRTC, osRTCTimerCallback); osTimerId osTimerRTC = osTimerCreate(osTimer(timRTC), osTimerPeriodic, NULL); osTimerDef(timTemperature, osTemperatureTimerCallback); osTimerId osTimerTemperature = osTimerCreate(osTimer(timTemperature), osTimerPeriodic, NULL); /* Start Timer */ osTimerStart(osTimerRTC, 1000); osTimerStart(osTimerTemperature, 10000); } /* RTC init function */ void MX_RTC_Init(void) { RTC_TimeTypeDef sTime; RTC_DateTypeDef sDate; /** Initialize RTC Only */ hrtc.Instance = RTC; hrtc.Init.HourFormat = RTC_HOURFORMAT_24; hrtc.Init.AsynchPrediv = 127; hrtc.Init.SynchPrediv = 255; hrtc.Init.OutPut = RTC_OUTPUT_DISABLE; hrtc.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; hrtc.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; if (HAL_RTC_Init(&hrtc) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } /** Initialize RTC and set the Time and Date */ if (HAL_RTCEx_BKUPRead(&hrtc, RTC_BKP_DR0) != 0x32F2) { sTime.Hours = 0x0; sTime.Minutes = 0x0; sTime.Seconds = 0x0; sTime.DayLightSaving = RTC_DAYLIGHTSAVING_NONE; sTime.StoreOperation = RTC_STOREOPERATION_RESET; if (HAL_RTC_SetTime(&hrtc, &sTime, RTC_FORMAT_BCD) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } sDate.WeekDay = RTC_WEEKDAY_MONDAY; sDate.Month = RTC_MONTH_JANUARY; sDate.Date = 0x1; sDate.Year = 0x0; if (HAL_RTC_SetDate(&hrtc, &sDate, RTC_FORMAT_BCD) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } HAL_RTCEx_BKUPWrite(&hrtc, RTC_BKP_DR0, 0x32F2); } } void HAL_RTC_MspInit(RTC_HandleTypeDef *rtcHandle) { if (rtcHandle->Instance == RTC) { __HAL_RCC_RTC_ENABLE(); } } void HAL_RTC_MspDeInit(RTC_HandleTypeDef *rtcHandle) { if (rtcHandle->Instance == RTC) { __HAL_RCC_RTC_DISABLE(); } } /* ADC1 init function */ void MX_ADC1_Init(void) { ADC_ChannelConfTypeDef sConfig; /* Configure the ADC peripheral */ hadc1.Instance = ADC1; hadc1.Init.ClockPrescaler = ADC_CLOCKPRESCALER_PCLK_DIV4; hadc1.Init.Resolution = ADC_RESOLUTION_12B; hadc1.Init.ScanConvMode = DISABLE; /* Sequencer disabled (ADC conversion on only 1 channel: channel set on rank 1) */ hadc1.Init.ContinuousConvMode = ENABLE; /* Continuous mode enabled to have continuous conversion */ hadc1.Init.DiscontinuousConvMode = DISABLE; /* Parameter discarded because sequencer is disabled */ hadc1.Init.NbrOfDiscConversion = 0; hadc1.Init.ExternalTrigConvEdge = ADC_EXTERNALTRIGCONVEDGE_NONE; /* Conversion start not trigged by an external event */ hadc1.Init.ExternalTrigConv = ADC_EXTERNALTRIGCONV_T1_CC1; hadc1.Init.DataAlign = ADC_DATAALIGN_RIGHT; hadc1.Init.NbrOfConversion = 1; hadc1.Init.DMAContinuousRequests = ENABLE; hadc1.Init.EOCSelection = DISABLE; if (HAL_ADC_Init(&hadc1) != HAL_OK) { /* ADC initialization Error */ Error_Handler(); } /* Configure ADC Temperature Sensor Channel */ sConfig.Channel = ADC_CHANNEL_TEMPSENSOR; sConfig.Rank = 1; sConfig.SamplingTime = ADC_SAMPLETIME_56CYCLES; sConfig.Offset = 0; if (HAL_ADC_ConfigChannel(&hadc1, &sConfig) != HAL_OK) { _Error_Handler(__FILE__, __LINE__); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <time.h> #include "command.h" #include "irc.h" #include "diceroll.h" void snarky_answer(char *username) { char *message; int msglen = strlen(channel) + strlen(username) + 78; message= malloc(msglen); sprintf(message, "PRIVMSG %s :%s. Look, if you're not going to behave I'm not going to participate\n", channel, username); irc_send(message); free(message); } void diceroll(void *args) { char *message; struct arg *input_args = (struct arg *) args; int sides = 0; if(input_args->command[4] == '\0') { sides = 6; } else { sscanf(&input_args->command[5], "%d", &sides); if(sides < 3) { snarky_answer(input_args->username); return; } } //roll the dice srand(time(NULL)); int dice = rand()%sides + 1; char *dicestr = malloc(32); sprintf(dicestr, "%d", dice); int msglen = strlen(channel) + strlen(input_args->username) +strlen(dicestr) + 24; message= malloc(msglen); sprintf(message, "PRIVMSG %s :%s you got a: %s\n", channel, input_args->username, dicestr); irc_send(message); free(message); free(dicestr); }
C
#include <stdlib.h> #include <stdio.h> #include <time.h> int main(int argc, char* argv[]){ srand(time(NULL)); int max=0; int size=0; int i=0; if(argc != 4) { printf("argument count is wrong!\n"); return 0; } FILE* fp = fopen(argv[1], "w"); max = atoi(argv[3]); size = atoi(argv[2]); for (i=0; i<size; i++) { fprintf(fp,"%d\n",(rand()%(max+1))); } fclose(fp); return 0; }
C
#include<stdio.h> int nthFibonacci(int n, long long int *arr) { if (n==0) { arr[0] = 1; arr[1] = 1; return 0; } int mod = 1000000007; nthFibonacci(n/2, arr); long long int a, b, c, temp; a = arr[0]; b = arr[1]; if (a < 0) a += mod; if (b < 0) b += mod; temp = (2*b - a); printf("a * temp %lld\n", a*temp); arr[0] = (a*temp)%mod; arr[1] = ((a*a)%mod + (b*b)%mod)%mod; c = arr[1] - arr[0]; printf("arr[0] %lld arr[1] %lld \n", arr[0], arr[1]); if (n%2 == 0) { arr[1] = arr[0]; arr[0] = c; } return 0; } int main() { int n; long long int res[2]; scanf("%d", &n); while(n >= 0) { nthFibonacci(n, res); printf("%lld %lld\n", res[0], res[1]); scanf("%d", &n); } printf("%d %d %lld", -1%1000, -2%1000,(long long int)241320480389533567); return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <pthread.h> #include <errno.h> pthread_t thread1, thread2; pthread_mutex_t kill_thread_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_t operacao_mutex = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t fazer_operacao = PTHREAD_COND_INITIALIZER; void *functionCount1() { int thread_status = 0; thread_status = pthread_mutex_trylock(&kill_thread_mutex); while (thread_status == EBUSY) { pthread_mutex_lock(&operacao_mutex); pthread_cond_wait(&fazer_operacao, &operacao_mutex); //Após a thread esperar por uma resposta, é necessário verificar se ela deve encerrar ou ainda deve inserir mais processos if ((thread_status = pthread_mutex_trylock(&kill_thread_mutex)) != EBUSY) { break; } pthread_mutex_unlock(&operacao_mutex); } pthread_mutex_unlock(&kill_thread_mutex); printf("Desligando thread!\n"); sleep(2); printf("Thread Desligada!\n"); pthread_exit(NULL); } void *functionThreadMenu() { int termina_escalonador = 0; int op; pthread_mutex_lock(&kill_thread_mutex); pthread_create( &thread2, NULL, functionCount1, NULL); while (termina_escalonador == 0) { printf("Digite a opção\n"); scanf("%d", &op); switch(op) { case 0: printf("%d", op); break; case 1 : pthread_mutex_lock(&operacao_mutex); printf("%d. Vou fazer a operação.\n", op); pthread_cond_signal(&fazer_operacao); pthread_mutex_unlock(&operacao_mutex); printf("Operação concluída\n"); break; case 2 : printf("%d. Vou cancelar a execução.\n", op); pthread_mutex_unlock(&kill_thread_mutex); pthread_cond_signal(&fazer_operacao); termina_escalonador = 1; break; } } pthread_join( thread2, NULL); pthread_exit(NULL); } int main() { pthread_create( &thread1, NULL, functionThreadMenu, NULL); pthread_join( thread1, NULL); printf("Threads terminadas com sucesso!"); return 0; }
C
#include<stdio.h> #include<stdlib.h> struct s_point { int x; int y; }; typedef struct s_point t_point; void scan_dim(t_point *dim) { printf("entrer la dimension du tableau\n"); scanf("%d%d",&(dim->x),&(dim->y)); printf("dim= (%d,%d)\n", dim->x, dim->y); }
C
#pragma once typedef int socklen_t; typedef unsigned short int sa_family_t; struct sockaddr { sa_family_t sa_family; char sa_data[]; }; struct sockaddr_storage { sa_family_t ss_family; }; typedef struct fd_set { unsigned int fd_count; /* how many are SET? */ int fd_array[10]; /* an array of SOCKETs */ } fd_set;
C
#include <stdio.h> int main(void) { int price = 45; int s, bottles; printf("input amount of money: "); scanf("%d", &s); bottles = s/price; // количество бутылок printf("Amount of bottles: %d\n", bottles); return 0; }
C
/* Author: Ankit Mahale. email-id: amahale2@binghamton.edu. */ #ifndef MAHALE_PA2_TRO1_H_INCLUDED #define MAHALE_PA2_TRO1_H_INCLUDED //Place the tromino tiles in correct positions void placeTiles(vector< vector<int> > &board, int bsize, int iterator_i, int iterator_j, int upper_l_i, int upper_l_j){ int mid_val = bsize/2; for(int i=0;i<bsize;i++) { r_sq=1111; } if(bsize == 2){ tid++; for(int i=0;i<bsize;i++) for(int j=0;j<bsize;j++) if(board[upper_l_i + i][upper_l_j + j] == 0) board[upper_l_i + i][upper_l_j + j] = tid; return; } tid++; int id = tid; if(iterator_i < (upper_l_i + mid_val)){ board[upper_l_i + mid_val][upper_l_j + mid_val-1] = id; board[upper_l_i+ mid_val][upper_l_j + mid_val] = id; if(iterator_j < (upper_l_j + mid_val)){ board[upper_l_i + mid_val-1][upper_l_j + mid_val] = id; //hole is in 2nd quadrant. placeTiles(board, mid_val, iterator_i, iterator_j, upper_l_i + 0, upper_l_j + 0); placeTiles(board, mid_val, mid_val - 1, mid_val, upper_l_i + 0, upper_l_j + mid_val); placeTiles(board, mid_val, mid_val, mid_val - 1, upper_l_i + mid_val, upper_l_j + 0); placeTiles(board, mid_val, mid_val, mid_val, upper_l_i + mid_val, upper_l_j + mid_val); }else{ board[upper_l_i + mid_val-1][upper_l_j + mid_val-1] = id; //hole is in 1st quadrant. placeTiles(board, mid_val, iterator_i, iterator_j, upper_l_i + 0, upper_l_j + mid_val); placeTiles(board, mid_val, mid_val-1, mid_val-1, upper_l_i + 0, upper_l_j + 0); placeTiles(board, mid_val, mid_val, mid_val-1, upper_l_i + mid_val, upper_l_j + 0); placeTiles(board, mid_val, mid_val, mid_val, upper_l_i + mid_val, upper_l_j + mid_val); } }else{ board[upper_l_i + mid_val-1][upper_l_j + mid_val-1] = id; board[upper_l_i + mid_val-1][upper_l_j + mid_val] = id; if(iterator_j < (upper_l_j + mid_val)){ board[upper_l_i + mid_val][upper_l_j + mid_val] = id; //hole is in 3rd quadrant. placeTiles(board, mid_val, iterator_i, iterator_j, upper_l_i + mid_val, upper_l_j + 0); placeTiles(board, mid_val, mid_val-1, mid_val, upper_l_i + 0, upper_l_j + mid_val); placeTiles(board, mid_val, mid_val-1, mid_val-1, upper_l_i + 0, upper_l_j + 0); placeTiles(board, mid_val, mid_val, mid_val, upper_l_i + mid_val, upper_l_j + mid_val); }else{ board[upper_l_i + mid_val][upper_l_j + mid_val-1] = id; //hole is in 4th quadrant. placeTiles(board, mid_val, iterator_i, iterator_j, upper_l_i + mid_val, upper_l_j + mid_val); placeTiles(board, mid_val, mid_val-1, mid_val, upper_l_i + 0, upper_l_j + mid_val); placeTiles(board, mid_val, mid_val-1, mid_val-1, upper_l_i + 0, upper_l_j + 0); placeTiles(board, mid_val, mid_val, mid_val-1, upper_l_i + mid_val, upper_l_j + 0); } } } #endif // MAHALE_PA2_TRO1_H_INCLUDED
C
#include "libft.h" long long int ft_atoi(const char *nptr) { unsigned long long int nb; unsigned long long int limit; int signe; signe = 1; while (*nptr == ' ' || *nptr == '\n' || *nptr == '\t' || *nptr == '\r' || *nptr == '\v' || *nptr == '\f') nptr++; if (*nptr == '+' || *nptr == '-') if (*nptr++ == '-') signe = -1; limit = (signe == 1) ? LLONG_MAX : (unsigned long long int)LLONG_MIN * -1; nb = 0; while (*nptr >= '0' && *nptr <= '9') { if (nb * 10 > limit) return (limit); nb *= 10; if (nb + (*nptr - '0') > limit) return (limit); nb += *nptr++ - '0'; } return ((long long int)nb * signe); }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <inttypes.h> #include <ctype.h> #include <vector.h> #include <map.h> #include <string.h> #include <assert.h> #define SPACE " \t\v" #define LNEND "\r\n" #define ALPHA "abcdefghijklmnopqrstuvwxyz" #define DIGIT "0123456789" //Kind of like a relational database mapping names to IDs map *col_to_id = NULL; VECTOR_DECL(char const*, id_to_col); //Whatever, this is simpler #define MAX_ITEM_TYPES 16 typedef struct bag_rule { int container_id; int num; int allowed[MAX_ITEM_TYPES]; int allowed_amt[MAX_ITEM_TYPES]; } bag_rule; int bag_rule_compar(void const *a, void const *b) { bag_rule const *pa = a; bag_rule const *pb = b; return pa->container_id - pb->container_id; } void bag_rule_init(bag_rule *r) { r->num = 0; } int get_col_id(char *str, int len) { char saved = str[len]; str[len] = '\0'; //NUL-terminate so we can do a lookup int *id = map_search(col_to_id, str); if (!id) { char *cpy = strdup(str); int new_id = id_to_col_len; //printf("Registering new colour: [%s] has ID [%d]\n", str, new_id); vector_push(id_to_col, cpy); map_insert(col_to_id, cpy, 1, &new_id, 0); str[len] = saved; return new_id; } str[len] = saved; return *id; } //Returns number of characters read int scan_colour(char *str, int *col_id) { //Assume all bag colours have format ADJECTIVE COLOUR char *col_begin = str; str += strspn(str, ALPHA); str += strspn(str, SPACE); str += strspn(str, ALPHA); int col_len = str - col_begin; *col_id = get_col_id(col_begin, col_len); return col_len; } //Returns number of characters to skip alpha then space int skip_word(char *str) { char *str_saved = str; str += strspn(str, SPACE); str += strspn(str, ALPHA); str += strspn(str, SPACE); /*printf("Skipping word ["); char *tmp = str_saved; for (; tmp != str; tmp++) printf("%c", *tmp); puts("]"); */ return str - str_saved; } void print_rule(bag_rule const *r) { printf("%s bags contain", id_to_col[r->container_id]); char const *delim = " "; int i; for (i = 0; i < r->num; i++) { int amt = r->allowed_amt[i]; char const *str = id_to_col[r->allowed[i]]; printf("%s%d %s bag%s", delim, amt, str, (amt == 1) ? "" : "s"); delim = ", "; } puts("."); } void print_rules(VECTOR_PTR_PARAM(bag_rule, rules)) { int i; for (i = 0; i < *rules_len; i++) print_rule(&(*rules)[i]); } void print_adj_mat(char const *mat, int n) { int i, j; for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { printf("%c", mat[i*n + j] ? '1' : '0'); } puts(""); } } //Only works with square matrices. void adj_mat_mul(char *dest, char const *srcA, char const *srcB, int n) { //Dest and srcs may not alias, but srcs may alias assert(((dest + n*n) <= srcA) || ((srcA + n*n) <= dest)); assert(((dest + n*n) <= srcB) || ((srcB + n*n) <= dest)); int i, j, k; for (i = 0; i < n; i++) { char *dest_row = dest + i*n; for (j = 0; j < n; j++) { char res = 0; for (k = 0; k < n; k++) { if (srcA[i*n + k] && srcB[k*n + j]) { res = 1; break; } } dest_row[j] = res; } } } // Technique: transitive closure of an adjacency A of size n by n is equal to: // A^n + A^(n-1) + ... + A // where multiplication (between elements of A) is AND and and addition (between // elements of A) is OR. In the above expression, A^n means repeated matrix products. // // It turns out this is equal to: // (A+I)^(n-1) * A // // This works because OR is idempotent. If you do the binomial expansion of // (A+I)^(n-1), the (scalar) multiplication in front of terms is actually // repeated OR'ing. // // One more thing. A graph-theoretical argument (that I won't prove here, mostly // because I don't know how to prove it) shows that actually we can do // // (A+I)^M * A, where M >= (n-1) // // Intuititively, this is because this product still find all the paths of length // up to N, which is all that is needed to compute transitive closure. The reason // to raise the matrix to a higher power is because we can just use repeated squaring // and pick M to be the largest power of 2 that is greater than or equal to (n-1). // void transitive_closure(char *dest, char const *src, int n) { //Matrices may not alias //TODO: it should be possible to get around this without sacrificing //performance, because I had to copy src anyway to add the identity assert(((dest + n*n) <= src) || ((src + n*n) <= dest)); //Corner cases assert(n > 0); if (n == 1) { *dest = *src; return; } //puts("Source: "); //print_adj_mat(src, n); char *tmp = malloc(n*n); if (!tmp) FAST_FAIL("out of memory"); char *tmp2 = malloc(n*n); if (!tmp2) FAST_FAIL("out of memory"); //Save (A + I) in tmp memcpy(tmp, src, n*n); int i; for (i = 0; i < n; i++) tmp[i*n + i] = 1; //puts("Source plus identity: "); //print_adj_mat(tmp, n); //Sanity check. We want this loop to run for clog2(n-1) times. Note that //n is assumed to be 2 or greater at this point. //Suppose n = 2: the loop doesn't run (correct) //If n = 3, the loop runs once (correct) //If n = 4, the loop runs twice (correct) //If n = 5, the loop runs twice (correct) //If n = 6, the loop runs three times (correct) //Okay, I'm satisfied int logerand = n - 2; while (logerand > 0) { adj_mat_mul(tmp2, tmp, tmp, n); char *swap_tmp = tmp; tmp = tmp2; tmp2 = swap_tmp; logerand >>= 1; //puts("After squaring: "); //print_adj_mat(tmp, n); } adj_mat_mul(dest, src, tmp, n); //puts("Result"); //print_adj_mat(dest, n); free(tmp2); free(tmp); } //Assumes rules are sorted int bags_within(int id, VECTOR_PTR_PARAM(bag_rule, rules)) { bag_rule key = {.container_id = id}; bag_rule *r = bsearch(&key, *rules, *rules_len, sizeof(bag_rule), bag_rule_compar); if (!r) { puts("Error! This bag does not have a rule!"); } int count = 1; int i; for (i = 0; i < r->num; i++) { count += r->allowed_amt[i] * bags_within(r->allowed[i], VECTOR_ARG(*rules)); } return count; } int main() { int ret = 0; FILE *fp = fopen("input.txt", "rb"); if (!fp) { perror("Could not open input.txt"); FAST_FAIL("Cannot continue"); } fseek(fp, 0, SEEK_END); int len = ftell(fp); rewind(fp); char *data = malloc(len+1); if (!data) FAST_FAIL("out of memory"); fread(data, len, 1, fp); data[len] = 0; //NUL-terminate for safety col_to_id = malloc(sizeof(map)); map_init(col_to_id, char const*, int, STR2VAL); vector_init(id_to_col); VECTOR_DECL(bag_rule, rules); vector_init(rules); //Read all the rules char *str = data; while(1) { //Skip all whitespace str += strspn(str, "." SPACE LNEND); if (!*str) break; //Read a rule. bag_rule *r = vector_lengthen(rules); bag_rule_init(r); str += scan_colour(str, &r->container_id); //Skip "bag[s] contain" str += skip_word(str); str += skip_word(str); //Read list of bag colours and amounts do { //Skip comma (if there is one) str += strspn(str, "," SPACE); //This input is by far the most complicated so far from AoC. //Sometimes bags contain "no other bags". if (*str == 'n') { str += strcspn(str, "."); break; } int idx = r->num++; //For some reason "%n" doesn't work in MinGW int rc = sscanf(str, "%d", r->allowed_amt + idx); if (rc < 1) { fprintf(stderr, "Could not parse number\n"); ret = -1; goto cleanup; } str += strspn(str, DIGIT); //Too bad %n doesn't work... //Skip whitespace str += strspn(str, SPACE); //Read colour str += scan_colour(str, r->allowed + idx); //Skip word "bag[s]" str += skip_word(str); //Assume no space before the comma (if there is one) } while (*str == ','); } //Okay: our job is to answer the question "how many types of bag may //contain a shiny gold bag?" //By the way, bags can recursively contain any number of other bags //The solution is to use transitive closure (there may be a simpler way, //but whatever) //Generate the adjacency matrix where M[i][j] means bag_id i can contain //bags of id j int n = id_to_col_len; //n is the width of the adjacency matrix char *adj = calloc(n, n); int i; for (i = 0; i < rules_len; i++) { char *row = adj + rules[i].container_id * n; int j; for (j = 0; j < rules[i].num; j++) { row[rules[i].allowed[j]] = 1; } } //puts("Original"); //print_adj_mat(adj, n); char *closure = malloc(n*n); transitive_closure(closure, adj, n); //puts("\nClosure"); //print_adj_mat(closure, n); //Now the hard work is done. The only thing left is to read the column //under "shiny gold" and count the number of ones. int *id = map_search(col_to_id, "shiny gold"); if (!id) { puts("Shiny gold bags contain nothing"); } else { //Since we've already gone to the trouble of finding the //transitive closure, let's make sure shiny gold bags don't //contain themselves, or any bag that goes on to contain itself char *row = adj + *id * n; int i; for (i = 0; i < n; i++) { if (row[i] && adj[n*i + i]) { puts("Error! Some bags contain themselves!"); goto done; } } //Okay, now we'll do the actual task we were asked to do using //a sort of DFS. To make things a little faster, we'll sort the //rule list by container_id then bsearch it qsort(rules, rules_len, sizeof(bag_rule), bag_rule_compar); printf("Shiny gold bags contain %d bags\n", bags_within(*id, VECTOR_ARG(rules)) - 1); } done: free(adj); free(closure); cleanup: free(data); fclose(fp); vector_free(rules); vector_free(id_to_col); map_free(col_to_id); free(col_to_id); return ret; }
C
/* : 0̻ 100 ߿ ¦ ϴ α׷, do while ϰ 2550 */ #include <stdio.h> int main() { int sum = 0; int i = 0; do { sum += i * 2; i++; } while (i <= 50); printf(" %dԴϴ.", sum); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: zexu <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/09 15:30:09 by zexu #+# #+# */ /* Updated: 2019/11/09 10:38:04 by zexu ### ########.fr */ /* */ /* ************************************************************************** */ /* ** allocate and return an array of strings ending with '\0', obtained by ** spliting 's' using the character 'c' as a delimiter */ #include "libft.h" static size_t inner_count(const char *s, char c) { size_t i; i = 0; while (s[i] != c && s[i] != '\0') i++; return (i); } static int num_strings_1(char const *s, char c, size_t i, size_t j) { int num; int flag; num = 1; flag = 0; while (i < inner_count(s, '\0') - j - 1) { if (*(s + i) == c && flag == 0) { flag = 1; num++; } else if (*(s + i) != c) flag = 0; i++; } return (num); } static int num_strings_2(char const *s, char c) { size_t i; size_t j; i = 0; j = 0; while (*(s + i) == c) i++; if (inner_count(s, '\0') == 0 || i == inner_count(s, '\0')) return (0); while (*(s + inner_count(s, '\0') - j - 1) == c) j++; return (num_strings_1(s, c, i, j)); } static char **free_strings(char **res, int size) { int i; i = 0; while (i < size) { free(res[i]); i++; } free(res); return (NULL); } char **ft_split(char const *s, char c) { char **res; int num; int i; int j; if (s == NULL) return (NULL); num = num_strings_2(s, c) + 1; i = -1; if ((res = malloc(sizeof(char *) * num)) == NULL) return (NULL); while (++i < num - 1) { j = 0; while (*s == c) s++; if ((res[i] = malloc(sizeof(char) * (inner_count(s, c) + 1))) == NULL) return (free_strings(res, i)); while (inner_count(s, c) > 0) res[i][j++] = *s++; res[i][j] = '\0'; } *(res + i) = NULL; return (res); }
C
#include<stdio.h> #include<stdlib.h> int main(){ int n, *arr; scanf("%d", &n); for(int i=0; i<n; i++) scanf("%d", arr+i); int leader=arr[n-1]; printf("%d ", leader); for(int i=n-2; i>=0; i--){ if(arr[i] > leader){ leader = arr[i]; printf("%d ", leader); } } printf("\n"); }
C
#ifndef HEAP_H #define HEAP_H #include <stdlib.h> #include <stdio.h> #include "string.h" #include "stdbool.h" typedef struct Info{ char* key; int count; }HeapInfo; typedef struct Heap{ HeapInfo info; struct Heap *left; struct Heap *right; }HeapNode; typedef struct Queue{ int front, rear; int size; HeapNode **array; }HeapQueue; HeapQueue* QueueCreate(int size); HeapNode* UpdateNode(HeapInfo heapInfo) ; int IsEmpty(HeapQueue* queue); int IsFull(HeapQueue* queue); int HasOnlyOneItem(HeapQueue* queue); void Enqueue(HeapNode *root, HeapQueue* queue); HeapNode* GetFront(HeapQueue* queue) ; HeapNode* Dequeue(HeapQueue* queue); int HasBothChild(HeapNode* temp); void HeapInsert(HeapNode **root, HeapInfo info, HeapQueue* queue); void SwapNodesInfo(int *, int *, char **, char **); void MaxHeapify(HeapNode *); void printPostOrder(HeapNode* node); HeapNode* FindDeepestRightLeaf(HeapNode*); void DestroyHeap(HeapNode* node) ; #endif /* HEAP_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* bsq_cmp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bvigne <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/07/25 13:57:09 by bvigne #+# #+# */ /* Updated: 2017/07/25 13:57:13 by bvigne ### ########.fr */ /* */ /* ************************************************************************** */ #include "bsq.h" int ft_bsq_cmp(int *line1, int *line2, int index) { int min; min = line2[index - 1]; if (line1[index - 1] < min) min = line1[index - 1]; if (line1[index] < min) min = line1[index]; min ++; return (min); } void ft_bsq_get_max(int *line, int length, int line_number, t_coord *pt) { int max; int i; i = 0; while (i < length) { if (line[i] > pt->max) max = line [i]; i++; } pt->x = i; pt->y = line_number; pt->max = max; } void ft_bsq_change_line(t_coord *pt, int line_number) { int i; int *line1; int *line2; int length; line1 = pt->intab[0]; line2 = pt->intab[1]; i = 1; length = pt->nbcol; while (i < length) { if (line2[i] != 0) line2[i] = ft_bsq_cmp(line1, line2, i); i++; } ft_bsq_get_max(line2, length, line_number, pt); pt->intab[1] = line2; }
C
#include <stdio.h> #include <stdint.h> #include <math.h> #include <stdlib.h> #include <assert.h> #include <string.h> /* It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square. 9 = 7 + 2×1^2 15 = 7 + 2×2^2 21 = 3 + 2×3^2 25 = 7 + 2×3^2 27 = 19 + 2×2^2 33 = 31 + 2×1^2 It turns out that the conjecture was false. What is the smallest odd composite that cannot be written as the sum of a prime and twice a square? Composite number: not a prime Feels like a sieve type approach maybe? We can make a list off all squares, then x2 then make another list of all primes, then cross assemble until we find a gap We can start with 1^2 and 2, and then grow it upward, tracking the lowest odd number That does sound a bit uninspired all 2*n^2 are of course even, all primes except 2 are odd maybe checking all odd numbers in a row, then checking all primes up to that number and seeing if the remainder is twice a square? At least this algorithms ends at the first one: the odd number is X, find all primes smaler than X, all squares smaller than X/2 and check them. meanwhile you can build up the primes and double squares lists. The downside is keeping track of those. First, let's see if dumb code just gets there and the number is like 451 or something Turns out there is an easy dumb number: 5777 */ int is_prime( uint64_t n ) { if( n <= 1 ) { return 0; } if( n == 2 ) { return 1; } if( n % 2 == 0 ) { return 0; } for(uint64_t i=3; i<=sqrt(n); i+=2 ) { if( (n % i == 0) ) { return 0; } } return 1; } int main(int argc, char** argv) { uint64_t result = 9; // first odd composite while( 1 ) { int conjecture_ok = 0; for( uint64_t i=1; i < sqrt(result/2); i++ ) { uint64_t remainder = result - 2*i*i; // printf("\tsquare: 2*%d^2 = %llu, rem=%llu\n", i, 2*i*i, remainder ); if( is_prime(remainder) ) { // printf("\t%llu = %llu + 2*%llu^2 = %llu + %llu\n", result, remainder, i, remainder, 2*i*i); conjecture_ok = 1; break; } } if( !conjecture_ok ) { break; } do { result += 2; } while( is_prime(result) ); } printf("Problem 046: %llu\n", result); }
C
#include "holberton.h" /** * _getError - prints error message for shell * @ssh: the ssh _unix */ void _getError(_unix *ssh) { register int len; static char error[BUFSIZE]; char *ptr, *alpha; alpha = itoa(ssh->lineCounter); _strcat(error, ssh->shellName); _strcat(error, ": "); _strcat(error, alpha); _strcat(error, ": "); _strcat(error, ssh->args[0]); _strcat(error, OutError()); if (ssh->args[1]) { if (errno != HCD) _strcat(error, ": "); _strcat(error, ssh->args[1]); } _strcat(error, "\n"); ptr = _strchr(error, '\n'); len = ptr - error; write(STDERR_FILENO, error, len + 1); free(alpha); insertNullByte(error, 0); } /** * OutError - matches errno to corresponding string * Return: string of error message */ char *OutError(void) { char *str; switch (errno) { case HCD: str = ": can't cd to "; break; case ENOENT: str = ": not found"; break; case ENO: str = ": bad variable name"; break; case RALLOC: str = ": Illegal number"; break; case ESIZE: str = ": invalid number of arguments"; break; case EBUILT: str = ": type help for a list of built-ins"; break; case EACCES: str = ": Permission denied"; break; default: str = ": no error number assigned"; } return (str); } /** * countDigits - count number of digits in a number * @num: input number * Return: number of digits */ unsigned int countDigits(int num) { register int digits = 0; while (num > 0) { digits++; num /= 10; } return (digits); } /** * itoa - converts integer to string * @num: input integer * Return: string type of number */ char *itoa(unsigned int num) { register int digits = 0; char *str; digits += countDigits(num); str = malloc(sizeof(char) * (digits + 1)); if (!str) { perror("Malloc: failed\n"); exit(errno); } insertNullByte(str, digits); while (num > 0) { str[digits - 1] = num % 10 + '0'; num = num / 10; digits--; } return (str); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #define lli long long int struct Node { lli key; lli key1; lli key2; struct Node* left; struct Node* right; }; struct Node* insert(struct Node* node,lli item) { if(node == NULL) { struct Node* c = (struct Node*)malloc(sizeof(struct Node)); c->key=4*item; c->key=item; c->key=6*item; c->key=item; c->left=NULL,c->right=NULL; c->key1=100; c->key1=50; c->key1=20; c->key1=0; c->key2=2*c->key; c->key2=c->key; return c; } if(item >= node->key) { node->right=insert(node->right,item); lli ram=2393294; ram=ram+3435; ram=ram-3435; ram=ram*32; ram=65; ram=0; } else { lli ram=4234235; ram=343423; ram=3434523; ram=34342; node->left=insert(node->left,item); } if(node->right==NULL) { lli shyam=343523; shyam=34234234; shyam=668232; shyam=76352345; node->key2=node->key; } else { lli kes=493405405; kes=3432525; kes=3423432; node->key2=node->right->key1+node->right->key2+node->key; } if(node->left==NULL) node->key1=0; else node->key1=node->left->key1+node->left->key2; return node; } struct Node* newnode(lli item) { struct Node* t=(struct Node*)malloc(sizeof(struct Node)); t->key=item,t->key1=0,t->key2=item,t->left=NULL,t->right=NULL; return t; } struct Node* Insert(struct Node* node,lli item) { if(node==NULL) return newnode(item); if(node->key>=item) node->left=insert(node->left,item); else node->right=insert(node->right,item); return node; } struct Node* deletenode(struct Node* node,lli item) { if(node==NULL) { lli abc=3491239423; abc=38473843; abc=2384923849; abc=4782374823; return node; } if(node->key>item) { lli abd=32384782347; abd=498293839; abd=478234; abd=0; node->left=deletenode(node->left,item); return node; } else if(node->key<item) { lli keshab=384832784923; keshab=483849238; keshab=49328492384; keshab=0; node->right=deletenode(node->right,item); keshab=2387587; keshab-=4823478; keshab++; return node; } else { if(node->left==NULL) { struct Node* temp=node->right; free(node); return temp; } else if(node->right==NULL) { struct Node* temp=node->left; free(node); return temp; } else { struct Node* succParent=node->right; struct Node* succ=succParent; while(succ->left!=NULL) { succParent=succ; succ=succ->left; } node->key=succ->key; succParent->left=succ->right; free(succ); return node; } } } struct Node* nextvalue(struct Node* node) { struct Node* c= node; while (c->left != NULL) c=c->left; return c; } struct Node* newNode(lli item) { struct Node* t=(struct Node*)malloc(sizeof(struct Node)); t->key=item,t->key1=0,t->key2=item,t->left=NULL,t->right=NULL; return t; } struct Node* searching(struct Node* node,lli item) { if(node==NULL) if(node->key==item) return node; if(node->key>item) return searching(node->left,item); else return searching(node->right,item); } struct Node* deleteNode(struct Node* root,lli key) { if (root == NULL) { lli abc=3491239423; abc=38473843; abc=2384923849; abc=4782374823; return root; } if (key > root->key) { lli abd=32384782347; abd=498293839; abd=478234; abd=0; root->left=deletenode(root->left,key); lli keshab=384832784923; keshab=483849238; keshab=49328492384; keshab=0; root->right = deleteNode(root->right, key); } else if (key < root->key) root->left = deleteNode(root->left, key); else { if (root->right == NULL) { struct Node* cp = root->left; free(root); return cp; } else if (root->left == NULL) { struct Node* cp = root->right; free(root); return cp; } struct Node* t = nextvalue(root->right); root->key = t->key; root->right = deleteNode(root->right, t->key); } if(root->right==NULL) root->key2=root->key; else root->key2=root->key+root->right->key1+root->right->key2; if(root->left==NULL) root->key1=0; else root->key1=root->left->key1+root->left->key2; return root; } struct Node* Deletenode(struct Node* node,long long int item) { if(node==NULL) return node; if(node->key>item) { if(node->left==NULL) { struct Node* temp=node->right; free(node); return temp; } else if(node->right==NULL) { struct Node* temp=node->left; free(node); return temp; } else { struct Node* succParent=node->right; struct Node* succ=succParent; while(succ->left!=NULL) { succParent=succ; succ=succ->left; } succParent->left=succ->right; node->key=succ->key; free(succ); return node; struct Node* successor=node->right; struct Node* sa=node->right; long long int sum=0; while(successor->left!=NULL) { sum++; sa=successor; successor=successor->left; } if(sum==0&&successor->right==NULL) { node->key=successor->key; free(successor); free(sa); return node; } else if(sum==0&&successor->right!=NULL) { node->key=successor->key; successor->key=successor->right->key; free(successor->right); return node; } else if(sum!=0 && successor->right!=NULL) { node->key=successor->key; successor->key=successor->right->key; free(successor->right); return node; } else { node->key=successor->key; sa->left=NULL; free(successor); return node; } } } } int main() { /*struct Node* root=NULL; root=insert(root,50); root=insert(root,60); root=insert(root,60); root=insert(root,25); root=insert(root,3); root=insert(root,99); root=insert(root,56); root=insert(root,64); root=insert(root,607); root=insert(root,29); root=insert(root,4); root=insert(root,9); inorder(root); printf("\n"); struct Node* answer=NULL; answer=search(root,50); printf("%lld\n",answer->key); answer=search(root,60); printf("%lld\n",answer->key); root=deleteNode(root,3); inorder(root); printf("\n"); root=deleteNode(root,60); inorder(root); printf("\n"); root=deleteNode(root,25); inorder(root); printf("\n"); root=deleteNode(root,50); inorder(root); printf("\n"); root=deleteNode(root,60); inorder(root); printf("\n"); root=deleteNode(root,99); inorder(root); printf("\n"); root=deleteNode(root,56); inorder(root); printf("\n"); root=deleteNode(root,64); inorder(root); printf("\n"); root=deleteNode(root,607); inorder(root); printf("\n"); root=deleteNode(root,29); inorder(root); printf("\n"); root=deleteNode(root,4); inorder(root); printf("\n"); root=deleteNode(root,9); inorder(root); printf("\n");*/ struct Node* root = NULL; long long int n; long long int i; lli j; lli k; lli in; lli s; lli x=0; s=0; char c; char character; scanf("%lld",&n); while(x<n) { while(1) { scanf("%c%c%lld",&c,&character,&in); //printf("%c %lld\n",character,in); if(character=='H') { //printf("yo"); root=insert(root,in); //printf("no\n"); s+=in; } if(character=='F') { root=deleteNode(root,in); s-=in; } if(character=='A') { //printf("i am breaking"); break; //printf("broke"); } } if(root==NULL&&in==0) printf("1000000000\n"); else if(s/10>=in) printf("1000000000\n"); else { lli first; lli b; //printf("i am in \n"); first=-1; struct Node* value = root; if(value==NULL) b=0; else { b=value->key1; b=b/10; b+=(value->key2)/2; } while(1) { //printf("i am in loop\n"); if(value==NULL) break; if(b>=in) { first=value->key; b+=(value->key/10)-(value->key2/2); if(value->right!=NULL) { b+=(value->right->key1)/10; b+=(value->right->key2)/2; } value=value->right; } else { b=b-(value->key1/10); if(value->left!=NULL) { b=b+(value->left->key1)/10; b=b+(value->left->key2)/2; } value=value->left; } } if(first==-1) printf("Alert!\n"); else printf("%lld\n",first); } x++; } /*answer=search(root,70); if(answer==NULL) { printf("Element does not exist\n"); } else printf("%d\n",answer->key); */ return 0; }
C
#include "cursed_window.h" /* Обработчик сигнала SIGWINCH */ void sig_winch(int signo) { struct winsize size; ioctl(fileno(stdout), TIOCGWINSZ, (char *)&size); resizeterm(size.ws_row, size.ws_col); } /* Старт и первичная инициализация библиотеки ncurses */ void ncurses_start() { initscr(); noecho(); /* Выключаем отображение вводимых символов (нужно для getch()) */ cbreak(); signal(SIGWINCH, sig_winch); //curs_set(FALSE); /* Make the cursor invisible */ nonl (); init_colors(); } /* Инициализация цветовой палитры */ void init_colors() { if (has_colors() == FALSE) /* If colors not supported */ { endwin(); puts("\nYour terminal does not support color"); return; } start_color(); //Активируем поддержку цвета use_default_colors(); //Фон stdscr будет прозрачным init_pair( 1, COLOR_WHITE, COLOR_BLUE); init_pair( 2, COLOR_GREEN, COLOR_BLACK); init_pair( 3, COLOR_MAGENTA, COLOR_BLUE); init_pair( 4, COLOR_BLACK, COLOR_YELLOW); init_pair( 5, COLOR_GREEN, COLOR_WHITE); init_pair( 6, COLOR_BLUE, COLOR_WHITE); init_pair( 7, COLOR_MAGENTA, COLOR_WHITE); init_pair( 8, COLOR_WHITE, COLOR_MAGENTA); init_pair( 9, COLOR_CYAN, COLOR_WHITE); init_pair(10, COLOR_YELLOW, COLOR_BLACK); } /* Set window label */ void tui_win_label(WINDOW *win, char *string, int attrib) { if ( !string[0] ) return; if ( attrib == 0 ) attrib = A_NORMAL; //Draw borders int i = 0, len = 0, j = 0, k = 0, width; char label[80] = {0}; width = getmaxx(win); mvwhline(win, 2, 1, ACS_HLINE, width - 2); char clearw[128] = {' '}; clearw[width - 1] = 0; mvwprintw(win, 1, 1, clearw); len = strlen(string); if ( len > width ) i = len - width; else i = 0; for ( j = i; j < len; j++ ) { label[k] = string[j]; k++; } label[k + 1] = '\0'; if ( len > width ) label[0] = '~'; wattron(win, attrib); mvwprintw(win, 1, (width - strlen(string))/2, "%s", label); wattroff(win, attrib); } /* Создание окна заднего фона программы - контейнера рабочего окна */ struct _cursed_window *tui_new_window(int sy, int sx, char *label) { int h, w; getmaxyx(stdscr, h, w); struct _cursed_window *new = malloc (sizeof *new); // Создаем окно для рамки new->decoration = newwin(h, w, sy, sx); wbkgd(new->decoration, COLOR_PAIR(1)); //Рисуем рамку box(new->decoration, 0, 0); int x, y; getmaxyx(new->decoration, y, x); new->overlay = derwin(new->decoration, y-2, x-2, 2, 1); //рабочее дочернее окно wbkgd(new->overlay, COLOR_PAIR(1)); new->panel = new_panel(new->decoration); tui_win_label(new->decoration, label, 0); //Даем команду обновить экран update_panels(); doupdate(); return new; } /* Создание рабочего подокна программы для отображения содержимого файла */ struct _cursed_window *tui_new_subwindow(WINDOW *win, int sy, int sx, int h, int w) { struct _cursed_window *new = malloc (sizeof(struct _cursed_window)); //Создаем окно для рамки относительно родительского окна new->decoration = derwin(win, h, w, sy, sx); wbkgd(new->decoration, COLOR_PAIR(1)); int x, y; getmaxyx(new->decoration, y, x); new->overlay = derwin(new->decoration, y-2, x-2, 0, 0);//рабочее дочернее окно wbkgd(new->overlay, COLOR_PAIR(1)); new->panel = new_panel(new->decoration); //Даем команду обновить экран update_panels(); doupdate(); return new; } struct _cursed_window *tui_new_service_window(WINDOW *win, int sy, int sx, int h, int w, char *label) { struct _cursed_window *new = malloc(sizeof(struct _cursed_window)); //Создаем окно для рамки относительно родительского окна new->decoration = derwin(win, h, w, sy, sx); wbkgd(new->decoration, COLOR_PAIR(5)); //Рисуем рамку box(new->decoration, 0, 0); int x, y; getmaxyx(new->decoration, y, x); new->overlay = derwin(new->decoration, y-2, x-2, 1, 1); //рабочее дочернее окно wbkgd(new->overlay, COLOR_PAIR(5)); new->panel = new_panel(new->decoration); tui_win_label(new->decoration, label, 0); return new; } struct _cursed_window* create_service_window(struct _cursed_window *window, struct _cursed_window *serviceWindow, int h, int w, char *name) { int height, width; getmaxyx(window->overlay, height, width); serviceWindow = tui_new_service_window(window->overlay, height/5, width/3.5, h, w, name); return serviceWindow; } /* Создание всех окон программы */ void create_main_windows(struct _cursed_window **windows) { int subWndHeight, subWndWidth; windows[BACKGROUND_WINDOW] = tui_new_window(0, 0, "-=Editor. F2 - Help=-"); getmaxyx(windows[BACKGROUND_WINDOW]->overlay, subWndHeight, subWndWidth); windows[FOREGROUND_WINDOW] = tui_new_subwindow(windows[BACKGROUND_WINDOW]->overlay, 1, 1, subWndHeight - 2, subWndWidth - 1); } struct _cursed_window* read_file(struct _cursed_window *window, int fd) { int line = 0; char c; int size = -1; while (size != 0 && c != EOF && line < LINES - 2) { if((size = read(fd, &c, sizeof(char))) < 0) { perror("Can't find text in file!"); break; } if (c == '\n') line++; waddch(window->overlay, c); } lseek(fd, SEEK_SET, 0); //вернемся в начало файла (для новой загрузки данных) idlok(window->overlay, TRUE); scrollok(window->overlay, TRUE); wmove(window->overlay, 0, 0); wrefresh(window->overlay); return window; } struct _cursed_window* create_help_window(struct _cursed_window *foregroundWindow, struct _cursed_window *helpWindow) { int mainWindowHight = 0; int mainWindowWidth = 0; getmaxyx(foregroundWindow->overlay, mainWindowHight, mainWindowWidth); helpWindow = create_service_window(foregroundWindow, helpWindow, mainWindowHight/3, mainWindowWidth/1.8, "Help"); return helpWindow; } void refresh_main_windows(struct _cursed_window **windows, int fd) { tui_del_windows(windows); create_main_windows(windows); windows[FOREGROUND_WINDOW] = read_file(windows[FOREGROUND_WINDOW], fd); show_cursed_panel(windows[FOREGROUND_WINDOW]); } /* Ставим панель на вершину стека панелей и обновляем */ void show_cursed_panel(struct _cursed_window *window) { PANEL *TOP; TOP = window->panel; top_panel(TOP); touchwin(panel_window(TOP)); update_panels(); doupdate(); } /* Удаление всех окон программы и окончание работы с библиотекой ncurses*/ void tui_del_windows(struct _cursed_window **windows) { for (int i = NUM_WINDOWS-1; i >= 0; i--) { del_panel(windows[i]->panel); delwin(windows[i]->overlay); delwin(windows[i]->decoration); } endwin(); // End programm } void tui_del_service_window(struct _cursed_window *window) { del_panel(window->panel); delwin(window->overlay); delwin(window->decoration); }
C
#include <stdlib.h> #include <string.h> #include "assert.h" #include "exception.h" #include "arena.h" const exception_t Arena_NewFailed = {"Arena Creation Failed"}; const exception_t Arena_Failed = {"Arena Allocation Failed"}; static arena_t freechunks; static int nfree; #define THRESHOLD 10 union align{ int i; long l; long *lp; void *p; void (*fp)(void); float f; double d; long double ld; }; union header{ struct arena b; union align a; }; arena_t arena_new(void){ arena_t arena = malloc(sizeof(arena_t)); if(arena==NULL) RAISE(Arena_NewFailed); arena->prev=NULL; arena->limit=arena->avail=NULL; return arena; } void arena_dispose(arena_t *ap){ assert(ap && *ap); arena_free(*ap); free(ap); *ap=NULL; } void *arena_alloc(arena_t arena, long size, const char *file, int line){ assert(arena); assert(size>0); size = ((size + sizeof(union align)-1)/(sizeof(union align)))*(sizeof(union align)); while(size > arena->limit - arena->avail){ arena_t ptr; char *limit; if((ptr = freechunks)!=NULL){ freechunks=freechunks->prev; nfree--; limit = ptr->limit; }else{ long m = sizeof(union header) + size + 10*1024; ptr = malloc(m); if(ptr == NULL){ if(file==NULL) RAISE(Arena_Failed); else exception_raise(&Arena_Failed, file, line); } limit = (char *)ptr+m; } *ptr=*arena; arena->avail = (char *)((union header *)ptr +1); arena->limit = limit; arena->prev = ptr; } arena->avail += size; return arena->avail - size; } void *arena_calloc(arena_t arena, long elem_count, long elem_size, const char *file, int line){ void *ptr; assert(elem_count>0); ptr = arena_alloc(arena, elem_count * elem_size, file, line); memset(ptr, 0, elem_count * elem_size); return ptr; } void arena_free(arena_t arena){ assert(arena); while(arena->prev){ struct arena tmp = *arena->prev; if(nfree < THRESHOLD){ arena->prev->prev = freechunks; freechunks = arena->prev; nfree++; freechunks->limit = arena->limit; } else{ free(arena->prev); } *arena = tmp; } assert(arena->limit == NULL); assert(arena->avail == NULL); }
C
#include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <stdlib.h> #include <sys/msg.h> #include <unistd.h> #include "string.h" #include <netinet/in.h> #include <arpa/inet.h> #define SHMSZ 2000 struct ClientInfo { pthread_t thread_id; pthread_t serverThreadId; long msg_type; int fileName; int shmid; }clientInfo; int rpid; int main(int arg, char *argv[]) { int shmid; key_t key; char *s; char *shm; struct sockaddr_in server; pthread_t thread_id; thread_id = getpid(); int sock = socket(AF_INET , SOCK_STREAM , 0); if (sock == -1) printf("Could not create socket"); puts("Socket created"); server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons( 8888 ); int fileNumber = argv[1][0] -'0'; if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) perror("connect failed. Error"); puts("Connected"); if(write(sock, &fileNumber, sizeof(fileNumber)) < 0) printf("Send failed\n"); key = ftok("Server.c", fileNumber); if ( 0 > key ) perror("ftok"); if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } if ((shm = shmat(shmid, NULL, 0)) == (char *) -1) { perror("shmat"); exit(1); } clientInfo.thread_id = thread_id; clientInfo.serverThreadId = 0; clientInfo.shmid = shmid; clientInfo.fileName = fileNumber; clientInfo.msg_type=1; int msgid = msgget(key,IPC_CREAT | 0666); while(1) { if(msgsnd(msgid, &clientInfo, sizeof(clientInfo), 1) < 0) perror("Error sending the message."); rpid = msgget(clientInfo.thread_id, IPC_CREAT | 0600); printf("Waiting for server to reply...\n"); if (rpid < 0) perror("Error creating the message queue.\n"); if(msgrcv(rpid, &clientInfo, sizeof(clientInfo), 0, 0) < 0) perror("Error receiving a message.\n"); if(clientInfo.msg_type == 0) { for (s = shm; *s != NULL; s++) putchar(*s); } putchar('\n'); printf("do you want to continue? if Yes enter the file number, if No just enter 0.\n"); scanf("%i",&clientInfo.fileName); if(clientInfo.fileName == 0){ clientInfo.msg_type = -1 ; msgsnd(msgid, &clientInfo, sizeof(clientInfo), 1); sleep(1); break; } } close(sock); msgctl(rpid,IPC_RMID,NULL); shmdt(shm); printf("Client has detached its shared memory... msgid %i\n", msgid); exit(0); }
C
/* * $Id: kkern.c,v 1.2 1996/05/01 12:08:38 gunter Exp $ * * $Log: kkern.c,v $ * Revision 1.2 1996/05/01 12:08:38 gunter * Replace several strcpy by memmove * * Revision 1.1.1.1 1996/03/08 15:32:57 mclareni * Kuip * */ /*CMZ : 2.06/03 09/01/95 10.05.13 by N.Cremel*/ /*-- Author : Alfred Nathaniel 07/08/92*/ /* kkern.c */ #include "kuip/kuip.h" /* * On some systems, e.g. IBM C/370, realloc() becomes very expensive if * there are a lot of allocated blocks and the number of bytes spills into * a different bucket size. We can lessen the effect by allocating for * string operations (strdup(), mstrcat()), a larger initial block size * in order to make realloc() effectively a null operation. */ #ifndef ALLOC_MIN_BYTES # define ALLOC_MIN_BYTES 1 #endif /* * return length of Fortran string ignoring trailing blanks */ size_t fstrlen( const char *str, size_t len ) { int *p; static int blanks = 0; if( len >= (sizeof blanks) * 4 ) { /* check single characters until next word boundary */ /* use type long here to be conform with 64 bit architectures*/ switch( (long)&str[len] & ( (sizeof blanks) - 1 ) ) { case 7: if( str[--len] != ' ' ) return len + 1; case 6: if( str[--len] != ' ' ) return len + 1; case 5: if( str[--len] != ' ' ) return len + 1; case 4: if( str[--len] != ' ' ) return len + 1; case 3: if( str[--len] != ' ' ) return len + 1; case 2: if( str[--len] != ' ' ) return len + 1; case 1: if( str[--len] != ' ' ) return len + 1; } if( blanks == 0 ) memset( (char*)&blanks, ' ', (sizeof blanks) ); /* check for full words of blanks */ for( p = (int*)&str[len]; len >= (sizeof blanks) && *--p == blanks; ) len -= (sizeof blanks); } /* check single characters again */ while( len > 0 && str[len-1] == ' ' ) len--; return len; } /* * copy Fortran string to allocated memory stripping trailing blanks */ char *fstrdup( const char *str, size_t len ) { return strndup( str, fstrlen( str, len ) ); } /* * like fstrdup() but return NULL if string is empty */ char *fstr0dup( const char *str, size_t len ) { size_t n = fstrlen( str, len ); if( n == 0 ) return NULL; return strndup( str, n ); } /* * like fstrdup() but trim leading blanks */ char *fstrtrim( const char *str, size_t len ) { while( len > 0 && *str == ' ' ) { len--; str++; } return fstrdup( str, len ); } /* * like fstr0dup() but trim leading blanks */ char *fstr0trim( const char *str, size_t len ) { while( len > 0 && *str == ' ' ) { len--; str++; } return fstr0dup( str, len ); } /* * assign a Fortran string and return the logical length */ size_t fstrset( char *str, size_t len, const char *cstr ) { size_t n = 0; size_t i; memset( str, ' ', len ); if( cstr != NULL ) { for( i = 0; i < len && cstr[i] != '\0'; i++ ) { if( (str[i] = cstr[i]) != ' ' ) n = i + 1; } #if 0 Unfortunately we cannot do this test for truncation because KUGETC/S is sometimes called with a short dummy string to load things for KUGETL if( cstr[i] != '\0' ) { while( cstr[i] == ' ' ) i++; if( cstr[i] != '\0' ) { printf( " *** A character parameter has been defined with insufficient length = %d\n", len ); } } #endif } return n; } /* * create a Fortran string array from a pointer array */ char *fstrvec( char **pstr, size_t n, size_t *mlen ) { char *fstr; if( n > 0 ) { int *plen = (int*)calloc( n, sizeof(int) ); int len = 1; int nlen; int i; for( i = 0; i < n; i++ ) { if( pstr[i] != NULL ) { plen[i] = strlen( pstr[i] ); if( plen[i] > len ) len = plen[i]; } } /* vector elements are padded to multiple of 8 */ *mlen = len = ((len - 1) / 8 + 1 ) * 8; nlen = n * len; fstr = malloc( nlen + 1 ); memset( fstr, ' ', nlen ); fstr[nlen] = '\0'; for( i = 0; i < n; i++ ) { if( plen[i] > 0 ) { memcpy( fstr + i * len, pstr[i], plen[i] ); } } free( (char*)plen ); } else { int nlen = 8; fstr = malloc( nlen + 1 ); memset( fstr, ' ', nlen ); fstr[nlen] = '\0'; } return fstr; } /* * like strtod() but (*tail != '\0') can be used to test for bad numbers * trailing blanks are ignored */ double fstrtod( const char *str, char **tail ) { double value = strtod( str, tail ); const char *ptail = *tail; if( *str == '\0' || ( ptail == str + 1 && !isdigit( str[0] ) ) ) { /* * in case str == "" * and stupid VMS RTL accepts "+" and "-" as valid numbers */ *tail = "error"; } else if( ptail != str ) { while( **tail == ' ' ) (*tail)++; /* ignore trailing blanks */ } return value; } /* * like strtol() but (*tail != '\0') can be used to test for bad numbers * trailing blanks are ignored */ int fstrtoi( const char *str, char **tail ) { int value = strtol( str, tail, 10 ); const char *ptail = *tail; if( *str == '\0' ) { *tail = "error"; } else if( ptail != str ) { while( **tail == ' ' ) (*tail)++; /* ignore trailing blanks */ } return value; } /* * convert double value into string representation with prec significant digits * equivalent to "%G" which behaves improperly on VAX/VMS */ char *strfromd( double dval, size_t prec ) { static char buffer[32]; char *digit = "0123456789"; char *p = buffer; double round = 5; double d; int i; if( dval == 0 ) return "0"; if( prec <= 0 ) prec = 6; for( i = 0; i < prec; i++ ) round *= 0.1; if( dval < 0 ) { *p++ = '-'; dval = -dval; } d = dval; while( d < 1 ) { d *= 10; round *= 0.1; } while( d >= 10 ) { d *= 0.1; round *= 10; } dval += round; if( dval < 1 && dval >= 0.0001 ) { *p++ = '0'; *p++ = '.'; while( dval < 0.1 ) { *p++ = '0'; dval *= 10; } for( i = 0; i < prec; i++ ) { int ival; dval *= 10; ival = dval; *p++ = digit[ival]; dval -= ival; } while( p[-1] == '0' ) p--; if( p[-1] == '.' ) p--; } else { int nexp = 0; int ndot = 0; if( dval >= 1000000 ) { while( dval >= 10 ) { dval *= 0.1; nexp++; } } while( dval < 1 ) { dval *= 10; nexp--; } while( dval >= 10 ) { dval *= 0.1; ndot++; } for( i = 0; i < prec; i++ ) { int ival = dval; *p++ = digit[ival]; if( i == ndot ) *p++ = '.'; dval = (dval - ival) * 10; } if( ndot < prec ) { while( p[-1] == '0' ) p--; } if( p[-1] == '.' ) p--; if( nexp != 0 ) { *p++ = 'E'; if( nexp < 0 ) { *p++ = '-'; nexp = -nexp; } else *p++ = '+'; if( nexp >= 100 ) { *p++ = digit[nexp/100]; nexp %= 100; } *p++ = digit[nexp/10]; *p++ = digit[nexp%10]; } } *p = '\0'; return buffer; } /* * convert int value into string representation with prec significant digits * equivalent to "%.<n>d" which behaves improperly on VAX/VMS */ char *strfromi( int ival, size_t prec ) { static char buffer[3][32]; static int nbuf = 0; char *p; int n; int i; if( ++nbuf >= 3 ) nbuf = 0; p = buffer[nbuf]; if( ival < 0 ) { *p++ = '-'; ival = -ival; } n = ival; while( n >= 10 ) { n /= 10; prec--; } for( i = 0; i < prec - 1; i++ ) *p++ = '0'; sprintf( p, "%d", ival ); return buffer[nbuf]; } #ifndef HAVE_MEMMOVE /* * memory move with possible overlap */ void *memmove( void *vdst, const void *vsrc, size_t n ) { char *dst = (char*)vdst; const char *src = (char*)vsrc; if( dst != src && n > 0 ) { if( dst > src && src + n < dst ) { while( n > 0 ) { n--; dst[n] = src[n]; } } else memcpy( dst, src, n ); } return dst; } #endif #ifndef HAVE_STRCASECMP /* * case insensitive string compare */ int strcasecmp( const char *str1, const char *str2 ) { return strncasecmp( str1, str2, strlen( str2 ) + 1 ); } /* * case insensitive string compare of n characters */ int strncasecmp( const char *str1, const char *str2, size_t n ) { while( n > 0 ) { int c1 = *str1; int c2 = *str2; if( isupper( c1 ) ) c1 = tolower( c1 ); if( isupper( c2 ) ) c2 = tolower( c2 ); if( c1 != c2 ) return c1 - c2; str1++; str2++; n--; } return 0; } #endif /* * find last occurence of anyone character */ char *strrpbrk( const char *str1, const char *str2 ) { char *p = strpbrk( str1, str2 ); if( p != NULL ) { char *s; while( (s = strpbrk( p + 1, str2 )) != NULL ) p = s; } return p; } #ifndef HAVE_STRRSTR /* * find last occurence of substring */ char *strrstr( const char *str1, const char *str2 ) { if( str1 == NULL || str2 == NULL ) return NULL; else if( *str2 == '\0' ) return (char*)str1; else { char *p = strstr( str1, str2 ); if( p != NULL ) { char *s; while( (s = strstr( p + 1, str2 )) != NULL ) p = s; } return p; } } #endif /* * copy string to allocated memory */ char *Strdup( const char *str ) { size_t bytes = strlen( str ) + 1; if( bytes < ALLOC_MIN_BYTES ) bytes = ALLOC_MIN_BYTES; return strcpy( malloc( bytes ), str ); } /* * like strdup() but return NULL if string is NULL or "" */ char *str0dup( const char *str ) { if( str == NULL || str[0] == '\0' ) return NULL; return Strdup( str ); } /* * like strdup() but string is n characters long and not terminated */ char *strndup( const char *str, size_t len ) { size_t bytes = len + 1; char *p; if( bytes < ALLOC_MIN_BYTES ) bytes = ALLOC_MIN_BYTES; p = strncpy( malloc( bytes ), str, len ); p[len] = '\0'; return p; } /* * strdup() of character representation of integer n */ char *stridup( int n ) { char buf[16]; sprintf( buf, "%d", n ); return Strdup( buf ); } /* * like strdup() but concatenate two strings */ char *str2dup( const char *str1, const char *str2 ) { return mstrcat( Strdup( str1 ), str2 ); } /* * like strdup() but concatenate three strings */ char *str3dup( const char *str1, const char *str2, const char *str3 ) { return mstr2cat( Strdup( str1 ), str2, str3 ); } /* * like strdup() but concatenate four strings */ char *str4dup( const char *str1, const char *str2, const char *str3, const char *str4 ) { return mstr3cat( Strdup( str1 ), str2, str3, str4 ); } /* * like strdup() but concatenate five strings */ char *str5dup( const char *str1, const char *str2, const char *str3, const char *str4, const char *str5 ) { return mstr4cat( Strdup( str1 ), str2, str3, str4, str5 ); } /* * concatenate two strings if the first one is allocated */ char *mstrcat( char *str1, const char *str2 ) { if( str1 == NULL ) return Strdup( str2 ); else { size_t len1 = strlen( str1 ); size_t len2 = strlen( str2 ); size_t bytes = len1 + len2 + 1; if( bytes < ALLOC_MIN_BYTES ) bytes = ALLOC_MIN_BYTES; str1 = realloc( str1, bytes ); strcpy( &str1[len1], str2 ); return str1; } } /* * like mstrcat() but concatenate three strings */ char *mstr2cat( char *str1, const char *str2, const char *str3 ) { return mstrcat( mstrcat( str1, str2 ), str3 ); } /* * like mstrcat() but concatenate four strings */ char *mstr3cat( char *str1, const char *str2, const char *str3, const char *str4 ) { return mstr2cat( mstrcat( str1, str2 ), str3, str4 ); } /* * like mstrcat() but concatenate five strings */ char *mstr4cat( char *str1, const char *str2, const char *str3, const char *str4, const char *str5 ) { return mstr3cat( mstrcat( str1, str2 ), str3, str4, str5 ); } /* * like mstrcat() but the second string is not terminated */ char *mstrncat( char *str1, const char *str2, size_t len2 ) { if( len2 > 0 ) { size_t len1 = strlen( str1 ); size_t bytes = len1 + len2 + 1; if( bytes < ALLOC_MIN_BYTES ) bytes = ALLOC_MIN_BYTES; str1 = realloc( str1, bytes ); strncpy( &str1[len1], str2, len2 ); str1[len1+len2] = '\0'; } return str1; } /* * append n times the character c to the allocated string */ char *mstrccat( char *str, char c, size_t n ) { if( n > 0 ) { size_t len = strlen( str ); size_t bytes = len + n + 1; if( bytes < ALLOC_MIN_BYTES ) bytes = ALLOC_MIN_BYTES; str = realloc( str, bytes ); while( n-- > 0 ) str[len++] = c; str[len] = '\0'; } return str; } /* * append the string representation of an integer to the allocated string */ char *mstricat( char *str, int n ) { char nstr[16]; sprintf( nstr, "%d", n ); return mstrcat( str, nstr ); } /* * find the maximum string length in an array of strings * if n == 0 the array is NULL terminated */ size_t mstrlen( char **str, size_t n ) { size_t nmax = (n != 0) ? n : (~0 >> 1); size_t mlen = 0; int i; for( i = 0; i < nmax; i++ ) { if( str[i] != NULL ) { size_t len = strlen( str[i] ); if( len > mlen ) mlen = len; } else if( n == 0 ) break; } return mlen; } /* * protect blanks inside quoted strings and do strtok( str, " " ) */ char *strqtok( char *str ) { char *tok; char *p; if( str != NULL ) { int quoted = 0; for( p = str; *p != '\0'; p++ ) { if( *p == '\'' ) quoted = !quoted; else if( *p == ' ' && quoted ) *p = '\n'; } } tok = strtok( str, " " ); if( tok != NULL ) { for( p = tok; *p != '\0'; p++ ) { if( *p == '\n' ) *p = ' '; } } return tok; } /* * convert a string to lowercase in place */ char *strlower( char *str ) { if( str != NULL ) { char *p; for( p = str; *p != '\0'; p++ ) if( isupper( *p ) ) *p = tolower( *p ); } return str; } /* * convert a string to uppercase in place */ char *strupper( char *str ) { if( str != NULL ) { char *p; for( p = str; *p != '\0'; p++ ) if( islower( *p ) ) *p = toupper( *p ); } return str; } /* * trim leading and trailing blanks */ char *strtrim( char *str ) { int n = strlen( str ); while( n > 0 && str[n-1] == ' ' ) n--; str[n] = '\0'; for( n = 0; str[n] == ' '; ) n++; if( n > 0 ) memmove( str, str + n, strlen(str+n) + 1); /* Overlapping, use memmove strcpy( str, str + n );*/ return str; } /* * replace tabs by an equivalent number of blanks and remove trailing blanks * argument string must be malloced */ char *struntab( char *line ) { char *p; int i; while( (p = strchr( line, '\t' )) != NULL ) { int n = p - line; char *newline = strndup( line, n ); newline = mstrccat( newline, ' ', 8 - n % 8 ); newline = mstrcat( newline, p + 1 ); free( line ); line = newline; } for( i = strlen( line ); i > 0; i-- ) { if( line[i-1] != ' ' && line[i-1] != '\n' ) { break; } } line[i] = '\0'; return line; } /* * replace blanks inside a string with '0' */ char *strblk0( char *str ) { int i; for( i = 0; i < strlen( str ); i++) { if (str[i] == ' ') str[i] = '0'; } return str; } /* * Calculate a 32-bit checksum for the file content. */ int checksum( const char *path ) { static int bogus_crc = 0x12345678; FILE *stream = fopen( path, "r" ); if( stream != NULL ) { unsigned crc = 0; int c; while( (c = getc( stream )) != EOF ) { int carry = crc & 1; crc = ( ( crc >> 1 ) & 0x7FFFFFFF ) + ( c & 0xFF ); if( carry ) crc |= 0x80000000; } fclose( stream ); return crc; } return ++bogus_crc; } #ifdef IBM370 /* * return dummy process id */ int getpid() { return 1; } #endif #ifdef IBMVM /* * copy file modification date into stamp buffer */ int get_stamp( path, stamp ) char *path; TimeStamp *stamp; { FILE *stream; char cmd[120]; char *p; sprintf( cmd, "LISTFILE %s (DATE EXEC", path ); while( (p = strchr( cmd, '.' )) != NULL ) *p = ' '; if( system( cmd ) == 0 && (stream = fopen( "CMS.EXEC", "r" )) != NULL && fgets( cmd, (sizeof cmd), stream ) != NULL ) { fclose( stream ); remove( "CMS.EXEC" ); strncpy( *stamp, cmd + 63, 17 ); (*stamp)[17] = '\0'; return 0; } return -1; } #endif #ifdef NEED_STRDUP # ifdef strdup # undef strdup # endif char *strdup( const char* str ) { return Strdup( str ); } #endif
C
/*** PROBLEM STATEMENT Multiply two matrices using a fucntion and pass two input matrices as parameter of the fucntion Input Format n1 = enter number of rows in 1st matrix n2 = enter number of rows in 2nd matrix m1 = enter number of columns in 1st matrix m2 = enter number of columns in 2nd matrix a = enter the 1st matrix b = enter the 2nd matrix Constraints 2<=n1,n2,m1,m3<=10 Output Format print the output Sample Input 0 2 2 2 2 1 2 2 1 2 4 1 2 Sample Output 0 4 8 5 10 ***/ #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> void mul(int a[10][10], int b[10][10], int n1, int m1, int m2) { int mult[10][10]; for (int i = 0; i < n1; ++i) { for (int j = 0; j < m2; ++j) { mult[i][j] = 0; for (int k = 0; k < m1; ++k) { mult[i][j] += a[i][k] * b[k][j]; } } } for (int i = 0; i < n1; i++) { for (int j = 0; j < m2; j++) { printf("%d ", mult[i][j]); } printf("\n"); } } int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int a[10][10], b[10][10], m1, n1, m2, n2; scanf("%d%d%d%d", &n1, &n2, &m1, &m2); for (int i = 0; i < n1; i++) { for (int j = 0; j < m1; j++) { scanf("%d", &a[i][j]); } } for (int i = 0; i < n2; i++) { for (int j = 0; j < m2; j++) { scanf("%d", &b[i][j]); } } mul(a, b, n1, m1, m2); return 0; }
C
#include "gfx/libaria/inc/libaria_editwidget.h" #include "gfx/libaria/inc/libaria_context.h" #include "gfx/libaria/inc/libaria_string.h" static laResult startEdit(laEditWidget* edit) { return LA_FAILURE; } static void endEdit(laEditWidget* edit) { } static void clear(laEditWidget* edit) { } static void accept(laEditWidget* edit) { } static void set(laEditWidget* edit, laString str) { } static void append(laEditWidget* edit, laString str) { } static void backspace(laEditWidget* edit) { } void _laEditWidget_Constructor(laEditWidget* edit) { _laWidget_Constructor((laWidget*)edit); edit->widget.editable = LA_TRUE; edit->startEdit = &startEdit; edit->endEdit = &endEdit; edit->clear = &clear; edit->accept = &accept; edit->append = &append; edit->set = &set; edit->backspace = &backspace; } void _laEditWidget_Destructor(laEditWidget* edit) { if(edit == NULL) return; _laWidget_Destructor((laWidget*)edit); } laResult laEditWidget_StartEdit() { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return LA_FAILURE; return edit->startEdit(edit); } void laEditWidget_EndEdit() { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return; edit->endEdit(edit); } void laEditWidget_Clear() { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return; edit->clear(edit); } void laEditWidget_Accept() { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return; edit->accept(edit); } void laEditWidget_Set(laString str) { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return; edit->set(edit, str); } void laEditWidget_Append(laString str) { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return; edit->append(edit, str); } void laEditWidget_Backspace() { laEditWidget* edit = laContext_GetEditWidget(); if(edit == NULL) return; edit->backspace(edit); }
C
#include <stdio.h> #include <stdlib.h> #include "compression.h" int main (int argc, char **argv){ FILE *file, *file2; file = fopen(argv[1], "rb"); file2 = fopen(argv[2], "wb"); //incrementNbits(512); if(!file || !file2){ fprintf(stderr, "Error : file is inaccessible.\n"); return 1; } else{ compress(file, file2); fclose(file); fclose(file2); } return 0; }
C
#include <CUnit/CUnit.h> #include <CUnit/Basic.h> #include <CUnit/Automated.h> #include <time.h> #include <stdlib.h> #include <stdio.h> #include <mergesort.h> void test_merge_sort_simple() { int array[] = {14, 33, 27, 10, 35, 19, 42, 44}; int length = sizeof(array) / sizeof(int); merge_sort(array, 0, length - 1); for (int i = 1; i < length; i++) { CU_ASSERT_TRUE(array[i - 1] < array[i]); } } void test_merge_sort_single() { int single_element_array[1] = {1}; int length = sizeof(single_element_array) / sizeof(int); merge_sort(single_element_array, 0, length - 1); CU_ASSERT_EQUAL(single_element_array[0], 1); } void test_merge_sort_sorted() { int sorted_array[] = {1, 2, 15, 45, 59, 65, 112, 545}; int length = sizeof(sorted_array) / sizeof(int); merge_sort(sorted_array, 0, length - 1); for (int i = 1; i < length; i++) { CU_ASSERT_TRUE(sorted_array[i - 1] < sorted_array[i]); } int sorted_array_reverse[] = {545, 112, 65, 59, 45, 15, 2, 1}; merge_sort(sorted_array_reverse, 0, length - 1); for (int i = 1; i < length; i++) { CU_ASSERT_TRUE(sorted_array_reverse[i - 1] < sorted_array_reverse[i]); } } void test_merge_sort_dupes() { int array_with_dupes[] = {54, 8, 34, 6, 8, 13, 15}; int length = sizeof(array_with_dupes) / sizeof(int); merge_sort(array_with_dupes, 0, length - 1); for (int i = 1; i < length; i++) { CU_ASSERT_TRUE(array_with_dupes[i - 1] <= array_with_dupes[i]); } int array_with_same[] = {42, 42, 42, 42, 42, 42, 42}; length = sizeof(array_with_same) / sizeof(int); merge_sort(array_with_same, 0, length - 1); for (int i = 1; i < length; i++) { CU_ASSERT_TRUE(array_with_same[i - 1] == array_with_same[i]); } } void test_merge_sort_random() { int array[50]; srand(time(NULL)); for (int i = 0; i < 50; i++) { array[i] = rand() % 512; } merge_sort(array, 0, 49); for (int i = 1; i < 50; i++) { CU_ASSERT_TRUE(array[i - 1] <= array[i]); } } int main(int argc, char *argv[]) { CU_initialize_registry(); CU_pSuite mergesort = CU_add_suite("Testing merge sort", NULL, NULL); CU_add_test(mergesort, "Simple", test_merge_sort_simple); CU_add_test(mergesort, "Single", test_merge_sort_single); CU_add_test(mergesort, "Sorted", test_merge_sort_sorted); CU_add_test(mergesort, "Dupes", test_merge_sort_dupes); CU_add_test(mergesort, "Random", test_merge_sort_random); CU_basic_run_tests(); CU_cleanup_registry(); return CU_get_error(); }
C
/* ==== test_create.c ============================================================ * Copyright (c) 1993 by Chris Provenzano, proven@athena.mit.edu * * Description : Test pthread_create() and pthread_exit() calls. * * 1.00 93/08/03 proven * -Started coding this file. */ #define PTHREAD_KERNEL #include <pthread.h> #include <stdio.h> #include "utils.h" void* new_thread(void* arg) { int i; printf("New thread was passed arg address %x\n", arg); printf("New thread stack at %x\n", &i); return(NULL); PANIC(); } main() { pthread_t thread; int i; printf("Original thread stack at %x\n", &i); if (pthread_create(&thread, NULL, new_thread, (void *)0xdeadbeef)) { printf("Error: creating new thread\n"); } pthread_exit(NULL); PANIC(); } 
C
/* Copyright (C) 2014 Frank Duignan 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "console.h" #include <stdio.h> // contains definitions for putchar, getchar void eputc(char c) { putchar(c); } void eputs(const char *String) { while(*String) { eputc(*String); String++; } } char egetc() { char input; input = getchar(); return input; } void printString(const char *String) { eputs(String); eputs("\r\n"); } char HexDigit(int Value) { if ((Value >=0) && (Value < 10)) return Value+'0'; else return Value-10 + 'A'; } void printHex(unsigned int Number) { // Output the number over the serial port as // as hexadecimal string. char TxString[9]; int Index=8; TxString[Index]=0; // terminate the string Index--; while(Index >=0) { TxString[Index]=HexDigit(Number & 0x0f); Number = Number >> 4; Index--; } eputs(TxString); }
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 symbol {scalar_t__ type; } ; struct gstr {unsigned int max_width; char* s; } ; /* Variables and functions */ scalar_t__ S_UNKNOWN ; int /*<<< orphan*/ str_append (struct gstr*,char const*) ; int /*<<< orphan*/ str_printf (struct gstr*,char*,char const*) ; int strlen (char const*) ; char* strrchr (char*,char) ; char* sym_get_string_value (struct symbol*) ; __attribute__((used)) static void expr_print_gstr_helper(void *data, struct symbol *sym, const char *str) { struct gstr *gs = (struct gstr*)data; const char *sym_str = NULL; if (sym) sym_str = sym_get_string_value(sym); if (gs->max_width) { unsigned extra_length = strlen(str); const char *last_cr = strrchr(gs->s, '\n'); unsigned last_line_length; if (sym_str) extra_length += 4 + strlen(sym_str); if (!last_cr) last_cr = gs->s; last_line_length = strlen(gs->s) - (last_cr - gs->s); if ((last_line_length + extra_length) > gs->max_width) str_append(gs, "\\\n"); } str_append(gs, str); if (sym && sym->type != S_UNKNOWN) str_printf(gs, " [=%s]", sym_str); }
C
#include <ignotum.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <fcntl.h> #include <sys/mman.h> void test2(void){ ignotum_search_t search; ignotum_maplist_t list; ignotum_mapinfo_t *map; off_t addr; size_t i; /* alloc two pages next to each other */ char *ptr = mmap((void *)0xd34d0000, 0x1000, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_FIXED|MAP_PRIVATE, -1, 0); /* different permissions to differ the maps, * maybe fail in a hardened system */ char *ptr2 = mmap((void *)0xd34d1000, 0x1000, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_ANONYMOUS|MAP_FIXED|MAP_PRIVATE, -1, 0); if(ptr == MAP_FAILED || ptr2 == MAP_FAILED){ printf("failed to mmap()\n"); return; } /* make the string avaliable in two differents map */ memcpy(ptr+0x1000-10, "0123456789abcdef", 16); /* 0 = current pid */ ignotum_getmaplist(&list, 0); /* set string to search */ ignotum_search_init(&search, "0123456789abcdef", 16); for(i=0; i<list.len; i++){ map = list.maps + i; /* only read memory that can be read, * and isn't associated with a file */ if(!map->is_r || map->pathname) continue; printf("searching %lx-%lx\n", map->start_addr, map->end_addr, map->pathname); if(ignotum_search_loop(&search, &addr, map->start_addr, (void *)map->start_addr, map->end_addr-map->start_addr) == IGNOTUM_FOUND){ printf("string found at: %lx\n", addr); } } free_ignotum_maplist(&list); } int main(void){ ignotum_search_t search; ignotum_mapinfo_t map; size_t len, i; off_t addr; char *aux; char test[]="abcdefghijklmnopq ------ leet --------"; printf("char test[] = %p\n", test); /* 0 = current pid */ ignotum_getmapbyaddr(&map, 0, (off_t)test); len = map.end_addr - map.start_addr; aux = (char *)map.start_addr; ignotum_search_init(&search, "abcdefghijklmnopq ------ leet", 29); if(ignotum_search_loop(&search, &addr, map.start_addr, aux, len) != IGNOTUM_FOUND){ printf("[error] not found ...\n"); } else { printf("string found at addr: %lx | %s\n", addr, (char *)addr); } /* circular search */ ignotum_search_init(&search, "------ leet", 11); for(i=0; i<len; i+=4){ if(ignotum_search_loop(&search, &addr, map.start_addr, aux+i, 4) == IGNOTUM_FOUND){ printf("string found at addr: %lx | %s\n", addr, (char *)addr); break; } /* you must ever update the virtual address or the not will match */ map.start_addr += 4; } free(map.pathname); printf("\n----- test2 -----\n"); test2(); return 0; }
C
/* Test dynamic refcount and copy behavior of separate structure members. */ #include <assert.h> #include <stdbool.h> #include <openacc.h> struct s { signed char a; float b; }; static void test(unsigned variant) { struct s s = { .a = 73, .b = -22 }; #pragma acc enter data copyin(s.a, s.b) assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); /* To verify that any following 'copyin' doesn't 'copyin' again. */ s.a = -s.a; s.b = -s.b; if (variant & 4) { if (variant & 8) { #pragma acc enter data copyin(s.b) } else acc_copyin(&s.b, sizeof s.b); assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); if (variant & 16) { #pragma acc enter data copyin(s.a) } else acc_copyin(&s.a, sizeof s.a); assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); if (variant & 32) { #pragma acc enter data copyin(s.a) acc_copyin(&s.b, sizeof s.b); #pragma acc enter data copyin(s.b) #pragma acc enter data copyin(s.b) acc_copyin(&s.a, sizeof s.a); acc_copyin(&s.a, sizeof s.a); acc_copyin(&s.a, sizeof s.a); } assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); } #pragma acc parallel \ copy(s.a, s.b) { #if ACC_MEM_SHARED if (s.a++ != -73) __builtin_abort(); if (s.b-- != 22) __builtin_abort(); #else if (s.a++ != 73) __builtin_abort(); if (s.b-- != -22) __builtin_abort(); #endif } #if ACC_MEM_SHARED assert(s.a == -72); assert(s.b == 21); #else assert(s.a == -73); assert(s.b == 22); #endif if (variant & 32) { if (variant & 1) { #pragma acc exit data copyout(s.a) finalize } else acc_copyout_finalize(&s.a, sizeof s.a); } else { if (variant & 1) { #pragma acc exit data copyout(s.a) } else acc_copyout(&s.a, sizeof s.a); if (variant & 4) { assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); #if ACC_MEM_SHARED assert(s.a == -72); assert(s.b == 21); #else assert(s.a == -73); assert(s.b == 22); #endif if (variant & 1) { #pragma acc exit data copyout(s.a) } else acc_copyout(&s.a, sizeof s.a); } } #if ACC_MEM_SHARED assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); assert(s.a == -72); assert(s.b == 21); #else assert(!acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); assert(s.a == 74); assert(s.b == 22); #endif if (variant & 32) { if (variant & 2) { #pragma acc exit data copyout(s.b) finalize } else acc_copyout_finalize(&s.b, sizeof s.b); } else { if (variant & 2) { #pragma acc exit data copyout(s.b) } else acc_copyout(&s.b, sizeof s.b); if (variant & 4) { #if ACC_MEM_SHARED assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); assert(s.a == -72); assert(s.b == 21); #else assert(!acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); assert(s.a == 74); assert(s.b == 22); #endif if (variant & 2) { #pragma acc exit data copyout(s.b) } else acc_copyout(&s.b, sizeof s.b); } } #if ACC_MEM_SHARED assert(acc_is_present(&s.a, sizeof s.a)); assert(acc_is_present(&s.b, sizeof s.b)); assert(s.a == -72); assert(s.b == 21); #else assert(!acc_is_present(&s.a, sizeof s.a)); assert(!acc_is_present(&s.b, sizeof s.b)); assert(s.a == 74); assert(s.b == -23); #endif } int main() { for (unsigned variant = 0; variant < 64; ++variant) test(variant); return 0; }
C
#include <stdio.h> int main() { int a; for(a=0;a<=255;a++) { printf("The value of ASCII of %c is %d\n", a, a); } return 0; }
C
/** * Author: Kothar Al Naamani * Date: 2020/08/20 * * A simple hello world program in C */ #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { printf ("Kothar Al Naamani!\n"); printf("Civil Engineering!\n"); printf ("Lawand Anwer!\n"); printf("Computer Science!\n"); return 0; }
C
#include <stdlib.h> extern char *getenv(const char *name); extern int foo(); extern int bar(); struct s3 { int i1; int i2; char *t3; }; struct s2 { int i1; char *t2; struct s3 s3; }; struct s1 { char *t1; struct s2 s2; }; int main() { struct s1 s1; s1.s2.s3.t3 = getenv("gude"); s1.s2.t2 = s1.s2.s3.t3; struct s3 s31 = s1.s2.s3; char *t1 = s31.t3; struct s3 s32; s31 = s32; char *nt1 = s31.t3; struct s2 *s21 = &s1.s2; char *t2 = s21->s3.t3; char *t3 = s21->t2; int nt2 = s21->i1; struct s2 **s22 = &s21; char *t4 = (*s22)->s3.t3; char *t5 = (*s22)->t2; *s22 = NULL; char *nt3 = (*s22)->s3.t3; char *nt4 = (*s22)->t2; return 0; }
C
#include<stdio.h> int main() { int _=10; //underscore_character is use as variable printf("%d\n",_); return 0; } /*OUTPUT 10 */
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <string.h> #include <ctype.h> char input[1024]; int input_Pos = 0; char buff[1024]; int buff_Pos = 0; void lex() { // Token 을 짤라서 buff[] 에 넣어주는 함수 memset(buff, 0, sizeof(buff)); buff_Pos = 0; while (isspace(input[input_Pos])) { input_Pos++; } while (!isspace(input[input_Pos]) && input[input_Pos] != 0) { buff[buff_Pos] = input[input_Pos]; buff_Pos++; input_Pos++; } } int perm(char * buff){ int result=0; // case - 문자로 지정하는 경우 if(strlen(buff)==9){ for(int i=0;i<3;i++){ if(buff[3*i] == 'r'){ result |= (S_IRUSR >> i*3); } if(buff[3*i+1] == 'w'){ result |= (S_IWUSR >> i*3); } if(buff[3*i+2] == 'x'){ result |= (S_IXUSR >> i*3); } } } // case - 8진법으로 지정하는 경우 else if(strlen(buff)==3){ result = strtol(buff,NULL,8); } return result; } int main(){ struct stat st; int mode = 0; gets(input); lex(); if(!strcmp(buff,"mychmod")){ // get next token lex(); mode = perm(buff); lex(); if(lstat(buff,&st) < 0){ perror(buff); exit(1); } chmod(buff,mode); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include <signal.h> /** * Simple implementation of the siginterrupt */ int siginterrupt(int sig, int flag) { struct sigaction sa; // retrieve current sigaction if (sigaction(sig, NULL, &sa) == -1) return -1; if (flag) sa.sa_flags &= ~SA_RESTART; else sa.sa_flags |= SA_RESTART; // apply new sigaction return sigaction(sig, &sa, NULL); } /** * Driver program for siginterrupt */ int main(int argc, char* argv[]) { siginterrupt(SIGINT, 1); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> struct node { char data[1000]; char name[1000]; int marks; struct node* next; }; typedef struct node node; void print(node* p,node *p1) { node *q=p1; while(p) { int sum=0; printf("%s %s ",p->data,p->name); q=p1; while(q) { if(!strcmp(p->data, q->data)) { printf("%d ",q->marks); sum+=q->marks; } q=q->next; } printf("%d\n",sum); p=p->next; } } node *createlist() { int x,n,t; scanf("%d %d",&n,&t); node *head=NULL,*p,*q,*head2=NULL; while(n--) { char a[11],b[100]; scanf("%s %s",a,b); node *temp=(node *)malloc(sizeof(node)); strcpy(temp->data,a); strcpy(temp->name,b); temp->next=NULL; if(!head) { head=temp; } else { p=head; while(p->next) { p=p->next; } p->next=temp; } } while(t--) { char z[11]; int s; scanf("%s %d",z,&s); node *temp1=(node *)malloc(sizeof(node)); strcpy(temp1->data,z); temp1->marks=s; temp1->next=NULL; if(!head2) { head2=temp1; } else { q=head2; while(q->next) { q=q->next; } q->next=temp1; } } print(head,head2); } int main() { int tc; scanf("%d",&tc); while(tc--) { node *p=createlist(); } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <math.h> #define GOOD_EXIT 1 #define BAD_EXIT 0 #define MAX_INPUT 60 #define BEGINNING_LINE 0 #define SKIP_FIRST 2 //prototypes int processLine(char *input, int totVSize, int curVSize, float *vect, int startI); char * makeVectorString(float *nums, int totsize); void printVector(char * vect); int getVSize(char *input); float calcNorm(float *vect, int vSize); void normalizeVect(float *vect, float *normVect, float norm, int vSize); //getVSize //handles obtaining vector size from user //returns an integer of the vector size //takes in string input //may output BAD INPUT, specifying user error int getVSize(char *input) { int i = 0; //index for iterating thru input char num[MAX_INPUT] = " "; //string for storing digit characters int j = 0; //index for tracking num string int vSize = 0; //stores the index for size of vector //while the characters of input are digits loop thru //and store the char to num while ((input[i] > '0' && input[i] <= '9')) { num[j] = input[i]; j++; i++; } //if the character after looping is anything but a digit or space, //print bad input & return 0 if (!((input[i] > '0' && input[i] <= '9') || input[i] == 10 || input[i] == ' ')) { printf("BAD INPUT\n"); return 0; } else { vSize = atoi(num); if (vSize > 0 && vSize <= 9) { return vSize; } else { printf("BAD INPUT\n"); return 0; } } } //proccessLine //process the string input to convert information to vector data //returns integer of the current size of the vector //takes in a string input, integer of total vector size and current vector size, float array for vector, and integer of starting index for processing //may output BAD INPUT specifying user error int processLine(char *input, int totVSize, int curVSize, float *vect, int startI) { int i = startI; //tracks index of input while (i < strlen(input)) { //if input contains anything except [0-9+-. ] print BAD INPUT and return -1 specifying error if (!((input[i] >= '0' && input[i] <= '9') || input[i] == ' ' || input[i] == '+' || input[i] == '-' || input[i] == 10 || input[i] == '.')) { printf("BAD INPUT\n"); return -1; } char num[MAX_INPUT] = " "; //string to store appropriate characters for conversion to float int j=0; //index for iterating thru num string //while the input is only [0-9+-.] and end of string is not reached while (((input[i] >= '0' && input[i] <= '9') || input[i] == '+' || input[i] == '-'|| input[i] == 10 || input[i] == '.') && i < strlen(input)) { //add characters to num string num[j] = input[i]; j++; i++; } //if num is non-empty and current size < total size //convert num and add to vector, increment current size if (strcmp(num, " ") != 0 && curVSize < totVSize){ vect[curVSize] = atof(num); curVSize++; i--; } if (curVSize == totVSize) { return curVSize; } i++; } return curVSize; } //calcNorm //calculate norm (length) of specified vector //takes in array of floats and size //returns float representing norm float calcNorm(float *vect, int vSize) { int i = 0; //index for for-loop float tot; //float for tracking and holding norm for (i = 0; i < vSize; i++) { tot+=pow(vect[i], 2); } tot = sqrt(tot); return tot; } //normalizeVect //normalizes a vector //takes in a float array of orginal vector and normalize vector, float norm value, and int size of vector void normalizeVect(float *vect, float *normVect, float norm, int vSize) { int i = 0; for (i = 0; i < vSize; i++) { normVect[i] = (vect[i] / norm); } } //printVector //prints vector in specified format //takes in a vector in string form //outputs vector in proper format void printVector(char * vect) { printf("[%s]", vect); } //makeVectorString //converts a float array to string form //takes in float array and size of array //returns a string version of vector char* makeVectorString(float *nums, int totsize) { static char temp[MAX_INPUT * 2]; //string for storing output temp[0] = '\0'; //reset temp to empty int i=0; //index for for-loop for (i=0;i<totsize;i++) { char temp2[10]; //string that stores indivdual floats sprintf(temp2, "%.3f, ", nums[i]); strcat(temp, temp2); } //add null character to specify end temp[strlen(temp)-2] = '\0'; return temp; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #define MAX 2 #define MIN 1 struct stat file; //MAX = (file.st_blksize+34)/42; struct node { int count; int offset[MAX+1]; char word[MAX+1][26]; struct node *link[MAX+1]; }; struct meaning { char word[50]; char mean[150]; }; struct node *root = NULL; void writeToFile(char word[], char mean[]) { struct meaning m; FILE *fp; fp = fopen("dictionary.bin", "a+"); if (fp == NULL) { printf("meanings file not found\n"); return; } strcpy(m.word, word); strcpy(m.mean, mean); fwrite(&m, sizeof(struct meaning), 1, fp); fclose(fp); } struct node * createNode(char word[], char mean[], struct node *child, int num) { struct node *newNode; newNode = (struct node *) malloc(sizeof(struct node)); strcpy(newNode->word[1],word); newNode->count = 1; newNode->link[0] = root; newNode->link[1] = child; newNode->offset[1] = num; return newNode; } /* Places the word in appropriate position */ void addWordToNode(char word[],char mean[], int num, int pos, struct node *node, struct node *child) { int j; j = node->count; while (j > pos) { strcpy(node->word[j + 1], node->word[j]); node->link[j + 1] = node->link[j]; node->offset[j+1] = node->offset[j]; j--; } strcpy(node->word[j + 1], word); node->link[j + 1] = child; node->count++; node->offset[j+1] = num; } /* split the node */ void splitNode (char word[], char mean[], int *off, char **pword, int pos, struct node *node, struct node *child, struct node **newNode) { int median; int j; if (pos > MIN) median = MIN + 1; else median = MIN; *newNode = (struct node *) malloc(sizeof(struct node)); j = median + 1; while (j <= MAX) { strcpy((*newNode)->word[j - median], node->word[j]); (*newNode)->link[j - median] = node->link[j]; (*newNode)->offset[j - median] = node->offset[j]; j++; } node->count = median; (*newNode)->count = MAX - median; if (pos <= MIN) { addWordToNode(word,mean,*off, pos, node, child); } else { addWordToNode(word,mean,*off, pos - median, *newNode, child); } strcpy(*pword, node->word[node->count]); *off = node->offset[node->count]; (*newNode)->link[0] = node->link[node->count]; (*newNode)->offset[0] = node->offset[node->count]; node->count--; } /* sets the word in the node */ int setWordInNode(char word[], char mean[],int num, int *off, char **pword, struct node *node, struct node **child) { int pos; if (node == NULL) { *pword = word; *off = num; *child = NULL; return 1; } if (strcmp(word, node->word[1]) < 0) { pos = 0; } else { for (pos = node->count; (strcmp(word, node->word[pos]) < 0 && pos > 1); pos--); if (strcmp(word, node->word[pos]) == 0) { printf("Duplicates not allowed\n"); return 0; } } if (setWordInNode(word, mean, num,off, pword, node->link[pos], child)) { if (node->count < MAX) { addWordToNode(*pword,mean,*off, pos, node, *child); } else { splitNode(*pword, mean, off, pword, pos, node, *child, child); return 1; } } return 0; } /* insert word in B-Tree */ void insertion(char word[], char mean[], int num) { int flag; char *i; int off; struct node *child; flag = setWordInNode(word, mean,num, &off, &i, root, &child); if (flag) { root = createNode(i, mean, child, off); } } /*To modify meaning of word in dictionary*/ void modify(char word[],char mean[], int *pos, struct node *myNode) { if (!myNode) { return; } if (strcmp(word, myNode->word[1]) < 0) { *pos = 0; } else { for (*pos = myNode->count; (strcmp(word, myNode->word[*pos]) < 0 && *pos > 1); (*pos)--); if (strcmp(word, myNode->word[*pos]) == 0) { FILE *fp; struct meaning m; strcpy(m.word, word); strcpy(m.mean, mean); fp = fopen("dictionary.bin","r+"); if (fp == NULL) { printf("meanings file not found\n"); return; } fseek(fp,sizeof(struct meaning)*myNode->offset[*pos],SEEK_SET); fwrite(&m, sizeof(struct meaning), 1, fp); fclose(fp); return; } } modify(word,mean, pos, myNode->link[*pos]); return; } /* search word in B-Tree */ void search(char word[], int *pos, struct node *myNode) { if (!myNode) { return; } if (strcmp(word, myNode->word[1]) < 0) { *pos = 0; //printf("%s\n",myNode->word[*pos]); } else { for (*pos = myNode->count; (strcmp(word, myNode->word[*pos]) < 0 && *pos > 1); (*pos)--); /*{ printf("%s\n",myNode->word[*pos]); }*/ if (strcmp(word, myNode->word[*pos]) == 0) { printf("\nThe meaning of word %s is:", myNode->word[*pos]); //printf("Offset = %d",myNode->offset[*pos]); FILE *fp; struct meaning m; fp = fopen("dictionary.bin","r"); fseek(fp,sizeof(struct meaning)*myNode->offset[*pos],SEEK_SET); fread(&m,sizeof(struct meaning),1,fp); printf("%s\n",m.mean); fclose(fp); return; } } //printf("%s\n",myNode->word[*pos]); search(word, pos, myNode->link[*pos]); return; } /* B-Tree Traversal */ void Print(struct node *myNode) { int i; if (myNode) { for (i = 0; i < myNode->count; i++) { Print(myNode->link[i]); printf("%s:", myNode->word[i + 1]); FILE *fp; struct meaning m; fp = fopen("dictionary.bin","r"); fseek(fp,sizeof(struct meaning)*myNode->offset[i+1],SEEK_SET); fread(&m,sizeof(struct meaning),1,fp); printf("%s\n",m.mean); fclose(fp); } Print(myNode->link[i]); } } int Load(int num) { FILE *fp; struct meaning m; fp = fopen("dictionary.bin","r"); if (fp == NULL) { printf("meanings file not found\n"); return 0; } while(fread(&m,sizeof(struct meaning),1,fp)) { insertion(m.word,m.mean,num++); //printf("%s:%s:%d,",m.word,m.mean,num); } fclose(fp); return num; } int main() { int ch; int num = 0; char word[50]; char mean[150]; /*for(int i = 0;i<100;i++) { scanf(" %[^\n]s", word); scanf(" %[^\n]s", mean); writeToFile(word,mean); insertion(word, mean, num++); }*/ num = Load(num); while (1) { printf("\n1. Insert\t2. Modify\t\n"); printf("3. Search\t4. Print\t5. Exit\nEnter your choice:"); scanf("%d", &ch); switch (ch) { case 1: printf("Enter the word:"); scanf(" %[^\n]s", word); printf("Enter the meaning:"); scanf(" %[^\n]s", mean); writeToFile(word,mean); insertion(word, mean, num++); break; case 2: printf("Enter the word for replacing the meaning : "); scanf(" %[^\n]s", word); printf("Enter the meaning : "); scanf(" %[^\n]s", mean); modify(word, mean, &ch, root); break; case 3: printf("Enter the element to search: "); scanf(" %[^\n]s", word); search(word, &ch, root); break; case 4: Print(root); printf("\n"); break; case 5: exit(0); default: printf("You have entered wrong option!!\n"); break; } } printf("\n"); return 0; }
C
// // Created by xixi2 on 2020/3/7. // 通过定时器来读取当前进程的未决信号集 #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include <signal.h> #include <string.h> #include <sys/time.h> void signalHandler() { sigset_t *set; sigpending(set); // 读取当前进程的未决信号集 for (int i = 1; i < 32; ++i) { if (sigismember(set, i)) { printf("1"); } else { printf("0"); } } printf("\n"); } int main() { signal(SIGALRM, signalHandler); struct itimerval new_value; // 首次触发的时间是2秒后 new_value.it_value.tv_sec = 2; new_value.it_value.tv_usec = 0; // 定时触发的时间是每1秒执行一次 new_value.it_interval.tv_sec = 1; new_value.it_interval.tv_usec = 0; setitimer(ITIMER_REAL, &new_value, NULL); while (1){ for(int i=0;i<10000;++i); sleep(1); } return 0; }
C
#include<stdio.h> #include<conio.h> #include<string.h> void convert(char a[20],int,int); void main() { char arr[20]; int base1,base2; printf("Enter the base : "); scanf("%d",&base1); printf("Enter the input : "); scanf("%s",arr); printf("Enter the base to convert : "); scanf("%d",&base2); convert(arr,base1,base2); getch(); } void convert(char a[20], int b1, int b2) { int i, r, n = 0, b = 1, count = 0, result; for(i=strlen(a)-1;i>=0;i--) { if(a[i] >= 'A' && a[i] <= 'Z') { result = a[i]-'0'-7; } else { result = a[i]-'0'; } n = result*b+n; b *=b1; } while(n != 0) { r = n%b2; result='0'+r; if(result > '9') { result +=7; } a[count]=result; count++; n=n/b2; } for(i = count-1; i >= 0; i--) { printf("%c",a[i]); } }
C
/* Private version of _pcre_valid_utf */ /************************************************* * Perl-Compatible Regular Expressions * *************************************************/ /* PCRE is a library of functions to support regular expressions whose syntax and semantics are as close as possible to those of the Perl 5 language. Written by Philip Hazel Copyright (c) 1997-2012 University of Cambridge ----------------------------------------------------------------------------- Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the University of Cambridge nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ----------------------------------------------------------------------------- */ /* This module contains an internal function for validating UTF-8 character strings. */ /************************************************* * Validate a UTF-8 string * *************************************************/ /* This function is called (optionally) at the start of compile or match, to check that a supposed UTF-8 string is actually valid. The early check means that subsequent code can assume it is dealing with a valid string. The check can be turned off for maximum performance, but the consequences of supplying an invalid string are then undefined. Originally, this function checked according to RFC 2279, allowing for values in the range 0 to 0x7fffffff, up to 6 bytes long, but ensuring that they were in the canonical format. Once somebody had pointed out RFC 3629 to me (it obsoletes 2279), additional restrictions were applied. The values are now limited to be between 0 and 0x0010ffff, no more than 4 bytes long, and the subrange 0xd000 to 0xdfff is excluded. However, the format of 5-byte and 6-byte characters is still checked. */ static int valid_utf8(const char *string, size_t length) // R change int->size_t { const char *p; for (p = string; length-- > 0; p++) { int ab, c, d; c = (unsigned char)*p; if (c < 128) continue; /* ASCII character */ if (c < 0xc0) return 1; /* Isolated 10xx xxxx byte */ if (c >= 0xfe) return 1; /* Invalid 0xfe or 0xff bytes */ ab = utf8_table4[c & 0x3f]; /* Number of additional bytes */ if (length < ab) return 1; length -= ab; /* Length remaining */ /* Check top bits in the second byte */ if (((d = *(++p)) & 0xc0) != 0x80) return 1; /* For each length, check that the remaining bytes start with the 0x80 bit set and not the 0x40 bit. Then check for an overlong sequence, and for the excluded range 0xd800 to 0xdfff. */ switch (ab) { /* 2-byte character. No further bytes to check for 0x80. Check first byte for for xx00 000x (overlong sequence). */ case 1: if ((c & 0x3e) == 0) return 1; break; /* 3-byte character. Check third byte for 0x80. Then check first 2 bytes for 1110 0000, xx0x xxxx (overlong sequence) or 1110 1101, 1010 xxxx (0xd800 - 0xdfff) */ case 2: if ((*(++p) & 0xc0) != 0x80) return 1; /* Third byte */ if (c == 0xe0 && (d & 0x20) == 0) return 1; if (c == 0xed && d >= 0xa0) return 1; break; /* 4-byte character. Check 3rd and 4th bytes for 0x80. Then check first 2 bytes for for 1111 0000, xx00 xxxx (overlong sequence), then check for a character greater than 0x0010ffff (f4 8f bf bf) */ case 3: if ((*(++p) & 0xc0) != 0x80) return 1; /* Third byte */ if ((*(++p) & 0xc0) != 0x80) return 1; /* Fourth byte */ if (c == 0xf0 && (d & 0x30) == 0) return 1; if (c > 0xf4 || (c == 0xf4 && d > 0x8f)) return 1; break; /* 5-byte and 6-byte characters are not allowed by RFC 3629, and will be rejected by the length test below. However, we do the appropriate tests here so that overlong sequences get diagnosed, and also in case there is ever an option for handling these larger code points. */ /* 5-byte character. Check 3rd, 4th, and 5th bytes for 0x80. Then check for 1111 1000, xx00 0xxx */ case 4: if ((*(++p) & 0xc0) != 0x80) return 1; /* Third byte */ if ((*(++p) & 0xc0) != 0x80) return 1; /* Fourth byte */ if ((*(++p) & 0xc0) != 0x80) return 1; /* Fifth byte */ if (c == 0xf8 && (d & 0x38) == 0) return 1; break; /* 6-byte character. Check 3rd-6th bytes for 0x80. Then check for 1111 1100, xx00 00xx. */ case 5: if ((*(++p) & 0xc0) != 0x80) return 1; /* Third byte */ if ((*(++p) & 0xc0) != 0x80) return 1; /* Fourth byte */ if ((*(++p) & 0xc0) != 0x80) return 1; /* Fifth byte */ if ((*(++p) & 0xc0) != 0x80) return 1; /* Sixth byte */ if (c == 0xfc && (d & 0x3c) == 0) return 1; break; } /* Character is valid under RFC 2279, but 4-byte and 5-byte characters are excluded by RFC 3629. The pointer p is currently at the last byte of the character. */ if (ab > 3) return 1; } return 0; }
C
#include <stdio.h> int main() { double var_runoob[10]={0,1,2,3,4,5,6,7,8,9}; double *p; p = &var_runoob[9]; // p = NULL; for(int i=0;i<10;i++) { printf("%p\n",p); printf("%f\n", *p); p--; printf("%f\n",var_runoob[i]); } return 0; }
C
/*At11.C*/ #include <stdio.h> int main() { int num, soma = 0; printf("\nDigite uma sequencia terminada por zero: "); do { scanf("%d", &num); soma = soma + num; } while (num != 0); printf("\nSoma da sequencia: %d\n", soma); return 0; }
C
#include <stdio.h> int main() { int arr[30],i,size,n,in,flag=0; printf("enter array size:"); scanf("%d",&size); printf("enter array:"); for(i=0;i<size;i++) { scanf("%d",&arr[i]); } printf("\nenter number to be inserted:"); scanf("%d",&n); printf("\nenter index:"); scanf("%d",&in); for(i=size;flag!=1;i--) { if(i==in) { arr[i+1]=arr[i]; arr[i]=n; flag=1; } else { arr[i+1]=arr[i]; arr[i]=0; } } for(i=0;i<size+1;i++) { printf("\n%d",arr[i]); } return 0; }
C
#include<stdio.h> void sort(int *arr,char*suit) { int i,j,n,flag,temp; n=5; for(i=1;i<n;i++) { flag=0; for(j=0;j<n-i;j++) if(arr[j]>arr[j+1]) { flag=1; temp=arr[j]; arr[j]=arr[j+1] ; arr[j+1]=temp; temp=suit[j]; suit[j]=suit[j+1] ; suit[j+1]=temp; } if(flag==0) break; } } int inCaseOfTie(int*value1,int*value2) { int i=4; while(value1[i]==value2[i]) i--; if(value1[i]>value2[i]) return 1; return 2; } int isSameSuit(char*suit) { int i; for(i=0;i<4;i++) if(suit[i]!=suit[i+1]) return 0; return 1; } int isRoyalFlush(int *value,char*suit) { if(!isSameSuit(suit)) return 0; if(value[0]==10 && value[0]==11 && value[0]==12 && value[0]==13 && value[0]==14) return 1; return 0; } int isStraightFlush(int *value,char*suit) { if(!isSameSuit(suit)) return 0; return isStraight(value,suit); } int isFourOfAKind(int *value) { if(value[0]==value[1] && value[0]==value[2] && value[0]==value[3]) return value[0]; if(value[1]==value[2] && value[1]==value[3] && value[1]==value[4]) return value[1]; return 0; } int isThreeOfAKind(int *value) { if(value[0]==value[1] && value[0]==value[2]) return value[0]; if(value[1]==value[2] && value[1]==value[3]) return value[1]; if(value[2]==value[3] && value[2]==value[4]) return value[2]; return 0; } int isTwoPairs(int*value) { if(value[0]==value[1]) { if(value[2]==value[3]) return 123; if(value[3]==value[4]) return 134; } if(value[1]==value[2] && value[3]==value[4]) return 1234; return 0; } int isOnePair(int*value) { if(value[0]==value[1]) return value[0]; if(value[1]==value[2]) return value[1]; if(value[2]==value[3]) return value[2]; if(value[3]==value[4]) return value[3]; return 0; } int isFullHouse(int *value) { if(value[0]==value[1] && value[2]==value[3] && value[3]==value[4]) return value[2]; if(value[3]==value[4] && value[0]==value[1] && value[1]==value[2]) return value[2]; return 0; } int isFlush(char*suit) { return isSameSuit(suit); } int isStraight(int *value) { if(value[1]==value[0]+1 && value[2]==value[0]+2 && value[3]==value[0]+3 && value[4]==value[0]+4) return 1; return 0; } int whoWins(int*value1,char*suit1,int*value2,char*suit2) { int player1pair1,player1pair2,player2pair1,player2pair2,a,b,c,d; if(isRoyalFlush(value1,suit1)) return 1; if(isRoyalFlush(value2,suit2)) return 2; if(isStraightFlush(value1,suit1) && !isStraightFlush(value2,suit2)) return 1; if(!isStraightFlush(value1,suit1) && isStraightFlush(value2,suit2)) return 2; if(isStraightFlush(value1,suit1) && isStraightFlush(value2,suit2)) // means both of the players are having a Straight Flush return inCaseOfTie(value1,value2); if(isFourOfAKind(value1) && !isFourOfAKind(value2)) return 1; if(!isFourOfAKind(value1) && isFourOfAKind(value2)) return 2; if(isFourOfAKind(value1) && isFourOfAKind(value2)) { if(isFourOfAKind(value1)> isFourOfAKind(value2)) return 1; if(isFourOfAKind(value1)< isFourOfAKind(value2)) return 2; return inCaseOfTie(value1,value2); } if(isFullHouse(value1) && !isFullHouse(value2)) return 1; if(!isFullHouse(value1) && isFullHouse(value2)) return 2; if(isFullHouse(value1) && isFullHouse(value2)) { if(isFullHouse(value1)> isFullHouse(value2)) return 1; if(isFullHouse(value1)< isFullHouse(value2)) return 2; return inCaseOfTie(value1,value2); } if(isFlush(suit1) && !isFlush(suit2)) return 1; if(!isFlush(suit1) && isFlush(suit2)) return 2; if(isFlush(suit1) && isFlush(suit2)) return inCaseOfTie(value1,value2); if(isStraight(value1) && !isStraight(value2)) return 1; if(!isStraight(value1) && isStraight(value2)) return 2; if(isStraight(value1) && isStraight(value2)) return inCaseOfTie(value1,value2); if(isThreeOfAKind(value1) && !isThreeOfAKind(value2)) return 1; if(!isThreeOfAKind(value1) && isThreeOfAKind(value2)) return 2; if(isThreeOfAKind(value1) && isThreeOfAKind(value2)) { if(isThreeOfAKind(value1)> isThreeOfAKind(value2)) return 1; if(isThreeOfAKind(value1)< isThreeOfAKind(value2)) return 2; return inCaseOfTie(value1,value2); } if(isTwoPairs(value1) && !isTwoPairs(value2)) return 1; if(!isTwoPairs(value1) && isTwoPairs(value2)) return 2; if(isTwoPairs(value1) && isTwoPairs(value2)) { player1pair1=value1[isTwoPairs(value1)%10]; player1pair2=value1[(isTwoPairs(value1)/100)%10]; player2pair1=value2[isTwoPairs(value2)%10]; player2pair2=value2[(isTwoPairs(value2)/100)%10]; a=(player1pair1>player1pair2?player1pair1:player1pair2); b=(player1pair1<player1pair2?player1pair1:player1pair2); c=(player2pair1>player2pair2?player2pair1:player2pair2); d=(player2pair1<player2pair2?player2pair1:player2pair2); if(a>c) return 1; else if (a<c) return 2; else if(b>d) return 1; else if (b<d) return 2; return inCaseOfTie(value1,value2); } if(isOnePair(value1) && !isOnePair(value2)) return 1; if(!isOnePair(value1) && isOnePair(value2)) return 2; if(isOnePair(value1) && isOnePair(value2)) { if(isOnePair(value1)> isOnePair(value2)) return 1; if(isOnePair(value1)< isOnePair(value2)) return 2; return inCaseOfTie(value1,value2); } return inCaseOfTie(value1,value2); } void print(int*value,char *suit) { int i; for(i=0;i<5;i++) printf("%d%c ",value[i],suit[i]); printf("\n"); } int main() { int n,i,j,answer=0; int value1[10],value2[10]; char suit1[10],suit2[10],temp; FILE *f; n=1000; f=fopen("poker.txt","r"); if(f) { for(i=0;i<n;i++) { for(j=0;j<5;j++) { fscanf(f," %c%c",&temp,&suit1[j]); if(temp=='T') value1[j]=10; else if(temp=='J') value1[j]=11; else if(temp=='Q') value1[j]=12; else if(temp=='K') value1[j]=13; else if(temp=='A') value1[j]=14; else value1[j]=temp-48; } for(j=0;j<5;j++) { fscanf(f," %c%c",&temp,&suit2[j]); if(temp=='T') value2[j]=10; else if(temp=='J') value2[j]=11; else if(temp=='Q') value2[j]=12; else if(temp=='K') value2[j]=13; else if(temp=='A') value2[j]=14; else value2[j]=temp-48; } sort(value1,suit1); sort(value2,suit2); if(whoWins(value1,suit1,value2,suit2)==1) answer++; } printf("answer = %d",answer); } else printf("There was some error in opening the file\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* model.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: itsuman <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/02 21:07:12 by itsuman #+# #+# */ /* Updated: 2017/06/02 21:07:19 by itsuman ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" char is_process(t_process **process, int i) { t_process *tmp; tmp = *process; while (tmp) { if (tmp->pc == i && tmp->live >= 0) return (tmp->p_id); tmp = tmp->next; } return (0); } int process_count(t_process *process) { int i; t_process *tmp; i = 0; tmp = process; while (tmp) { if (tmp->live >= 0) i++; tmp = tmp->next; } return (i); } void create_process(t_data **data, int index, int p_num, unsigned char p_id) { int i; t_process *var; t_process *last; i = 1; var = (t_process *)malloc(sizeof(t_process)); last = (*data)->prcs; var->numb = (*data)->procnumb++; var->p_num = p_num; var->p_id = p_id; var->pc = index; var->live = 0; var->carry = 0; var->delay = 0; var->registers[0] = p_num; while (i < REG_NUMBER) var->registers[i++] = 0; var->next = (*data)->prcs; (*data)->prcs = var; } void create_map(t_data **data) { int i; int n; unsigned int j; t_player *var; var = (*data)->player; i = 0; while (i < (*data)->amount_players) { if (i == 0) n = 0; else n = (MEM_SIZE / (*data)->amount_players) * i; j = 0; create_process(&(*data), n, var->number, var->id); while (j < var->header->prog_size) { (*data)->map[n] = var->prog_cod[j]; (*data)->map_v[n] = var->id; n++; j++; } var = var->next; i++; } } void model(t_data **data) { (*data)->speed = 20000; (*data)->procnumb = 1; (*data)->win = (*data)->player; create_map(&(*data)); start_process(&(*data)); free_player(&(*data)->player); free_process(&(*data)->prcs); }
C
/* ============================================================================ Name : ejercicio_clase_9_bien.c Author : cgimenez Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <limits.h> #define LENGHT 50 #define SIZEARRAY 5 #define TRUE 1 #define FALSE 0 typedef struct { char name[LENGHT]; int file; int isEmpty; } Student; int createStudent(Student* pArrayStudent, int sizeArray, int index); int createStudent(Student* pArrayStudent, int sizeArray, int index) { int ret = -1; Student bufferStudent; if(pArrayStudent != NULL && sizeArray >= 0 && index < sizeArray) { if(!utn_getInt() && !utn_getNombre() //getFile o getLegajo--> Generar la funcion ) { pArrayStudent[index] = bufferStudent; pArrayStudent[index].isEmpty = FALSE; } } return ret; } int printStudent(Student* pArrayStudent, int sizeArray) { int ret = -1; if(pArrayStudent != NULL && sizeArray > 0) { ret = 0; for (int i = 0; i < sizeArray; i++) { if(pArrayStudent[i].isEmpty == FALSE) { printf("%s - %d\n", pArrayStudent[i].name, pArrayStudent[i].file); } } } return ret; } int initStudent(Student* pArrayStudent, int sizeArray) { int ret = -1; if(pArrayStudent != NULL && sizeArray > 0) { ret = 0; for (int i = 0; i < sizeArray; i++) { pArrayStudent[i].isEmpty = TRUE; } } return ret; } int main(void) { setbuf(stdout,NULL); char questionContinue = 'S'; int flagOk; int option; int index; Student arrayStudent[SIZEARRAY]; initStudent(arrayStudent, SIZEARRAY); do { getIntWithLimits("\n1- Ingresar Nombre\n2- Ingresar legajo\n3- Imprimir listado estudiantes\n4- Salir\n\nSeleccione una opcion: ", "Ingresar una opcion entre [1-4]", "Ingresar un caracter numerico", &option, 3, 1, 4); Student aux; switch(option) { case 1: if(!getIntWithLimits("\nIndice?","Ingresar una opcion entre [1-4]", "Ingresar un caracter numerico", &option, 3, 1, 4)) { createStudent(arrayStudent, SIZEARRAY, index); } break; case 2: if(!getIntWithLimits("Ingrese un Legajo: ", "Ingresar legajo entre [1-5] ", "Ingresar un caracter numerico", &aux.file, 3, 1, 5)) { arrayStudent[i].file= aux; } break; case 3: printArray(arrayStudent, SIZEARRAY); break; case 4: printf("\n *** Adios! *** \n"); questionContinue = 'N'; break; }while(option!=4); return EXIT_SUCCESS; }
C
#include <stdio.h> int add(int a, int b){ return (a + b); } int find_product(int* array, int len){ if (len == 1) return array[0]; return(add(find_product(array, len - 1), array[len - 1])); } int main(int argc, char const *argv[]) { int nums[] = {1,2,3,4,5,6,7,8,9,10}; int sum = find_product(nums, (sizeof(nums)/sizeof(nums[0]))); printf("The sum of elements is %d\n",sum); return 0; }
C
#include "decoder_task.h" uint32_t strBinToInt (char* strBin) { uint32_t result = 0; uint32_t p2 = 1; for (int c = strlen(strBin) - 1;c >= 0;c--) { if (strBin[c] == '1') { result += p2; } p2 *= 2; } return result; } void cardClear() { card.read = 0; for (int i = 0; i <= sizeof(card.bites); i++) { card.bites[i] = 0; } card.bitesQnt = 0; //Liczba odebranych bitw for (int i = 0; i <= sizeof(card.standard); i++) { card.standard[i] = 0; } strcpy(card.standard,"Nieznany"); card.inum = 0; //Inum; card.unum = 0; //Unum } uint8_t verifyWiegandParity (uint8_t parityLeftType, uint8_t parityLeftStart, uint8_t parityLeftEnd, uint8_t parityRightType, uint8_t parityRightStart, uint8_t parityRightEnd) { uint8_t parityLeftBit = 0; if (card.bites[0] == '0') { parityLeftBit = 0; } else { parityLeftBit = 1; } uint8_t parityRightBit = 0; if (card.bites[36] == '0') { parityRightBit = 0; } else { parityRightBit = 1; } uint8_t parityLeftCount = 0; uint8_t parityRightCount = 0; //Zliczanie bitw dodatnich for (uint8_t i = parityLeftStart; i <= parityRightEnd; i++) { if (card.bites[i] == '1' && i >= parityLeftStart && i <= parityLeftEnd) { parityLeftCount++; } if (card.bites[i] == '1' && i >= parityRightStart && i <= parityRightEnd) { parityRightCount++; } } /* * Jeli * parzysto zliczonych bitow po lewej razem z lewym bitem parzystoci = typ parzystoci lewej strony * oraz * parzysto zliczonych bitow po prawej razem z prawym bitem parzystoci = typ parzystoci prawej strony * to parzysto jest zgodna. */ if (((parityLeftCount + parityLeftBit) % 2 == parityLeftType) && ((parityRightCount + parityRightBit) % 2 == parityRightType)) { return 1; } else { return 0; } } void decodeWiegandFields(uint8_t inumStart, uint8_t inumLength, uint8_t unumStart, uint8_t unumLength) { if (inumLength != 0) { char strInum[inumLength]; memcpy(strInum, &card.bites[inumStart], inumLength); strInum[inumLength] = '\0'; card.inum = strBinToInt(&strInum[0]); } else { card.inum = 0; } if (unumLength != 0) { char strUnum[unumLength]; memcpy(strUnum, &card.bites[unumStart], unumLength); strUnum[unumLength] = '\0'; card.unum = strBinToInt(&strUnum[0]); } else { card.unum = 0; } } uint8_t decodeWiegand() { switch (card.bitesQnt) { case 26: { //Wiegand 26 z numerem instalacji if (verifyWiegandParity(0, 1, 12, 1, 13, 24)) { decodeWiegandFields(1, 8, 9, 16); strcpy(card.standard, "H10301"); } break; } default: { strcpy(card.standard,"Nieznany"); card.inum = 0; card.unum = 0; break; } } return 1; } uint32_t interruptTime = 0; uint32_t osTime = 0; //Obsuga przerwania od DATA 0 i DATA 1 void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin) { //readWiegand(); interruptTime = HAL_GetTick(); if (GPIO_Pin == PIN_DATA_0) { card.bites[card.bitesQnt] = '0'; card.bitesQnt++; } if (GPIO_Pin == PIN_DATA_1) { card.bites[card.bitesQnt] = '1'; card.bitesQnt++; } } void vTaskDecoder(void *pvParameters) { //Ustawianie czasw interruptTime = HAL_GetTick(); osTime = HAL_GetTick(); //Uchwyty na semafory xSemaphoreCardReadUART = xSemaphoreCreateBinary(); xSemaphoreCardReadLCD = xSemaphoreCreateBinary(); //Uchwyty na kolejki xQueueCardStructUART = xQueueCreate(1, sizeof(card)); xQueueCardStructLCD = xQueueCreate(1, sizeof(card)); for (;;) { vTaskDelay(1); //Minimalnie opnienie dla synchronizacji interruptTime i osTime. osTime = HAL_GetTick(); if (abs(osTime - interruptTime) > MAX_WIEGAND_BIT_TIME && interruptTime > 0) { //Zerowanie czasw interruptTime = 0; osTime = 0; //Dekodowanie Wieganda decodeWiegand(); //Ustawianie semafora dla UART i LCD xSemaphoreGive(xSemaphoreCardReadUART); xSemaphoreGive(xSemaphoreCardReadLCD); //Wysyanie kolejki z danymi odczytu do UART i LCD xQueueSend(xQueueCardStructUART, (void *) &card, (portTickType) 10); xQueueSend(xQueueCardStructLCD, (void *) &card, (portTickType) 10); cardClear(); } } }
C
/*Find four elements i,j,k and l in an array such that i+j=k+l Method 1: Brute force for(i=1 to n) for(j=i+1 to n) for(k=j+1 to n) for(l=k+1 to n) TC=O(n^4) - useless! SC=O(1) Method 2: For every pair of elements in the array, add a node to the balanced BST. Each node contains (sum of pair,#pairs with this sum or frequency) -->(pair 1) -->(pair 2) So, a node contains the sum, count of pairs with this sum and this node points to a LL which contains all the pairs with this sum! When the frequency of any existing node is incremented, we understand that these pairs have same sum. All possible pairs can be found in - O(nc2)=O(n^2) Time to build BST = n^2logn^2=O(2n^2logn) = O(n^2logn) TC=O(n^2logn) SC=O(n^2) Method 3: Use hash table in place of BBST to reduce the TC to linear Finding possible pairs - O(n^2) Build a hash table for each of the possible sums - O(n^2)*O(1) Each cell of hash table is a structure containing a sum, a count and a pointer pointing to a LL containing the pairs which sum to this particular sum. Traverse the hash table to find out the sums for which the count is >1. These pairs will have same sum! - O(n^2) TC=O(n^2) SC=O(n^2) */ #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> struct data { int count; struct node *head; }; struct node { int first; int second; struct node *next; }; void ijkl_equalSum_3(int arr[],int n) { int i,j,pair_sum,k; struct data *hashTable; hashTable = (struct data *)calloc(50,sizeof(struct data)); printf("hash table[0].count: %d head: %p\t:",hashTable[0].count,hashTable[0].head); for(i=0;i<n;i++) { for(j=i+1;j<n;j++) { pair_sum=arr[i]+arr[j]; struct node *new=(struct node*)malloc(sizeof(struct node*)); new->first=arr[i]; new->second=arr[j]; new->next=NULL; if(hashTable[pair_sum].count==0) { hashTable[pair_sum].count++; hashTable[pair_sum].head=new; } else //add the node at the head of the list { hashTable[pair_sum].count++; new->next=hashTable[pair_sum].head; hashTable[pair_sum].head=new; } } } for(k=0;k<50;k++) { if(hashTable[k].count==0) continue; else if(hashTable[k].count==1) { printf("pair sum: %d count: %d\t:",k,hashTable[k].count); printf("pair: %d-%d\n",hashTable[k].head->first,hashTable[k].head->second); printf("\n"); } else { printf("The following pairs have same sum:\n"); printf("pair sum: %d count: %d\t:",k,hashTable[k].count); printf("\n"); struct node *ptr; ptr= hashTable[k].head; while(ptr) { printf("pair: %d-%d\n",ptr->first,ptr->second); ptr=ptr->next; } } } } int main() { int arr[]={6,2,3,4,5}; int size=sizeof(arr)/sizeof(arr[0]); printf("Method 3:\n"); ijkl_equalSum_3(arr,size); }
C
/* atan function */ #include "xmath.h" double atan(double x) { /* compute atan(x) */ unsigned short hex; static const double piby2 = {1.57079632679489661923}; switch (_Dtest (&x)) { /* test for specia1 codes */ case NAN: errno = EDOM; return (x); case INF: return (DSIGN(x) ? -piby2 : piby2); case 0: return (0.0); default: /* finite */ if (x < 0.0) { x = -x; hex = 0x8; } else hex = 0x0; if (1.0 < x) { x = 1.0 / x; hex ^= 0x2; } return (_Atan(x, hex)); } }