language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <sys/ioctl.h> #include <fcntl.h> #include <unistd.h> // for read, write, close //#include <linux/ioctl.h> // for _IORD _IOWR //#define MY_MACIG 'G' #define MY_MACIG ']' #define READ_IOCTL _IOR(MY_MACIG, 0, int) #define WRITE_IOCTL _IOW(MY_MACIG, 1, int) int main(){ char buf[200]; int fd = -1; if ((fd = open("/dev/my_device", O_RDWR)) < 0) { perror("open"); return -1; } printf("READ_IOCTL user: %d\n",READ_IOCTL); printf("WRITE_IOCTL user: %d\n",WRITE_IOCTL); if(ioctl(fd, WRITE_IOCTL, "hello world") < 0) perror("first ioctl"); if(ioctl(fd, READ_IOCTL, buf) < 0) perror("second ioctl"); printf("message: %s\n", buf); /*--------------------------------------------*/ char message[200]="Hell Yeah!"; int ret; ret=write(fd,message,10); //tries to write 10 bytes if (ret==-1) printf("Error write\n"); ret=read(fd,buf,10); //tries to read 10 bytes if (ret==-1) printf("Error read\n"); buf[ret]='\0'; printf("buf: %s ;length: %d bytes\n",buf,ret); close(fd); return 0; }
C
#ifndef COLOR_H_ #define COLOR_H_ struct Color { float r, g, b; Color() : r(0), g(0), b(0) {} Color(float _r, float _g, float _b) : r(_r), g(_g), b(_b) {} Color operator+(const Color& c) const { return Color(r+c.r, g+c.g, b+c.b); } Color operator*(float f) const { return Color(r*f, g*f, b*f); } Color operator/(float f) const { return Color(r/f, g/f, b/f); } Color& operator+=(const Color& c) { r += c.r; g += c.g; b += c.b; return *this; } Color correct(float gamma) const; }; #endif
C
#include <stdio.h> #include <stdlib.h> int main() { int a[26]={0}; char s[1001]; fgets(s,1001,stdin); int i=0,j=0; while(s[j]!='\0') { if(s[j]>='a'&&s[j]<='z') {i=s[j] - 'a'; a[i]++;} if(s[j]>='A'&&s[j]<='Z') {i=s[j] - 'A'; a[i]++;} j++; } for(i=0;i<26;i++) { if(a[i]!=0) { printf("%c - ", 'a'+i); printf("%d \n", a[i]);} } }
C
#include <stdio.h> #include <stdlib.h> int main() { int i,a,b,hasil; printf("====Bentuk Iteratif====\n\n"); printf("Masukkan angka : "); scanf("%d", &a); printf("Masukkan pangkat : "); scanf("%d", &b); for (i=1; i<=b; i++) hasil =hasil*a; printf("Hasil dari %d pangkat %d = %d\n", a,b,hasil); return 0; }
C
#include "colors.h" #include <stdio.h> #include <stdlib.h> #include <omp.h> int main(int argc, char *argcv[]){ int iam = 0, np = 1; int p = atoi(argcv[1]); int datos[100]; int i = 0, j = 0; #pragma omp parallel num_threads(p) private(iam, np, i) shared(j) { #if defined(_OPENMP) np = omp_get_num_threads(); iam = omp_get_thread_num(); #endif for(i=0;i<5;i++){ //#pragma omp critical { j++; } } printf("\tSoy el thread "YELLOW"%d"RESET", valor actual de j: "GREEN"%d"RESET"\n", iam, j); } printf("\t\tSoy el thread "YELLOW"%d"RESET", valor FINAL de j: "GREEN"%d"RESET"\n", iam, j); }
C
/* * UART.c * * Created on: Feb 21, 2019 * Author: ryanjl9, Ben Pierre, Anthony Rosenhamer * */ #include <UART.h> #include <MOVEMENT.h> #include <lcd.h> #include <final.h> #define BIT0 0x01 #define BIT1 0x02 #define BIT2 0x04 #define BIT3 0x08 #define BIT4 0x10 #define BIT5 0x20 #define BIT6 0x40 #define BIT7 0x80 char data; char message[21]; char command[21]; int len; int distance = 0; /** * uart_init: This method is used to initialize the uart module * * CALL THIS METHOD */ void uart_init() { SYSCTL_RCGCGPIO_R |= 0x02; SYSCTL_RCGCUART_R |= 0x02; GPIO_PORTB_AFSEL_R |= (BIT0 | BIT1); GPIO_PORTB_PCTL_R |= 0x00000011; GPIO_PORTB_DEN_R |= (BIT0 | BIT1); GPIO_PORTB_DIR_R &= 0xFE; GPIO_PORTB_DIR_R |= 0x02; UART1_CTL_R &= ~UART_CTL_UARTEN; //104. 11 //8, 44 UART1_IBRD_R = 8; UART1_FBRD_R = 44; UART1_CC_R = 0; UART1_LCRH_R = 0x60; UART1_ICR_R |= 0x0030; UART1_IM_R |= 0x0010; //6 NVIC_PRI1_R |= 0x00002000; NVIC_EN0_R |= 0x00000040; IntRegister(INT_UART1, uart_handler); UART1_CTL_R = 0x0301; IntMasterEnable(); } /** * uart_sendChar: This method is used to send data to putty */ void uart_sendChar(char ldata) { while((UART1_FR_R & 0x20) != 0); // Loops until a character is available to be transmitted UART1_DR_R = ldata; } /** * uart_recieve: This method is used to recieve data from putty */ char uart_recieve() { return (char) (UART1_DR_R & 0xFF); } /** * uart_handler: This method is used to handle interrupts involving uart */ void uart_handler() { data = uart_recieve(); // if(data > 31 && data < 127){ // message[len] = data; // len++; // } if (data == '.') { lcd_clear(); len = 0; } else lcd_putc(data); message[len] = data; len++; if (data == ',') { lcd_clear(); lcd_printf("%s", message); //Handle move inputs if (message[1] == 'f' || message[1] == 'l' || message[1] == 'r' || message[1] == 'b') { char sub[4]; int c =0; while(c<3){ sub[c]= message[2+c]; c++; } sub[c]='\0'; int target = atoi(sub); lcd_printf("%i , %s",target, sub); if (message[1]== 'f') { char positionStr[10] = { 0 }; move_forward(target); sprintf(positionStr, ".o %c %d %d,", currentPosition.appCommand, botX, botY); uart_sendStr(positionStr); } else if (message[1]== 'b') { char positionStr[10] = { 0 }; move_backward(target); sprintf(positionStr, ".o %c %d %d,", currentPosition.appCommand, botX, botY); uart_sendStr(positionStr); } else if (message[1] =='l') { char positionStr[10] = { 0 }; turn_left(target); sprintf(positionStr, ".o %c %d %d,", currentPosition.appCommand, botX, botY); uart_sendStr(positionStr); } else { char positionStr[10] = { 0 }; turn_right(target); sprintf(positionStr, ".o %c %d %d,", currentPosition.appCommand, botX, botY); uart_sendStr(positionStr); } }else if(message[1]=='m'){ lcd_printf("BUM BUM BUM< SWEEEETTTT CARRROOOLLINNNNEEE"); }else if(message[1]=='s'){ lcd_printf("Scanning, Scanning"); radarSweep(); } } UART1_ICR_R |= 0x0030; } /** * print: This method is used to send information back to putty formatted * * CALL THIS METHOD */ void print(char* dir, int dist) { char mes[21] = { 0 }; char* buffer; int i; strcat(mes, "DIR: "); strcat(mes, dir); strcat(mes, "\r\nDIST: "); asprintf(&buffer, "%i", dist); strcat(mes, buffer); strcat(mes, "\0"); for (i = 0; i < strlen(mes); i++) { uart_sendChar(mes[i]); timer_waitMillis(10); } uart_sendChar('\r'); uart_sendChar('\n'); } void uart_sendStr(const char *data){ //until we reach a null character while (*data != '\0'){ //send the current character uart_sendChar(*data); // increment the pointer. data++; } } void radarSweep(){ double degree =0; char message[20]; // String to hold measurements move_servo(degree);//Moves to starting position timer_waitMillis(500); uart_sendChar('p');//Tells app to wait for more commands while(degree<181) { ir_getDistance(); ping_getDistance(); sprintf(message, "%0.2f", ir_distance); uart_sendStr(message); uart_sendChar(' '); sprintf(message, "%0.2f", ping_distance); uart_sendStr(message); uart_sendChar(','); timer_waitMillis(100); degree+=2; if(degree<181) move_servo(degree); } }
C
#include <stdio.h> #include <stdlib.h> unsigned int fibo[51] = { 0, }; void InitFibo(void) { fibo[0] = 0; fibo[1] = 1; for (int i = 2; i < 51; ++i) { fibo[i] = fibo[i - 1] + fibo[i - 2]; } } void Print(int num) { if (num < 3) { printf("Error!"); return; } for (int i = 1; i <= num; ++i) { printf("%10d", fibo[i]); if (i % 8 == 0 && i != num) { printf("\n"); } } } int main() { int temp = 0; InitFibo(); while (1) { scanf("%d", &temp); if (temp != 0) { Print(temp); printf("\n\n"); } else { break; } } return 0; } /* 쳲еǰnn3룺ж룬ÿһnΪ0ʱС ÿnn3ʱ쳲еǰnÿ8һпɲ8 ÿĿΪ10Ҷ룬ÿո룩Error!ÿи */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* apply_char_bonus.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: vgoncalv <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/12 15:56:41 by vgoncalv #+# #+# */ /* Updated: 2021/07/12 15:56:41 by vgoncalv ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static char *get_pad_w(int size) { char *pad; if (size < 0) return (ft_strdup("")); pad = ft_calloc(size + 1, sizeof(char)); if (pad == NULL) return (NULL); while (size--) pad[size] = ' '; return (pad); } int apply_width_char(char **str, t_arg *arg) { char *res; char *temp; if (**str != 0) { if (apply_width(str, arg)) return (FT_PRINTF_ERROR); return (0); } temp = get_pad_w(arg->width - 1); if (arg->flags & LEFT_JUSTIFY) res = ft_memjoin(*str, temp, 1, ft_strlen(temp) + 1); else res = ft_memjoin(temp, *str, ft_strlen(temp), 2); safe_free((void **)&temp); safe_free((void **)str); *str = res; if (*str == NULL) return (FT_PRINTF_ERROR); return (0); }
C
#include<stdio.h> int main() { int a,b=0; scanf("%d",&a); while(a!=0) { a/=10; b++; } printf("%d",b); return 0; }
C
#include<stdio.h> //printf #include<string.h> //strlen #include<stdlib.h> #include<sys/socket.h> //socket #include<arpa/inet.h> //inet_addr #include<unistd.h> #define SERV "\x1B[35m" #define CLIENT "\x1B[36m" #define RESET "\033[0m" int readline(int, char *, int); int main(int argc , char *argv[]) { int sock, server_port, n_len; int err = 0; // 0 - no error struct sockaddr_in server; char message[1000] , server_reply[2000], server_addr[16], server_tmp_port[6]; puts("Insert server addres (default 127.0.0.1)"); fgets(server_addr, sizeof server_addr, stdin); puts("Insert server port (default 8888)"); fgets(server_tmp_port, sizeof server_tmp_port, stdin); server_port = strtoul(server_tmp_port, NULL,10); if(server_addr[0] == '\n'){ strcpy(server_addr, "127.0.0.1"); } if(server_addr[strlen(server_addr)-1] == '\n') server_addr[strlen(server_addr)-1] = '\0'; if(server_port == 0){ server_port = 8888; } //Create socket 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( server_addr ); server.sin_family = AF_INET; server.sin_port = htons( server_port ); //Connect to remote server if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) { perror("connect failed. Error"); return 1; } puts("Connected"); printf(SERV "Colour of Server messages \n" RESET); printf(CLIENT "Colour of Your messages \n\n" RESET); //keep communicating with server while(1){ bzero(server_reply, sizeof server_reply); bzero(message, sizeof message); printf(CLIENT "$ "); fgets (message, sizeof message, stdin); printf(RESET); if(strncmp(message,"quit",4) != 0){ //Send some data if( send(sock , message , strlen(message) , 0) > 0){ puts("Send failed"); err = 1; break; } //Receive a reply from the server //if( recv(sock , server_reply , 2000 , 0) < 1){ if( readline(sock , server_reply , 2000) > 0){ puts(server_reply); if(strncmp(server_reply, "len ", 4) == 0){ n_len = strtoul(message+4, NULL,10); for(int i = 0; i < n_len; i++){ readline(sock , server_reply+strlen(server_reply) , 2000-strlen(server_reply)); puts(server_reply); } } } else{ puts("recv failed"); break; } printf(SERV "%s" RESET, server_reply); } else break; } if(shutdown(sock, SHUT_RDWR) == 0){ puts("Socket is shuted down o.0"); } else puts("Failed to shutdown soket"); if(close(sock) == 0){ puts("Socket closed"); } else{ puts("Failed to close socket"); err = 2; } return err; } int readline(int fd, char *buf, int len){ char tmp = ' '; char *p = &tmp; int rc; for(int i = 0; i < len; i++){ rc = recv( fd, p, 1, 0 ); if( rc == 0 ) return 0; buf[i] = *p; if( (int)*p == '\n'){ //buf[i] = '\0'; return i + 1; } } buf[ len - 1 ] = '\0'; return -1; }
C
/* chapter 03 exercise */ #include <stdio.h> int main() { /* data type size */ printf("data type size\n"); printf("int size is %d Bytes\n\n", sizeof(int)); printf("short size is %d Bytes\n\n", sizeof(short)); printf("long size is %d Bytes\n\n", sizeof(long)); printf("long long size is %d Bytes\n\n", sizeof(long long)); printf("char size is %d Bytes\n\n", sizeof(char)); printf("float size is %d Bytes\n\n", sizeof(float)); printf("double size is %d Bytes\n\n", sizeof(double)); /* 03-01 */ printf("03-01\n"); int i_a=2147483647; float f_a=99999999999999;//99999999999999999999999999999999999999.999999999999999999999999999999999999999999999999999999999; printf("int %d+1 overflow is %d \n", i_a,i_a+1); printf("float(underflow) %f*9999999999999999 overflow is %f \n\n", f_a, f_a*999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999); /* 03-02 */ printf("03-02\n"); char c_a; printf("Please key in ASCII code number: "); scanf("%d", &c_a); printf("Number %d ASCII code is %c\n\n",c_a,c_a); /* 03-03 */ printf("03-03\n"); printf("\a \7"); printf("Startled by the sudden sound, Sally shouted\n"); printf("\"By the Great Pumpkin, what was that!\"\n\n"); /* 03-04 */ printf("03-04\n"); float f_b=21.290000; printf("The input is %f or %e\n\n", f_b, f_b); /* 03-05 */ printf("03-05\n"); int i_year; printf("How old are you:"); scanf("%d", &i_year); printf("%d year have %d second\n\n",i_year, i_year*365*24*60*60); /* 03-06 */ /* quartintM%dB%fAJ1100A׳@ˡA?*/ /* ŧiADAn`NAMX榡*/ printf("03-06\n"); double d_water; double d_quart; printf("Please key in quart number:"); scanf("%lf", &d_quart); // d_water=(i_quart*950)/3.0e-23; // printf(" %lf quart are equal to %lf water\n\n", d_quart, d_water); printf(" %lf quart are equal to %lf water\n\n", d_quart, (d_quart*950)/3.0e-23); /* 03-07 */ printf("03-07\n"); float f_inch,f_cm; printf("Please key in your stature for inch:"); scanf("%f", &f_inch); printf("%f inch are equal to %f cm.\n", f_inch,f_inch*2.54); printf("Please key in your stature for cm:"); scanf("%f", &f_cm); printf("%f cm are equal to %f inch.\n", f_cm,f_cm/2.54); /* exercise end */ return 0; }
C
#ifndef FILE_H #define FILE_H #include <stdio.h> #include <stdlib.h> typedef struct queue_cell { void* x; struct queue_cell* next; struct queue_cell* prev; } queue_cell; typedef struct queue { queue_cell* head; queue_cell* tail; int size; } queue; /** * @brief Create a Queue object FILO * * @return stack* */ queue* create_queue(); /** * @brief return whether the queue is empty or not * * @param s * @return int */ int is_queue_empty(queue* s); /** * @brief push an element at the beginning of the queue * * @param s * @param a */ void add_queue(queue* s, void* a); /** * @brief pop an element from the end of the queue, * if the queue is empty, return a null element * * @param s * @return element */ void* last_queue(queue* s); /** * @brief Print a queue (Use it if the queue is int composed) * * @param c * @param buf */ void print_queue_int(int c, char* buf); void print_queue_cell(queue_cell* c, void(print_func)(void*, char*), FILE* file); void print_queue(queue* s, void(print_func)(void*, char*), FILE* file); /** * @brief concat the second queue at the end of the first, * not regarding whether there are empty or not * * @param s1 * @param s2 */ void concat_queue(queue* s1, queue* s2); /** * @brief copy a queue into another * * @param s * @return queue* */ queue* copy_queue(queue* s); /** * @brief free a queue and all the queue_cell inside * * @param s */ void destroy_queue(queue* s); /** * @brief translate a queue into a table * * @param s * @return void** */ void** queue_to_tab(queue* s); #endif
C
// Dijkstra ADT interface for Ass2 (COMP2521) #include "Dijkstra.h" #include "PQ.h" #include <stdlib.h> #include <assert.h> #include <stdio.h> // helper functions #include <limits.h> static void deletePreviousPredNodesOfVertex(ShortestPaths* paths, Vertex v) { for (PredNode* node = paths->pred[v], *nextNode; node != NULL; node = nextNode) { nextNode = node->next; free(node); } } // helper functions ShortestPaths dijkstra(Graph g, Vertex v) { const int nV = numVerticies(g); ShortestPaths paths; paths.noNodes = nV; paths.src = v; paths.pred = calloc(nV, sizeof(PredNode*)); paths.dist = calloc(nV, sizeof(int)); // for the purpose of this algorithm 3 arrays are needed: Known, Dist, Pred bool known[nV]; for (int i = 0; i < nV; i++) { known[i] = false; paths.dist[i] = INT_MAX; // refer to infinity paths.pred[i] = NULL; // NULL refers to no predecesser } // initialise entry into pq PQ pq = newPQ(); ItemPQ item = {.key = v, .value = 0}; // first value is not important paths.dist[item.key] = 0; // source has no cost associated addPQ(pq, item); // main loop while (!PQEmpty(pq)) { ItemPQ srcItem = dequeuePQ(pq); known[srcItem.key] = true; for (adjListNode* node = outIncident(g, srcItem.key); node != NULL; node = node->next) { if (!known[node->w]) { int nodalCost = paths.dist[srcItem.key] + node->weight; if (nodalCost < paths.dist[node->w]) { paths.dist[node->w] = nodalCost; // new predNodes deletePreviousPredNodesOfVertex(&paths, node->w); // assert(paths.pred[node->w] == NULL); // might not be set to NULL paths.pred[node->w] = malloc(sizeof(PredNode)); paths.pred[node->w]->v = srcItem.key; paths.pred[node->w]->next = NULL; } else if (nodalCost == paths.dist[node->w]) { // edge case where there should be multiple predecessors & dist is same // the break condition in for loop header should never be triggered for (PredNode* curPredNode = paths.pred[node->w]; curPredNode != NULL; curPredNode = curPredNode->next) { if (curPredNode->next == NULL) { curPredNode->next = malloc(sizeof(PredNode)); curPredNode->next->v = srcItem.key; curPredNode->next->next = NULL; break; } } } item.key = node->w; item.value = nodalCost; addPQ(pq, item); // only adds if new cost is lower } } } for (Vertex curVertex = 0; curVertex < nV; curVertex++) { if (paths.pred[curVertex] == NULL && paths.dist[curVertex] == INT_MAX) paths.dist[curVertex] = 0; } freePQ(pq); return paths; } void showShortestPaths(ShortestPaths sps) { int i = 0; printf("Node %d\n",sps.src); printf(" Distance\n"); for (i = 0; i < sps.noNodes; i++) { if(i == sps.src) printf(" %d : X\n",i); else printf(" %d : %d\n",i,sps.dist[i]); } printf(" Preds\n"); for (i = 0; i < sps.noNodes; i++) { int numPreds = 0; int preds[sps.noNodes]; printf(" %d : ",i); PredNode *curr = sps.pred[i]; while (curr != NULL && numPreds < sps.noNodes) { preds[numPreds++] = curr->v; curr = curr->next; } // Insertion sort for (int j = 1; j < numPreds; j++) { int temp = preds[j]; int k = j; while (preds[k - 1] > temp && k > 0) { preds[k] = preds[k - 1]; k--; } preds[k] = temp; } for (int j = 0; j < numPreds; j++) { printf("[%d]->", preds[j]); } printf("NULL\n"); } } void freeShortestPaths(ShortestPaths paths) { for (int i = 0; i < paths.noNodes; i++) { PredNode* tempNode = NULL; for (PredNode* node = paths.pred[i]; node != NULL; node = tempNode) { tempNode = node->next; free(node); } } free(paths.pred); }
C
#include <stdio.h> int y = 5; // in Global space-> outside of main int main(){ // C is white space insensitive printf("\tHello World\n \t!!!\n"); /* This is amulti line comment */ printf("\t numbers %d %c %f \n",5,'h',2.5); //these are format specifiers double x2 = 2.0; // can force data types also-> but needs to specify what int X2= 3;// suggest its a constant value unsigned long x3 = 1000; //allows for a really long number printf("\t hello world %d %f \n",x2,x3); //------------------------- // double p=2.0,q,r=7.0; return 0; }
C
#include <pthread.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> /* Compile: gcc thread-dekker.c -o thread-dek.out -lpthread */ volatile int s = 0; volatile int order = 0; volatile int interest[2] = {0, 0}; void* fthread0(void* v) { int i; for (i = 0; i < 4; ++i) { interest[0] = 1; // Indica interes sleep(2); while (interest[1]) { // Mientras el otro thread ejecuta if (order != 0) { interest[0] = 0; while (order != 0); // Verifica orden interest[0] = 1; } } s = 0; printf("Thread 0 -> s:%d\n", s); order = 1; interest[0] = 0; } } void* fthread1(void* v) { int i; for (i = 0; i < 4; ++i) { interest[1] = 1; // Indica interes sleep(2); while (interest[0]) { // Mientras el otro thread ejecuta if (order != 1) { interest[1] = 0; while (order != 1); // Verifica orden interest[1] = 1; } } s = 1; printf("Thread 1 -> s:%d\n", s); order = 0; interest[1] = 0; sleep(1); } } int main() { pthread_t thread0, thread1; pthread_create(&thread0, NULL, fthread0, NULL); pthread_create(&thread1, NULL, fthread1, NULL); pthread_join(thread0, NULL); pthread_join(thread1, NULL); return 0; }
C
#include <stdio.h> #include <stdlib.h> void hanio(int,char,char,char); int main(void){ while(1){ int n; scanf("%d",&n); hanoi(n,'A','B','C'); } system("pause"); return 0; } void hanoi(int n, char A, char B, char C){ if(n==1){ printf("move sheet from %c to %c\n",A,C); } else{ hanoi(n-1,A,C,B); hanoi(1,A,B,C); hanoi(n-1,B,A,C); } }
C
#include "../include/mnblas.h" #include "../include/complexe2.h" #include <stdlib.h> #include <stdio.h> /* * 2 FLOP */ void mnblas_saxpy(const int N, const float alpha, const float *X, const int incX, float *Y, const int incY) { unsigned int i = 0; //on part du postulat que incX = incY /// register unsigned int maxIter = N/incX; plus besoin de ça #pragma omp parallel for for (i = 0; i < N; i += incX) { Y[i] = alpha * X[i] + Y[i]; i += incY; } } /* * 2 FLOP */ void mnblas_daxpy(const int N, const double alpha, const double *X, const int incX, double *Y, const int incY) { unsigned int i = 0; //on part du postulat que incX = incY //register unsigned int maxIter = N/incX; plus besoin de ça #pragma omp parallel for for (i = 0; i < N; i += incX) { Y[i] = alpha * X[i] + Y[i]; i += incY; } } /* * 8 FLOP */ void mnblas_caxpy(const int N, const void *alpha, const void *X, const int incX, void *Y, const int incY) { unsigned int i = 0; //on part du postulat que incX = incY //register unsigned int maxIter = N/incX; plus besoin de ça #pragma omp parallel for for (i = 0; i < N; i += incX) { complexe_float_t mult_scalaire = mult_complexe_float(*(complexe_float_t *)alpha, ((complexe_float_t *)X)[i]); ((complexe_float_t *)Y)[i] = add_complexe_float(mult_scalaire, ((complexe_float_t *)Y)[i]); i += incY; } } /* * 8 FLOP */ void mnblas_zaxpy(const int N, const void *alpha, const void *X, const int incX, void *Y, const int incY) { register unsigned int i = 0; //on part du postulat que incX = incY //register unsigned int maxIter = N/incX; plus besoin de ça #pragma omp parallel for for (i = 0; i < N; i += incX) { complexe_double_t mult_scalaire = mult_complexe_double(*(complexe_double_t *)alpha, ((complexe_double_t *)X)[i]); ((complexe_double_t *)Y)[i] = add_complexe_double(mult_scalaire, ((complexe_double_t *)Y)[i]); i += incY; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* move_s.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: minhkim <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/05/11 13:14:57 by minhkim #+# #+# */ /* Updated: 2021/05/11 13:14:58 by minhkim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../cub3d.h" void move_s_a(t_game *game) { double new_x; double new_y; new_x = game->player.x - game->player.move_speed * cos(to_radian((game->player.rot_angle + 45))); new_y = game->player.y - game->player.move_speed * sin(to_radian((game->player.rot_angle + 45))); if (move_check(game, game->player.rot_angle - 135) && !check_sprite(game, new_x, new_y) && new_x < game->common_tsize * game->map.columns && new_y < game->common_tsize * game->map.rows && new_x >= 0 && new_y >= 0) { game->player.x = new_x; game->player.y = new_y; } } void move_s_d(t_game *game) { double new_x; double new_y; new_x = game->player.x - game->player.move_speed * cos(to_radian((game->player.rot_angle - 45))); new_y = game->player.y - game->player.move_speed * sin(to_radian((game->player.rot_angle - 45))); if (move_check(game, game->player.rot_angle - 225) && !check_sprite(game, new_x, new_y) && new_x < game->common_tsize * game->map.columns && new_y < game->common_tsize * game->map.rows && new_x >= 0 && new_y >= 0) { game->player.x = new_x; game->player.y = new_y; } } void move_s(t_game *game) { double new_x; double new_y; new_x = game->player.x - game->player.move_speed * cos(to_radian((game->player.rot_angle))); new_y = game->player.y - game->player.move_speed * sin(to_radian((game->player.rot_angle))); if (move_check(game, game->player.rot_angle - 180) && !check_sprite(game, new_x, new_y) && new_x < game->common_tsize * game->map.columns && new_y < game->common_tsize * game->map.rows && new_x >= 0 && new_y >= 0) { game->player.x = new_x; game->player.y = new_y; } }
C
/* Routines for parsing arguments */ #include <stdlib.h> #include <ctype.h> #include "db.h" #include "config.h" #include "match.h" #include "externs.h" #define DOWNCASE(x) (isupper(x) ? tolower(x) : (x)) static dbref exact_match = NOTHING; /* holds result of exact match */ static int check_keys = 0; /* if non-zero, check for keys */ static dbref last_match = NOTHING; /* holds result of last match */ static int match_count; /* holds total number of inexact matches */ static dbref match_who; /* player who is being matched around */ static const char *match_name; /* name to match */ static int preferred_type = NOTYPE; /* preferred type */ void init_match(dbref player, const char *name, int type) { exact_match = last_match = NOTHING; match_count = 0; match_who = player; match_name = name; check_keys = 0; preferred_type = type; } void init_match_check_keys(dbref player, const char *name, int type) { init_match(player, name, type); check_keys = 1; } static dbref choose_thing(dbref thing1, dbref thing2) { int has1; int has2; if (thing1 == NOTHING) { return thing2; } else if (thing2 == NOTHING) { return thing1; } if (preferred_type != NOTYPE) { if (Typeof(thing1) == preferred_type) { if (Typeof(thing2) != preferred_type) { return thing1; } } else if (Typeof(thing2) == preferred_type) { return thing2; } } if (check_keys) { has1 = could_doit(match_who, thing1); has2 = could_doit(match_who, thing2); if (has1 && !has2) { return thing1; } else if (has2 && !has1) { return thing2; } /* else fall through */ } return (random() % 2 ? thing1 : thing2); } void match_player(void) { dbref match; const char *p; if (*match_name == LOOKUP_TOKEN) { for (p = match_name + 1; isspace(*p); p++); if ((match = lookup_player(p)) != NOTHING) { exact_match = match; } } } /* returns nnn if name = #nnn, else NOTHING */ static dbref absolute_name(void) { dbref match; if (*match_name == NUMBER_TOKEN) { match = parse_dbref(match_name+1); if (match < 0 || match >= db_top) { return NOTHING; } else { return match; } } else { return NOTHING; } } void match_absolute(void) { dbref match; if ((match = absolute_name()) != NOTHING) { exact_match = match; } } void match_me(void) { if (!string_compare(match_name, "me")) { exact_match = match_who; } } void match_here(void) { if (!string_compare(match_name, "here") && db[match_who].location != NOTHING) { exact_match = db[match_who].location; } } static void match_list(dbref first) { dbref absolute; absolute = absolute_name(); if (!controls(match_who, absolute)) { absolute = NOTHING; } DOLIST(first, first) { if (first == absolute) { exact_match = first; return; } else if (!string_compare(db[first].name, match_name)) { /* if there are multiple exact matches, randomly choose one */ exact_match = choose_thing(exact_match, first); } else if (string_match(db[first].name, match_name)) { last_match = first; match_count++; } } } void match_possession(void) { match_list(db[match_who].contents); } void match_neighbor(void) { dbref loc; if ((loc = db[match_who].location) != NOTHING) { match_list(db[loc].contents); } } void match_exit(void) { dbref loc; dbref exit; dbref absolute; const char *match; const char *p; if ((loc = db[match_who].location) != NOTHING) { absolute = absolute_name(); if (!controls(match_who, absolute)) { absolute = NOTHING; } DOLIST(exit, db[loc].exits) { if (exit == absolute) { exact_match = exit; } else { match = db[exit].name; while (*match) { /* check out this one */ for (p = match_name; (*p && DOWNCASE(*p) == DOWNCASE(*match) && *match != EXIT_DELIMITER); p++, match++); /* did we get it? */ if (*p == '\0') { /* make sure there's nothing afterwards */ while (isspace(*match)) { match++; } if (*match == '\0' || *match == EXIT_DELIMITER) { /* we got it */ exact_match = choose_thing(exact_match, exit); goto next_exit; /* got this match */ } } /* we didn't get it, find next match */ while (*match && *match++ != EXIT_DELIMITER); while (isspace(*match)) { match++; } } } next_exit: ; } } } void match_everything(void) { match_exit(); match_neighbor(); match_possession(); match_me(); match_here(); if (Wizard(match_who)) { match_absolute(); match_player(); } } dbref match_result(void) { if (exact_match != NOTHING) { return exact_match; } else { switch (match_count) { case 0: return NOTHING; case 1: return last_match; default: return AMBIGUOUS; } } } /* use this if you don't care about ambiguity */ dbref last_match_result(void) { if (exact_match != NOTHING) { return exact_match; } else { return last_match; } } dbref noisy_match_result(void) { dbref match; switch (match = match_result()) { case NOTHING: notify(match_who, NOMATCH_MESSAGE); return NOTHING; case AMBIGUOUS: notify(match_who, AMBIGUOUS_MESSAGE); return NOTHING; default: return match; } }
C
#include <stdio.h> unsigned int dim_right(unsigned int w){ return w^(w&-w);} unsigned int dim_left(unsigned int w){ unsigned int pos = 0, c = w; while (c>0){ c/=2; pos++;} return w^(1<<(pos-1));} unsigned int flip(unsigned int w, unsigned int f){ if ((w|1<<f)!=w) return (w|1<<f); return w^(1<<f);} int main(void){ unsigned int slowo, f; scanf("%u %u",&slowo, &f); printf("%u %u %u", dim_right(slowo), dim_left(slowo), flip(slowo,f)); return 0;}
C
#include<stdio.h> #include<unistd.h> #define CHUNK 65536 int main(int argc, char **argv) { if (argc != 2) { printf("xor_e2 {filename}\n"); return -1; } FILE *fd; unsigned char d[CHUNK]; fd = fopen(argv[1], "r+"); unsigned int i, xz_read; while((xz_read = fread(&d, sizeof(char), CHUNK, fd)) == CHUNK) { for (i=0; i<CHUNK; i++) d[i] ^= 0xe2; fseek(fd, SEEK_CUR-CHUNK-1, SEEK_CUR); fwrite(&d, sizeof(char), CHUNK, fd); } /* fread discards incomplete object so last iteration done separately */ fread(&d, sizeof(char), xz_read, fd); for (i=0; i<xz_read; i++) d[i] ^= 0xe2; fseek(fd, SEEK_CUR-xz_read-1, SEEK_CUR); fwrite(&d, sizeof(char), xz_read, fd); fclose(fd); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main_ls.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tgreil <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/16 12:26:19 by tgreil #+# #+# */ /* Updated: 2018/06/30 19:24:47 by tgreil ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void ls_initializer(t_container *c) { ft_bzero(c, sizeof(t_container)); c->option = 0; c->list_param.start = NULL; c->list_param.list_len = 0; c->list_param.path = NULL; } int ls_function_rec(t_container *c, t_list_manag *list) { list->act = list->start; while (list->act) { if (list->act->state == -2) { if (list->level > 0 || list->act->prev) ft_printf("\n"); ft_printf("%s:\n", list->act->name_pathed); ft_printf("!2!%s%s: Permission denied\n", LS_ERROR_MSG, list->act->name); } else if (S_ISDIR(list->act->stat.st_mode) && (option_is_set(c->option, OPTION_RR) || !list->level) && (!list->level || (ft_strcmp(list->act->name, ".") && ft_strcmp(list->act->name, "..")))) ls_function(c, &list->act->folder); list->act = list->act->next; } return (E_SUCCESS); } int ls_function(t_container *c, t_list_manag *list) { if (ft_ls_apply(c, list) == E_ERROR) return (E_ERROR); list_sort(list, option_is_set(c->option, OPTION_R), &sort_name); if (option_is_set(c->option, OPTION_T)) list_sort(list, option_is_set(c->option, OPTION_R), &sort_date); print_result(c, list); ls_function_rec(c, list); return (E_SUCCESS); } int ls_exit(t_list_manag *list, int status) { t_list_ls *last; list->act = list->start; while (list->act) { last = list->act; if (list->act->folder.list_len > 0) ls_exit(&list->act->folder, status); free(last->name); free(last->name_pathed); free(last->folder.path); list->act = list->act->next; free(last); } return (status); } int main(int ac, char **av) { t_container c; ls_initializer(&c); if (param_handler(&c, ac, av) == E_ERROR) return (E_ERROR); c.list_param.level = 0; if (ls_function(&c, &c.list_param) == E_ERROR) return (E_ERROR); return (ls_exit(&c.list_param, E_SUCCESS)); }
C
#include <stdio.h> #include "sqlite3.c" #include <time.h> #include <stdlib.h> static int callback(void *NotUsed, int argc, char **argv, char **azColName) { int i; for(i = 0; i<argc; i++) { printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL"); } printf("\n"); return 0; } int main(int argc, char* argv[]) { sqlite3 *db; char *zErrMsg = 0; int rc; char* sql; rc = sqlite3_open("d", &db); if( rc ) { fprintf(stderr, "Can't open database: %s\n", sqlite3_errmsg(db)); return(0); } else { fprintf(stderr, "Opened database successfully\n"); } int i; for (i = 0;i < 99; i++) { sql = "INSERT INTO Event(event_id, event_name, event_date, host_id, host_zip, host_country, host_telephone, host_state, host_city) " "VALUES (abs(random() % 10000), 'First', '2020-12-02 17:30', 5555, 32901, 'US', abs(random()) % 9000000000 + 95000000, 'FL', 'Melbourne');" "INSERT INTO Venue(venue_id, venue_name, venue_address, venue_contact, zip_code, country, state, city, event_id) " "VALUES (abs(random() % 10000), 'Civic Ctr', '500 Main St', abs(random()) % 9000000000 +95000000, abs(random()) % 90000 + 9950, 'US', 'CA', 'Los Angeles', last_insert_rowid());" "INSERT INTO Author(author_id, author_name, author_company, author_address, zip_code, country, state, city, venue_id) " "VALUES (abs(random() % 10000), 'George R.R. Martin', 'Dragon Publishing LLC', '200 Main St', abs(random()) % 90000 + 9950, 'US', 'CA', 'Los Angeles', last_insert_rowid()); " "INSERT INTO Paper(paper_id, paper_word_count, paper_name, paper_title, author_id, editor_id, editor_contact, zip_code) " "VALUES (abs(random() % 10000), 2003, 'Game of Thrones I', 'Let the Games Begin', last_insert_rowid(), abs(random()) % 10000, abs(random()) % 9000000000 + 95000000, abs(random()) % 90000 + 9950);" "INSERT INTO Reviewer(reviewer_id, reviewer_address, reviewer_name, reviewer_contact, zip_code, country, state, city, paper_id) " "VALUES (abs(random() % 10000), '1321 State Rd', 'David', abs(random()) % 9000000000 +95000000, abs(random()) % 90000 + 9950, 'US', 'ME', 'Eliot', last_insert_rowid());" "INSERT INTO Chair(chair_name, committee, responsibility, head, reviewer_id) " "VALUES ('Setup', 'Alex, Parthil', 'Setup event', 'Dr. Silaghi', last_insert_rowid());"; rc = sqlite3_exec(db, sql, callback, 0, &zErrMsg); } if(rc != SQLITE_OK){ fprintf(stderr, "SQL error: %s\n", zErrMsg); sqlite3_free(zErrMsg); } else { fprintf(stdout, "Records created successfully\n"); } sqlite3_close(db); return 0; }
C
#include <stdio.h> #include <assert.h> #include "ArrayList.h" void ListInit(Array* array) { array->length = 0; array->curPosition = -1; } void LInsert(Array* array, LData data) { assert(array->length < LIST_LEN); array->arr[array->length++] = data; } int LFirst(Array* array, LData* pdata) { if (array->length == 0) { return FALSE; } array->curPosition = 0; *pdata = array->arr[0]; return TRUE; } int LNext(Array* array, LData* pdata) { if (array->curPosition >= array->length-1) { return FALSE; } *pdata = array->arr[++array->curPosition]; return TRUE; } LData LRemove(Array* array) { int rpos = array->curPosition; LData removeData = array->arr[rpos]; size_t i; for (i = rpos; i < array->length - 1; ++i) { array->arr[i] = array->arr[i + 1]; } --array->curPosition; --array->length; return removeData; } int LCount(const Array* array) { return array->length; }
C
#include "tree.h" #include "visualtree.h" #include <stdio.h> #include <assert.h> #include <time.h> int main(){ /*node *t = scan_tree(); int i; for( i = 0; i < 100; i++){ if (find_bst(t,i)){ printf("%d ", i); } } printf("\n"); write_tree(t); t = insert_bst(t, 2); t = insert_bst(t, 15); write_tree(t);*/ char ch; int data; node *t = NULL; printf("1. construire un nouvel arbre à partir d'une suite d'entiers (`s 7 5 0 0 12 10 0 0 0')\n"); printf("2. construire un arbre avec un nombre d'entiers aléatoires : (a 500')\n"); printf("3. insérer un élément dans l'arbre (`i 18')\n"); printf("4. faire une recherche dans l'arbre (`f 42')\n"); printf("5. afficher les entiers de l'arbre triés en ordre croissant (t)\n"); printf("6. eleminer une elment (r 42)\n"); printf("7. terminer le programme (q)\n"); scanf(" %c", &ch); while(ch != 'q'){ { if (ch =='s'){ free_tree(t); t = scan_tree(); } if (ch == 'a'){ free_tree(t); scanf("%d", &data); t = tree_alea(data); } if (ch == 'i'){ scanf("%d", &data); t = insert_bst(t, data); } if (ch == 'f'){ scanf("%d", &data); if (find_bst(t, data)) printf("Trouvé\n"); else printf("Pas Trouvé\n"); } if (ch == 't'){ display_infix(t); } if (ch == 'r'){ scanf("%d", &data); t = remove_bst(t, data); } } printf("1. construire un nouvel arbre à partir d'une suite d'entiers (`s 7 5 0 0 12 10 0 0 0')\n"); printf("2. construire un arbre avec un nombre d'entiers aléatoires : (a 500')\n"); printf("3. insérer un élément dans l'arbre (`i 18')\n"); printf("4. faire une recherche dans l'arbre (`f 42')\n"); printf("5. afficher les entiers de l'arbre triés en ordre croissant (t)\n"); printf("6. eleminer une elment (r 42)\n"); printf("7. terminer le programme (q)\n"); scanf(" %c", &ch); } free_tree(t); /****Chrono****/ /*node *t = NULL; printf("%f\n", chrono(t, 8000000)); 8.10⁶ elements printf("%f\n", chrono_ordre(t, 75000)); 7,5.10⁴ elements */ /****test****/ /*node *t = NULL; t = tree_alea(500); int i, random; srand(time(NULL)); for(i = 0; i < 200; i++){ random = rand() % (999); } write_tree(t);*/ return 0; }
C
#include<stdio.h> int main() { char ch; printf("enter the character"); scanf("%c",ch); int lowercasevowel,uppercasevowel; lowercasevowel=(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u') uppercasevowel=(ch=='A'||ch=='E'||ch==I||ch=='O'||ch=='U') if(lowercasevowel||uppercasevowel) { printf("%c is a vowel",c); } else { printf("is consonent %c",c); } return 0; }
C
/****************************************************** * DSA Lab Test 2: Problem 1 (tree.h) * * Do not edit this file. * ****************************************************/ #include <stdbool.h> #ifndef TREE_H_INCLUDED #define TREE_H_INCLUDED struct _tnode { unsigned int data; struct _tnode *left, *right; }; typedef struct _tnode *tree; enum probability {LEMPTY, REMPTY, NONEMPTY}; unsigned int* createList(unsigned int p); tree constructTree(unsigned int *list, unsigned int len); bool matchTreeIterative(tree root, unsigned int *x, unsigned int size); #endif // TREE_H_INCLUDED
C
/*Задача 2. Дефинирайте и инициализирайте двумерен масив с по 5 елемента (5 x 5). След като сте готови, направете въвеждане на данните в масива, като четете от потребителя със scanf. */ #include <stdio.h> int main(void) { int matrix[5][5]; int i, j; for (i = 0; i < 5; i++) { for (j = 0; j < 4; j++) { printf("Item[%d][%d]=", i, j); scanf("%d", &matrix[i][j]); } } for (i = 0; i < 5; i++) { printf("\n"); for (j = 0; j < 4; j++) { printf("%d ", matrix[i][j]); } } return 0; }
C
#include "structs.h" #include "functions.h" #include <math.h> #include <time.h> #include <stdio.h> #include <string.h> #include <stdlib.h> struct euc_vec{ float *vector; //array of random coordinates float t; }; struct Node{ char name[12]; int visited; int center; //cluster which belongs to int center2; //second best cluster float dist_center; //distance from center of cluster float dist_center2; //distance of second best center float* array; //array of coordinates of item }; struct List_nodes{ Node point; //list of nodes (each node represents an item) List_nodes *next; }; struct List_pointers{ long int id; //we use ID to avoid unnecessary computations Node *nodeptr; //list of pointers to nodes (each pointer points to a specific node) List_pointers *next; }; struct euc_cluster{ Node *nodeptr; //pointer to center int items; //number of items in cluster float silhouette; //silhouette pointer }; int F_Euclidean(unsigned long int ID,int hash_size){ return ID%hash_size; } unsigned long int ID_euclidean(int **G_h, int no_G, Node p, int size, long int *random_r, int k,euc_vec *vectors,int W){ unsigned long int M=pow(2,32)-5; int i,j; unsigned long int sum=0; float t; for(i=0;i<k;i++){ t= H_euclidean(vectors[G_h[no_G][i]],p,size,W); t=t*random_r[i]; sum= sum+ t; } if(sum<0) sum=sum*(-1); return sum%M; } long int H_euclidean(euc_vec vector_t, Node p,int size,int W){ int i; long int j; float sum=0; for(i=0; i<size; i++){ sum=sum+ (vector_t.vector[i]*p.array[i]); //inner product } sum=(sum+vector_t.t)/W; j=sum; return j; } float euclidean_distance(float *point, float *item, int size){ int i; float sum=0,square; for(i=0; i<size; i++){ square= point[i]-item[i]; square=pow(square,2); //(xi-yi)^2 for each coordinate sum=sum + square; } sum=sqrt(sum); return sum; } List_nodes* Euclidean_input(FILE *fd,int* final_size, int * item){ int items=0; List_nodes *listn=NULL; int size=0; int tempsize=2; char bla[12]; float * array; array=malloc(tempsize*sizeof(float)); fscanf(fd, "%s",bla); items++; char c; c='t'; while(c!='\n') { fscanf(fd, "%f%c", &(array[size]), &c); size++; //finds the dimension of vector if (size==tempsize-1){ tempsize*=2; array=realloc(array, tempsize*sizeof(float)); } } array=realloc(array, size*sizeof(float)); List_nodes *tempnod; tempnod=malloc(sizeof(List_nodes)); strcpy(tempnod->point.name,bla); memset(bla, 0, sizeof(bla)); tempnod->point.array=array; tempnod->point.visited=0; tempnod->next=listn; listn=tempnod; int i; while(!feof(fd)){ fscanf(fd, "%s", bla); items++; if (!strcmp(bla,"")){ items--; break; } tempnod=malloc(sizeof(List_nodes)); strcpy(tempnod->point.name,bla); memset(bla, 0, sizeof(bla)); tempnod->point.array=malloc(size*sizeof(float)); tempnod->point.visited=0; //fill list of items for(i=0;i<size;i++) { fscanf(fd, "%f", &(tempnod->point.array[i])); } tempnod->next=listn; listn=tempnod; } *final_size=size; *item=items; printf("File Read with success\n"); List_nodes *pointer=listn; return listn; } void init_randvec(euc_vec **randvec,int L, int k,int W,int size){ int i,j; (*randvec)=malloc(L*k*(sizeof(euc_vec))); for(i=0;i<L*k;i++){ (*randvec)[i].vector=malloc(size*sizeof(float)); } for(i=0;i<L*k;i++){ (*randvec)[i].t=((float)rand()/(float)(RAND_MAX)*W); for(j=0;j<size;j++){ (*randvec)[i].vector[j]=marsaglia(); //initialise array of rand vectors using gaussian distribution } } } void init_array(Node ***array,List_nodes *listn, int items){ int i; //array of items to easy find the items (*array)=malloc(items*(sizeof(Node*))); i=items-1; List_nodes *pointer=listn; while(pointer!=NULL){ (*array)[i]=&pointer->point; (*array)[i]->center=-1; (*array)[i]->center2=-1; pointer=pointer->next; i--; } } void print_array(Node **array, int items){ int i; for(i=0; i<items ;i++){ printf("%s,%f\n",array[i]->name,array[i]->array[0]); } } void init_euc_cl(euc_cluster **clusters,int no_cl){ (*clusters)=malloc(no_cl*sizeof(euc_cluster)); printf("Clusters initialized!\n"); } void euc_init_parkjun(Node **array,int items,int size,euc_cluster **clusters,int no_cl){ //initialization concentrate int i,j,z; float **distances; distances= malloc(items*sizeof(float*)); for(i=0;i<items;i++){ distances[i]=malloc(items*sizeof(float)); } float distance; for(i=0;i<items;i++){ for(j=0;j<items;j++){ distance=euclidean_distance(array[i]->array,array[j]->array,size); distances[i][j]=distance; } } float *vi; Node **temparray; temparray=malloc(items*sizeof(Node*)); for(i=0;i<items;i++){ temparray[i]=array[i]; } vi=malloc(items*sizeof(float)); int t; float dist; for(i=0;i<items;i++){ vi[i]=0; for(j=0;j<items;j++){ dist=0; for(t=0; t<items; t++){ dist= dist+ distances[j][t]; } distance= distances[i][j]; vi[i]=vi[i]+ (distance/dist); } } Node *temp; float swap; for(z=0; z<items-1; z++){ for(i=0; i<items-z-1; i++){ if(vi[i]>vi[i+1]){ temp=temparray[i]; swap=vi[i]; vi[i]=vi[i+1]; temparray[i]=temparray[i+1]; vi[i+1]=swap; temparray[i+1]=temp; } } } for(i=0;i<no_cl;i++){ (*clusters)[i].nodeptr=temparray[i]; (*clusters)[i].items=0; (*clusters)[i].silhouette=0; } for(i=0;i<items;i++){ free(distances[i]); } free(distances); free(temparray); free(vi); } void print_clusters(euc_cluster *clusters,int no_cl){ //we dont use this function. it is just for check int i; for(i=0;i<no_cl;i++) printf("CLUSTER-%d: {size: %d, medoid: %s}\n",i+1,clusters[i].items,clusters[i].nodeptr->name); } void init_hash(List_pointers ****hashtable,euc_vec *randvec,int size,int k,int L,int hashsize,List_nodes *listn,int **G_h,int W,long int *random_r){ int i,j; *hashtable=malloc(sizeof(List_pointers **)*hashsize); for(i=0;i<hashsize;i++){ (*hashtable)[i]=malloc(sizeof(List_pointers*)*L); for(j=0;j<L;j++){ (*hashtable)[i][j]=NULL; } } printf("Hashtables allocated\n"); List_nodes *pointer=listn; int bucket; long int g; while(pointer!=NULL){ for(i=0;i<L;i++){ g=ID_euclidean(G_h,i, pointer->point, size,random_r,k,randvec,W); bucket= F_Euclidean(g,hashsize); //F returns the bucket of the hashtable where the item must be stored List_pointers *temptr; temptr=malloc(sizeof(List_pointers)); temptr->nodeptr=&(pointer->point); temptr->id=g; temptr->next=(*hashtable)[bucket][i]; (*hashtable)[bucket][i]=temptr; } pointer=pointer->next; } printf("Data stored in hashtables\n"); } //assignment by ANN void euc_by_ANN(euc_cluster *clusters,int no_cl,int items, Node **array,int size,List_pointers ***hashtables,int k,int L,int W,euc_vec *randvec,long int *random_r,int hashsize,int **G_h){ int i,j,sum=0; float min_distance,min_distance1,distance; for(i=0; i<no_cl; i++){ for(j=0; j<no_cl; j++){ if(j!=i){ distance=euclidean_distance(clusters[i].nodeptr->array,clusters[j].nodeptr->array,size); if(i==0 && j==1) min_distance=distance; if(distance<min_distance) min_distance=distance; } } } min_distance1=min_distance; min_distance=min_distance/2; int bucket,id,flag,flag1; do{ flag=0; for(i=0;i<no_cl;i++){ for(j=0;j<L;j++){ id=ID_euclidean(G_h,j,*clusters[i].nodeptr, size,random_r,k,randvec,W); bucket= F_Euclidean(id,hashsize); List_pointers *go=hashtables[bucket][j]; while(go!=NULL){ distance=euclidean_distance(go->nodeptr->array,clusters[i].nodeptr->array,size); if(distance<=min_distance){ if(go->nodeptr->center==-1){ flag=1; sum++; go->nodeptr->dist_center=distance; go->nodeptr->center=i; } else{ if(distance < go->nodeptr->dist_center){ flag=1; go->nodeptr->dist_center2=go->nodeptr->dist_center; go->nodeptr->center2=go->nodeptr->center; go->nodeptr->dist_center=distance; go->nodeptr->center=i; } } } go=go->next; } } } min_distance= 2*min_distance; //double the radius }while(flag==1); //stops when none of the centers has new item for(i=0;i<items;i++){ //check for items left without center and add 2nd best center float dist1; if(array[i]->center==-1){ dist1= euclidean_distance(array[i]->array,clusters[0].nodeptr->array,size); array[i]->center=0; array[i]->dist_center=dist1; for(j=1;j<no_cl;j++){ dist1= euclidean_distance(array[i]->array,clusters[j].nodeptr->array,size); if(dist1<array[i]->dist_center){ array[i]->center2=array[i]->center; array[i]->dist_center2=array[i]->dist_center; array[i]->center=j; array[i]->dist_center=dist1; } } } if(array[i]->center2==-1){ if(array[i]->center==0){ dist1= euclidean_distance(array[i]->array,clusters[1].nodeptr->array,size); array[i]->center2=1; array[i]->dist_center2=dist1; } else{ dist1= euclidean_distance(array[i]->array,clusters[0].nodeptr->array,size); array[i]->center2=0; array[i]->dist_center2=dist1; } for(j=2;j<no_cl;j++){ dist1= euclidean_distance(array[i]->array,clusters[j].nodeptr->array,size); if(dist1<array[i]->dist_center2 && array[i]->center!=j){ array[i]->dist_center2=dist1; array[i]->center2=j; } } } } } //pam assignment void euc_pam_ass(euc_cluster *clusters,int no_cl,int items, Node **array,int size){ int i,j; float distance; for(i=0;i<items;i++){ distance=euclidean_distance(array[i]->array,clusters[0].nodeptr->array,size); array[i]->center2=-1; array[i]->dist_center=distance; //finds first best array[i]->center=0; for(j=1;j<no_cl;j++){ distance=euclidean_distance(array[i]->array,clusters[j].nodeptr->array,size); if(distance<array[i]->dist_center){ array[i]->dist_center2=array[i]->dist_center; array[i]->center2=array[i]->center; array[i]->dist_center=distance; array[i]->center=j; } } } for(i=0;i<items;i++){ if(array[i]->center2==-1){ for(j=1;j<no_cl;j++){ //check for second best (it might already exist from the first "for") distance=euclidean_distance(array[i]->array,clusters[j].nodeptr->array,size); if(distance!=array[i]->dist_center){ if(array[i]->center2==-1){ array[i]->dist_center2=distance; array[i]->center2=j; } else if(distance<array[i]->dist_center2 ){ array[i]->dist_center2=distance; array[i]->center2=j; } } } } } } //assignment by clarans int euc_clarans(euc_cluster **clusters,int no_cl,int items, Node **array,int size,int s, int Q){ int i,j,flag=0,w; euc_cluster *tempclusters; int **m_t; m_t=malloc(Q*sizeof(int*)); for(i=0;i<Q;i++){ m_t[i]=malloc(2*sizeof(int)); } int random; for(i=0;i<Q;i++){ random=rand()%(no_cl*items); m_t[i][0]=random%no_cl; m_t[i][1]=random/no_cl; } float J=0; for(i=0;i<items;i++){ J=J+array[i]->dist_center; } flag=0; float best_J=J; float dJ,distance,J_new; for(w=0;w<s;w++){ for(i=0;i<Q;i++){ dJ=0; for(j=0;j<items;j++){ distance= euclidean_distance(array[j]->array,array[m_t[i][1]]->array,size); if(array[j]->center==m_t[i][0]){ if(array[j]->dist_center2>=distance){ dJ=dJ+distance- array[j]->dist_center; //as written in theory } else{ dJ=dJ+array[j]->dist_center2 - array[j]->dist_center; } } else{ if(array[j]->dist_center>distance){ dJ=dJ+distance- array[j]->dist_center; } } } J_new=J+dJ; if(J_new<J && J_new<best_J){ (*clusters)[m_t[i][0]].nodeptr=array[m_t[i][1]]; best_J=J_new; flag=1; } } } for(i=0;i<items;i++){ array[i]->center=-1; array[i]->center2=-1; } for(i=0;i<Q;i++){ free(m_t[i]); } free(m_t); return flag; } int euc_Loyds(euc_cluster **clusters, int no_cl, int items, Node **array, int size){ int i,j,flag=0,k; float J=-1,distance,sum; Node *p; for(j=0;j<no_cl;j++){ J=-1; for(i=0;i<items;i++){ sum=0; if(array[i]->center==j){ for(k=0;k<items;k++){ if(array[k]->center==j){ distance=euclidean_distance(array[i]->array,array[j]->array,size); //calculate medoids sum=sum+distance; if(J==-1){ J=sum; p=array[i]; } if(sum<J){ J=sum; p=array[i]; } } } } } if(p!=(*clusters)[j].nodeptr){ flag=1; (*clusters)[j].nodeptr=p; } } if(flag==1){ for(i=0;i<items;i++){ array[i]->center=-1; array[i]->center2=-1; } } return flag; } void k_medoids(int k,int size,int items,Node ***array,euc_cluster **clusters){ int centers_count=1; int random,*cent_pos,flag,flag1,i,l,j; srand(time(NULL)); float *prob,sum,sumtemp,rand_sum,temp,min; float *previous_rands; random=rand() % items; cent_pos=malloc(k*sizeof( int)); prob=malloc((items+1)*sizeof( float)); previous_rands=malloc(k*sizeof(float)); cent_pos[0]=random; (*clusters)[centers_count-1].nodeptr=(*array)[random]; centers_count++; while(centers_count<=k){ sum=0.0; for (i=0;i<items;i++){ flag=0; for(l=0;l<centers_count-1;l++){ if(i==cent_pos[l]) flag=1; } if(flag==0){ min=euclidean_distance((*array)[i]->array,(*clusters)[0].nodeptr->array,size); for(j=1;j<centers_count-1;j++){ temp=euclidean_distance((*array)[i]->array,(*clusters)[j].nodeptr->array,size); if(temp<min){ min=temp; } } prob[i]=min; sum+=pow(prob[i],2); } } rand_sum = (float)rand()/(float)(RAND_MAX/sum); flag1=1; flag=0; while(flag==0){ for(j=0;j<centers_count-2;j++){ if(rand_sum==previous_rands[j]) flag1=0; } if(flag1==1){ previous_rands[centers_count-2]=rand_sum; flag=1; } else rand_sum = (float)rand()/(float)(RAND_MAX/sum); } flag=0; i=0; sumtemp=0; while(i<items && flag==0){ flag1=0; for(l=0;l<centers_count-1;l++){ if(i==cent_pos[l]) flag1=1; } if(flag1==0){ sumtemp+=pow(prob[i],2); if(sumtemp>=rand_sum){ //if the new temp surpasses the rand ,means we found our new center (*clusters)[centers_count-1].nodeptr=(*array)[i]; cent_pos[centers_count-1]=i; flag=1; } } i++; } centers_count++; } free(cent_pos); free(prob); free(previous_rands); } void euc_silhouette(euc_cluster *clusters, Node **array,int size,int no_cl,int items){ int i,j; float dista=0, distb=0,s; int suma,sumb; for(i=0;i<no_cl;i++){ clusters[i].items=0; clusters[i].silhouette=0; } for(i=0;i<items;i++){ dista=0; distb=0; suma=0; sumb=0; for(j=0;j<items;j++){ if(array[i]->center==array[j]->center){ dista=dista+ euclidean_distance(array[i]->array,array[j]->array,size); suma++; } else if(array[i]->center2==array[j]->center){ distb=distb+ euclidean_distance(array[i]->array,array[j]->array,size); sumb++; } } dista=dista/suma; distb=distb/sumb; if(dista>=distb) s= distb/dista -1; else s=1- dista/distb; clusters[array[i]->center].items++; clusters[array[i]->center].silhouette+=s; } for(i=0;i<no_cl;i++){ clusters[i].silhouette=clusters[i].silhouette/clusters[i].items; } } void euc_print_data(FILE *output,euc_cluster *clusters, Node **array, int size, int items, int no_cl,int flag,double time){ int i,j,flag1=0; for(i=0; i<no_cl; i++){ fprintf(output,"CLUSTER-%d: {size: %d, medoid: %s}\n",i+1,clusters[i].items,clusters[i].nodeptr->name); } fprintf(output,"clustering time:%f\n",time); fprintf(output,"Silhouette: ["); for(i=0;i<no_cl;i++){ if(i!=0) fprintf(output,","); fprintf(output,"%f",clusters[i].silhouette); clusters[i].silhouette=0; clusters[i].items=0; clusters[i].nodeptr=NULL; } fprintf(output,"]\n"); if(flag==1){ for(i=0;i<no_cl;i++){ flag1=1; fprintf(output,"CLUSTER-%d: {",i+1); for(j=0;j<items;j++){ if(array[j]->center==i){ if(flag1==1){ fprintf(output,"%s",array[j]->name); flag1=0; } else fprintf(output,",%s",array[j]->name); } } fprintf(output,"}\n"); } } for(i=0;i<items;i++){ array[i]->center=-1; array[i]->center2=-1; } } void free_hash(List_pointers ****hashtable, int hashsize,int L){ int i,j; List_pointers *temp; for(i=0;i<hashsize;i++){ for(j=0;j<L;j++){ temp=(*hashtable)[i][j]; while(temp!=NULL){ List_pointers *temptemp; temptemp=temp; temp=temp->next; free(temptemp); } } free((*hashtable)[i]); } free(*hashtable); (*hashtable)=NULL; } void free_list_nodes(List_nodes **listn, int size){ List_nodes *templist; int i; while((*listn)!=NULL){ templist=(*listn); (*listn)=(*listn)->next; free(templist->point.array); free(templist); } } void free_randvec(euc_vec **randvec, int L, int k){ int i; for(i=0;i<L*k;i++){ free((*randvec)[i].vector); } free(*randvec); (*randvec)=NULL; } void euc_main(FILE *input,FILE *output,int k,int no_cl, int Q, int s,int L,int W,int com){ clock_t begin, end; double time_spent; int **G_h; int size,o,items,i,j,ok; List_nodes *listn; //list of elements read from file listn=Euclidean_input(input,&size, &items); //store elements from file in list if(k>(log(items)/log(2))){ k=(log(items)/log(2))-1; printf("k is to big, k is going to be %d\n",k); } euc_vec *randvec; // random vectors init_randvec(&randvec,L,k,W,size); initG_h(&G_h,k,L,1,size); int hashsize=items/8; List_pointers ***hashtables; long int *random_r; //1d array with random r random_r=malloc(k*sizeof(long int)); for(i=0;i<k;i++){ random_r[i]=(long int)rand(); } init_hash(&hashtables,randvec,size,k,L,hashsize,listn,G_h,W,random_r); //store itmes from list to hashtables with euclidean method fclose(input); Node **objects; init_array(&objects,listn,items); euc_cluster *clusters; init_euc_cl(&clusters,no_cl); printf("Writing in file...\n"); for(i=1;i<3;i++){ //here starts the combination of the algorithms for(j=0;j<4;j++){ begin=clock(); if(i==1) k_medoids(no_cl,size,items,&objects,&clusters); else if(i==2) euc_init_parkjun(objects,items,size,&clusters,no_cl); if (j==0){ fprintf(output,"Algorithm: I%dA1U1\n",i); do{ euc_pam_ass(clusters,no_cl,items,objects,size); ok=euc_Loyds(&clusters,no_cl,items,objects,size); }while(ok==1); end=clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; euc_silhouette(clusters,objects,size,no_cl,items); euc_print_data(output,clusters,objects,size,items,no_cl,com,time_spent); } else if(j==1){ fprintf(output,"Algorithm: I%dA1U2\n",i); for(o=0;o<s;o++){ euc_pam_ass(clusters,no_cl,items,objects,size); ok=euc_clarans(&clusters,no_cl,items,objects,size,1,Q); } euc_pam_ass(clusters,no_cl,items,objects,size); end=clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; euc_silhouette(clusters,objects,size,no_cl,items); euc_print_data(output,clusters,objects,size,items,no_cl,com,time_spent); } else if(j==2){ fprintf(output,"Algorithm: I%dA2U1\n",i); do{ euc_by_ANN(clusters,no_cl,items,objects,size,hashtables,k,L,W,randvec,random_r,hashsize,G_h); ok=euc_Loyds(&clusters,no_cl,items,objects,size); }while(ok==1); end=clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; euc_silhouette(clusters,objects,size,no_cl,items); euc_print_data(output,clusters,objects,size,items,no_cl,com,time_spent); } else if(j==3){ fprintf(output,"Algorithm: I%dA2U2\n",i); for(o=0;o<s;o++){ euc_by_ANN(clusters,no_cl,items,objects,size,hashtables,k,L,W,randvec,random_r,hashsize,G_h); ok=euc_clarans(&clusters,no_cl,items,objects,size,1,Q); } euc_by_ANN(clusters,no_cl,items,objects,size,hashtables,k,L,W,randvec,random_r,hashsize,G_h); end=clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; euc_silhouette(clusters,objects,size,no_cl,items); euc_print_data(output,clusters,objects,size,items,no_cl,com,time_spent); } } } fclose(output); free(clusters); free(objects); free_randvec(&randvec,L,k); free_hash(&hashtables,hashsize,L); free_list_nodes(&listn,size); freeG_h(&G_h,L); free (random_r); }
C
#include <stdio.h> #include <string.h> #define MAX 999 #define MIN 100 int itostr(int n, int str[]); int isPalindrome(int str[], int length); int main(void) { int a, b, largest = 0, pdt, length; int pdt_str[15]; for (a = MAX; a >= MIN; a--) { for (b = MAX; b >= MIN; b--) { pdt = a*b; length = itostr(pdt, pdt_str); if (isPalindrome(pdt_str, length)&& (pdt > largest)) { largest = pdt; } } } printf("largest: %d", largest); return 0; } int itostr(int n, int str[]) { int i = 0; while (n > 0) { str[i++] = n%10; n /= 10; } return i; } int isPalindrome(int str[], int length) { if (length == 1) return 1; else if (length == 2) return str[0] == str[1]; else return ((str[0] == str[length-1]) && (isPalindrome(++str, length-2))); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "zend_hash.h" int main(int argc, char **argv) { HashTable ht; HashPosition pos; char *str_key, *str_val; ulong num_key; uint str_key_len; int key_type; zend_hash_init(&ht, 2, NULL); zend_hash_add(&ht, "aaa", 3, "1111111111111111", 0, NULL); zend_hash_add(&ht, "bbb", 3, "2222222222222222", 0, NULL); zend_hash_add(&ht, "ccc", 3, "3333333333333333", 0, NULL); zend_hash_index_update(&ht, 4, "4444444444444444", 0, NULL); str_val = NULL; zend_hash_find(&ht, "bbb", 3, (void**)&str_val); printf("find(bbb) = %s\n", str_val); zend_hash_internal_pointer_reset_ex(&ht, &pos); while (zend_hash_get_current_data_ex(&ht, (void **)&str_val, &pos) == SUCCESS) { key_type = zend_hash_get_current_key_ex(&ht, &str_key, &str_key_len, &num_key, 0, &pos); switch(key_type) { case HASH_KEY_IS_STRING: printf("%s => %s\n", str_key, str_val); break; case HASH_KEY_IS_LONG: printf("%ld => %s\n", num_key, str_val); break; EMPTY_SWITCH_DEFAULT_CASE() } zend_hash_move_forward_ex(&ht, &pos); } zend_hash_destroy(&ht); return 0; }
C
#include <stdio.h> #include <string.h> int main() { char text[100], ch; int type, key, i=0, length; printf("Enter the text: "); gets(text); printf("Chose an option: \n"); printf("0 - Encrypt \n"); printf("1 - Decrypt \n"); scanf("%d", &type); while((type < 0) || (type > 1)) { printf("Wrong option! %d \n",type); printf("Chose an option: \n"); printf("0 - Encrypt \n"); printf("1 - Decrypt \n"); scanf("%d", &type); } printf("Enter the key: \n"); scanf("%d", &key); if(type == 0) { length = strlen(text); for(i = 0; i<= length; i++) { if((text[i] >= 65)&&(text[i] <= 90)) { ch = text[i] + key; if(ch > 90) { ch = ch % 90 + 64; } printf("%c",ch); } else if((text[i] >= 97)&&(text[i] <= 122)) { ch = text[i] + key; if(ch > 122) { ch = ch % 122 + 96; } printf("%c",ch); } else { printf("%c",text[i]); } } } else { length = strlen(text); for(i = 0; i<= length; i++) { if((text[i] >= 65)&&(text[i] <= 90)) { ch = text[i] - key; if(ch < 65) { ch = 90 - (64 - ch); } printf("%c",ch); } else if((text[i] >= 97)&&(text[i] <= 122)) { ch = text[i] - key; if(ch < 97) { ch = 122 - (96 - ch); } printf("%c",ch); } else { printf("%c",text[i]); } } } return 0; }
C
#include<stdio.h> #include<LPC17xx.h> #include <stdlib.h> #include<string.h> unsigned char a[] = "7500398BBC7B"; char* itoa(int num, char* str); void reverse(char str[], int length); int cal(int l,int k); void uart_init(void); int main() { char i; char last[6],first[4]; itoa(cal(9,5),last); itoa(cal(5,3),first); SystemInit(); //Uart intialization LPC_PINCON->PINSEL0 |= 0x00000050; uart_init(); for(i=0; last[i]!='\0' ; i++) { while((LPC_UART0->LSR&0x20) != 0x20) {} LPC_UART0->THR = last[i]; } return 0; } int cal(int l,int k) { char i,j=0,s=0; for(i=l;i>k;i--) { if(a[i]>=0x30 && a[i]<=0x39) { a[i]=a[i]-0x30; } if(a[i]>=0x41 && a[i]<=0x46) { a[i]=a[i]-0x31; } s+=a[i]*22^(j); j++; } return s; } char* itoa(int num, char* str) { int i = 0; // Process individual digits while (num != 0) { int rem = num % 10; str[i++] = (rem > 9)? (rem-10) + 'a' : rem + '0'; num = num/10; } str[i] = '\0'; // Append string terminator // Reverse the string reverse(str, i); return str; } void reverse(char str[], int length) { int start = 0; int end = length -1; int t; while (start < end) { t=*(str+start); str[start]= *(str+end); str[end] = t; start++; end--; } }
C
/* EE231002 Lab10. Academic Competition 107061113, 李柏葳 Date: 2018/11/26 */ #include <stdio.h> struct STU { // student info char fName[15]; // first name char lName[15]; // last name double math, sci, lit; // score of each subject double total; // total score double min; // min score among 3 subject int winTotal; // if win grand prize int winSubj; // if win subject prize }; struct STU list[100]; // make 100 student's info void readdata(void); // get data void total(void); // total 3 scores void min(void); // get min score of 3 subj. void wingrand(void); // output who win grand void winmath(void); // who win math void winsci(void); // who win science void winlit(void); // who win literature void subjprize0(void); // reset the subj. prize counter int main(void) { int i; for (i = 0; i < 100; i++) { // reset all total prize counter list[i].winTotal = 0; } subjprize0(); // instruction all above readdata(); total(); min(); wingrand(); winmath(); winsci(); winlit(); return 0; } void readdata(void) // read in student info { int i; while (getchar() != '\n') {}; // discard first line for (i = 0; i < 100; i++) { // scan in 100 students info scanf("%s%s%lf%lf%lf", list[i].fName, list[i].lName, &list[i].math, &list[i].sci, &list[i].lit); } return; } void total(void) // sum their 3 scores { int i; for (i = 0; i < 100; i++) { // sum every student's 3 score in their total list[i].total = list[i].math + list[i].sci + list[i].lit; } return; } void min(void) // get min score of each student { int i; for (i = 0; i < 100; i++) { list[i].min = list[i].math; // set min is math score if (list[i].min > list[i].sci) // if sci is lower, replace min list[i].min = list[i].sci; if (list[i].min > list[i].lit) // if lit is lower, replace min list[i].min = list[i].lit; } return; } void wingrand(void) // print out grand result { int i,j; float max; // store current max score int index = 0; // store highest score index printf("Grand Prize:\n"); // print categories for (j = 1; j <= 5; j++) { // get 5 highest max = 0; // reset max value for (i = 0; i < 100;i++) { // find highest score if (max < list[i].total && list[i].min >= 80 && list[i].winTotal == 0) { // reset max if he not win grand and score higher than max max = list[i].total; // store new score index = i; // get index } } printf(" %d: %s %s %.1lf\n", j, list[index].fName, // print result list[index].lName, list[index].total); list[index].winTotal = 1; // tag student win grand } return; } void winmath(void) // print out math result { int i,j; float max; int index = 0; printf("Math Prize:\n"); for (j = 1; j <= 10; j++) { // print 10 highest math score max = 0; for (i = 0; i < 100;i++) { // get max score if (list[i].winTotal == 0 && list[i].winSubj == 0 && list[i].min >= 60 && max < list[i].math) { // store max value if he not win grand and math award max = list[i].math; // store max value index = i; // get highest student index } } printf(" %d: %s %s %.1lf\n", j, list[index].fName, // print result list[index].lName, list[index].math); list[index].winSubj = 1; // tag the student get subject award } subjprize0(); // reset subject tag return; } void winsci(void) // print science award winners { int i,j; float max; int index = 0; // highest score's index printf("Science Prize:\n"); for (j = 1; j <= 10; j++) { // print top 10 result max = 0; for (i = 0; i < 100; i++) { // get new score if (list[i].winTotal == 0 && list[i].winSubj == 0 && list[i].min >= 60 && max < list[i].sci) { // store max value if he not win grand and sci award max = list[i].sci; // store higher science score index = i; // higher score's index } } printf(" %d: %s %s %.1lf\n", j, list[index].fName, // print stu score list[index].lName, list[index].sci); list[index].winSubj = 1; } subjprize0(); // reset tag if subject done return; } void winlit(void) // print literature result { int i,j; float max; int index = 0; printf("Literature Prize:\n"); for (j = 1; j <= 10; j++) { // get top10 result max = 0; for (i = 0; i < 100;i++) { if (list[i].winTotal == 0 && list[i].winSubj == 0 && list[i].min >= 60 && max < list[i].lit) { // store max value if he not win grand and math award max = list[i].lit; // store higher score index = i; // get higher score's index } } printf(" %d: %s %s %.1lf\n", j, list[index].fName, // print stu result list[index].lName, list[index].lit); list[index].winSubj = 1; // tag win lit prize } return; } void subjprize0(void) { // reset subject prize value int i; for (i = 0;i < 100; i++) { list[i].winSubj = 0; } return; }
C
#ifndef __LIMITED_LIST__ #define __LIMITED_LIST__ #include <stddef.h> #include <stdlib.h> // type of elements stored typedef size_t LL_Value; // definition of a structure that allows to store // a maximum number of elements as circular array typedef struct { // pointer to the stored data LL_Value *values; // maximum number of elements size_t max_size; // current number of elements stored size_t cur_size; // index of the first element size_t start_pos; // next index in which we can insert an element size_t next_pos; } Limited_List; /*** USEFUL MACROS ***/ // retrieves the element at the position 'p' from the Limited_List 'll' #define LIMITED_LIST_GET(ll,p) (ll)->values[((ll)->start_pos+(p))%(ll)->max_size] void Limited_List_init(Limited_List *ll); void Limited_List_add(Limited_List *ll, LL_Value value); void Limited_List_destroy(Limited_List *ll); #endif /* __LIMITED_LIST__ */
C
#include <stdio.h> int decTobin(int n); int main() { int decimal = 5; printf("Enter a decimal number%d\n ", decimal); printf("Binary number of %d is %d\n ", decimal, decTobin(decimal)); return 0; } int decTobin(int n) { int remainder; int binary = 0, i = 1; while(n != 0) { remainder = n % 2; n = n / 2; binary = binary + (remainder * i); i = i * 10; } return binary; }
C
/* param.c */ /* vim: set shiftwidth=4 cindent : */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tdcg.h" #include "param.h" Param *create_param() { Param *param = (Param *)malloc(sizeof(Param)); return param; } void free_param(Param *param) { free(param->value); free(param->name); free(param->type); free(param); } void param_read(Param *param, char *line) { char *p = line; char *q = p; int len = strlen(p); int pos = 0; /* type */ for (; pos<len; pos++, p++) { if (*p == ' ') break; } param->type = (char *)malloc(sizeof(char)*pos+1); memcpy(param->type, q, pos); param->type[pos] = '\0'; /* pass space */ for (;;) { if (*p == ' ') p++; else break; } q = p; len = strlen(p); pos = 0; /* name */ for (; pos<len; pos++, p++) { if (*p == ' ') break; else if (*p == '=') break; } param->name = (char *)malloc(sizeof(char)*pos+1); memcpy(param->name, q, pos); param->name[pos] = '\0'; /* pass space and equal */ for (;;) { if (*p == ' ') p++; else if (*p == '=') p++; else break; } /* value */ len = strlen(p); pos = 0; param->value = (char *)malloc(sizeof(char)*len); q = param->value; int quote = 0; int paren = 0; for (; pos<len; pos++, p++) { if (*p == ' ') { if (quote) *q++ = *p; else if (paren) ; else break; } else if (*p == '"') quote = !quote; else if (*p == '[') paren = 1; else if (*p == ']') paren = 0; else *q++ = *p; } *q = '\0'; } void param_dump(Param *param) { printf("type %s name %s value %s\n", param->type, param->name, param->value); }
C
#ifndef __UTILS_H__ #define __UTILS_H__ #define DEBUG_FLAG 0 #define BITS_PER_CHAR 8 #define RUNLENGTH_MASK 0x1 #define HUFFMAN_MASK 0x2 #define DIFFERENCE_MASK 0x4 #define huge_t unsigned long long #define large_t unsigned long #define BITS_PER_BYTE 8 /* *** References *** * http://soundfile.sapp.org/doc/WaveFormat/ * http://stackoverflow.com/questions/13660777/c-reading-the-data-part-of-a-wav-file * * Struct que representa o header dos arquivos .wav */ typedef struct WAV_HEADER{ char RIFF[4]; /* RIFF Header Magic header */ unsigned int ChunkSize; /* RIFF Chunk Size */ char WAVE[4]; /* WAVE Header */ char fmt[4]; /* FMT header */ unsigned int Subchunk1Size; /* Size of the fmt chunk */ unsigned short AudioFormat; /* Audio format 1=PCM,6=mulaw,7=alaw, 257=IBM Mu-Law, 258=IBM A-Law, 259=ADPCM */ unsigned short NumOfChan; /* Number of channels 1=Mono 2=Sterio */ unsigned int SamplesPerSec; /* Sampling Frequency in Hz */ unsigned int bytesPerSec; /* bytes per second */ unsigned short blockAlign; /* 2=16-bit mono, 4=16-bit stereo */ unsigned short bitsPerSample; /* Number of bits per sample */ char Subchunk2ID[4]; /* "data" string */ unsigned int Subchunk2Size; /* Sampled data length */ } wav_hdr; /* Headers abaixo ja estao alinhados de 8 em 8 bytes */ /* Header geral para o arquivo comprimido */ typedef struct encodeHeader { /* 00000DHR (D - Diferença; H - Huffman; R - Runlength) */ unsigned int encodeType; unsigned long long totalLength; unsigned int originalFileSize; unsigned long int fillingBits; } enc_hdr; /* Headers estático e dinâmico para codificação por diferenças*/ typedef struct { large_t numberOfSamplesPerChannel; unsigned short channels; short originalBitsPerSample; } StaticDifferentialHeader; typedef struct { StaticDifferentialHeader sheader; short *encodedBitsPerSample; } DifferentialHeader; /* Header presente no caso de haver codificacao Runlength */ typedef struct runlengthHeader { unsigned int runlengthNumBits; unsigned int runlengthPadding; } run_hdr; /* Header presente no caso de haver codificacao Huffman */ typedef struct huffmanHeader { unsigned int huffmanFrequenciesCount; unsigned int huffmanMaxValue; } huf_hdr; #endif
C
#include<stdio.h> #include<stdlib.h> #include "stack.h" #include "List.h" int label(char); int main(){ int T; scanf("%d",&T); char a = getchar(); int i; for(i = 0; i < T; i++){ a = getchar(); stack* st = stack_new(); int n = 0; while(1){ if(a == '\n'){ if(stack_is_empty(st)) printf("1\n"); else printf("0\n"); break ; } if(label(a) > 0){ n = label(a); stack_push(st,a); a = getchar(); continue; } if(label(a) == -n){ stack_pop(st); if(!stack_is_empty(st)) n = label(st->top->head->data); else n = 0; a = getchar(); continue ; } else stack_push(st,a); a = getchar(); } } return 0; } int label(char a){ switch(a){ case '(' : return 1; case ')' : return -1; case '{' : return 2; case '}' : return -2; case '[' : return 3; case ']' : return -3; default : return 0; } }
C
#include <stdio.h> #include <stdlib.h> #include "PilhaDupla.h" #define tam 100 typedef int TipoItem; // Pilha de numeros inteiros, os pares vão para um lado e os impares para outro typedef struct{ int Topo,Base; }IndicePilha; struct tipopilhadupla{ int Item[tam]; IndicePilha Pilha1,Pilha2; }; TipoPilhaDupla * IniciaPilha(void){ TipoPilhaDupla * p = (TipoPilhaDupla*)malloc(sizeof(TipoPilhaDupla)); p->Pilha1.Base = 0; p->Pilha1.Topo = -1; p->Pilha2.Base = tam-1; p->Pilha2.Topo = tam; return p; } void push (TipoPilhaDupla * pilha, int item){ if(!pilha || pilha->Pilha1.Topo == pilha->Pilha2.Topo-1){ printf("\nPilha cheia.\n"); return; } if(item % 2 == 0){ pilha->Item[pilha->Pilha1.Topo+1] = item; pilha->Pilha1.Topo++; }else{ pilha->Item[pilha->Pilha2.Topo-1] = item; pilha->Pilha2.Topo--; } } int pop(TipoPilhaDupla * pilha){ int num; if(!pilha || (pilha->Pilha1.Topo==-1 && pilha->Pilha2.Topo==tam)){ printf("\nPilha vazia\n"); return -0; } if(pilha->Pilha1.Topo != -1){ num = pilha->Item[pilha->Pilha1.Topo+1]; pilha->Pilha1.Topo--; return num; } if(pilha->Pilha1.Topo == -1){ num = pilha->Item[pilha->Pilha2.Topo-1]; pilha->Pilha2.Topo++; } return num; } void imprime(TipoPilhaDupla * pilha){ int i=0; if(!pilha){ return; } printf("\nPILHA 1 - Pares\n"); for(i=(pilha->Pilha1.Topo);i>=0;i--){ printf("%d ", pilha->Item[i]); } printf("\nPILHA 2- Impares\n"); for(i=(pilha->Pilha2.Topo);i<=pilha->Pilha2.Base;i++){ printf("%d ", pilha->Item[i]); } } //Destroi a pilha; void destroi(TipoPilhaDupla * pilha){ if(!pilha){ return; } free(pilha); }
C
#include <stdio.h> int zheng(int x) { if(x<10) return x; else return 10*zheng(x/10)+x%10; } void ni(int x) { if(x<10) printf("%d",x); else { printf("%d",x%10); ni(x/10); } } void main() { int a; printf("һ"); scanf("%d",&a); printf("Ϊ%d\n",zheng(a)); printf("Ϊ"); ni(a); }
C
/* malloc(size): size:要凑到最大数据类型所占字节的整数倍 realloc(void *p,size_t size): size 连续存储空间。 如果p的地址满足size的要求,在原始位置的空间后增加。 如果p的地址不能满足size的要求,则重新分配,将原来的地址的数据复制到现在的空间上 */ #include <stdio.h> #include <stdlib.h> int main1(void) { int *p1 = malloc(4*sizeof(int)); // allocates enough for an array of 4 int int *p2 = malloc(sizeof(int[4])); // same, naming the type directlyi int *p3=malloc(4*sizeof *p3); // int *p3 = malloc(4*sizeof *p3); // same, without repeating the type name if(p1) { for(int n=0; n<4; ++n) // populate the array p1[n] = n*n; for(int n=0; n<4; ++n) // print it back out printf("p1[%d] == %d\n", n, p1[n]); } free(p1); free(p2); free(p3); } int main(){ void *p=malloc(12);// int *x=p;// printf("x=%p\n",x); for (int i=0; i<4; i++) { x[i]=i; } // for (int i=0;i<4;i++) { // printf("x[%d]=%d %p",i,x[i],x+i); // // } //增加2个整数 int *q; q=realloc(x,10); printf("q=%p\n",q); q[4]=40; q[5]=50; for (int i=0; i<6; i++,q++) { printf("q[%d]=%d\n",i,*q); } free(p); free(q); return 0; }
C
/*C programs to demonstrate TCP sockets programming. C code of client process that connects to server through socket.*/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <netdb.h> #define SERVICE_PORT 8888 /*hard-coded port number.*/ int conn(char *host, int port); /*Connects to host, port and returns socket.*/ void disconn(int fd); /*To close a socket connection.*/ int debug = 1; int main(int argc, char **argv) { extern char *optarg; extern int optind; int c, err = 0, fd, port = SERVICE_PORT; /*SERVICE_PORT is the default port, File descriptor for socket.*/ char *prompt = 0, *host = "localhost"; /*Default host.*/ static char usage[] = "usage: %s [-h serverhost] [-p port]\n"; while((c = getopt(argc, argv, "dh:p:")) != -1) { switch(c) { case 'h': host = optarg; break; case 'p': port = atoi(optarg); if(port < 1024 || port > 65535) { fprintf(stderr, "Invalid port number: %s\n", optarg); err = 1; } break; case '?': err = 1; break; } } if(err || (optind < argc)) { /*In case of error or extra arguments.*/ fprintf(stderr, usage, argv[0]); exit(1); } printf("Connecting to %s, port %d\n", host, port); if((fd = conn(host, port)) < 0) /*Connection.*/ exit(1); /*In case something goes wrong.*/ disconn(fd); /*To disconnect.*/ return 0; } int conn(char *host, int port) { struct hostent *hp; /*For host information.*/ unsigned int alen; /*For address length when port number is received.*/ struct sockaddr_in myaddr; /*Client address.*/ struct sockaddr_in servaddr; /*Server address.*/ int fd; /*fd is the file descriptor for the connected socket.*/ if(debug) printf("Conn (host=\"%s\", port=\"%d\")\n", host, port); if((fd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Cannot create socket"); return -1; } memset((char *) &myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(0); if(bind(fd, (struct sockaddr *) &myaddr, sizeof(myaddr)) < 0) { perror("Bind failed"); close(fd); return -1; } alen = sizeof(myaddr); if(getsockname(fd, (struct sockaddr *) &myaddr, &alen) < 0) { perror("Getsockname failed"); close(fd); return -1; } if(debug) printf("Local port number = %d\n", ntohs(myaddr.sin_port)); memset((char*) &servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(port); hp = gethostbyname(host); if(!hp) { fprintf(stderr, "Could not obtain address of %s\n", host); close(fd); return -1; } memcpy((void *) &servaddr.sin_addr, hp->h_addr_list[0], hp->h_length); /*To put the host's address into the server address structure.*/ if(connect(fd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { /*To connect to server.*/ perror("Connect failed"); close(fd); return -1; } if(debug) printf("Connected socket = %d\n", fd); return fd; } void disconn(int fd) { /*To disconnect from the server.*/ if(debug) printf("Disconn (%d)\n", fd); shutdown(fd, 2); /*2 means future sends & receives are disallowed.*/ }
C
#include <string.h> #include "heclib7.h" /** * Function: ztsGetStandardInterval * * Use: Public * * Description: Get a standard DSS time interval in seconds from the E part, or the E part from the interval in seconds. * Also will return a list of standard intervals. * * Declaration: int ztsGetStandardInterval(int dssVersion, int *intervalSeconds, char *Epart, size_t sizeofEpart, int *operation); * * Parameters: int dssVersion * The DSS Version the results are for. Must either be 6 or 7. (Versions have different intervals) * * int *intervalSeconds (input or output) * If operation is EPART_TO_SECONDS_TO_EPART or EPART_TO_SECONDS, this is returned with the time interval, in seconds from the E part. * If operation is SECONDS_TO_EPART, the E part is returned using this time interval. * If operation is BEGIN_ENUMERATION or CONTINUE_ENUMERATION, this is returned with the a time interval from the list. * * char *Epart (input or output) * The E part of the pathname, either determined from the interval, or used to determine the interval * * size_t sizeofEpart (input) * The size of the E part, used when returning the E part from the interval. * * int *operation * A flag telling ztsGetStandardInterval7 what to do, set operation to: * EPART_TO_SECONDS_TO_EPART (0) to go from char Epart to intervalSeconds AND change the E part to the standard for that interval. * EPART_TO_SECONDS (1) to go from char Epart to intervalSeconds * SECONDS_TO_EPART (2) to go from intervalSeconds to char Epart * BEGIN_ENUMERATION (3) to begin a list of valid E parts (intervals used to keep track) * CONTINUE_ENUMERATION (4) In a list of valid E parts (returns -1 at end) * * * Returns: 0 for regular interval * 1 for irregular interval * STATUS_NOT_OKAY for error or end of list * * Remarks: For a operation set to EPART_TO_SECONDS_TO_EPART or EPART_TO_SECONDS, the function tries to recognized the E part to get the interval. * When operation is set to EPART_TO_SECONDS_TO_EPART, the standard E part is returned in Epart. For example, if you pass * an E part of "1MON", the E part will be returned with "1Month". * To get a list of intervals, begin operation with BEGIN_ENUMERATION. ztsGetStandardInterval7 will return * the interval in seconds and the E part for the first valid interval, as well as change operation to CONTINUE_ENUMERATION. Subsequent * calls (without changing operation), will enumerate the valid intervals, including irregular interval and pseudo-regular, returning * the interval in seconds and E part for each one. When the enumeration is exhausted, STATUS_NOT_OKAY is returned (see example). * * * Standard Intervals: * Name Seconds * "1Year" 31536000 (365 days) * "1Month" 2592000 (30 days) * "Semi-Month" 1296000 (15 days) * "Tri-Month" 864000 (10 days) * "1Week" 604800 (7 days, EOP Saturday, 2400 (7)) * "1Day" 86400 * "12Hour" 43200 * "8Hour" 28800 * "6Hour" 21600 * "4Hour" 14400 * "3Hour" 10800 * "2Hour" 7200 * "1Hour" 3600 * "30Minute" 1800 * "20Minute" 1200 * "15Minute" 900 * "12Minute" 720 * "10Minute" 600 * "6Minute" 360 * "5Minute" 300 * "4Minute" 240 * "3Minute" 180 * "2Minute" 120 * "1Minute" 60 * "30Second" 30 * "20Second" 20 * "15Second" 15 * "10Second" 10 * "6Second" 6 * "5Second" 5 * "4Second" 4 * "3Second" 3 * "2Second" 2 * "1Second" 1 * "IR-Century" -5 * "IR-Decade" -4 * "IR-Year" -3 * "IR-Month" -2 * "IR-Day" -1 * * * Example - print a list of standard intervals: * * int intervalSeconds, operation, version; * char Epart[20]; * * operation = BEGIN_ENUMERATION; * version = zgetVersion(ifltab); * while (ztsGetStandardInterval(version, &intervalSeconds, Epart, sizeof(Epart), &operation) == STATUS_OKAY) { * if (intervalSeconds > 0) { * printf("Regual Interval = %s, intervalSeconds = %d\n", Epart, intervalSeconds); * } * else { * printf("Irregual Interval = %s\n", Epart); * } * } * * * * Author: Bill Charley, 2014 * * Organization: US Army Corps of Engineers, Hydrologic Engineering Center (USACE HEC) * All Rights Reserved * **/ int ztsGetStandardInterval(int dssVersion, int *intervalSeconds, char *Epart, size_t sizeofEpart, int *operation) { int *secondsInInterval; int i; int len1; int len2; int same; int pseudoRegular; int dim; if (dssVersion == 6) { secondsInInterval = secondsInInterval6; dim = sizeof(secondsInInterval6) / sizeof(secondsInInterval6[0]); } else { secondsInInterval = secondsInInterval7; dim = sizeof(secondsInInterval7) / sizeof(secondsInInterval6[7]); } if ((*operation == EPART_TO_SECONDS) || (*operation == EPART_TO_SECONDS_TO_EPART)) { // set operation = EPART_TO_SECONDS_TO_EPART to go from char Epart to intervalSeconds AND return // the standard E part for that interval. // set operation = EPART_TO_SECONDS To go from char Epart to intervalSeconds len2 = (int)strlen(Epart); if (Epart[0] == '~') { pseudoRegular = 1; len2--; sizeofEpart--; } else { pseudoRegular= 0; } for (i=0; i<dim; i++) { if (dssVersion == 6) { len1 = (int)strlen(eParts6[i]); if (len2 < len1) { len1 = len2; } same = zstringCompare(&Epart[pseudoRegular], eParts6[i], (size_t)len1); } else { len1 = (int)strlen(eParts7[i]); if (len2 < len1) { len1 = len2; } same = zstringCompare(&Epart[pseudoRegular], eParts7[i], (size_t)len1); } if (same) { if (pseudoRegular) { // If quasi-regular interval (i.e., irregular), return the block size if (dssVersion == 6) { if (secondsInInterval[i] < SECS_IN_30_MINUTES) { // e.g., minute data // Less than 30 minutes (SECS_IN_30_MINUTES seconds) goes in to blocks of 1 day *intervalSeconds = -BLOCK_1_DAY; } else if (secondsInInterval[i] < SECS_IN_1_DAY) { // e.g., hourly data // Less than 6 hours (SECS_IN_1_DAY seconds) goes in to blocks of 1 month *intervalSeconds = -BLOCK_1_MONTH; } else if (secondsInInterval[i] < SECS_IN_1_WEEK) { // e.g., daily data // Less than 1 week goes in to blocks of 1 year *intervalSeconds = -BLOCK_1_YEAR; } else if (secondsInInterval[i] < SECS_IN_1_MONTH) { // e.g., monthly data // 1 month and less (2,592,000 seconds) goes in to blocks of 1 decade *intervalSeconds = -BLOCK_1_DECADE; } else { //if (secondsInInterval[i] <= SECS_IN_1_YEAR) { // e.g., yearly // Above one month goes into blocks of 1 century *intervalSeconds = -BLOCK_1_CENTURY; } } else { if (secondsInInterval[i] < SECS_IN_30_MINUTES) { // e.g., minute data // Less than 30 minutes INTVL_30_MINUTEseconds) goes in to blocks of 1 day *intervalSeconds = -BLOCK_1_DAY; } else if (secondsInInterval[i] < SECS_IN_6_HOURS) { // e.g., hourly data // DSS-7 change, 6, 8, 12 hours goes into blocks of a year // DSS-6 had 6, 8, 12 hours going into blocks of a month // Less than 6 hours (21,600 seconds) goes in to blocks of 1 month *intervalSeconds = -BLOCK_1_MONTH; } else if (secondsInInterval[i] < SECS_IN_1_WEEK) { // e.g., daily data // Less than 1 week goes in to blocks of 1 year *intervalSeconds = -BLOCK_1_YEAR; } else if (secondsInInterval[i] < SECS_IN_1_MONTH) { // e.g., monthly data // 1 month and less (2,592,000 seconds) goes in to blocks of 1 decade *intervalSeconds = -BLOCK_1_DECADE; } else { //if (secondsInInterval[i] <= SECS_IN_1_YEAR) { // e.g., yearly // Above one month goes into blocks of 1 century *intervalSeconds = -BLOCK_1_CENTURY; } } } else { *intervalSeconds = secondsInInterval[i]; } if (*operation == EPART_TO_SECONDS_TO_EPART) { if (dssVersion == 6) { stringCopy(&Epart[pseudoRegular], sizeofEpart, eParts6[i], strlen(eParts6[i])); } else { stringCopy(&Epart[pseudoRegular], sizeofEpart, eParts7[i], strlen(eParts7[i])); } } if (*intervalSeconds > 0) { return 0; } else { return 1; } } } } else if (*operation == SECONDS_TO_EPART) { // set operation = SECONDS_TO_EPART To go from intervalSeconds to char Epart // Note, quasi-interval is not returned here for irregular, only block size for (i=0; i<dim; i++) { if (*intervalSeconds == secondsInInterval[i]) { if (dssVersion == 6) { stringCopy(Epart, sizeofEpart, eParts6[i], strlen(eParts6[i])); } else { stringCopy(Epart, sizeofEpart, eParts7[i], strlen(eParts7[i])); } return 0; } } } else if (*operation == BEGIN_ENUMERATION) { // set operation = BEGIN_ENUMERATION to begin a list of valid E parts (intervals used to keep track) *intervalSeconds = secondsInInterval[0]; if (dssVersion == 6) { stringCopy(Epart, sizeofEpart, eParts6[0], strlen(eParts6[0])); } else { stringCopy(Epart, sizeofEpart, eParts7[0], strlen(eParts7[0])); } *operation = CONTINUE_ENUMERATION; return 0; } else if (*operation == CONTINUE_ENUMERATION) { // set operation = CONTINUE_ENUMERATION In a list of valid E parts (returns -1 at end) for (i=0; i<dim; i++) { if (*intervalSeconds == secondsInInterval[i]) { if (i == (dim-1)) { *intervalSeconds = 0; *operation = -1; return STATUS_NOT_OKAY; } if (dssVersion == 6) { stringCopy(Epart, sizeofEpart, eParts6[i+1], strlen(eParts6[i+1])); } else { stringCopy(Epart, sizeofEpart, eParts7[i+1], strlen(eParts7[i+1])); } *intervalSeconds = secondsInInterval[i+1]; return 0; } } } return STATUS_NOT_OKAY; }
C
#include "../include/get_next_line.h" int make_line(int fd, char **save, char **line) { int i = 0; char *tmp; while(save[fd][i] != '\0' && save[fd][i] != '\n') i++; if(save[fd][i] == '\0') { *line = ft_strdup(save[fd]); free(save[fd]); return 0; } *line = ft_substr(save[fd],0,i); tmp = ft_strdup(&save[fd][i+1]); free(save[fd]); save[fd] = tmp; return 1; } int check_ret(int fd, char **save, int ret, char **line) { if(ret < 0) return -1; if(ret == 0 && save[fd] == NULL) { *line = ft_strdup(""); return 0; } return make_line(fd,save,line); } int get_next_line(int fd, char **line) { int ret; int flag = 0; char *buff; char static *save[8]; char *tmp; if(!(buff = (char*)malloc(sizeof(char)*1001))) return -1; if(save[fd] && ft_strchr(save[fd],'\n') != NULL) { flag = 1; ret = 1; } while(flag != 1 && (ret = read(fd,buff,1000)) > 0) { buff[ret] = '\0'; if(!(save[fd])) { save[fd] = ft_strdup(buff); } else { tmp = ft_strjoin(save[fd],buff); free(save[fd]); save[fd] = tmp; } if(ft_strchr(save[fd],'\n') != NULL) break; } free(buff); return check_ret(fd,save,ret,line); }
C
// // Shaun Chemplavil U08713628 // [email protected] // C / C++ Programming I : Fundamental Programming Concepts // 146359 Raymond L. Mitchell Jr. // 04 / 23 / 2020 // C1A6E1_main.c // Win10 // Visual C++ 19.0 // // This program prompts the user to enter a string and returns the length // using strlen and MyStrlen // #include <stdio.h> #include <string.h> #define LENGTH 129 size_t MyStrlen(const char *s1); int main(void) { char input[LENGTH]; // get the users string printf("Enter a string: "); fgets(input, LENGTH, stdin); // remove newline character from string input[strcspn(input, "\n")] = '\0'; // display results printf("strlen(\"%s\") returned %d\n", input, (int)strlen(input)); printf("MyStrlen(\"%s\") returned %d\n", input, (int)MyStrlen(input)); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { int n1,n2,n3; printf("digite o primeiro valor:"); scanf("%d",&n1); printf("digite o segundo numero:"); scanf("%d",&n2); printf("digite o terceiro nunero:"); scanf("%d",&n3); if(n1<n2 && n2<n3) { printf("em ordem crescente: %d,%d,%d",n1,n2,n3); }else if(n2<n1 && n1<n3) { printf("em ordem crescente: %d,%d,%d",n2,n1,n3); }else if (n2<n3 && n3<n1) { printf("em ordem crescente: %d,%d,%d,",n2,n3,n1); }else if (n1<n3 && n3<n2) { printf("em ordem crescente: %d,%d,%d",n1,n3,n2); }else if (n3<n1 && n1<n2) { printf("em ordem crescente: %d,%d,%d",n3,n1,n2); }else if (n3<n2 && n2<n1) { printf("em ordem crescente: %d,%d,%d,",n3,n2,n1); return 0; } }
C
#include <string.h> #include <stdio.h> #include <stdlib.h> struct student { char* name ; struct student* stds[20]; }; void stdsShow(struct student* root, char* prefix) { if(root->name) printf(strcat("%s\n", prefix), root->name); for(int i=0; i<20; i++) { if(root->stds[i]) { stdsShow(root->stds[i], strcat(" ", prefix)); } } } void passArray(char *a) { printf("passArray: \n"); fflush(stdout); printf("%s\n", a); fflush(stdout); a[1]="a"; printf("%s\n", a); fflush(stdout); } int main(int argc, char* argv) { char* b="hello"; passArray(b); printf("%s\n", b); fflush(stdout); struct student s; struct student a= {.name="forfrt"}; for(int i=0; i<20; i++) { a.stds[i]=NULL; } printf("stds[0].name: %p\n", a.stds[0]); fflush(stdout); a.stds[1]->name="xhj"; a.stds[2]->name="xhj"; a.stds[9]->name="zj"; a.stds[9]->name="hcx"; a.stds[9]->stds[2]->name="tdhcx"; stdsShow(&a, ""); }
C
// Put values in arrays byte invader1a[] = { B00011000, // First frame of invader #1 B00111100, B01111110, B11011011, B11111111, B00100100, B01011010, B10100101 }; byte invader1b[] = { B00011000, // Second frame of invader #1 B00111100, B01111110, B11011011, B11111111, B00100100, B01011010, B01000010 }; byte invader2a[] = { B00100100, // First frame of invader #2 B00100100, B01111110, B11011011, B11111111, B11111111, B10100101, B00100100 }; byte invader2b[] = { B00100100, // Second frame of invader #2 B10100101, B11111111, B11011011, B11111111, B01111110, B00100100, B01000010 }; byte invader3a[] = //same as 1a { B00011000, // First frame of invader #1 B00111100, B01111110, B11011011, B11111111, B00100100, B01011010, B10100101 }; byte invader3b[] = //same as 1b { B00011000, // Second frame of invader #1 B00111100, B01111110, B11011011, B11111111, B00100100, B01011010, B01000010 }; byte invader4a[] = //same as 2a { B00100100, // First frame of invader #2 B00100100, B01111110, B11011011, B11111111, B11111111, B10100101, B00100100 }; byte invader4b[] = //same as 2b { B00100100, // Second frame of invader #2 B10100101, B11111111, B11011011, B11111111, B01111110, B00100100, B01000010 };
C
/*条件变量的基本操作和认识*/ #include <stdio.h> #include <errno.h> #include <unistd.h> #include <stdlib.h> int have_noodle = 0; //pthread_cond_t cond = PTHREAD_COND_INITIALIZER; //使用一个条件变量可能会导致唤醒紊乱,所以用两个条件变量 pthread_cond_t chimian; //吃面的人等在这 pthread_cond_t zuomian; //做面的人等在这 pthread_mutex_t mutex; void *thr_sale(void *arg) { while(1){ pthread_mutex_lock(&mutex); //有面没人吃则等待 while(have_noodle != 0){ //sleep(1); //int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex); // cond:条件变量 // mutex:互斥锁 //条件变量为什么需要锁? //答:此处的have_noodle就是我们的判断条件,这是一个全局变量,是临界资源。它的操作就应该受保护,条件变量的使用势必会用到外部条件的判断,外部条件的判断通常是全局数据,所以需要加锁。 pthread_cond_wait(&zuomian, &mutex); } printf("sale----make noodles!!\n"); have_noodle = 1; //int pthread_cond_broadcast(pthread_cond_t *cond); // 唤醒所有等待线程 //int pthread_cond_signal(pthread_cond_t *cond); // 唤醒至少一个等待的线程 pthread_cond_signal(&chimian); pthread_mutex_unlock(&mutex); } return NULL; } void *thr_buy(void *arg) { while(1){ pthread_mutex_lock(&mutex); while(have_noodle == 0){ pthread_cond_wait(&chimian, &mutex); //sleep(1); } printf("buy --- delicious!!\n"); have_noodle = 0; //吃完面就唤醒做面的人 pthread_cond_signal(&zuomian); pthread_mutex_unlock(&mutex); } return NULL; } int main() { pthread_t tid1, tid2; int ret, i; pthread_cond_init(&chimian, NULL); pthread_cond_init(&zuomian, NULL); pthread_mutex_init(&mutex, NULL); for(i = 0; i < 2; i++){ ret = pthread_create(&tid1, NULL, thr_sale, NULL); if(ret != 0) { printf("thread create error\n"); } } for(i = 0; i < 4; i++){ ret = pthread_create(&tid2, NULL, thr_buy, NULL); if(ret != 0) { printf("thread create error\n"); } } pthread_join(tid1, NULL); pthread_join(tid2, NULL); pthread_cond_destroy(&chimian); pthread_cond_destroy(&zuomian); pthread_mutex_destroy(&mutex); return 0; }
C
#pragma once struct BTree { char data; struct BTree *left; struct BTree *right; }; typedef struct BTree BTree; typedef struct BTree Node; typedef struct BTree* NodePtr; typedef struct BTree* TreePTr; /* construct */ struct BTree *btree_create(char root, struct BTree *left, struct BTree *right); void btree_destroy(struct BTree *root); /* rebuild the tree */ struct BTree *btree_from_pre_mid(char *pre, char *mid, int len); struct BTree *btree_from_post_mid(char *post, char *mid, int len); struct BTree *btree_from_level_mid(char *level, char *mid, int len); struct BTree *btree_build_search_tree(char s[]); struct BTree *btree_find(struct BTree *root, char value); /* tranversal */ void btree_pre_order(struct BTree *root); void btree_mid_order(struct BTree *root); void btree_post_order(struct BTree *root); void btree_level_order(struct BTree *root); /* basic property */ int btree_depth(struct BTree *root); int btree_leaves(struct BTree *root); void btree_flip(struct BTree *root); int btree_is_same(struct BTree *a, struct BTree *b); // 1 for iso, 0 for not int btree_is_isomorphic(struct BTree *a, struct BTree *b);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fillit.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: abibyk <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/07 21:24:32 by abibyk #+# #+# */ /* Updated: 2018/03/07 21:27:26 by abibyk ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef FILLIT_H # define FILLIT_H # include <stdlib.h> # include <stdio.h> # include <unistd.h> # include <fcntl.h> typedef struct s_shape { char arr[4][4]; } t_shape; typedef struct s_point { int x; int y; } t_point; typedef struct s_points { char letter; t_point arr[4]; } t_points; typedef struct s_map { char **arr; int y_len; int x_len; } t_map; void errmsg(void); int last_char(char *fn); int get_size(char *file_name); void fill_array(char *fn, t_shape *mas, int size); int check_shape(t_shape *obj, int size); t_map *fillit(t_shape *pt, int size); t_map *map_creation(int num); int map_min_size(int n); t_points **trans_chars(t_shape *obj, int size); int placing(t_points *figure, t_map *map, int i, int j); void removing(t_points *figure, t_map *map, int i, int j); t_map *map_resizing(t_map *old_map); void show(t_map *result); void ft_putchar(char c); #endif
C
/* Interface for hiding processes, files and the rootkit itself */ #ifndef _HIDING_H #define _HIDING_H #include "config.h" #define log(...) if (DEBUG) printk(__VA_ARGS__) // Returns whether the rootkit module is hidden or not bool is_module_hidden(void); // Returns whether a filename is hidden or not bool is_file_hidden(const char* name); // Returns whether a PID is hidden or not bool is_pid_hidden(int pid); // Returns the hidden PID referenced in a pathname as the basename or as a // folder, or -1 is there isn't any. int pid_in_pathname(const char __user* pathname); // Hides the module. int hide_module(void); // Unhides the module. int unhide_module(void); // Hides a file int hide_file(const char* name); // Unhides a file int unhide_file(const char* name); // Hides a PID int hide_pid(int pid); // Unhides a PID int unhide_pid(int pid); // Frees the list of hidden files and the list of hidden PIDs void delete_lists(void); // Logs every hidden file and PID void print_hidden(void); #endif
C
// // parser.c // loxi - a Lox interpreter // // Created by Marco Caldarelli on 16/10/2017. // #include "parser.h" #include "common.h" #include "error.h" #include "expr.h" #include "error.h" #include "expr.h" typedef struct Parser { Token *tokens; Token *current; Token *previous; const char *source; Error *error; } Parser; typedef struct { Expr *expr; bool error; } ParseResult; /* Recursive descent parser */ static Parser * parser_init(Token *tokens, const char *source) { Parser *parser = lox_alloc(Parser); parser->tokens = tokens; parser->current = tokens; parser->previous = NULL; parser->source = source; parser->error = NULL; return parser; } static void parser_free(Parser *parser) { if (parser->error) { freeError(parser->error); } lox_free(parser); } // Returns the previous token static inline Token * parser_previous(Parser *parser) { return parser->previous; } // Returns the current token without consuming it static inline Token * parser_peek(Parser *parser) { return parser->current; } // True if all tokens have been consumed static inline bool parser_isAtEnd(Parser *parser) { return parser_peek(parser)->type == TT_EOF; } // Consume a token and return it static inline Token * parser_advance(Parser *parser) { if (!parser_isAtEnd(parser)) { parser->previous = parser->current; parser->current = parser->current->nextInScan; } return parser_previous(parser); } // Returns true if the current token is of the given type, without consuming it. static inline bool parser_check(Parser *parser, TokenType type) { if (parser_isAtEnd(parser)) { return false; } return parser_peek(parser)->type == type; } // Consumes the current token and returns true if it is of type1 or type2 static bool parser_match2(Parser *parser, TokenType type1, TokenType type2) { if(parser_check(parser, type1) || parser_check(parser, type2)) { parser_advance(parser); return true; } return false; } // Consumes the current token and returns true if it is an operator of type 'type' static bool parser_match1(Parser *parser, TokenType type) { if(parser_check(parser, type)) { parser_advance(parser); return true; } return false; } #define parser_match(parser, array) parser_match_(parser, array, ARRAY_COUNT(array)) static bool parser_match_(Parser *parser, const TokenType *types, int32_t count) { for (int32_t index = 0; index < count; index++) { if (parser_check(parser, types[index])) { parser_advance(parser); return true; } } return false; } // static void parser_synchronize(Parser *parser) { parser_advance(parser); while (!parser_isAtEnd(parser)) { if (parser_previous(parser)->type == TT_SEMICOLON) { return; } switch (parser_peek(parser)->type) { case TT_CLASS: case TT_FUN: case TT_VAR: case TT_FOR: case TT_IF: case TT_WHILE: case TT_PRINT: case TT_RETURN: return; default: break; } parser_advance(parser); } } static inline Error * parser_throwError(Token *token, const char *message, Parser *parser) { lox_token_error(parser->source, token, message); // NOTE: we only keep track of the last error that occurred for now. if(parser->error) { freeError(parser->error); } parser->error = initError(token, message); return parser->error; } // Consumes and returns the current token if it is of type `type`; otherwise, set a parse error and return NULL. static Token * parser_consume(Parser *parser, TokenType type, const char *message) { if (parser_check(parser, type)) { return parser_advance(parser); } parser_throwError(parser_peek(parser), message, parser); return NULL; } static Expr * parse_expression(Parser *parser); // NOTE: primary → "true" | "false" | "null" | "nil" // | NUMBER | STRING // | "(" expression ")" // | IDENTIFIER ; static Expr * parse_primary(Parser *parser) { Expr *result = NULL; if (parser_match1(parser, TT_FALSE)) { result = init_bool_literal(false); } else if (parser_match1(parser, TT_TRUE)) { result = init_bool_literal(true); } else if (parser_match1(parser, TT_NIL)) { result = init_nil_literal(); } else if (parser_match(parser, ((TokenType[]){TT_NUMBER, TT_STRING}))) { result = init_literal(parser_previous(parser)); } else if (parser_match1(parser, TT_SUPER)) { Token *keyword = parser_previous(parser); if (!parser_consume(parser, TT_DOT, "Expect '.' after 'super'.")) { return NULL; } Token *method = parser_consume(parser, TT_IDENTIFIER, "Expect superclass method name."); result = init_super(keyword, method); } else if (parser_match1(parser, TT_THIS)) { result = init_this(parser_previous(parser)); } else if (parser_match1(parser, TT_IDENTIFIER)) { result = init_variable(parser_previous(parser)); } else if (parser_match1(parser, TT_LEFT_PAREN)) { Expr *expr = parse_expression(parser); if(expr == NULL) { free_expr(expr); } else { if (!parser_consume(parser, TT_RIGHT_PAREN, "Expect ')' after expression.")) { free_expr(expr); } else { result = init_grouping(expr); } } } else { parser_throwError(parser_peek(parser), "Expect expression.", parser); } return result; } static Expr * parse_call(Parser *parser); // NOTE: unary → ( "!" | "-" ) unary | call ; static Expr * parse_unary(Parser *parser) { Expr *result; if (parser_match(parser, ((TokenType[]){TT_BANG, TT_MINUS}))) { Token *operator = parser_previous(parser); Expr *right = parse_unary(parser); if(right) { result = init_unary(operator, right); } else { result = NULL; } } else { result = parse_call(parser); } return result; } static Expr * parse_finishCall(Expr *callee, Parser *parser) { Expr *arguments = NULL; if (!parser_check(parser, TT_RIGHT_PAREN)) { do { if (expr_count(arguments) >= LOX_MAX_ARG_COUNT) { // NOTE: reports an error but does not throw it; the parser is still in a valid state parser_throwError(parser_peek(parser), "Cannot have more than " XSTR(LOX_MAX_ARG_COUNT) " arguments.", parser); } Expr *expr = parse_expression(parser); if (expr == NULL) { free_expr(arguments); free_expr(callee); return NULL; } arguments = expr_appendTo(arguments, expr); } while (parser_match1(parser, TT_COMMA)); } Token *paren = parser_consume(parser, TT_RIGHT_PAREN, "Expect ')' after arguments."); if (paren == NULL) { free_expr(arguments); free_expr(callee); return NULL; } Expr *call = init_call(callee, paren, arguments); return (void *)call; } // NOTE: call → primary ( "(" arguments? ")" | "." IDENTIFIER )* ; static Expr * parse_call(Parser *parser) { Expr *expr = parse_primary(parser); if (expr == NULL) { return NULL; } while (true) { if (parser_match1(parser, TT_LEFT_PAREN)) { expr = parse_finishCall(expr, parser); } else if (parser_match1(parser, TT_DOT)) { Token *name = parser_consume(parser, TT_IDENTIFIER, "Expect property name after '.'."); if (name == NULL) { free_expr(expr); return NULL; } expr = init_get(expr, name); } else { break; } } return expr; } // NOTE: multiplication -> unary ( ( "/" | "*" ) unary )* ; static Expr * parse_multiplication(Parser *parser) { Expr *expr = parse_unary(parser); if(expr == NULL) { return NULL; } while (parser_match(parser, ((TokenType[]){TT_SLASH, TT_STAR}))) { Token *operator = parser_previous(parser); Expr *right = parse_unary(parser); if(right == NULL) { free_expr(expr); return NULL; } expr = init_binary(expr, operator, right); } return expr; } // NOTE: addition -> multiplication ( ( "-" | "+" ) multiplication )* ; static Expr * parse_addition(Parser *parser) { Expr *expr = parse_multiplication(parser); if(expr == NULL) { return NULL; } while (parser_match(parser, ((TokenType[]){TT_MINUS, TT_PLUS}))) { Token *operator = parser_previous(parser); Expr *right = parse_multiplication(parser); if(right == NULL) { free_expr(expr); return NULL; } expr = init_binary(expr, operator, right); } return expr; } // NOTE: comparison -> addition ( ( ">" | ">=" | "<" | "<=" ) addition )* ; static Expr * parse_comparison(Parser *parser) { Expr *expr = parse_addition(parser); if(expr == NULL) { return NULL; } const TokenType tokens[] = {TT_GREATER, TT_GREATER_EQUAL, TT_LESS, TT_LESS_EQUAL}; while (parser_match(parser, tokens)) { Token *operator = parser_previous(parser); Expr *right = parse_addition(parser); if(right == NULL) { free_expr(expr); return NULL; } expr = init_binary(expr, operator, right); } return expr; } // NOTE: equality -> comparison ( ( "!=" | "==" ) comparison )* ; static Expr * parse_equality(Parser *parser) { Expr *expr = parse_comparison(parser); if(expr == NULL) { return NULL; } while (parser_match2(parser, TT_BANG_EQUAL, TT_EQUAL_EQUAL)) { Token *operator = parser_previous(parser); Expr *right = parse_comparison(parser); if(right == NULL) { free_expr(expr); return NULL; } expr = init_binary(expr, operator, right); } return expr; } // NOTE: logic_and → equality ( "and" equality )* ; static Expr * parse_and(Parser *parser) { Expr *expr = parse_equality(parser); if(expr == NULL) { return NULL; } while (parser_match1(parser, TT_AND)) { Token *operator = parser_previous(parser); Expr *right = parse_equality(parser); if(right == NULL) { free_expr(expr); return NULL; } expr = init_logical(expr, operator, right); } return expr; } // NOTE: logic_or → logic_and ( "or" logic_and )* ; static Expr * parse_or(Parser *parser) { Expr *expr = parse_and(parser); if(expr == NULL) { return NULL; } while (parser_match1(parser, TT_OR)) { Token *operator = parser_previous(parser); Expr *right = parse_and(parser); if(right == NULL) { free_expr(expr); return NULL; } expr = init_logical(expr, operator, right); } return expr; } // assignment → ( call "." )? IDENTIFIER "=" assignment | logic_or; static Expr * parse_assignment(Parser *parser) { Expr *expr = parse_or(parser); // Expr *expr = parse_equality(parser); if (parser_match1(parser, TT_EQUAL)) { Token *equals = parser_previous(parser); Expr *value = parse_assignment(parser); if (expr->type == EXPR_Variable) { Variable *varExpr = (Variable *)expr; Token *name = varExpr->name; lox_free(varExpr); return init_assign(name, value); } else if (expr->type == EXPR_Get) { Get *getExpr = (Get *)expr; Expr *setExpr = init_set(getExpr->object, getExpr->name, value); lox_free(getExpr); return setExpr; } parser_throwError(equals, "Invalid assignment target.", parser); } return expr; } // NOTE: expression -> assignment ; static Expr * parse_expression(Parser *parser) { return parse_assignment(parser); } // NOTE: exprStmt → expression ";" ; static Stmt * parse_expressionStatement(Parser *parser) { Expr *expr = parse_expression(parser); if(expr == NULL) { return NULL; } if(!parser_consume(parser, TT_SEMICOLON, "Expect ';' after expression.")) { free_expr(expr); return NULL; } Stmt *result = initExpression(expr); return result; } static Stmt * parse_declaration(Parser *parser); // Parses a block, starting from the token following the opening brace. // If the block is parsed without errors, the closing brace is consumed, // and the list of statements found in the block is returned. static Stmt * parse_block(Parser *parser) { Stmt *first = NULL; Stmt *last = NULL; while (!parser_check(parser, TT_RIGHT_BRACE) && !parser_isAtEnd(parser)) { Stmt *statement = parse_declaration(parser); if (statement == NULL) { // NOTE: There was an error in the statement. We skip to the next statement continue; } if(last) { last->next = statement; } else { first = statement; } last = statement; assert(last->next == NULL); } if (!parser_consume(parser, TT_RIGHT_BRACE, "Expect '}' after block.")) { freeStmt(first); return NULL; } return first; } // NOTE: printStmt → "print" expression ";" ; static Stmt * parse_printStatement(Parser *parser) { Expr *value = parse_expression(parser); if(value == NULL) { return NULL; } if (!parser_consume(parser, TT_SEMICOLON, "Expect ';' after value.")) { free_expr(value); return NULL; } Stmt *result = initPrint(value); return result; } // NOTE: returnStmt → "return" expression? ";" ; static Stmt * parse_returnStatement(Parser *parser) { Token *keyword = parser_previous(parser); Expr *value = NULL; if (!parser_check(parser, TT_SEMICOLON)) { value = parse_expression(parser); } if (!parser_consume(parser, TT_SEMICOLON, "Expect ';' after value.")) { free_expr(value); return NULL; } Stmt *result = initReturn(keyword, value); return result; } static Stmt * parse_forStatement(Parser *parser); static Stmt * parse_ifStatement(Parser *parser); static Stmt * parse_whileStatement(Parser *parser); // NOTE: statement → exprStmt | ifStmt | printStmt | returnStmt | whileStmt | block ; static Stmt * parse_statement(Parser *parser) { if (parser_match1(parser, TT_FOR)) { return parse_forStatement(parser); } if (parser_match1(parser, TT_IF)) { return parse_ifStatement(parser); } if (parser_match1(parser, TT_PRINT)) { return parse_printStatement(parser); } if (parser_match1(parser, TT_RETURN)) { return parse_returnStatement(parser); } if (parser_match1(parser, TT_WHILE)) { return parse_whileStatement(parser); } if (parser_match1(parser, TT_LEFT_BRACE)) { return initBlock(parse_block(parser)); } return parse_expressionStatement(parser); } static Stmt * parse_varDeclaration(Parser *parser); // NOTE: for loop desugaring into while loop. static Stmt * parse_forStatement(Parser *parser) { if (!parser_consume(parser, TT_LEFT_PAREN, "Expect '(' after 'for'.")) { return NULL; } Stmt *initializer; if (parser_match1(parser, TT_SEMICOLON)) { initializer = NULL; } else { if (parser_match1(parser, TT_VAR)) { initializer = parse_varDeclaration(parser); } else { initializer = parse_expressionStatement(parser); } if (initializer == NULL) { return NULL; } } Expr *condition = NULL; if (!parser_check(parser, TT_SEMICOLON)) { condition = parse_expression(parser); if (condition == NULL) { freeStmt(initializer); return NULL; } } if (!parser_consume(parser, TT_SEMICOLON, "Expect ';' after loop condition.")) { freeStmt(initializer); free_expr(condition); return NULL; } Expr *increment = NULL; if (!parser_check(parser, TT_RIGHT_PAREN)) { increment = parse_expression(parser); if (increment == NULL) { freeStmt(initializer); free_expr(condition); return NULL; } } if (!parser_consume(parser, TT_RIGHT_PAREN, "Expect ')' after for clauses.")) { freeStmt(initializer); free_expr(condition); free_expr(increment); return NULL; } Stmt *body = parse_statement(parser); if (increment != NULL) { body = initBlock(stmt_appendTo(body, initExpression(increment))); } if (condition == NULL) { condition = init_bool_literal(true); } body = initWhile(condition, body); if (initializer != NULL) { body = initBlock(stmt_appendTo(initializer, body)); } return body; } // NOTE: ifStmt → "if" "(" expression ")" statement ( "else" statement )? ; // NOTE: To solve the dangling else ambiguity, we bind the `else` to the nearest `if` that precedes it. static Stmt * parse_ifStatement(Parser *parser) { if(!parser_consume(parser, TT_LEFT_PAREN, "Expect '(' after 'if'.")) { return NULL; } Expr *condition = parse_expression(parser); if (condition == NULL) { return NULL; } if (!parser_consume(parser, TT_RIGHT_PAREN, "Expect ')' after if condition.")) { free_expr(condition); return NULL; } Stmt *thenBranch = parse_statement(parser); if(thenBranch == NULL) { free_expr(condition); return NULL; } Stmt *elseBranch = NULL; if (parser_match1(parser, TT_ELSE)) { elseBranch = parse_statement(parser); if(elseBranch == NULL) { free_expr(condition); freeStmt(thenBranch); return NULL; } } Stmt *result = initIf(condition, thenBranch, elseBranch); return result; } static Stmt * parse_varDeclaration(Parser *parser) { Token *name = parser_consume(parser, TT_IDENTIFIER, "Expect variable name."); if (name == NULL) { return NULL; } Expr *initializer = NULL; if (parser_match1(parser, TT_EQUAL)) { initializer = parse_expression(parser); if (initializer == NULL) { return NULL; } } if (!parser_consume(parser, TT_SEMICOLON, "Expect ';' after variable declaration.")) { free_expr(initializer); return NULL; } Stmt *result = initVar(name, initializer); return result; } static Stmt * parse_whileStatement(Parser *parser) { if (!parser_consume(parser, TT_LEFT_PAREN, "Expect '(' after 'while'.")) { return NULL; } Expr *condition = parse_expression(parser); if (condition == NULL) { return NULL; } if (!parser_consume(parser, TT_RIGHT_PAREN, "Expect ')' after if condition.")) { free_expr(condition); return NULL; } Stmt *body = parse_statement(parser); if (body == NULL) { free_expr(condition); return NULL; } Stmt *result = initWhile(condition, body); return (void *)result; } typedef enum { FK_Function = 0, FK_Method, // NOTE: FK_Count must be the last entry FK_Count, } FunctionKind; static char *FKErrorName = {"Expect function name."}; static char *FKErrorParen = {"Expect '(' after function name."}; static char *FKErrorBody = {"Expect '{' before function body."}; // function → IDENTIFIER "(" parameters? ")" block ; static Stmt * parse_function(Parser *parser, FunctionKind kind) { assert(kind < FK_Count); Token *name = parser_consume(parser, TT_IDENTIFIER, FKErrorName); if(name == NULL) { return NULL; } if(!parser_consume(parser, TT_LEFT_PAREN, FKErrorParen)) { return NULL; } Token **parameters = lox_allocn(Token*, LOX_MAX_ARG_COUNT); if(parameters == NULL) { fatal_outOfMemory(); } int32_t parametersCount = 0; if (!parser_check(parser, TT_RIGHT_PAREN)) { // The function has at least one parameter do { if (parametersCount >= LOX_MAX_ARG_COUNT) { parser_throwError(parser_peek(parser), "Cannot have more than " XSTR(LOX_MAX_ARG_COUNT) " parameters.", parser); lox_free(parameters); return NULL; } Token *identifier = parser_consume(parser, TT_IDENTIFIER, "Expect parameter name."); if(identifier == NULL) { return NULL; } assert(parametersCount < LOX_MAX_ARG_COUNT); parameters[parametersCount++] = identifier; } while (parser_match1(parser, TT_COMMA)); } if(!parser_consume(parser, TT_RIGHT_PAREN, "Expect ')' after parameters.")) { lox_free(parameters); return NULL; } if(!parser_consume(parser, TT_LEFT_BRACE, FKErrorBody)) { lox_free(parameters); return NULL; } Stmt *body = parse_block(parser); // NOTE: if block is NULL, the function has an empty body. This is allowed. Stmt *function = initFunction(name, parameters, parametersCount, body); return function; } // classDecl → "class" IDENTIFIER ( "<" IDENTIFIER )? "{" function* "}" ; static Stmt * parse_classDeclaration(Parser *parser) { Token *name = parser_consume(parser, TT_IDENTIFIER, "Expect class name."); Expr *superclass = NULL; if (parser_match1(parser, TT_LESS)) { if (!parser_consume(parser, TT_IDENTIFIER, "Expect superclass name.")) { return NULL; } superclass = init_variable(parser_previous(parser)); } if ((name == NULL) || (!parser_consume(parser, TT_LEFT_BRACE, "Expect '{' before class body."))) { return NULL; } Stmt *methods = NULL; while (!parser_check(parser, TT_RIGHT_BRACE) && !parser_isAtEnd(parser)) { Stmt *method = parse_function(parser, FK_Method); if (method == NULL) { freeStmt(methods); return NULL; } method->next = methods; methods = method; } if(!parser_consume(parser, TT_RIGHT_BRACE, "Expect '}' after class body.")) { return NULL; } Stmt *classStmt = initClass(name, superclass, (FunctionStmt *)methods); return classStmt; } // NOTE: declaration → classDecl | funDecl | varDecl | statement ; static Stmt * parse_declaration(Parser *parser) { Stmt *result; if (parser_match1(parser, TT_CLASS)) { result = parse_classDeclaration(parser); } else if (parser_match1(parser, TT_FUN)) { result = parse_function(parser, FK_Function); } else if (parser_match1(parser, TT_VAR)) { result = parse_varDeclaration(parser); } else { result = parse_statement(parser); } if(result == NULL) { parser_synchronize(parser); } return result; } // NOTE: program → statement* EOF ; static Stmt * parse_program(Parser *parser) { Stmt *firstStmt = NULL; Stmt *lastStmt = NULL; while(!parser_isAtEnd(parser)) { Stmt *statement = parse_declaration(parser); if (statement == NULL) { continue; } if(lastStmt) { lastStmt->next = statement; lastStmt = statement; } else { firstStmt = statement; lastStmt = statement; } assert(lastStmt->next == NULL); } return firstStmt; } Stmt * parse(Token *tokens, const char *source) { Parser *parser = parser_init(tokens, source); Stmt *statements = parse_program(parser); parser_free(parser); return statements; }
C
//스타수열 최종ver : ver4 반례 [1,1,0] 수정 #include <stdio.h> #include <stdlib.h> typedef struct star { int len, flag, bfIdx; }Star; void initStar(Star* star, int a_len); void updateLen(Star* star, int curIdx); void lastUpdate(Star* star, int curIdx); int solution(int a[], int a_len); int main() { int* a; int a_len; scanf("%d\n", &a_len); a = (int*)malloc(a_len*sizeof(int)); for(int i=0; i < a_len; i++) scanf("%d", &a[i]); printf("%d\n", solution(a, a_len)); return 0; } void initStar(Star* star, int a_len) { Star* p; for(int i = 0; i < a_len; i++) { p = star + i; p->flag = p->len = 0; } } void updateLen(Star* star, int curIdx) { int bfIdx = star->bfIdx; if(star->flag == 0) { //처음 업데이트 되는 경우일 때 if(curIdx > 0) { star->flag = -1; star->len += 2; } else { star->flag = 1; star->len += 2; } star->bfIdx = curIdx; return; } if(star->flag == -1) { //이전 인덱스가 왼쪽과 묶인 경우 if(curIdx - bfIdx > 1) { star->flag = -1; star->len += 2; } //왼쪽에 자리가 있는 경우 else { star->flag = 1; star->len += 2; } //왼쪽에 자리가 없는 경우 } else { //if(star->flag == 1) //이전 인덱스가 오른쪽과 묶인 경우 if(curIdx == bfIdx + 1) { star->flag = 1; } //현재 인덱스가 이전 인덱스와 묶여있었던 경우 else if(curIdx - (bfIdx + 1) > 1) { star->flag = -1; star->len += 2; } //왼쪽에 자리가 있는 경우 else { star->flag = 1; star->len += 2; } //왼쪽에 자리가 없는 경우 } star->bfIdx = curIdx; } void lastUpdate(Star* star, int curIdx) { //마지막 원소인 경우 해당 스타배열 기준으로 왼쪽 자리가 남아있는 경우만 len갱신 int bfIdx = star->bfIdx; if(star->flag == -1) { if(curIdx - bfIdx > 1) star->len += 2; } else { if(curIdx == bfIdx + 1) star->len -= 2; else if(curIdx - (bfIdx + 1) > 1) star->len += 2; } } int solution(int a[], int a_len) { int i, max; Star* star; if(a_len == 1) return 0; //1. a_len만큼 star배열 동적할당 후 초기화 star = (Star*)malloc(a_len * sizeof(Star)); initStar(star, a_len); //2. a[]돌면서 star[]채우기 이 때 각 리스트의 최대 스타수열 길이 len을 저장 for(i = 0; i < a_len - 1; i++){ updateLen(star+a[i], i); } lastUpdate(star+a[i], i); //3. star[] 돌면서 최대길이 max찾기 max = star[0].len; for(i = 1; i < a_len; i++){ if(star[i].len > max) max = star[i].len; } return max; }
C
#ifndef UTILS_H #define UTILS_H #include <sys/time.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <errno.h> #if defined(DEBUG) #define P_DEBUG(...) fprintf(stderr,"[DEBUG] : "__VA_ARGS__) #else #define P_DEBUG(...) #endif #define ERR(msg) fprintf(stderr, "%s\n", msg) #define P_ERR(msg,err) fprintf(stderr, "%s : %s\n", msg, strerror(err)) typedef struct { unsigned long long int milisec; unsigned long long int seconds; unsigned long long int minutes; unsigned long long int hours; } TimeFormat; int copy_until_delim(char *source, char *dest, int sz, int *offset, const char *delim); char count_bytes(char *filepath, long *n_bytes); void diff_time(struct timeval *t_start, struct timeval *t_end, TimeFormat *t_diff); int check_dir_access(char *dir); void str_to_lowercase(char *str); int write_to_file(char *buf, char *filepath, size_t len); char is_dir_empty(const char *dir_path); long ceil_division(long a, long b); #endif
C
#include "lists.h" /** * free_dlistint - Frees a linked list * @head: Holds the head * Return: none */ void free_dlistint(dlistint_t *head) { dlistint_t *swappity, *tmp; if (!head) return; for (swappity = head->next; swappity; swappity = tmp) { tmp = swappity->next; free(swappity); } free(head); }
C
#include "../../includes.h" HashMapEntry *map_entry_new(char *key, void *value, size_t size) { HashMapEntry *entry = (HashMapEntry*)malloc(sizeof(HashMapEntry)); if(entry) { entry->key = strdup(key); entry->value = NULL; // Set value to NULL before calling map_entry_set map_entry_set(entry, value, size); entry->next = NULL; } return entry; } void map_entry_set(HashMapEntry *entry, void *value, size_t size) { if(!entry || !value) return; if(entry->value) free(entry->value); entry->value = malloc(size); entry->size = size; memcpy(entry->value, value, size); } HashMapEntry *map_entry_get(HashMapEntry *entries, char *key) { while(entries) { if(!strcmp(entries->key, key)) return entries; entries = entries->next; } return NULL; } void map_entry_append(HashMapEntry **entries, char *key, void *value, size_t size) { while(*entries) entries = &(*entries)->next; *entries = map_entry_new(key, value, size); } void map_entry_free(HashMapEntry **entries) { if(!entries) return; while(*entries) { HashMapEntry *tmp = (*entries)->next; free((*entries)->key); free((*entries)->value); free(*entries); *entries = tmp; } *entries = NULL; }
C
#include "pileup.h" /* * Fetches the next base => the nth base at unpadded position pos. (Nth can * be greater than 0 if we have an insertion in this column). Do not call this * with pos/nth lower than the previous query, although higher is better. * (This allows it to be initialised at base 0.) * * Stores the result in base and also updates is_insert to indicate that * this sequence still has more bases in this position beyond the current * nth parameter. * * Returns 1 if a base was fetched * 0 if not (eg ran off the end of sequence) */ static int get_next_base(pileup_t *p, int pos, int nth, int of, int *is_insert) { seq_t *s = p->s; int comp = (s->len < 0) ^ p->r->comp; int more = 1; int justify = 0; int ilen; p->base = '?'; *is_insert = 0; #if 1 /* Find pos first */ while (p->pos < pos) { p->nth = 0; if (p->cigar_len == 0) { if (p->cigar_ind >= s->alignment_len) return 0; if (comp) { int r_ind = s->alignment_len - p->cigar_ind - 2; p->cigar_len = s->alignment[r_ind]; p->cigar_op = s->alignment[r_ind+1]; } else { p->cigar_len = s->alignment[p->cigar_ind]; p->cigar_op = s->alignment[p->cigar_ind+1]; } p->cigar_ind += 2; } switch (p->cigar_op) { case 'H': p->cigar_len = 0; break; case 'S': case 'M': p->pos++; p->seq_offset++; p->cigar_len--; break; case 'D': p->pos++; p->cigar_len--; break; case 'P': p->cigar_len = 0; /* An insert that doesn't consume seq */ break; case 'I': p->seq_offset += p->cigar_len; p->cigar_len = 0; break; } } if (p->pos < pos) return 0; // /* Compute total size of insert due to this seq */ // ilen = 0; // if (comp && nth /*&& p->in_size == 0*/) { // int tmp_ind = p->cigar_ind; // int tmp_op = p->cigar_op; // int r_ind; // // if (p->cigar_len == 0 && tmp_ind < s->alignment_len) { // r_ind = s->alignment_len - tmp_ind - 2; // tmp_op = s->alignment[r_ind+1]; // tmp_ind += 2; // } // // while (tmp_ind < s->alignment_len) { // if (tmp_op == 'I' || tmp_op == 'P') { // r_ind = s->alignment_len - tmp_ind - 2; // ilen += s->alignment[r_ind+2]; // tmp_op = s->alignment[r_ind+1]; // tmp_ind += 2; // } else { // break; // } // } // } /* Now at pos, find nth base */ while (p->nth < nth && more) { if (p->cigar_len == 0) { if (p->cigar_ind >= s->alignment_len) return 0; /* off end of seq */ if (comp) { int r_ind = s->alignment_len - p->cigar_ind - 2; p->cigar_len = s->alignment[r_ind]; p->cigar_op = s->alignment[r_ind+1]; } else { p->cigar_len = s->alignment[p->cigar_ind]; p->cigar_op = s->alignment[p->cigar_ind+1]; } p->cigar_ind += 2; } switch (p->cigar_op) { case 'H': p->cigar_len = 0; break; case 'S': case 'M': case 'D': more = 0; break; case 'P': p->cigar_len--; p->nth++; more = 1; break; case 'I': // if (comp && of - p->nth > ilen) { // p->nth++; // more = 0; // justify = 1; // break; // } p->cigar_len--; p->nth++; p->seq_offset++; more = 1; break; } } if (justify || (p->nth < nth && p->cigar_op != 'I')) { p->base = '-'; p->qual = 0; } else { if (p->cigar_op == 'D') { p->base = '*'; p->qual = 0; } else if (p->cigar_op == 'P') { p->base = '+'; p->qual = 0; } else { if (comp) { p->qual = s->conf[ABS(s->len) - (p->seq_offset+1)]; p->base = complement_base(s->seq[ABS(s->len) - (p->seq_offset+1)]); } else{ p->qual = s->conf[p->seq_offset]; p->base = s->seq[p->seq_offset]; } } } if (p->cigar_len == 0 && p->cigar_ind < s->alignment_len) { /* * Query next operation to check for 'I', but don't modify our * p->cigar_ fields as the callback function may need to query * these to know where we are during CIGAR processing. */ int tmp_ind = p->cigar_ind; int tmp_len = p->cigar_len; int tmp_op = p->cigar_op; do { int r_ind; r_ind = comp ? s->alignment_len - tmp_ind - 2 : tmp_ind; tmp_len = s->alignment[r_ind]; tmp_op = s->alignment[r_ind+1]; if (tmp_op == 'I' || tmp_op == 'P') { *is_insert += tmp_len; } else { break; } tmp_ind += 2; } while (tmp_ind < s->alignment_len); // int tmp_len, tmp_op; // if (comp) { // int r_ind = s->alignment_len - p->cigar_ind - 2; // tmp_len = s->alignment[r_ind]; // tmp_op = s->alignment[r_ind+1]; // } else { // tmp_len = s->alignment[p->cigar_ind]; // tmp_op = s->alignment[p->cigar_ind+1]; // } // if (tmp_op == 'I' || tmp_op == 'P') // *is_insert = tmp_len; } else { int tmp_ind = p->cigar_ind; int tmp_len = p->cigar_len; int tmp_op = p->cigar_op; while (tmp_op == 'I' || tmp_op == 'P') { int r_ind; *is_insert += tmp_len; tmp_ind += 2; if (tmp_ind >= s->alignment_len) break; r_ind = comp ? s->alignment_len - tmp_ind - 2 : tmp_ind; tmp_len = s->alignment[r_ind]; tmp_op = s->alignment[r_ind+1]; } } if (comp) { p->sclip = (p->seq_offset+1 <= ABS(s->len) - s->right || p->seq_offset > ABS(s->len) - s->left); } else { p->sclip = (p->seq_offset+1 < s->left || p->seq_offset >= s->right); } return 1; #else /* May need to catch up to pos on the first time through */ for (;;) { int tmp_pos; /* Fetch next base */ if (p->cigar_len == 0) { if (p->cigar_ind >= s->alignment_len) return 0; if (comp) { int r_ind = s->alignment_len - p->cigar_ind - 2; p->cigar_len = s->alignment[r_ind]; p->cigar_op = s->alignment[r_ind+1]; } else { p->cigar_len = s->alignment[p->cigar_ind]; p->cigar_op = s->alignment[p->cigar_ind+1]; } p->cigar_ind += 2; } /* Pos is an unpadded position, nth is the nth base at that pos */ tmp_pos = p->pos; switch (p->cigar_op) { case 'S': case 'M': case 'P': if (nth) { p->sclip = p->cigar_op == 'S' ? 1 : p->last_sclip; p->base = '-'; nth--; } else { p->sclip = p->cigar_op == 'S' ? 1 : 0; p->last_sclip = p->sclip; p->pos++; p->cigar_len--; p->qual = comp ? s->conf[ABS(s->len) - (p->seq_offset+1)] : s->conf[p->seq_offset]; p->base = comp ? complement_base(s->seq[ABS(s->len) - ++p->seq_offset]) : s->seq[p->seq_offset++]; } break; case 'D': p->sclip = p->last_sclip; if (nth) { p->base = '-'; p->qual = 0; nth--; } else { p->pos++; p->cigar_len--; p->base = '*'; p->qual = 0; } break; case 'I': p->last_sclip = 0; p->cigar_len--; p->qual = comp ? s->conf[ABS(s->len) - (p->seq_offset+1)] : s->conf[p->seq_offset]; p->base = comp ? complement_base(s->seq[ABS(s->len) - ++p->seq_offset]) : s->seq[p->seq_offset++]; break; case 'H': p->cigar_len = 0; /* just skip it */ break; default: fprintf(stderr, "Unrecognised cigar operation: %c\n", p->cigar_op); p->cigar_len = 0; /* just skip it */ } /* indel next? */ if (comp) { int r_ind = s->alignment_len - p->cigar_ind - 2; if (tmp_pos >= pos && p->cigar_len == 0 && p->cigar_ind < s->alignment_len && (s->alignment[r_ind+1] == 'I' || s->alignment[r_ind+1] == 'P')) { p->cigar_len = s->alignment[r_ind]; p->cigar_op = 'I'; p->cigar_ind += 2; *is_insert = p->cigar_len; return 1; } } else { if (tmp_pos >= pos && p->cigar_len == 0 && p->cigar_ind < s->alignment_len && (s->alignment[p->cigar_ind+1] == 'I' || s->alignment[p->cigar_ind+1] == 'P') { p->cigar_len = s->alignment[p->cigar_ind]; p->cigar_op = 'I'; p->cigar_ind += 2; *is_insert = p->cigar_len; return 1; } } if (tmp_pos >= pos) { *is_insert = (p->cigar_op == 'I' || p->cigar_op == 'P') ? p->cigar_len : 0; return 1; } } #endif return 0; } static int pileup_sort(const void *a, const void *b) { const pileup_t *p1 = (const pileup_t *)a; const pileup_t *p2 = (const pileup_t *)b; return p1->r->start - p2->r->start; } /* * Loops through a set of supplied ranges producing columns of data. * When found, it calls func with clientdata as a callback. Func should * return 0 for success and non-zero for failure. * * Returns 0 on success * -1 on failure */ int pileup_loop(GapIO *io, rangec_t *r, int nr, int start, int start_nth, int end, int end_nth, int (*func)(void *client_data, pileup_t *p, int pos, int nth), void *client_data) { int i, j, ret = -1; pileup_t *parray, *p, *next, *active = NULL; int is_insert, nth = 0, of = 0; int col = 0; /* * Allocate an array of parray objects, one per sequence, * and sort them into positional order. * * While processing, we also thread a linked list through the parray[] * to keep track of current "active" sequences (ones that overlap * our X column). */ parray = malloc(nr * sizeof(*parray)); for (i = j = 0; i < nr; i++) { if ((r[i].flags & GRANGE_FLAG_ISMASK) == GRANGE_FLAG_ISSEQ) { parray[j].r = &r[i]; parray[j].s = cache_search(io, GT_Seq, r[i].rec); cache_incr(io, parray[j].s); j++; } } nr = j; qsort(parray, nr, sizeof(*parray), pileup_sort); /* * Loop through all seqs in range producing padded versions. * For each column in start..end * 1. Add any new sequences to our 'active' linked list through parray. * 2. Foreach active sequence, fetch the next base and an indication * of whether more bases are at this column. * 3. If at sequence EOF, remove from 'active' linked list, otherwise * display the base. * 4. Loop. We may stall and loop multiple times on the same column * while we've determined there are still more bases at this * column (ie an insert). */ j = 0; i = start; nth = start_nth; while (i <= end || (i == end && nth <= end_nth)) { int v; pileup_t *last; /* Add new seqs */ /* FIXME: optimise this in case of very long seqs. May want to * process CIGAR and jump ahead */ while (j < nr && parray[j].r->start <= i) { if ((parray[j].r->flags & GRANGE_FLAG_ISMASK) == GRANGE_FLAG_ISSEQ) { p = &parray[j]; p->start = 1; p->next = active; active = p; p->pos = parray[j].r->start-1; p->cigar_len = 0; p->cigar_ind = 0; p->cigar_op = 'X'; p->seq_offset = -1; //p->last_sclip = 1; } j++; } /* Pileup */ is_insert = 0; for (p = active, last = NULL; p; p = next) { int ins; next = p->next; if (get_next_base(p, i, nth, of, &ins)) { last = p; } else { /* Remove sequence */ if (last) { last->next = p->next; } else { active = p->next; } } if (is_insert < ins) is_insert = ins; } /* active is now a linked list, so pass into the callback */ v = func(client_data, active, i, nth); if (v == 1) break; /* early abort */ if (v != 0) goto error; if (is_insert) { nth++; if (of < is_insert) of = is_insert; } else { nth = 0; of = 0; i++; } } ret = 0; error: /* Tidy up */ for (i = 0; i < nr; i++) { cache_decr(io, parray[i].s); //free(parray[i].s); } free(parray); return ret; }
C
/* Editor de la matriz de enemigos para Kraptor NOTA: si se ejecuta con krapmain.dat presente en el mismo directorio, _MUESTRA_ los enemigos con sprites, en vez de usar los numeros. [cool!] Kronoman 2003 En memoria de mi querido padre Teclas: DELETE = casilla a 0 BARRA = situar valor seleccionado FLECHAS = mover cursor + y - del keypad: alterar valor en +1 1 y 2 : alterar valor en +10 0 : valor a 0 C : limpiar grilla a ceros S : salvar grilla L : cargar grilla V : ver fondo sin grilla R : agregar enemigos del tipo seleccionado al azar ESC : salir NOTA: los mapas se guardan con las funciones especiales de Allegro para salvar los integers en un formato standard, de esa manera, me ahorro los problemas con diferentes tama~os de enteros segun la plataforma. */ #include <stdio.h> #include <stdlib.h> #include <allegro.h> /* Tamao del fondo */ #define W_FONDO 600 #define H_FONDO 4000 /* Grilla WxH */ #define W_GR 40 #define H_GR 40 /* Grilla */ long grilla[W_FONDO / W_GR][H_FONDO / H_GR]; /* En vgrilla pasar -1 para dibujarla, o 0 para ver el bitmap suelto */ int vgrilla = -1; int xp = 0, yp = 0, vp = 1; /* x,y, valor a colocar */ // cache de sprites de los enemigos, para mostrarlos en pantalla... :) // funciona si esta presenta krapmain.dat en el lugar #define MAX_SPR 100 // sprites cargados 0..MAX_SPR - 1 BITMAP *sprite[MAX_SPR]; DATAFILE *data = NULL; // datafile /* Bitmap cargado en RAM del fondo */ BITMAP *fnd; PALETTE pal; /* paleta */ /* Buffer de dibujo */ BITMAP *buffer; // Esto carga de disco el cache de sprites // COOL! void cargar_cache_sprites() { DATAFILE *p = NULL; // punteros necesarios int i; // para el for char str[1024]; // string de uso general for (i = 0; i < MAX_SPR; i++) sprite[i] = NULL; data = load_datafile("krapmain.dat"); if (data == NULL) return; // no esta presente el archivo - DEBUG, informar, o algo... :P p = find_datafile_object(data, "enemigos"); if (p == NULL) { unload_datafile(data); data = NULL; return; } set_config_data((char *)p->dat, p->size); for (i=0; i < MAX_SPR; i++) { /* Seccion ENEMIGO_n */ sprintf(str,"ENEMIGO_%d", i); // buscar el 1er cuadro de animacion del enemigo unicamente... p = find_datafile_object(data, get_config_string(str, "spr", "null")); if (p == NULL) p = find_datafile_object(data, get_config_string(str, "spr_0", "null")); if (p != NULL) sprite[i] = (BITMAP *)p->dat; } // NO se debe descargar el datafile, porque suena todo! [los sprites deben permanecer en RAM] } // Limpia la grilla con ceros void limpiar_grilla() { int xx, yy; /* limpio la grilla a ceros */ for (xx =0; xx < W_FONDO / W_GR; xx++) for (yy =0; yy < H_FONDO / H_GR; yy++) grilla[xx][yy] = 0; } // Redibuja la pantalla void redibujar() { int iy, ix; clear(buffer); blit(fnd, buffer, 0, yp * H_GR,0,0,600,480); /* grilla */ if (vgrilla) { for (ix=0; ix < W_FONDO / W_GR; ix ++ ) line(buffer, ix*W_GR, 0, ix*W_GR, 480, makecol(255,255,255)); for (iy=0; iy < H_FONDO / H_GR; iy ++ ) line(buffer, 0, iy*H_GR, fnd->w, iy*H_GR, makecol(255,255,255)); } /* cursor */ line(buffer, xp * W_GR, 0, (xp * W_GR) + W_GR, H_GR, makecol(255, 255, 255)); line(buffer, xp * W_GR, H_GR, (xp * W_GR) + W_GR, 0, makecol(255, 255, 255)); /* mostrar los valores (o sprite, si esta disponible) que contiene la matriz */ text_mode(makecol(0,0,0)); for (ix=0; ix < W_FONDO / W_GR; ix ++ ) { for (iy=0; iy < H_FONDO / H_GR; iy ++ ) { if (yp + iy < H_FONDO / H_GR ) { if (grilla[ix][yp+iy] != 0) { // ver si hay un sprite disponible... if ( (grilla[ix][yp+iy] > 0) && (grilla[ix][yp+iy] < MAX_SPR) ) { if ( sprite[grilla[ix][yp+iy]-1] != NULL ) { if (vgrilla) stretch_sprite(buffer, sprite[grilla[ix][yp+iy]-1], ix*W_GR, iy*H_GR, W_GR, H_GR); else draw_sprite(buffer, sprite[grilla[ix][yp+iy]-1], (W_GR / 2) - (sprite[grilla[ix][yp+iy]-1]->w / 2) + (ix*W_GR), (H_GR / 2) - (sprite[grilla[ix][yp+iy]-1]->h / 2) + (iy*H_GR)); } } // valor numerico textprintf(buffer, font, (ix*W_GR)+(W_GR/2), (iy*H_GR)+(H_GR/2), makecol(255,255,255), "%d", (int)grilla[ix][yp+iy]); } } } } /* panel de informacion */ text_mode(-1); // texto (-1=trans, 1 solido) textprintf(buffer, font, 600,0,makecol(255,255,255), "x:%d", xp); textprintf(buffer, font, 600,20,makecol(255,255,255), "y:%d", yp); textprintf(buffer, font, 600,40,makecol(255,255,255), "v:%d", vp); if ((vp > 0) && (vp < MAX_SPR)) if (sprite[vp-1] != NULL) stretch_sprite(buffer, sprite[vp-1], 600, (text_height(font)*2)+40, 40, 40); /* mandar a pantalla */ scare_mouse(); blit(buffer, screen, 0,0, 0,0,SCREEN_W, SCREEN_H); unscare_mouse(); } void editar_mapa() { int k; char salvar[1024]; /* archivo a salvar */; salvar[0] = '\0'; redibujar(); while (1) { k = readkey() >> 8; if (k == KEY_UP) yp--; if (k == KEY_DOWN) yp++; if (k == KEY_LEFT) xp--; if (k == KEY_RIGHT) xp++; if (k == KEY_SPACE) grilla[xp][yp] = vp; if (k == KEY_DEL) grilla[xp][yp] = 0; if (k == KEY_PLUS_PAD) vp++; if (k == KEY_MINUS_PAD) vp--; if (k == KEY_0) vp = 0; if (k == KEY_1) vp += 10; if (k == KEY_2) vp -= 10; if (k == KEY_V) vgrilla = !vgrilla; if (k == KEY_R) { // agregar 1 enemigo al azar... :P // en una casilla vacia solamente int xd, yd; xd = rand()% (W_FONDO / W_GR); yd = rand()% (H_FONDO / H_GR); if (grilla[xd][yd] == 0) { grilla[xd][yd] = vp; yp = yd; xp = xd; // feedback al user } } if (k == KEY_ESC) { if ( alert("Salir de la edicion.", "Esta seguro", "Se perderan los datos no salvados", "Si", "No", 'S', 'N') == 1) return; } if (k == KEY_C) { if ( alert("Limpiar grilla.", "Esta seguro", NULL, "Si", "No", 'S', 'N') == 1) { limpiar_grilla(); alert("La grilla se reinicio a ceros (0)", NULL, NULL, "OK", NULL, 0, 0); } } if (k == KEY_S) { if (file_select_ex("Archivo de grilla a salvar?", salvar, NULL, 512, 0, 0)) { PACKFILE *fp; int xx, yy; if ((fp = pack_fopen(salvar, F_WRITE)) != NULL) { // escribo la grilla en formato Intel de 32 bits for (xx =0; xx < W_FONDO / W_GR; xx++) for (yy =0; yy < H_FONDO / H_GR; yy++) pack_iputl(grilla[xx][yy], fp); pack_fclose(fp); alert("Archivo salvado.", salvar, NULL, "OK", NULL, 0, 0); } else { alert("Fallo la apertura del archivo!", salvar, NULL, "OK", NULL, 0, 0); } }; } if (k == KEY_L) { if (file_select_ex("Archivo a cargar?", salvar, NULL, 512, 0, 0)) { PACKFILE *fp; int xx, yy; if ((fp = pack_fopen(salvar, F_READ)) != NULL) { // leo la grilla en formato Intel de 32 bits for (xx =0; xx < W_FONDO / W_GR; xx++) for (yy =0; yy < H_FONDO / H_GR; yy++) grilla[xx][yy] = pack_igetl(fp); pack_fclose(fp); alert("Archivo cargado.", salvar, NULL, "OK", NULL, 0, 0); } else { alert("Fallo la apertura del archivo!", salvar, NULL, "OK", NULL, 0, 0); } }; } if (yp < 0) yp =0; if (yp > (H_FONDO / H_GR)-1) yp = (H_FONDO / H_GR)-1; if (xp < 0) xp =0; if (xp > (W_FONDO / W_GR)-1) xp = (W_FONDO / W_GR)-1; redibujar(); } } int main() { RGB_MAP tmp_rgb; /* acelera los calculos de makecol, etc */ char leerbmp[1024]; /* fondo a cargar */ int card = GFX_AUTODETECT, w = 640 ,h = 480 ,color_depth = 8; /* agregado por Kronoman */ allegro_init(); install_timer(); install_keyboard(); install_mouse(); srand(time(0)); set_color_depth(color_depth); if (set_gfx_mode(card, w, h, 0, 0)) { allegro_message("set_gfx_mode(%d x %d x %d bpp): %s\n", w,h, color_depth, allegro_error); return 1; } leerbmp[0] = '\0'; if (!file_select_ex("Cargue el fondo por favor.", leerbmp, NULL, 512, 0, 0)) return 0; fnd = load_bitmap(leerbmp, pal); if (fnd == NULL || fnd->w != W_FONDO || fnd->h != H_FONDO) { allegro_message("No se pueden cargar o es invalido \n %s!\n", leerbmp); return 1; } set_palette(pal); clear(screen); cargar_cache_sprites(); // cargar la cache de sprites... COOL! gui_fg_color = makecol(255,255,255); gui_bg_color = makecol(0,0,0); set_mouse_sprite(NULL); /* esto aumenta un monton los fps (por el makecol acelerado... ) */ create_rgb_table(&tmp_rgb, pal, NULL); /* rgb_map es una global de Allegro! */ rgb_map = &tmp_rgb; buffer=create_bitmap(SCREEN_W, SCREEN_H); clear(buffer); show_mouse(screen); limpiar_grilla(); /* Rock & Roll! */ editar_mapa(); if (data != NULL) unload_datafile(data); data = NULL; return 0; } END_OF_MAIN();
C
/** * @file ub_event_realloc.h * @brief * @author John F.X. Galea */ #ifndef EVENTS_HEAP_REALLOC_UB_EVENT_REALLOC_H_ #define EVENTS_HEAP_REALLOC_UB_EVENT_REALLOC_H_ #include "dr_api.h" #include "drmgr.h" #include "dr_defines.h" /** * @struct ub_realloc_data_t * * @var ub_realloc_data_t::addr The addr of the reallocated block. * @var ub_realloc_data_t::passed_addr The passed addr. * @var ub_realloc_data_t::size The size of the reallocated block. */ typedef struct { void *addr; void *passed_addr; void *pc; void *return_pc; size_t size; } ub_ev_realloc_data_t; /** * Callback function which is triggered upon the successful allocation of * heap memory. */ typedef void (*ub_ev_handle_heap_realloc_event_t)(ub_ev_realloc_data_t *realloc_data); /** * Initialises the context responsible for hooking heap reallocation * functions. */ void ub_ev_heap_realloc_init_ctx( ub_ev_handle_heap_realloc_event_t pre_realloc_hndlr, ub_ev_handle_heap_realloc_event_t post_realloc_hndlr); /** * Destroys the heap reallocation context. */ void ub_ev_heap_realloc_destroy_ctx(); #endif /* EVENTS_HEAP_REALLOC_UB_EVENT_REALLOC_H_ */
C
#include <ctype.h> #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #define MAX 256 void show_error_msg() { char error_message[30] = "An error has occurred\n"; write(STDERR_FILENO, error_message, strlen(error_message)); } // Note: This function returns a pointer to a substring of the original string. // If the given string was allocated dynamically, the caller must not overwrite // that pointer with the returned value, since the original pointer must be // deallocated using the same allocator with which it was allocated. The return // value must NOT be deallocated using free() etc. char *trim_whitespace(char *str) { if (str == NULL) { return NULL; } char *end; // Trim leading spaces while (isspace((unsigned char)*str)) { str++; } // All spaces? if (*str == 0) { return str; } // Trim trailing spaces end = str + strlen(str) - 1; while (end > str && isspace((unsigned char)*end)) { end--; } // Write new null terminator character end[1] = '\0'; return str; } bool startswith(const char *prefix, const char *str) { size_t len_pre = strlen(prefix), len_str = strlen(str); return len_str < len_pre ? false : strncmp(str, prefix, len_pre) == 0; } bool endswith(const char *suffix, const char *str) { size_t len_suf = strlen(suffix), len_str = strlen(str); return len_str < len_suf ? false : strcmp(str + len_str - len_suf, suffix) == 0; } int main(int argc, char *argv[]) { if (argc > 2) { show_error_msg(); exit(EXIT_FAILURE); } bool batch_mode = false; char prompt[7] = "wish> "; char *path[MAX] = { "/bin", "/usr/bin", NULL }; int rc, p = 0; pid_t pid[MAX]; char *token, *command; char *delimiter = " \t", *redirect_token = ">", *parallel_token = "&"; FILE *stream; int output_fd; size_t n; char *line = NULL; if (argc == 2) { batch_mode = true; stream = fopen(argv[1], "r"); if (stream == NULL) { show_error_msg(); exit(EXIT_FAILURE); } } else { batch_mode = false; stream = stdin; printf("%s", prompt); } while (getline(&line, &n, stream) != -1) { line = trim_whitespace(line); if (strcmp(line, "") == 0) { goto PROMPT; } while ((command = trim_whitespace(strsep(&line, parallel_token))) != NULL) { token = trim_whitespace(strsep(&command, delimiter)); command = trim_whitespace(command); if (strcmp(token, "") == 0) { break; } else if (strcmp(token, "exit") == 0) { if (command != NULL) { show_error_msg(); continue; } exit(EXIT_SUCCESS); } else if (strcmp(token, "cd") == 0) { if (command == NULL) { show_error_msg(); continue; } char *dest = trim_whitespace(strsep(&command, delimiter)); rc = chdir(dest); if (rc == -1) { show_error_msg(); } } else if (strcmp(token, "path") == 0) { if (command == NULL) { path[0] = NULL; } for (int i = 0; i < MAX; i++) { if (path[i] == NULL) { break; } path[i] = strdup(trim_whitespace(strsep(&command, delimiter))); if (command == NULL) { path[i + 1] = NULL; break; } } } else { pid[p] = fork(); if (pid[p] < 0) { // fork failed, print error message show_error_msg(); } else if (pid[p] == 0) { // child (new process) char *arguments[MAX]; arguments[0] = strdup(token); if (command != NULL) { char *output_file; char *found = trim_whitespace(strsep(&command, redirect_token)); // check if contains arguments if (strcmp(found, "") != 0) { int i = 1; char *argument; while ((argument = trim_whitespace(strsep(&found, delimiter))) != NULL && i < MAX - 1) { arguments[i] = strdup(argument); i++; } arguments[i++] = NULL; // mark end of array } else { arguments[1] = NULL; } // check if contains the redicrect token if (command) { // check if contains another redirect token found = trim_whitespace(strsep(&command, redirect_token)); if (command) { show_error_msg(); exit(EXIT_FAILURE); } // check if specifies more than one file output_file = trim_whitespace(strsep(&found, delimiter)); if (found) { show_error_msg(); exit(EXIT_FAILURE); } // redirect stdout and stderr to an output file output_fd = open(output_file, O_CREAT | O_WRONLY | O_TRUNC, S_IRWXU); if (output_fd < 0) { show_error_msg(); exit(EXIT_FAILURE); } // redirect the child's stdout to the output file if (dup2(output_fd, STDOUT_FILENO) < 0) { close(output_fd); show_error_msg(); exit(EXIT_FAILURE); } // redirect the child's stderr to the output file if (dup2(output_fd, STDERR_FILENO) < 0) { close(output_fd); show_error_msg(); exit(EXIT_FAILURE); } } } else { arguments[1] = NULL; // mark end of array } for (int i = 0; i < MAX; i++) { if (path[i] == NULL) { rc = -1; break; } char *exec_path; if (startswith("/", token)) { exec_path = malloc(sizeof(token)); strcpy(exec_path, token); } else if (endswith("/", path[i])) { exec_path = malloc(sizeof(path[i]) + sizeof(token) + 1); strcpy(exec_path, path[i]); strcat(exec_path, token); } else { exec_path = malloc(sizeof(path[i]) + sizeof(token) + sizeof("/") + 1); strcpy(exec_path, path[i]); strcat(exec_path, "/"); strcat(exec_path, token); } if (access(exec_path, X_OK) == 0) { // child process will block here if it can be invoked normally rc = execv(exec_path, arguments); break; // finish iterate if child process failed } } if (rc == -1) { show_error_msg(); exit(EXIT_FAILURE); } } else { if (++p >= MAX) { show_error_msg(); if (batch_mode) { exit(EXIT_FAILURE); } } } } } // parent goes down this path while (p > 0) { rc = waitpid(pid[--p], NULL, 0); if (rc == -1) { show_error_msg(); if (batch_mode) { exit(EXIT_FAILURE); } } } PROMPT: if (!batch_mode) { printf("%s", prompt); } } fclose(stream); close(output_fd); return 0; }
C
#include <stdio.h> typedef unsigned int u32; char *ctable = "0123456789ABCDEF"; void prints(char * str) { int s_index = 0; while (str[s_index] != '\0') { putchar(str[s_index]); s_index++; } } int rpu(u32 x, int base) { char c; if (x){ c = ctable[x % base]; rpu(x / base, base); putchar(c); } } void printnum(u32 n, int base) { if (n < 0) { putchar('-'); n *= -1; } (n == 0) ? putchar('0') : rpu(n, base); } int printu(u32 n) { (n == 0) ? putchar('0') : rpu(n, 10); } /* printd() */ void printd(int n) { printnum(n, 10); } /* printx() */ void printx(u32 n) { printnum(n, 16); } /* printo() */ void printo(u32 n) { printnum(n, 8); } void myprintf(char * str, ...) { int * stkptr = (int *) getebp() + 3; int s_index = 0, a_index = 0; while (str[s_index] != '\0') { if (str[s_index] == '%') { int stkptr_add = 1, s_index_add = 2; switch (str[s_index + 1]){ case 'c': { putchar(* stkptr); } break; case 's': { prints(* stkptr); } break; case 'u': { printu(* stkptr); } break; case 'd': { printd(* stkptr); } break; case 'o': { printo(* stkptr); } break; case 'x': { printx(* stkptr); } break; default: { putchar('%'); stkptr_add = 0; s_index_add = 1; } break; } stkptr += stkptr_add; s_index += s_index_add; } else { putchar(str[s_index]); if (str[s_index] == '\n') { putchar('\r'); }; s_index++; } } } int main(int argc, char *argv[], char *env[]) { prints("Shoobee doobee\ndoowop bang boom!\n"); myprintf("cha=%c string=%s\ dec=%d hex=%x oct=%o neg=%d\n", 'A', "this is a test", 100, 100, 100, -100); myprintf("Number of CMD line args (argc): %u\n", argc); for(int i = 0; i < argc; i++) { myprintf("Cmd line arg #%d = %s\n", i, argv[i]); } myprintf("\n"); for(int i = 0; env[i] != NULL; i++){ myprintf("Env. Var. #%u: %s\n", i, env[i]); } }
C
#include <stdio.h> void test() { // empty statement ; } int main() { int x = 0; test(); printf("%d\n", x); return 0; }
C
/* Author: Andrew Tee * Partner(s) Name: * Lab Section: * Assignment: Lab #6 Exercise #2 * Exercise Description: [optional - include for your own benefit] * * I acknowledge all content contained herein, excluding template or example * code, is my own original work. * * Demo Link: https://youtu.be/qz1JVSg-hjo * */ #include <avr/io.h> #include <avr/interrupt.h> #ifdef SIMULATE #include "simAVRHeader.h" #endif volatile unsigned char TimerFlag = 0; void TimerISR() { TimerFlag = 1; } unsigned long _avr_timer_M = 1; unsigned long _avr_timer_cntcurr = 0; void TimerOn() { TCCR1B = 0x0B; OCR1A = 125; TIMSK1 = 0x02; TCNT1 = 0; _avr_timer_cntcurr = _avr_timer_M; SREG |= 0x80; } void TimerOff() { TCCR1B = 0x00; } ISR(TIMER1_COMPA_vect) { _avr_timer_cntcurr--; if (_avr_timer_cntcurr == 0) { TimerISR(); _avr_timer_cntcurr = _avr_timer_M; } } void TimerSet (unsigned long M) { _avr_timer_M = M; _avr_timer_cntcurr = _avr_timer_M; } enum LED_States {init, forward, backward, wait_on, wait_off} LED_State; void Tick(){ switch(LED_State){ case init: PORTB = 0x01; LED_State = forward; break; case forward: if((~PINA & 0x01) == 0x01) LED_State = wait_on; else if(PORTB == 0x04){ PORTB = PORTB >> 1; LED_State = backward; } else{ PORTB = PORTB << 1; LED_State = forward; } break; case backward: if((~PINA & 0x01) == 0x01) LED_State = wait_on; else if(PORTB == 0x01){ PORTB = PORTB << 1; LED_State = forward; } else{ PORTB = PORTB >> 1; LED_State = backward; } break; case wait_on: LED_State = ((~PINA & 0x01) == 0x01) ? wait_on : wait_off; break; case wait_off: if((~PINA & 0x01) == 0x01){ PORTB = 0x01; LED_State = forward; } else{ LED_State = wait_off; } break; default: break; } switch(LED_State){ case init: break; default: break; } } int main(void){ DDRB = 0xff; PORTB = 0x00; DDRA = 0x00; PORTA = 0xff; TimerSet(150); TimerOn(); LED_State = init; while(1){ Tick(); while(!TimerFlag){} TimerFlag = 0; } }
C
#include <stdlib.h> #include <error.h> #include <SDL2/SDL.h> #include "eventHandler.h" #include "player.h" typedef struct app{ SDL_Renderer *renderer; SDL_Window *window; } App; #define SCREEN_HEIGHT 720 #define SCREEN_WIDTH 1020 int initSDL(App *app); int main(int argc, char *argv[]){ App app; if(! initSDL(&app)) return EXIT_FAILURE; player_create(0,0,64,64); SDL_Event event; while(1){ player_draw(app.renderer); eventHandler(&event); // Render to Screen SDL_RenderPresent(app.renderer); SDL_Delay(200); } // Destroy SDL_DestroyRenderer(app.renderer); SDL_DestroyWindow(app.window); SDL_Quit(); return 0; } int initSDL(App *app){ int rendFlag = SDL_RENDERER_ACCELERATED; int windFlag = 0; if(SDL_Init(SDL_INIT_VIDEO) < 0){ fprintf(stderr, "Could not initialize SDL: %s\n", SDL_GetError()); return -1; } app->window = SDL_CreateWindow("Main Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, windFlag); if(!app->window){ fprintf(stderr, "Could not open window: %s\n", SDL_GetError()); return -1; } SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "linear"); app->renderer = SDL_CreateRenderer(app->window, -1, rendFlag); if(!app->renderer){ fprintf(stderr, "Could not create renderer: %s\n", SDL_GetError()); return -1; } return 1; }
C
#include <stdio.h> int main() { int (*ptr)[4]; int i, j; ptr=(int(*)[4])malloc(3*4*sizeof(int)); for (i=0; i<3; i++) for (j=0;j<4; j++) scanf("%d", *(ptr+i)+j); for (i=0; i<3; i++) for (j=0;j<4; j++) printf("massive[%d][%d]= %d, adres= %p\n", i, j, *(*(ptr+i)+j), *(ptr+i)+j); return 0; }
C
// eqstring.c: Solution of wave equation using time stepping // saves output to 3D grid format used by gnuplot #include <stdio.h> #include <math.h> #define rho .01 // density per length #define ten 40 // tension #define max 100 // time steps main() { int i, k; double x[101][3]; FILE *out; out = fopen("eqstring.dat", "w") for (i = 0; i<81; i++) x[i][0] = .00125; for (i = 81; i<101; i++) x[i][0] = .1 - .005*(i-80); for (i = 1; i<100; i++) x[i][1] = x[i][0] + .5*(x[i+1][0] + x[i-1][0] - 2*x[i][0]); for (k = 1; k<max; k++) {for (i=1; i<100; i++) x[i][2] = 2*x[i][1]-x[i][0]+(x[i+1][1]+x[i-1][1]-2*x[i][1]); for (i=0; i<101; i++){ x[i][0] = x[i][1]; x[i][1] = x[i][2]; } if ((k%5) ==0) { for (i =0; i<101; i++) {// print every 5th point fprintf(out, "%f\n", x[i][2]); // empty line for gnuplot } } printf("data stored in eqstring.dat\n"); fclose(out) }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> #include<limits.h> int main(void) { int first_iteration; int num; int N; int i; long long j; long long r; long long t; long long p; long long x; scanf("%d", &num); for (i = 1; i <= num; ++i) { scanf("%lld %lld", &r, &t); for (j = 0, x = 0; x <= t; ++j) { x += (2 * (r + (j * 2))) + 1; } j--; printf("Case #%d: %lld\n", i, j); } return 0; }
C
/** * hdr_thread.h * Written by Philip Orwig and released to the public domain, * as explained at http://creativecommons.org/publicdomain/zero/1.0/ */ #ifndef HDR_THREAD_H__ #define HDR_THREAD_H__ #include <stdint.h> #if defined(_WIN32) || defined(_WIN64) || defined(__CYGWIN__) #define HDR_ALIGN_PREFIX(alignment) __declspec( align(alignment) ) #define HDR_ALIGN_SUFFIX(alignment) typedef struct hdr_mutex { uint8_t _critical_section[40]; } hdr_mutex; #else #include <pthread.h> #define HDR_ALIGN_PREFIX(alignment) #define HDR_ALIGN_SUFFIX(alignment) __attribute__((aligned(alignment))) typedef struct hdr_mutex { pthread_mutex_t _mutex; } hdr_mutex; #endif #ifdef __cplusplus extern "C" { #endif struct hdr_mutex* hdr_mutex_alloc(void); void hdr_mutex_free(struct hdr_mutex*); int hdr_mutex_init(struct hdr_mutex* mutex); void hdr_mutex_destroy(struct hdr_mutex* mutex); void hdr_mutex_lock(struct hdr_mutex* mutex); void hdr_mutex_unlock(struct hdr_mutex* mutex); void hdr_yield(void); int hdr_usleep(unsigned int useconds); #ifdef __cplusplus } #endif #endif
C
#include <CUnit/CUnit.h> #include <stdio.h> #include "cmat.h" #include "test_sub.h" #define N(x) (sizeof(x) / sizeof(*x)) static int create_matrix(const matrix_info_t* info, cmat_t** dst) { return cmat_new(info->val, info->rows, info->cols, dst); } static void check_matrix(cmat_t* ptr, const matrix_info_t* info) { int res; cmat_check(ptr, info->val, &res); CU_ASSERT(res == 0); CU_ASSERT(ptr->rows == info->rows); CU_ASSERT(ptr->cols == info->cols); } static void test_normal_1(void) { cmat_t* m1; cmat_t* m2; cmat_t* m3; int i; int err; for (i = 0; i < N(data); i++) { create_matrix(&data[i].op1, &m1); create_matrix(&data[i].op2, &m2); err = cmat_sub(m1, m2, &m3); CU_ASSERT(err == 0); #if 0 printf("\n"); cmat_print(m1, NULL); printf("\n"); cmat_print(m2, NULL); printf("\n"); cmat_print(m3, NULL); #endif check_matrix(m3, &data[i].ans); cmat_destroy(m1); cmat_destroy(m2); cmat_destroy(m3); } } static void test_normal_2(void) { cmat_t* m1; cmat_t* m2; int i; int err; for (i = 0; i < N(data); i++) { create_matrix(&data[i].op1, &m1); create_matrix(&data[i].op2, &m2); #if 0 printf("\n"); cmat_print(m1, NULL); printf("\n"); cmat_print(m2, NULL); #endif err = cmat_sub(m1, m2, NULL); CU_ASSERT(err == 0); #if 0 printf("\n"); cmat_print(m1, NULL); #endif check_matrix(m1, &data[i].ans); cmat_destroy(m1); cmat_destroy(m2); } } static void test_error_1(void) { int err; cmat_t* m; float v[] = { 1, 2, 3, 4 }; cmat_new(v, 2, 2, &m); err = cmat_sub(m, NULL, NULL); CU_ASSERT(err == CMAT_ERR_BADDR); cmat_destroy(m); } static void test_error_2(void) { int err; cmat_t* m; float v[] = { 1, 2, 3, 4 }; cmat_new(v, 2, 2, &m); err = cmat_sub(NULL, m, NULL); CU_ASSERT(err == CMAT_ERR_BADDR); cmat_destroy(m); } void init_test_sub() { CU_pSuite suite; suite = CU_add_suite("sub", NULL, NULL); CU_add_test(suite, "sub#1", test_normal_1); CU_add_test(suite, "sub#2", test_normal_2); CU_add_test(suite, "sub#E1", test_error_1); CU_add_test(suite, "sub#E2", test_error_2); }
C
#include "std.h" #include "list.h" List list_new(i32 size){ size = size < 10 ? 10 : size; List list = malloc(sizeof(struct List)); list->elements_size = size; list->elements = malloc(sizeof(i32) * size); list->size = 0; return list; }; void list_free(List this){ free(this->elements); free(this); } bool list_is_empty(List this){ return this->size == 0; } void list_increase_capacity(List this){ i32 new_size = this->size * 1.5; i32* new_elements = malloc(sizeof(i32) * new_size); for(i32 i = 0; i < this->size; i++){ new_elements[i] = this->elements[i]; } this->elements_size = new_size; free(this->elements); this->elements = new_elements; } bool list_contains(List this, i32 element){ for(i32 i = 0; i < this->size; i++){ if(this->elements[i] == element){ return true; } } return false; } void list_add(List this, i32 element){ if(this->elements_size == this->size){ list_increase_capacity(this); } this->elements[this->size++] = element; } i32 list_get(List this, i32 index){ return this->elements[index]; }
C
/* Esercizio 96 In un vettore sono contenuti i prezzi di vendita di un determinato prodotto relativamente agli N supermercati dove è presente. Il codice del supermercato corrisponde all'indice del vettore. Scrivi un programma che dopo aver caricato i dati permetta di: a. stampare il minimo prezzo registrato e il codice del supermercato in cui si è rilevato; b. stampare la differenza di ciascun prezzo da uno specifico valore fornito in input; c.dato il codice di un supermercato, ne stampi il prezzo o una segnalazione se non è presente. */ #include <stdio.h> #include <stdlib.h> #include <math.h> #define N 5 main() { float prices[N], min, offset; int i, choice, code = 0; for(i = 0; i < N; i++) { printf("Inserire il prezzo del %d supermercato: ", i + 1); scanf("%f", &prices[i]); // fflush(stdin); } printf("Quale programma vuoi eseguire?\n"); printf("1. Stampare il minimo prezzo registrato e il codice del supermercato.\n"); printf("2. Stampare la differenza di ciascun prezzo da uno specifico valore inserito in input.\n"); printf("3. Dato il codice di un supermercato, ne stampi il prezzo o una segnalazione se non e' presente..\n"); scanf("%d", &choice); while(choice < 1 && choice > 3) { printf("Scelta non valida. Inserire un altro valore."); scanf("%d", &choice); } switch(choice) { case 1: min = prices[0]; for(i = 0; i < N; i++) { if(min > prices[i]) { min = prices[i]; code = i; } } printf("Il minimo prezzo registrato e': %0.2f\n", min); printf("Il codice del supermercato e': %d\n", code); break; case 2: printf("Inserire l'offset: "); scanf("%0.2f", &offset); for(i = 0; i < N; i++) { printf("La differenza con l'offset e': %0.2f euro.\n", prices[i] - offset); } break; case 3: printf("Inserire il codice del supermercato: "); scanf("%d", &code); while(code < 0 || code >= N) { printf("Codice inserito non valido.\n"); printf("Inserire un altro codice: "); scanf("%d", &code); } printf("Il prezzo relativo al supermercato %d e' %0.2f\n", code, prices[code]); break; default: break; } system("pause"); }
C
#include <reg51.h> #include <intrins.h> unsigned char key_s, key_v, tmp; char code str[] = "I love zhu xiao ying--CUMT \n\r"; void send_int(void); void send_str(); bit scan_key(); void proc_key(); void delayms(unsigned char ms); void send_char(unsigned char txd); sbit K1 = P1^4; main() { send_int(); TR1 = 1; // ʱ1 while(1) { if(scan_key()) // ɨ谴 { delayms(10); // ʱȥ if(scan_key()) // ٴɨ { key_v = key_s; // ֵ proc_key(); // } } if(RI) // Ƿݵ { RI = 0; tmp = SBUF; // ݴյ P0 = tmp; // ݴ͵P0 send_char(tmp); // شյ } } } void send_int(void) { TMOD = 0x20; // ʱ18λԶģʽ, ڲ TH1 = 0xF3; // 2400 TL1 = 0xF3; SCON = 0x50; // 趨пڹʽ PCON&= 0xef; // ʲ IE = 0x0; // ֹκж } bit scan_key() // ɨ谴 { key_s = 0x00; key_s |= K1; return(key_s ^ key_v); } void proc_key() // { if((key_v & 0x01) == 0) { // K1 send_str(); // ִ } } void send_char(unsigned char txd) // һַ { SBUF = txd; while(!TI); // ݴ TI = 0; // ݴͱ־ } void send_str() // ִ { unsigned char i = 0; while(str[i] != '\0') { SBUF = str[i]; while(!TI); // ݴ TI = 0; // ݴͱ־ i++; // һַ } } void delayms(unsigned char ms) // ʱӳ { unsigned char i; while(ms--) { for(i = 0; i < 120; i++); } }
C
/* * Naglowki.h * * Created: 2016-12-31 18:23:00 * Author: Nathir */ // Zastanow sie czy przerwanie osiagniecia pozycji zadanej nie powinno czasem miec priorytetu MID. Jest wazniejsze od np. przyspieszania/hamowania // /* krancowki - drgaja styki okres drgan 1ms drgania wystepuja przy zalaczaniu i wylaczaniu styku i jest kijowo */ //PODLACZENIA /* Sterownik silnika: Pulse (przez tranzystor) - E4 DIR (tranzystor) - E1 krancowka lewa (normalnie zamknieta) - D0 krancowka prawa (normalnie zamknieta) - D1 */ //WYKORZYSTYWANE PERYFERIA WEWNETRZNE /* //######################################################################### ****TIMERY***** //######################################################################### C0 - enkoder C1 - przyspieszanie wozka E0 - aktualne polozenie wozka E1 - generowanie przebiegu silnika //######################################################################### *** SYSTEM ZDARZEN***** //######################################################################### CH0 - enkoder CH1 - taktowanie licznika pozycji wozka //######################################################################### *** PRZERWANIA I PRIORYTETY *** //######################################################################### -------> LOW (TCC1_OVF_vect) //od timera przyspieszania (TCE0_CCA_vect) //pozycja: dolna granica (TCE0_CCB_vect) //pozycja: gorna granica (TCE0_CCC_vect) //pozycja: poczatek hamowania (TCE0_CCD_vect) //pozycja: zadana -------> MED -------> HI PORTD_INT0_vect //krancowka lewa PORTD_INT1_vect //krancowka prawa */ #ifndef INCFILE1_H_ #define INCFILE1_H_ #endif /* INCFILE1_H_ */ #define F_CPU 32000000UL #include <avr/io.h> #include <avr/interrupt.h> #include <util/delay.h> #include "hd44780.h" //######################################################################### //*****************STALE****************** //######################################################################### #define lewo 0 #define prawo 1 //********************************* //parametry silnika #define MAKS_CZESTOTLIWOSC_SILNIKA 12000UL //********************************* //parametry przyspieszania i hamowania //PRZYSPIESZANIE #define OKRES_PRZYSPIESZANIA 90UL //co jaki czas jest aktualizowana predkosc #define KROK_PRZYSPIESZANIA 10UL // co jaka wartosc predkosc rosnie #define PREDKOSC_POCZATKOWA_PRZYSPIESZANIA 1000 //--wynikowe przyspieszenie #define WARTOSC_PRZYSP ((500000/OKRES_PRZYSPIESZANIA)*(KROK_PRZYSPIESZANIA)) //HAMOWANIE #define OKRES_HAMOWANIA 90UL #define KROK_HAMOWANIA 20UL #define PREDKOSC_KONCOWA_HAMOWANIA (PREDKOSC_POCZATKOWA_PRZYSPIESZANIA) //--wynikowe hamowanie #define WARTOSC_HAMOW ((500000/OKRES_HAMOWANIA)*(KROK_HAMOWANIA)) #define przyspieszanie 1 #define brak 0 #define hamowanie -1 //RAMPY RUCHU //Roznica miedzy maks i minimalna predkoscia #define DELTA_V (MAKS_CZESTOTLIWOSC_SILNIKA-PREDKOSC_POCZATKOWA_PRZYSPIESZANIA) //Minimalna droga dla rampy typu 1 #define DROGA_MIN_RAMPY_1 ((uint32_t)((((PREDKOSC_POCZATKOWA_PRZYSPIESZANIA*DELTA_V)+((float)(DELTA_V)*(DELTA_V)/2))/(float)WARTOSC_HAMOW/WARTOSC_PRZYSP)*(WARTOSC_HAMOW+WARTOSC_PRZYSP))) #define STALA_WCZESNEGO_HAMOWANIA_RAMPY_1 ((uint32_t)((((float)PREDKOSC_POCZATKOWA_PRZYSPIESZANIA/WARTOSC_HAMOW*DELTA_V)+((float)DELTA_V/WARTOSC_HAMOW*DELTA_V/2)))) //rzutujemy floaty na inty //typy rampy #define pierwszy 1 #define drugi 2 //********************************* //licznik pozycji #define POZYCJA_KRANCOWKA_LEWA 100 #define ZAPASOWY_ODSTEP_OD_KRANCOWEK 400 //######################################################################### //**************ZMIENNE GLOBALNE******************* //######################################################################### extern volatile signed char GLOB_kierunek_zmiany_predkosci; extern volatile uint8_t GLOB_flaga_rampa_pozycja_osiagnieta; //######################################################################### //**************FUNKCJE******************* //######################################################################### //PrzyMain void Osc32MHz(void); void konfiguracja(void); void bazuj(void); //Silnik uint16_t przelicz_predkosc_na_compare(uint16_t czestotliwosc); uint16_t przelicz_compare_na_predkosc(uint16_t compare); void init_silnik(void); void wylacz_silnik(void); void wlacz_silnik(void); void kierunek_silnik(uint8_t kierunek); void ustaw_predkosc_silnik(uint16_t predkosc); void init_przyspieszanie(void); void wlacz_licznik_przyspieszania(void); void wylacz_licznik_przyspieszania(void); void wlacz_silnik_z_przyspieszaniem(void); //Licznik krokow (aktualne polozenie) void init_liczenie_krokow(void); void kierunek_liczenie_krokow(uint8_t kierunek); void zeruj_liczenie_krokow(void); void nadpisz_liczenie_krokow(uint16_t wartosc); uint16_t wartosc_licznika_krokow(void); void init_krancowki(void); //Rampa ruchu void Rampa_Jedz_Do_Pozycji(uint16_t pozycja); uint8_t TypRampy(uint16_t modul_drogi); int16_t Przelicz_pozycje_bezwgledna_na_wzgledna_droge(uint16_t pozycja); void R1_ustaw_wartosci_compare(int16_t droga_wzgledna, int8_t znak); void R2_ustaw_wartosci_compare(uint16_t modul_drogi,int8_t znak); uint16_t R2_licz_x2(uint16_t modul_drogi); //Enkoder i odchylenie wahadla void init_enkoder(void); void zeruj_licznik_enkodera(void); void nadpisz_licznik_enkodera(uint16_t wartosc); void resetuj_punkt_odniesienia_enkodera(void); //RegulatorPID float RegulatorPID(uint16_t wyjscie);
C
/*Write a C program to input length in centimeter and convert it to meter and kilometer*/ #include<stdio.h> int main(){ int cm,m,km; printf("enter the value in cm:"); scanf("%d",&cm); m = cm/100; printf("metres = %d\n",m); km = cm/1000; printf("kilometres = %d\n",km); return 0; }
C
#include <stdio.h> int main(void) { int c = 7; int d = (c/2); printf("%i\n", d); return 0; }
C
#include <stdio.h> int main(void) { int n,result = 1; printf("%-8s%-14s\n","n","Factorial of n"); for (n = 1;n <= 5;n++) { result = result * n; printf("%-8d%-14d\n",n,result); } return 0; }
C
/** * un programma, lanciato due volte come trasmittente e ricevente, * comunica tramite una pipe con nome sul file-system (FIFO); * da invocare come: * - trasmittente: fifo T * - ricevente: fifo R * * tentano di scambiarsi messaggi di dimensione variabile * (dimostrando i limiti delle pipe/fifo) */ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #define BUFSIZE 1024 #define NUM_MSG 20 int main(int argc, char *argv[]) { int i, fd, len; char buffer[BUFSIZE]; const char *pathname = "/tmp/fifo"; if (argc < 2) { fprintf(stderr, "uso: %s T|R\n", argv[0]); exit(1); } if (argv[1][0] == 'T') { // trasmittente if (mkfifo(pathname, 0777) == -1) { perror(pathname); exit(1); } if ((fd = open(pathname, O_WRONLY)) == -1) { perror(pathname); unlink(pathname); exit(1); } for (i = 0; i < NUM_MSG; i++) { snprintf(buffer, BUFSIZE, "msg-%d: Hello!", i); write(fd, buffer, strlen(buffer) + 1); sleep(1); // senza questa pausa ci sono dei problemi: perche'? printf("messaggio n.%d inviato: '%s'\n", i, buffer); } exit(0); } else if (argv[1][0] == 'R') { // ricevente if ((fd = open(pathname, O_RDONLY)) == -1) { perror(pathname); unlink(pathname); exit(1); } for (i = 0; i < NUM_MSG; i++) { buffer[0] = '\0'; // azzero la stringa residua del buffer len = read(fd, buffer, BUFSIZE); // qui non specifico la dimensione del messaggio ma la capienza del // buffer printf("messaggio ricevuto (%d byte): %s\n", len, buffer); } unlink(pathname); exit(0); } else { fprintf(stderr, "parametro non atteso!\n"); unlink(pathname); exit(1); } }
C
#include <stdio.h> int main(void){ char *string = "Hello Arrays"; char character_array[7] = "abc123"; printf("the string is %s",string); printf("the array is %s",character_array); }
C
#include "dothat.h" #include <unistd.h> #include <stdio.h> int main() { DOTHAT* d = dothat_init(); dothat_lcd_clear(d); dothat_lcd_home(d); dothat_input_recalibrate(d); int active = 1; while( active != 0 ) { uint8_t inp = dothat_input_poll(d); char inputtext[] = { '-', '-', '-', '-', '-', '-', 0 }; if( (inp & DOTHAT_CANCEL) != 0 ) { inputtext[0] = 'Q'; active = 0; } if( (inp & DOTHAT_LEFT) != 0 ) { inputtext[1] = 'L'; } if( (inp & DOTHAT_RIGHT) != 0 ) { inputtext[2] = 'R'; } if( (inp & DOTHAT_UP) != 0 ) { inputtext[3] = 'U'; } if( (inp & DOTHAT_DOWN) != 0 ) { inputtext[4] = 'D'; } if( (inp & DOTHAT_BUTTON) != 0 ) { inputtext[5] = 'B'; } dothat_lcd_home(d); dothat_lcd_write_text(d, (char*)&inputtext); usleep(50000); } dothat_shutdown(d); }
C
#include <stdio.h> #include <stdlib.h> void basic() { long int i = 0; long int j; int done = 0; while (!done) { i += 20; done = 1; // 20 (2*2*5) 2, 4, 10, 20 // 19 // 18 (2*3*3) 2, 6, 9, 18 // 17 // 16 (2*2*2*2) 2, 4, 8, 16 // 15 (3*5) 3, 5 // 14 (2*7) 2, 7 // 13 // 12 (2*2*3) 2, 3 // 11 // no need to check for 1-9, because they are included in the // numbers above for (j = 11; j <= 20 && done; ++j) { done = done && (i % j == 0); } } printf("%ld\n", i); } int main(int argc, char **argv) { basic(); return 0; }
C
#include "types.h" #include "stat.h" #include "user.h" int numPasses; int numThreads; int currPass = 1; int holder = 0; lock_t lock; int sequenceNum = 0; void passFrisbee(void* arg) { int threadnumber = *(int*)arg; for(;;) { //printf(0,"Thread %d from the top\n", threadnumber); int check, skip, break_; do { check = sequenceNum; break_ = 0; if(numPasses <= 0) { break_ = 1; } // if(check != sequenceNum) // { // printf(0,"c:%d, s:%d\n", check, sequenceNum); // } }while(check != sequenceNum); if(break_ == 1) { break; } do { check = sequenceNum; skip = 0; if(holder != threadnumber) { skip = 1; } // if(check != sequenceNum) // { // printf(0,"c:%d, s:%d\n", check, sequenceNum); // } }while(check != sequenceNum); if(skip == 1) { sleep(1); continue; } // printf(0,"Thread %d trying to acquire, holder is %d\n", threadnumber, holder); seqlock_acquire(&lock, &sequenceNum); // printf(0,"thread %d acquired lock\n", threadnumber); holder++; if(holder == numThreads) { holder = 0; } printf(0, "Pass number no. %d, Thread %d is passing the token to %d\n", currPass, threadnumber, holder); numPasses--; currPass++; seqlock_release(&lock, &sequenceNum); // printf(0,"Thread %d released \n",threadnumber); } return; } int main(int argc, char *argv[]) { if(argc != 3) { printf(0,"Usage: frisbee numThreads numPasses\n"); exit(); } numThreads = atoi(argv[1]); numPasses = atoi(argv[2]); printf(0,"Num Threads: %d, Num Passes: %d\n", numThreads, numPasses); lock_init(&lock); int i,rc; for(i = 0; i < numThreads; i++) { int * t = malloc(sizeof(*t)); *t = i; // printf(0,"t = %d\n", *t); rc = thread_create((void*)passFrisbee,(void*)t); // printf(0,"rc = %d\n", rc); } // sleep(500); // printf(0,"lock->locked: %d\n", lock.locked); for(i = 0; i < numThreads; i++) { wait(); } printf(0,"Simulation of frisbee game has finished, %d rounds were played in total!\n", currPass-1); exit(); }
C
#include<stdio.h> #include<math.h> double gamma_function(double); int main(){ double a=-2*M_PI, b=2*M_PI, dx=0.013; for(double x=a;x<b;x+=dx) printf("%g %g %g\n",x,gamma_function(x),tgamma(x)); return 0; }
C
#include<stdio.h> int N, Num[20][20], Re[21][21][21][41]; void Search(int xa, int xb, int xc, int step) { if (Re[xa][xb][xc][step] == 0) { int ya, yb, yc; ya = step - xa - 1; yb = step - xb - 1; yc = step - xc - 1; if (xa < N && xb < N && xc < N && ya < N && yb < N && yc < N) { Re[xa][xb][xc][step] += Num[xa][ya]; if (xb != xa) Re[xa][xb][xc][step] += Num[xb][yb]; if (xc != xa && xc != xb) Re[xa][xb][xc][step] += Num[xc][yc]; int temp = 0; Search(xa + 1, xb + 1, xc + 1, step + 1); if (temp < Re[xa + 1][xb + 1][xc + 1][step + 1]) temp = Re[xa + 1][xb + 1][xc + 1][step + 1]; Search(xa + 1, xb + 1, xc, step + 1); if (temp < Re[xa + 1][xb + 1][xc][step + 1]) temp = Re[xa + 1][xb + 1][xc][step + 1]; Search(xa + 1, xb, xc + 1, step + 1); if (temp < Re[xa + 1][xb][xc + 1][step + 1]) temp = Re[xa + 1][xb][xc + 1][step + 1]; Search(xa, xb + 1, xc + 1, step + 1); if (temp < Re[xa][xb + 1][xc + 1][step + 1]) temp = Re[xa][xb + 1][xc + 1][step + 1]; Search(xa, xb, xc + 1, step + 1); if (temp < Re[xa][xb][xc + 1][step + 1]) temp = Re[xa][xb][xc + 1][step + 1]; Search(xa, xb + 1, xc, step + 1); if (temp < Re[xa][xb + 1][xc][step + 1]) temp = Re[xa][xb + 1][xc][step + 1]; Search(xa + 1, xb, xc, step + 1); if (temp < Re[xa + 1][xb][xc][step + 1]) temp = Re[xa + 1][xb][xc][step + 1]; Search(xa, xb, xc, step + 1); if (temp < Re[xa][xb][xc][step + 1]) temp = Re[xa][xb][xc][step + 1]; Re[xa][xb][xc][step] += temp; } } } int main() { int a, b; scanf("%d", &N); for (a = 0; a < N; a++) for (b = 0; b < N; b++) scanf("%d", &Num[a][b]); Search(0, 0, 0, 1); printf("%d\n", Re[0][0][0][1]); return 0; }
C
/* * Project Arduino.c * * Created: 25-Oct-17 14:27:50 * Author : Arneldvdv */ #include <avr/io.h> #include <avr/delay.h> //blink every half second #define BLINK_DELAY 500 // switch every 10 seconds #define UP_DOWN_DELAY 100000 // stop blinking after 5 seconds #define Blink_CD 5000 int main(void) { //define ports DDRB |= _BV(DDB0); DDRB |= _BV(DDB1); DDRB |= _BV(DDB2); DDRD &= _BV(DDD4); DDRD &= _BV(DDD5); while (1) { PORTB |= _BV(PORTB0); _delay_ms(UP_DOWN_DELAY); PORTB &= ~ _BV(PORTB0); PORTB |= _BV(PORTB2); _delay_ms(UP_DOWN_DELAY); PORTB &= ~ _BV(PORTB2); if (PINB & 0b00000111){ PORTB |= _BV(PORTB1); _delay_ms(BLINK_DELAY); } } }
C
#include <stdio.h> #include <stdlib.h> #include "src/tables.h" #include "assembler.h" int grade_pass_two(char* in_name, char* out_name, SymbolTable* symtbl, SymbolTable* reltbl) { FILE *input = fopen(in_name, "r"); FILE *output = fopen(out_name, "w"); if (!input || !output) { return -1; } int retval = pass_two(input, output, symtbl, reltbl); fclose(input); fclose(output); return retval; } int grade_branch_one() { SymbolTable* symtbl = create_table(SYMTBL_UNIQUE_NAME); SymbolTable* reltbl = create_table(SYMTBL_NON_UNIQUE); add_to_table(symtbl, "l1", 0); add_to_table(symtbl, "l2", 4); add_to_table(symtbl, "l3", 16); int retval = grade_pass_two("../test_input/branch.s", "out/branch.out", symtbl, reltbl); free_table(symtbl); free_table(reltbl); return retval; } int grade_branch_two() { SymbolTable* symtbl = create_table(SYMTBL_UNIQUE_NAME); SymbolTable* reltbl = create_table(SYMTBL_NON_UNIQUE); add_to_table(symtbl, "l1", 131072); add_to_table(symtbl, "l2", 131076); int retval = grade_pass_two("../test_input/branch2.s", "out/branch2.out", symtbl, reltbl); int correct = (retval == 0); retval = grade_pass_two("../test_input/branch3.s", "out/branch3.out", symtbl, reltbl); correct &= (retval == -1); free_table(symtbl); free_table(reltbl); return correct; } int main(int argc, char** argv) { if (argc != 2) { return -1; } switch (atoi(argv[1])) { case 0: return grade_branch_one(); case 1: return grade_branch_two() ? 0 : 1; default: return -1; } }
C
/* * Dati due vettori di medesima dimensione crea un terzo vettore popolandolo in maniera alternata */ #include <stdio.h> #include <time.h> #include <stdlib.h> int alterna(int v1[], int v2[], int v3[], int n); void stampa (int n , int v[]); int main() { srand(time(NULL)); int n =0 ,i = 0,s = 0; printf("Inserisci la dimensione dei vettori\n"); scanf("%d",&n); int v1[n],v2[n],v3[2*n]; for(i=0;i<n;i++) { v1[i]=rand()%100+1; } stampa(n, v1); for(i=0;i<n;i++) { v2[i]=rand()%100+1; } stampa(n, v2); s=alterna(v1,v2,v3,n); stampa(2*n, v3); printf("La somma del terzo vettore e': %d",s); return 0; } int alterna(int v1[], int v2[], int v3[], int n) { int i = 0; int j = 0; int k = 0; int somma = 0; for(i = 0; i < 2*n ; i++) { if(i % 2 == 0) { v3[i] = v1[j]; j++; } else { v3[i] = v2[k]; k++; } somma += v3[i]; } return somma; } void stampa (int n , int v[]) { int i = 0; for(i = 0; i < n ; i++) { printf("%d\t", v[i]); } printf("\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sort_sprites.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: qperrot- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/23 13:32:32 by qperrot- #+# #+# */ /* Updated: 2020/01/23 13:47:59 by qperrot- ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <unistd.h> #include "mlx.h" #include "keys.h" #include "cub3d.h" #define EMPTY 0 #define WALL 1 void ft_dist_sprit_player(data_t *data) { int i; i = 0; while (i < data->numSprites) { data->bufferSprites[i][2] = ((data->posX - data->bufferSprites[i][0]) * (data->posX - data->bufferSprites[i][0])) + ((data->posY - data->bufferSprites[i][1]) * (data->posY - data->bufferSprites[i][1])); i++; } ft_sort_sprites(data); } void ft_take_coord(data_t *data) { int i; int x; int y; x = 0; i = 0; while (x < data->num_of_line) { y = 0; while (y < data->num_of_el) { if (data->map_n[x][y] == 2) { data->bufferSprites[i][0] = x; data->bufferSprites[i][1] = y; data->bufferSprites[i][2] = ((data->posX - x) * (data->posX - x)) + ((data->posY - y) * (data->posY - y)); i++; } y++; } x++; } ft_sort_sprites(data); } // void ft_count_sprites(data_t *data) // { // int x; // int y; // x = 0; // while (x < data->num_of_line) // { // y = 0; // while (y < data->num_of_el) // { // if (data->map_n[x][y] == 2) // data->numSprites++; // y++; // } // x++; // } // } void ft_take_coord_sprites(data_t *data) { int i; ft_count_sprites(data); ft_free_sprite(data); i = 0; if (!(data->bufferSprites = (int**)malloc(sizeof(int*) * (data->numSprites)))) { printf("ERROR\n"); ft_error_exit(data); } while (i < data->numSprites) { if (!(data->bufferSprites[i] = (int*)malloc(sizeof(int) * (3)))) { printf("ERROR\n"); ft_error_exit(data); } i++; } ft_take_coord(data); } void ft_swap_buf(data_t *data, int i, int x) { int tmp[1][3]; tmp[0][0] = data->bufferSprites[i][0]; tmp[0][1] = data->bufferSprites[i][1]; tmp[0][2] = data->bufferSprites[i][2]; data->bufferSprites[i][0] = data->bufferSprites[x][0]; data->bufferSprites[i][1] = data->bufferSprites[x][1]; data->bufferSprites[i][2] = data->bufferSprites[x][2]; data->bufferSprites[x][0] = tmp[0][0]; data->bufferSprites[x][1] = tmp[0][1]; data->bufferSprites[x][2] = tmp[0][2]; } void ft_sort_sprites(data_t *data) { int x; int i; i = data->numSprites - 1; while (i > 0) { x = i - 1; while (x >= 0) { if (data->bufferSprites[i][2] > data->bufferSprites[x][2]) { ft_swap_buf(data, i, x); i = data->numSprites; break ; } else x--; } i--; } }
C
#include <stdio.h> #include <setjmp.h> #include <mz/mz_libs.h> #include <mz/mz_cunit.h> static jmp_buf buf; static int first_enter = 0; static int first_returns = 0; static int sceond_enter = 0; static int sceond_returns = 0; static int static_var = 0; static void second(void) { sceond_enter = 1; longjmp(buf,1); // jumps back to where setjmp was called - making setjmp now return 1 //assert_fail("code after longjump() shall never get ran."); sceond_returns = 1; } static void first(void) { first_enter = 1; second(); printf("code after a function with call to longjump() shall never get ran."); first_returns = 1; } static void test_setjmp(void) { int stack_var = 0; int jret = setjmp(buf); stack_var++; // change to stack var reverted after longjump() static_var++; // change to static var can't reverted by longjump() if (!jret) { mz_cunit_assert_int(MZ_TRUE,1, stack_var); mz_cunit_assert_int(MZ_TRUE,1, static_var); first(); // when executed, setjmp returns 0 printf("code after a function with call another function which call to longjump() shall never get ran."); } else { // when longjmp jumps back, setjmp returns 1 mz_cunit_assert_int(MZ_TRUE,1, stack_var); mz_cunit_assert_int(MZ_TRUE,2, static_var); //assert_true(first_enter); //assert_true(sceond_enter); //assert_false(sceond_returns); } mz_cunit_assert_int(MZ_TRUE,1, jret); } void unit_test_setjmp() { test_setjmp(); }
C
/* #!/usr/bin/perl use Data::Dumper; my $sn = 8; sub getPowerLevel { my $x = shift; my $y = shift; my $rackID = $x + 10; my $pwrlev = $rackID * $y; $pwrlev += $sn; $pwrlev *= $rackID; $pwrlev = substr( $pwrlev, -3, 1 ) - 5; return $pwrlev; } @tests = ( [ 3, 5, 8 ], [ 122, 79, 57 ], [ 217, 196, 39 ], [ 101, 153, 71 ], ); printf( "---- tests -----\n" ); for( my $i = 0 ; $i < 4 ; $i++ ) { my $x = $tests[$i][0]; my $y = $tests[$i][1]; $sn = $tests[$i][2]; printf( "$x,$y [$sn] = %d\n", getPowerLevel( $x, $y ) ); } my $w=300; my $h=300; my @grid; my @scores; $sn = 5034; # build the power levels for( my $y = 0 ; $y <= $h ; $y++ ) { for( my $x = 0 ; $x<= $w ; $x++ ) { $grid[ $x ][ $y ] = getPowerLevel( $x, $y ); } } # dump it out for( my $y = 0 ; $y <= $h ; $y++ ) { printf( "\n ($y) " ); for( my $x = 0 ; $x<= $w ; $x++ ) { printf "% 3d ", $grid[ $x ][ $y ]; } printf( "\n" ); } # figure out 3x3 scores $lrgVal = 0; $lrgX = 0; $lrgY = 0; $lrgSZ = 0; $sz = 3; for( $sz = 1 ; $sz <= 300 ; $sz++ ) { printf( "Trying size=$sz\n" ); for( my $y = 0 ; $y < $h-$sz-1 ; $y++ ) { for( my $x=0 ; $x < $w-$sz-1 ; $x++ ) { $s = 0; for ( my $my ; $my < $sz ; $my++ ) { for ( my $mx ; $mx < $sz ; $mx++ ) { $s += $grid[ $x+$mx ][ $y+$my ]; } } #$scores[$x][$y] = $s; if( $s > $lrgVal ) { $lrgVal = $s; $lrgX = $x; $lrgY = $y; $lrgSZ = $sz; } } } } printf( "Largest score is $lrgVal at $lrgX,$lrgY,$lrgSZ\n" ); */ #include <stdio.h> #include <stdlib.h> int ** grid; void newGrid() { grid = (int **)malloc( sizeof( int* ) * 300 ); for( int i =0 ; i < 301 ; i++ ) { grid[ i ] = (int *)malloc( sizeof( int ) * 300 ); } } void populateGrid( int serno ) { int v=0; int v2; int rackid = 0; for( int x = 0 ; x < 300 ; x++ ) { rackid = x+10; for( int y = 0 ; y < 300 ; y++ ) { v = ((rackid * y)+serno)*rackid; v = v/100 - (10*(v/1000)); v -= 5; grid[x][y] = v; } } } int highestV = -999; int highestX; int highestY; void findHighest( int sz ) { int thisV; int mx, my; for( int x=0 ; x<(300-sz) ; x++ ) { for( int y=0 ; y<(300-sz) ; y++ ) { thisV = 0; for( mx=x ; mx < x+sz ; mx++ ) { for( my=y ; my < y+sz ; my++ ) { thisV += grid[ mx ][ my ]; } } if( thisV > highestV ) { highestV = thisV; highestX = x; highestY = y; printf( "New highest: %d at %d,%d,%d\n", highestV, highestX, highestY, sz ); } } } printf( "Highest found %d at %d,%d,%d\n", highestV, highestX, highestY, sz ); } int main( int argc, char ** argv ) { int serno = 0; int sz = 0; if( argc != 2 ) { printf( "Usage: %s <SerialNo>\n", argv[0] ); exit(-1); } newGrid(); serno = atoi( argv[1] ); printf( "SerialNumber: %d\n", serno ); populateGrid( serno ); for( sz=1; sz<300 ; sz++ ) { findHighest( sz ); } }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_4__ TYPE_1__ ; /* Type definitions */ typedef int /*<<< orphan*/ zdictParams ; struct TYPE_4__ {int notificationLevel; int /*<<< orphan*/ dictID; } ; typedef TYPE_1__ ZDICT_params_t ; typedef int /*<<< orphan*/ U32 ; typedef scalar_t__ BYTE ; /* Variables and functions */ int /*<<< orphan*/ DISPLAY (char*,...) ; size_t MAX (size_t,int) ; int /*<<< orphan*/ RAND_buffer (int /*<<< orphan*/ *,void*,size_t const) ; size_t const ZDICT_CONTENTSIZE_MIN ; size_t ZDICT_DICTSIZE_MIN ; size_t ZDICT_finalizeDictionary (scalar_t__*,size_t,scalar_t__* const,size_t const,scalar_t__* const,size_t*,unsigned int const,TYPE_1__) ; int /*<<< orphan*/ ZDICT_getErrorName (size_t) ; scalar_t__ ZDICT_isError (size_t) ; int /*<<< orphan*/ free (scalar_t__* const) ; scalar_t__* malloc (int) ; int /*<<< orphan*/ memset (TYPE_1__*,int /*<<< orphan*/ ,int) ; __attribute__((used)) static int genRandomDict(U32 dictID, U32 seed, size_t dictSize, BYTE* fullDict) { /* allocate space for samples */ int ret = 0; unsigned const numSamples = 4; size_t sampleSizes[4]; BYTE* const samples = malloc(5000*sizeof(BYTE)); if (samples == NULL) { DISPLAY("Error: could not allocate space for samples\n"); return 1; } /* generate samples */ { unsigned literalValue = 1; unsigned samplesPos = 0; size_t currSize = 1; while (literalValue <= 4) { sampleSizes[literalValue - 1] = currSize; { size_t k; for (k = 0; k < currSize; k++) { *(samples + (samplesPos++)) = (BYTE)literalValue; } } literalValue++; currSize *= 16; } } { size_t dictWriteSize = 0; ZDICT_params_t zdictParams; size_t const headerSize = MAX(dictSize/4, 256); size_t const dictContentSize = dictSize - headerSize; BYTE* const dictContent = fullDict + headerSize; if (dictContentSize < ZDICT_CONTENTSIZE_MIN || dictSize < ZDICT_DICTSIZE_MIN) { DISPLAY("Error: dictionary size is too small\n"); ret = 1; goto exitGenRandomDict; } /* init dictionary params */ memset(&zdictParams, 0, sizeof(zdictParams)); zdictParams.dictID = dictID; zdictParams.notificationLevel = 1; /* fill in dictionary content */ RAND_buffer(&seed, (void*)dictContent, dictContentSize); /* finalize dictionary with random samples */ dictWriteSize = ZDICT_finalizeDictionary(fullDict, dictSize, dictContent, dictContentSize, samples, sampleSizes, numSamples, zdictParams); if (ZDICT_isError(dictWriteSize)) { DISPLAY("Could not finalize dictionary: %s\n", ZDICT_getErrorName(dictWriteSize)); ret = 1; } } exitGenRandomDict: free(samples); return ret; }
C
#include <stdio.h> #include <string.h> #define BUFFERSIZE 100005 int numArr[BUFFERSIZE] = { 0, }; int haveNum[BUFFERSIZE] = { 0, }; int count; int before; void tokenizer(char arr[]) { int i, j, num; char *tempToken; char *context = NULL; char tempArr[BUFFERSIZE] = { NULL, }; char *Word[BUFFERSIZE] = { NULL, }; for (i = 0; i < (signed)strlen(arr); i++) { tempArr[i] = arr[i]; } tempToken = strtok(tempArr, " "); for (i = 0; tempToken != NULL; i++) { Word[i] = tempToken; tempToken = strtok(NULL, " "); } i = i - 1; for (; i >= 0; i--) { num = 0; for (j = 0; j < (signed)strlen(Word[i]); j++) { num = 10 * num + (Word[i][j] - '0'); } numArr[num]++; } } void printNum(int c, int num) { int i = 0; for (; i < c; i++) { printf("%d ", num); numArr[num]--; } } int checkAble(int minNum) { if (numArr[minNum + 1] != 0) { return 1; } else return 2; } int main(void) { int i, j, n, temp, minIndex, check; char arr[BUFFERSIZE]; while (fgets(arr, BUFFERSIZE, stdin) != NULL) { count = 0; for (i = 0; i < BUFFERSIZE; i++) { numArr[i] = 0; haveNum[i] = 0; } arr[strlen(arr) - 1] = '\0'; n = 0; for (j = 0; j < (signed)strlen(arr); j++) { n = 10 * n + (arr[j] - '0'); } fgets(arr, BUFFERSIZE, stdin); arr[strlen(arr) - 1] = '\0'; tokenizer(arr); for (i = 0; i < BUFFERSIZE; i++) { if (numArr[i]) haveNum[count++] = i; } for (i = 0; i < count; i++) { for (j = 1; j < count; j++) { if (haveNum[j] < haveNum[j - 1]) { temp = haveNum[j - 1]; haveNum[j - 1] = haveNum[j]; haveNum[j] = temp; } } } minIndex = 0; before = -10; for (i = 0; i < n; i++) { while (numArr[haveNum[minIndex]] == 0) { minIndex++; } check = checkAble(haveNum[minIndex]); if ((before + 1) == haveNum[minIndex]) { printNum(1, haveNum[minIndex + 1]); before = before + 1; continue; } if (check == 1) { if (haveNum[minIndex + 2] != 0) { printNum(1, haveNum[minIndex]); } else { printNum(1, haveNum[minIndex + 1]); } } else if (check == 2) { printNum(1, haveNum[minIndex]); } before = haveNum[minIndex]; } printf("\n"); } return 0; }
C
#include <stdio.h> #define INF 999999 int min(int a, int b) { return a>b?b:a; } int main() { int d[3][3]={{0,4,11},{6,0,2},{3,INF,0}}; int p[3][3] = {{-1,1,1}, {2,-1,2},{3,-1,-1}}; int n=3; for(int k=0; k<n; k++) { for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { int D=d[i][j]; d[i][j] = min(d[i][j], d[i][k]+d[k][j]); if(D!=d[i][j]) p[i][j] = k+1; } } } printf("Distance matrix:\n"); for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { printf("%d ", d[i][j]); } printf("\n"); } printf("\nPredecessor matrix: \n"); for(int i=0; i<n; i++) { for(int j=0; j<n; j++) { if(p[i][j] ==-1) printf("N "); else printf("%d ", p[i][j]); } printf("\n"); } }
C
#include <stdlib.h> #include <string.h> #include <image.h> #include <source.h> Pixel::Pixel(void) {r = 0; g = 0; b = 0;}; Pixel::Pixel(unsigned char red, unsigned char green, unsigned char blue) { r = red; g = green; b = blue; }; //setter void Pixel::ResetRGB(unsigned char red, unsigned char green, unsigned char blue) { r = red; g = green; b = blue; } //getters unsigned char Pixel::Getr() { return r; } unsigned char Pixel::Getg() { return g; } unsigned char Pixel::Getb() { return b; } //Image constructors Image::Image(void) { maxval = 255; ResetSize(0,0); pixel = NULL; }; Image::Image(Image &im) { width = im.width; height = im.height; maxval = im.maxval; pixel = new Pixel[im.width * im.height]; if (pixel == NULL) { pixel = new Pixel[width * height]; }; } Image::Image(Pixel *p, int w, int h, int max) { width = w; height = h; maxval = max; pixel = new Pixel[width * height]; }; //destructor Image::~Image() { if (pixel != NULL){ delete [] pixel; }; } //setters void Image::ResetSize(int wid, int hei) { width = wid; height = hei; }; void Image::ResetPixel(Pixel *pix) { if (pixel==NULL) { pixel = new Pixel[width * height]; } memcpy(pixel, pix, sizeof(Pixel) * width * height); } void Image::ResetMax(int maxv) { maxval = maxv; } //getters Pixel* Image::GetPix() { return pixel; } int Image::GetWidth() { return width; } int Image::GetHeight() { return height; } int Image::GetMaxval() { return maxval; } void Image::SetSource(Source *s) { sour = s; } void Image::Update() { sour->Update(); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #define N 100 //done typedef struct { int num; char foodname[20]; int money; } caidan; //done typedef struct { int num; char name[20]; char sec[20]; char VIP; } customer; //done typedef struct { char name[20]; long sec; } master; typedef struct { customer ID; int num; caidan food[20]; double all_money; } diandan; int inputnum(); void hello(); void masterhello(); void master_doing(); void anlienhello(); void customerhello1(); void customer_doing(); void customer_doing_net(); void customercreate(); int customerchazhao(customer find); void customer_write(customer inp); caidan searchfood(int a); void caidancreate(); void caidan_write(caidan inp); void caidan_master(); void showcaidan(); void removefood(int q); void customer_manage(); void showcustomer(); void removecustomer(char name1[]); int customervipchazhao(customer find, customer root[]); void customer_doing_diancan(customer inputname); void customer_doing_diancan_add(customer inputname); int searchfod(int a); void food_write(caidan diandan[], int i); void customer_doing_diancan_delete(customer inputname); void customer_doing_diancan_delete_remove(int a); void customer_doing_diancan_view(); void customer_doing1(customer inputname); void customer_doing_jiezhang(customer inputname); void master_doing_incomeview(); int main() { hello(); } //这是第一个欢迎界面,done void hello() { int i; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 欢迎进入bingo餐厅! \n"); printf(" 请问您是什么身份 \n"); printf(" 1 MASTER\n"); printf(" 2 顾客\n"); printf(" 3 外星人\n"); printf(" 0 退出\n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); while (1) { i = inputnum(); switch (i) { case 1: { masterhello(); break; } case 2: { customerhello1(); break; } case 3: { anlienhello(); break; } case 0: { exit(0); } default: { printf("error"); } } } } //这是管理员欢迎界面,done void masterhello() { int i; int flag = 0; master Name[2] = { {"bingoner", 123456}, {"admin", 000000} }; master inputname; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); A: printf(" 尊敬的master,请输入您的账号 \n"); scanf("%s", inputname.name); printf(" 请输入密码 \n"); scanf("%ld", &inputname.sec); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); for (i = 0; i < 2; i++) { if ((inputname.sec == Name[i].sec) && (strcmp(inputname.name, Name[i].name) == 0)) { printf("登陆成功!\n"); master_doing(); break; } else if (i == 1 && ((inputname.sec != Name[i].sec) || (strcmp(inputname.name, Name[i].name) != 0))) { printf("账号密码错误,请重新登陆!\n"); flag++; if (flag == 3) { printf("您已经3次输错"); exit(0); } goto A; } } } //这是管理员执行命令界面 void master_doing() { int i; while (1) { printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 您要执行什么操作 \n"); printf(" 1 查找、浏览和更新用户信息 \n"); printf(" 2 输入、查询、浏览更新菜单信息 \n"); // printf(" 3 外卖统计分析功能 \n"); printf(" 4 收入浏览 \n"); printf(" 0 退出 \n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); i = inputnum(); switch (i) { case 1: { customer_manage(); break; } case 2: { caidan_master(); break; } case 3: { } case 4: { master_doing_incomeview(); break; } case 0: { exit(0); } default: { printf("您输入存在错误!"); } } } } //这是顾客欢迎界面,done void customerhello1() { char a; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf("尊敬的顾客您想来点什么吗?我们有最新的菜品如果想看的话请输入【y】,不想请输入其他字符 \n"); scanf(" %c", &a); if (a == 'y' || a == 'Y') { printf(" 1 佛跳墙\n"); printf(" 2 大肠刺身\n"); printf(" 3 东北大骨\n"); printf(" 4 皇家东坡肉\n"); goto B; } else { B: customer_doing(); } } //这是顾客操作界面 void customer_doing() { static int i = 1; char ch, sh; int sucess, flag = 0; customer inputname; C: printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 您有账户吗:\n"); printf(" 如果没有账户请输入回车创建,如果有请输入y或Y:\n"); sh = getchar(); ch = getchar(); if (ch == '\n') { customercreate(); goto D; } D: printf(" 请输入您的账户名:\n"); scanf("%s", inputname.name); printf(" 请输入您的密码:\n"); scanf("%s", inputname.sec); sucess = customerchazhao(inputname); if (sucess == 1) { customer_doing1(inputname); } else { printf("您输入错误,请重新输入\n"); goto C; } } //这是网上点餐界面 void customer_doing_net() { printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 您好这里是网上点餐服务 \n"); printf(" 请您输入您想要点的菜品 \n"); printf(" 请留下您的电话号码\n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); } //这是数字输入函数,done int inputnum() { int i; scanf("%d", &i); return i; } //这是彩蛋,done void anlienhello() { printf("对不起,暂不提供服务.\n"); exit(0); } //这是账户创建,done void customercreate() { customer inputname; int i, n; char seccheak[20]; customer root[N]; FILE *fp; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].name); fscanf(fp, "%s", root[i].sec); fscanf(fp, "%c", &root[i].VIP); } fclose(fp); n = i; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 您好,欢迎来到账户创建界面 \n"); printf(" 您是我们第%d位创建账户者 \n", n); printf(" 首先请您输入您的账户名 \n"); scanf("%s", inputname.name); printf(" 请您输入您的密码\n"); scanf("%s", inputname.sec); printf(" 请再次输入您的密码 \n"); scanf("%s", seccheak); printf(" 您是否想加入VIP \n"); scanf(" %c", &inputname.VIP); if (strcmp(inputname.sec,seccheak)==0) { printf("创建成功! \n"); inputname.num = i; customer_write(inputname); } else { printf("创建失败! \n"); } printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); } //这是查找登陆账户,done int customerchazhao(customer find) { int flag = 0; customer root[N]; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].name); fscanf(fp, "%s", root[i].sec); fscanf(fp, " %c", &root[i].VIP); } fclose(fp); for (n = 0; n < i - 1; n++) { if ((strcmp(find.name, root[n].name) == 0) && (strcmp(find.sec,root[n].sec))==0) { flag++; return 1; } } if (flag == 0) { return -1; } } //这是录入信息,done void customer_write(customer inp) { FILE *fp; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "a")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } fprintf(fp, "%3d %s %s", inp.num, inp.name, inp.sec); fprintf(fp, " %c", inp.VIP); fprintf(fp, "\n"); fclose(fp); } //这是检索食物价格,done caidan searchfood(int a) { caidan root[N]; caidan guke; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/food.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].foodname); fscanf(fp, "%d", &root[i].money); } fclose(fp); for (n = 0; n < i; n++) { if (a == root[n].num) { guke.num = root[n].num; strcpy(guke.foodname, root[n].foodname); guke.money = root[n].money; return guke; } } } //这是创建菜单,done void caidancreate() { caidan inputname; char ch; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" master您好,欢迎来到菜单创建界面 \n"); printf(" 您可以查看当前菜单,如果查看请输入【y】\n"); scanf(" %c", &ch); if (ch == 'y') { showcaidan(); } printf(" 首先请您输入菜名号: \n"); scanf("%d", &inputname.num); printf(" 请您输入菜名:\n"); scanf("%s", inputname.foodname); printf(" 请输入价格: \n"); scanf("%d", &inputname.money); caidan_write(inputname); printf("创建成功! \n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); caidan_master(); } //这是写菜单,done void caidan_write(caidan inp) { FILE *fp; if ((fp = fopen("/home/bingoner/桌面/homework/food.txt", "a")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } fprintf(fp, "\n%14d%s%14d", inp.num, inp.foodname, inp.money); fclose(fp); } //这是管理菜单界面,done void caidan_master() { int i, n; A:printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 您要执行什么操作 \n"); printf(" 1 输入菜单信息 \n"); printf(" 2 查询菜单信息 \n"); printf(" 3 更新菜单信息 \n"); printf(" 0 退出 \n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); i = inputnum(); switch (i) { case 1: { caidancreate(); break; } case 2: { showcaidan(); caidan_master(); break; } case 3: { printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 请输入您要删除的菜品号 \n"); n = inputnum(); removefood(n); caidan_master(); break; } case 0: { master_doing(); } default: { printf("error"); goto A; } } } //这是展示菜单,done void showcaidan() { caidan root[N]; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/food.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].foodname); fscanf(fp, "%d", &root[i].money); } printf("菜号 菜名 单价\n"); for (n = 0; n < i; n++) { printf("%d %s%14d", root[n].num, root[n].foodname, root[n].money); printf("\n"); } fclose(fp); } //这是删除菜品,仅限管理,done void removefood(int q) { int i, f = -1; int num; caidan root[N]; FILE *fp, *fn; if ((fp = fopen("/home/bingoner/桌面/homework/food.txt", "r")) == NULL) { printf("can not open file\n"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].foodname); fscanf(fp, "%d", &root[i].money); } fclose(fp); for (num = 0; num < i; num++) { if (q == root[num].num) { if (num < i - 1) { for (f = num; f < i; f++) { root[num].num = root[num + 1].num; strcpy(root[num].foodname, root[num + 1].foodname); root[num].money = root[num + 1].money; } } if ((fn = fopen("/home/bingoner/桌面/homework/food.txt", "w")) == NULL) { printf("文件打不开!\n"); printf("\npress enter to return menu\n"); exit(0); } for (num = 0; num < i - 1; num++) { fprintf(fn, "\n%14d%s%14d", root[num].num, root[num].foodname, root[num].money); } fclose(fn); printf("\n删除成功!\n"); printf("\npress enter to return menu\n"); getchar(); getchar(); caidan_master(); } } if (f < 0) { printf("\n您所查找的信息不存在!\n"); printf("\npress enter to return menu\n"); getchar(); getchar(); caidan_master(); } } //这部分管理用户信息,done void customer_manage() { int i, n; char name1[20]; A:printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 您要执行什么操作 \n"); printf(" 1 添加用户信息 \n"); printf(" 2 查询用户信息 \n"); printf(" 3 更新用户信息 \n"); printf(" 0 退出 \n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); i = inputnum(); switch (i) { case 1: { customercreate(); customer_manage(); break; } case 2: { showcustomer(); customer_manage(); break; } case 3: { printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 请输入您要删除的用户名 \n"); scanf("%s", name1); removecustomer(name1); customer_manage(); break; } case 0: { master_doing(); break; } default: { printf("error"); goto A; } } } //这部分显示customer信息,done void showcustomer() { customer root[N]; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].name); fscanf(fp, "%s", root[i].sec); fscanf(fp, " %c", &root[i].VIP); } printf("单号 用户名 密码 VIP\n"); for (n = 0; n < i - 1; n++) { printf("%d\t\t%s\t\t%s\t\t", root[n].num, root[n].name, root[n].sec); printf(" %c", root[n].VIP); printf("\n"); } fclose(fp); } //这部分移除用户信息,done void removecustomer(char name1[]) { int i, f = -1; int num; customer root[N]; FILE *fp, *fn; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "r")) == NULL) { printf("can not open file\n"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%3d", &root[i].num); fscanf(fp, "%s", root[i].name); fscanf(fp, "%s", root[i].sec); fscanf(fp, " %c", &root[i].VIP); } fclose(fp); for (num = 0; num < i; num++) { if (strcmp(name1, root[num].name) == 0) { if (num < i - 1) { for (f = num; f < i; f++) { root[f].num = root[f + 1].num; strcpy(root[f].name, root[f + 1].name); strcpy(root[f].sec,root[f + 1].sec); root[f].VIP = root[f + 1].VIP; } } if ((fn = fopen("/home/bingoner/桌面/homework/customer.txt", "w")) == NULL) { printf("文件打不开!\n"); printf("\npress enter to return menu\n"); exit(0); } for (num = 0; num < i - 2; num++) { fprintf(fn, "%3d %s %s %c\n", root[num].num, root[num].name, root[num].sec, root[num].VIP); } fclose(fn); printf("\n删除成功!\n"); printf("\npress enter to return menu\n"); getchar(); getchar(); customer_manage(); } } if (f < 0) { printf("\n您所查找的信息不存在!\n"); printf("\npress enter to return menu\n"); getchar(); getchar(); customer_manage(); } } int customervipchazhao(customer find, customer root[]) { int flag = 0; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%3d", &root[i].num); fscanf(fp, "%s", root[i].name); fscanf(fp, "%s", root[i].sec); fscanf(fp, " %c", &root[i].VIP); } fclose(fp); for (n = 0; n < i; i++) { if (find.VIP == root[n].VIP) { flag++; return 0.8; } } if (flag == 0) { return 1; } } void customer_doing_diancan(customer inputname) { int i; A: printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 顾客您好,现在请选择您要进行的操作 \n"); printf(" 1 查看菜单 \n"); printf(" 2 点餐 \n"); printf(" 3 减餐 \n"); printf(" 4 查看点菜 \n"); printf(" 0 退出 \n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); i = inputnum(); switch (i) { case 1: { showcaidan(); goto A; break; } case 2: { customer_doing_diancan_add(inputname); break; } case 3: { customer_doing_diancan_delete(inputname); break; } case 4: { customer_doing_diancan_view(); goto A; break; } case 0: { customer_doing1(inputname); break; } default: { printf("error"); goto A; } } } void customer_doing_diancan_add(customer inputname) { caidan diandan[N]; int i = 0, a; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); A: printf(" 顾客您好,现在请选择您要点的菜,输入菜单号输入0结束 \n"); a = inputnum(); if (a != 0) { if (searchfod(a) == 1) { diandan[i] = searchfood(a); i++; goto A; } else if (searchfod(a) == 0) { printf("点餐失败!"); goto A; } } else if (a == 0) { printf("点餐完成!"); food_write(diandan, i); customer_doing_diancan(inputname); } } int searchfod(int a) { caidan root[N]; int flag = 0; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/food.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].foodname); fscanf(fp, "%d", &root[i].money); } fclose(fp); for (n = 0; n < i; n++) { if (a == root[n].num) { return 1; } } if (flag == 0) { return 0; } } void food_write(caidan diandan[], int i) { FILE *fp; int n; if ((fp = fopen("/home/bingoner/桌面/homework/moneyedit.txt", "a")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (n = 0; n < i; n++) { fprintf(fp, "%3d%s %5d", diandan[n].num, diandan[n].foodname, diandan[n].money); fprintf(fp, "\n"); } fclose(fp); } void customer_doing_diancan_delete(customer inputname) { caidan diandan[N]; int i = 0, a; printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); A: printf(" 顾客您好,现在请选择您要删除的菜,输入菜单号输入0结束 \n"); a = inputnum(); if (a != 0) { if (searchfod(a) == 1) { customer_doing_diancan_delete_remove(a); goto A; } else if (searchfod(a) == 0) { printf("减餐失败!"); goto A; } } else if (a == 0) { printf("减餐完成!"); customer_doing_diancan(inputname); } } void customer_doing_diancan_delete_remove(int a) { int i, f = -1,k; int num; caidan root[N]; FILE *fp, *fn; if ((fp = fopen("/home/bingoner/桌面/homework/moneyedit.txt", "r")) == NULL) { printf("can not open file\n"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].foodname); fscanf(fp, "%d", &root[i].money); } fclose(fp); for (num = 0; num < i; num++) { if (a == root[num].num) { if (num < i - 1) { for (f = num; f < i-1; f++) { root[f].num = root[f + 1].num; strcpy(root[f].foodname, root[f + 1].foodname); root[f].money = root[f + 1].money; } } if ((fn = fopen("/home/bingoner/桌面/homework/moneyedit.txt", "w")) == NULL) { printf("文件打不开!\n"); printf("\npress enter to return menu\n"); exit(0); } for (k = 0; k < i - 2; k++) { fprintf(fn, "%3d%s %5d\n", root[k].num, root[k].foodname, root[k].money); } fclose(fn); printf("\n删除成功!\n"); break; } } } void customer_doing_diancan_view() { caidan root[N]; FILE *fp; int i, n; if ((fp = fopen("/home/bingoner/桌面/homework/moneyedit.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].num); fscanf(fp, "%s", root[i].foodname); fscanf(fp, "%d", &root[i].money); } printf("菜号 菜名 单价\n"); for (n = 0; n < i - 1; n++) { printf("%d %s%14d", root[n].num, root[n].foodname, root[n].money); printf("\n"); } fclose(fp); } void customer_doing1(customer inputname) { int i; A:printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf(" 顾客您好,现在请选择您要进行的操作 \n"); printf(" 1 点餐 \n"); // printf(" 2 外卖订购 \n"); printf(" 3 结帐 \n"); printf(" 0 退出 \n"); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); i = inputnum(); switch (i) { case 1: { customer_doing_diancan(inputname); break; } case 2: { customer_doing_net(); break; } case 3: { customer_doing_jiezhang(inputname); break; } case 0: { exit(0); } default: { printf("error"); goto A; } } } void customer_doing_jiezhang(customer inputname) { diandan cus; caidan jiezhang[N]; customer root[N]; int flag = 0; char ch; FILE *fp,*fn,*fm; int i, n, p,k; double all_money = 0; if ((fp = fopen("/home/bingoner/桌面/homework/customer.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%3d", &root[i].num); fscanf(fp, "%s", root[i].name); fscanf(fp, "%s", root[i].sec); fscanf(fp, " %c", &root[i].VIP); } fclose(fp); for (n = 0; n < i; n++) { if (strcmp(inputname.name, root[n].name) == 0) { inputname.num = root[n].num; strcpy(inputname.name,root[n].name); inputname.VIP = root[n].VIP; if ((fn = fopen("/home/bingoner/桌面/homework/moneyedit.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fn); i++) { fscanf(fp, "%d", &jiezhang[i].num); fscanf(fp, "%s", jiezhang[i].foodname); fscanf(fp, "%d", &jiezhang[i].money); } for (p = 0;p<i;p++) { all_money += jiezhang[p].money; } fclose(fn); if ((inputname.VIP == 'y')||(inputname.VIP == 'Y')) { all_money = all_money*0.8; printf("您是我们的VIP客户,本次共消费%lf元.",all_money); break; } else if((inputname.VIP == 'n')||(inputname.VIP == 'N')) { printf("您本次共消费%lf元.",all_money); break; } } } if ((fm = fopen("/home/bingoner/桌面/homework/kehumingxi.txt", "a")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } cus.ID.num = inputname.num; strcpy(cus.ID.name,inputname.name); cus.ID.VIP = inputname.VIP; cus.num = i; for (k = 0;k<i;k++) { cus.food[k].num = jiezhang[k].num; strcpy(cus.food[k].foodname,jiezhang[k].foodname); cus.food[k].money = jiezhang[k].money; } cus.all_money = all_money; fprintf(fm,"%3d %s %c\n",cus.ID.num,cus.ID.name,cus.ID.VIP); fprintf(fm,"%d\n",cus.num); for (k = 0;k<i-1;k++) { fprintf(fm,"%3d %s %d\n",cus.food[k].num,cus.food[k].foodname,cus.food[k].money); } fprintf(fm,"%.2lf\n",cus.all_money); fclose(fm); if ((fn = fopen("/home/bingoner/桌面/homework/moneyedit.txt", "w")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } fclose(fn); printf("请按任意键结束..........."); ch = getchar(); exit(0); } void master_doing_incomeview() { diandan root[N]; FILE *fp; int i, n,k,p; if ((fp = fopen("/home/bingoner/桌面/homework/kehumingxi.txt", "r")) == NULL) { printf("FAILURE OPEN FILE!"); exit(0); } for (i = 0; !feof(fp); i++) { fscanf(fp, "%d", &root[i].ID.num); fscanf(fp, "%s", root[i].ID.name); fscanf(fp, " %c", &root[i].ID.VIP); fscanf(fp,"%d",&root[i].num); for (k = 0;k<root[i].num-1;k++) { fscanf(fp,"%d",&root[i].food[k].num); fscanf(fp,"%s",root[i].food[k].foodname); fscanf(fp,"%d",&root[i].food[k].money); } fscanf(fp,"%lf",&root[i].all_money); } for (p = 0;p<i-1;p++) { printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf("num 顾客名 是否VIP\n"); printf("%3d %s %c\n",root[p].ID.num,root[p].ID.name,root[p].ID.VIP); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf("编号 菜名 价格\n"); for (n = 0; n < root[p].num; n++) { printf("%d %s%14d", root[p].food[n].num, root[p].food[n].foodname, root[p].food[n].money); printf("\n"); } printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf("总价为\n"); printf("%lf\n",root[p].all_money); printf("+++++++++++++++++++++++++++++++++++++++++++++++++++++ \n"); printf("\n"); } fclose(fp); }
C
#include "display.h" //printf override static FILE display_stdout_override = FDEV_SETUP_STREAM(display_write_char,NULL,_FDEV_SETUP_WRITE); void display_setup() { display_mode_instruction(); spi_send_display(FUNCTION_SET); _delay_ms(2); spi_send_display(BIAS_SET); _delay_ms(2); spi_send_display(POWER_CONTROL); _delay_ms(2); spi_send_display(FOLLOWER_CONTROL); _delay_ms(2); spi_send_display(CONTRAST_SET); _delay_ms(2); spi_send_display(FUNCTION_SET2); _delay_ms(2); spi_send_display(DISPLAY_ON_OFF); _delay_ms(2); spi_send_display(CLEAR_DISPLAY); _delay_ms(2); spi_send_display(ENTRY_MODE_SET); _delay_ms(2); spi_send_display(DISABLE_CURSOR); _delay_ms(2); display_mode_write(); stdout = &display_stdout_override; } void display_mode_instruction() { PORTB &=~ (1<<PINB1); } void display_mode_write() { PORTB |= (1<<PINB1); } void display_set_stdout(){ stdout = &display_stdout_override; } void spi_send_display(uint8_t message) { PORTB &=~ (1<<PINB2); SPDR = message; while((SPSR & (1<<SPIF)) == 0); PORTB |= (1<<PINB2); } int display_write_char(char c, FILE *stream) { spi_send_display(c); _delay_us(30); return 0; } void display_set_cursor_pos(uint8_t pos){ display_mode_instruction(); spi_send_display(0x80|pos); display_mode_write(); _delay_us(30); } void display_clear(){ display_mode_instruction(); spi_send_display(0b00000001); display_mode_write(); _delay_ms(2); } void display_clear_line(uint8_t line){ display_set_cursor_pos(line<<4); for(uint8_t i = 0; i < 16; i++){display_write_char(' ', NULL);} } void display_clear_top_rows(){ display_set_cursor_pos(0); for(uint8_t i = 0; i < 32; i++){display_write_char(' ', NULL);} display_set_cursor_pos(0); } void display_turnoff(){ PORTB &= 0b11111001; spi_send_display(0b00001000); _delay_us(30); } void display_set_character_pgm(uint8_t char_code, const uint8_t rows[8]){ for (uint8_t i = 0; i < 8; i++){ //Set CGRAM address display_mode_instruction(); spi_send_display(0x40|(char_code<<3)|(i)); _delay_us(30); //Write row to character display_mode_write(); spi_send_display(pgm_read_byte(&(rows[i]))); _delay_us(30); } }
C
#include <stdio.h> #include <stdlib.h> struct my { int a; struct my *next; }; struct my *p = NULL; void put(const struct my *my_p) { printf("Put element: 0x%x\n", my_p); if (p == NULL){ printf("Empty list\n"); p = my_p; return; } struct my *cur = p; while (1){ printf("cur: 0x%x\n", cur); printf("cur->next: 0x%x\n", cur->next); if (cur->next == NULL) break; cur = cur->next; } cur->next = my_p; printf("set cur->next: 0x%x\n", cur->next); } struct my *get(int a) { if (p == NULL){ printf("There are no elements\n"); return NULL; } struct my *cur = p; while (1){ printf("Current element: %d\n", cur->a); if (cur->a == a){ return cur; } printf("Next: 0x%x\n", cur->next); if (cur->next != NULL) cur = cur->next; else return NULL; } } int main(int argc, char** argv) { struct my *my_p; for (int i = 0; i < 10; i++){ my_p = (struct my *)malloc(sizeof(struct my)); my_p->a = i; put(my_p); } struct my *s = get(5); printf("s: %d\n", s->a); return 0; }
C
#include<stdio.h> main(){ char str[10][20]; int i; for(i = 0; i < 10; i++){ str[i][0] = '\0'; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <conio.h> #include <ctype.h> #include "input.h" void menu() { printf("1- Agregar Numero\n"); printf("2- Modificar Numero\n"); printf("3- Borrar Numero\n"); printf("4- Calcular campos Par/Impar/Primo\n"); printf("5- Informar\n\n"); printf("6- Salir\n\n"); } int validaNumero(char numero[]) { int i; for (i=0; i<strlen(numero); i++) { if(!isdigit(numero[i])) { printf("Ingrese SOLO numeros.\n"); return 0; } } return 1; } int validaFloat(char numero[]) { int i; for (i=0; i<strlen(numero); i++) { if(!isdigit(numero[i])) { if (numero[i] != '.') { printf("Ingrese SOLO numeros.\n"); return 0; } } } return 1; } int validaLetra(char caracter[]) { int i; for (i=0; i<strlen(caracter); i++) { //if(!isalpha(caracter[i])) if(!((caracter[i]>=65 && caracter[i]<=90) || (caracter[i]>=97 && caracter[i]<=122) || (caracter[i] != "/n"))) { printf("Ingrese SOLO letras.\n"); return 0; } } return 1; } int getInt(int* input,char message[],char eMessage[], int lowLimit, int hiLimit) { char auxNum[30]; int aux, numValidado; printf("%s", message); do{ fflush(stdin); scanf("%s", auxNum); numValidado = validaNumero(auxNum); } while(numValidado == 0); aux = atoi(auxNum); if (aux < lowLimit || aux > hiLimit){ printf("%s\n", eMessage); return -1; } else{ *input = aux; return 0; } } int getFloat(float* input,char message[],char eMessage[], float lowLimit, float hiLimit) { char auxNum[30]; float aux; int numValidado; printf("%s", message); do{ fflush(stdin); scanf("%s", auxNum); numValidado = validaFloat(auxNum); } while(numValidado == 0); aux = atof(auxNum); if (aux < lowLimit || aux > hiLimit){ printf("%s\n", eMessage); return -1; } else{ *input = aux; return 0; } } /*int getChar(char* input,char message[],char eMessage[], char lowLimit, char hiLimit) { //......... //......... //......... //......... return 0; }*/ int getString(char* input,char message[],char eMessage[], int lowLimit, int hiLimit) { char aux[hiLimit]; char auxLet[30]; int letraValidada; printf("%s", message); do{ fflush(stdin); scanf("%[^\n]", auxLet); letraValidada = validaLetra(auxLet); } while(letraValidada == 0); strcpy(aux, auxLet); if (strlen(aux) < lowLimit || strlen(aux) > hiLimit){ printf("%s\n", eMessage); return -1; } else{ strcpy(input, aux); return 0; } }