language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/* * Michael Weir, Owen Dunn, Anthony Nguyen * Programming Project 1: Reliable File Transfer over UDP * Cis 457 * Fall 2018 * * Client: * When started, the client asks for the IP address and a port number. * If valid data is given, the client will then use this information * to send data. he client then prompts the user for a file name to * request from the server (or file path). If the file is found in the * server it will be sent to the client over several packets with data * size of 1024 bytes each. * * Run: ./exename portnumber ipaddress filename */ #include <sys/socket.h> #include <netinet/in.h> #include <stdio.h> #include <string.h> #include <unistd.h> #include <arpa/inet.h> #include <stdlib.h> #include <math.h> #include <limits.h> #include "project1.h" // implementation in .h file int main(int argc, char** argv){ int portnumber, n; char ipaddr[100]; char line[1024]; char packet[PACKET_DATA_SIZE+H_SIZE]; FILE *outfile; printf("--------------UDP file transfer client--------------\n"); printf("Files are created in the current directory.\n"); printf("Files must be in the current directory of the server.\n"); printf("Run: ./exename portnumber ipaddress filename\n"); // Allow command line input. (save time testing) if (argc == 4) { // Read the port number. portnumber = atoi(argv[1]); if (!isValidPort(portnumber)) { printf("Invalid port number.\n"); return -1; } printf("Using port: %d\n", portnumber); // Read the ip address. strcpy(ipaddr, argv[2]); // error test for ipaddr if ( !isValidIpAddress(ipaddr) ) { printf("Invalid ipv4 address.\n"); return -1; } printf("Using ip address: %s\n", ipaddr); // Read the file name. strcpy(line, argv[3]); // add error test for filename? printf("Asking for file: %s\n", line); } else { printf("Invalid command line input.\n"); printf("Run: ./exename portnumber ipaddress filename\n"); return -1; } int sockfd = socket(AF_INET, SOCK_DGRAM, 0); // using UDP if(sockfd < 0) { printf("Error creating socket\n"); return -1; } struct timeval timeout; timeout.tv_sec = 1; // seconds timeout.tv_usec = 20; // micro sec //set options sockfd, option1, option2 setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)); struct sockaddr_in serveraddr; serveraddr.sin_family = AF_INET; serveraddr.sin_port = htons(portnumber); serveraddr.sin_addr.s_addr = inet_addr(ipaddr); // Request the file. // TODO Resend request until confirmed. int fileRequestDone = 0; socklen_t len = sizeof(serveraddr); int /*bytesRead,*/ fileSize; char filehdr[1]; while (!fileRequestDone) { n = sendto(sockfd, line, strlen(line)+1, 0, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); if (n == -1) { printf("Error: file name not sent to server.\n"); } else { // get the file size from the server // TODO Try until get this value. n = recvfrom(sockfd, packet, PACKET_DATA_SIZE+H_SIZE, 0, (struct sockaddr*)&serveraddr, &len); if(n == -1) { printf("Did not receive file size in time. Retrying.\n"); } else { fileSize = atoi(packet); if (fileSize > 0 && fileSize < INT_MAX) { filehdr[0] = 'a'; printf("Sending ack for file data.\n"); n = sendto(sockfd, &filehdr[0], 1, 0, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); printf("File data attempted ACK sent: n = %d, data[0] = %u\n", n, filehdr[0]); if (n == -1) { printf("File data ACK for packet %u not sent.\n", filehdr[0]); } else { printf("ACK for packet %u sent.\n", filehdr[0]); fileRequestDone = 1; } } } } } printf("File request accepted and file size received.\n"); clearBuffer(line); printf("File size to write: %d bytes\n", fileSize); clearBuffer(packet); int totalPackets = (int)ceil((double)fileSize / PACKET_DATA_SIZE); printf("Client will receive %d packets of data.\n", totalPackets); int transferComplete; //int sizeReceived; //ssize_t msgSize; // how to print value? int i; int packetsWritten = 0; // keep going until all packets written swpState swp; swp.LFR = 0; swp.LAF = WINDOW_SIZE; swp.NFE = 1; u_int8_t sendAck = 0, ackNum = 0; //uint8_t client_seqnum = 1; // use seqnum from server packets only? uint8_t freeQSlot = 0; int inQ = 0; // if packet already in the Q char hdr[H_SIZE+1]; // Collect packets from the server until the full file is received. outfile = fopen("sentFile", "w"); // account for all file types while( !transferComplete ) { // until all data received n = recvfrom(sockfd, packet, PACKET_DATA_SIZE+H_SIZE, 0, (struct sockaddr*)&serveraddr, &len); if(n==-1) { printf("Error: didn't receive a packet in time.\n"); continue; } printf("Header value: %u\n", (uint8_t)packet[0]); //TEST printf("n = %d\n", n); //test // See if can accept a packet. if ( n > 0 && (swp.LAF - swp.LFR <= WINDOW_SIZE) ) { printf("LFR: %u, LAF: %u, NFE: %u\n", swp.LFR, swp.LAF, swp.NFE); if ( packet[0] <= swp.LFR || packet[0] > swp.LAF ) { printf("Packet %u outside of frame. Not accepted.\n", (uint8_t)packet[0]); if((uint8_t)packet[0] <= (uint8_t)swp.LFR) { sendAck = 1; ackNum = packet[0]; } } else { // packet is within the window // First check if it's the NFE. Append data to file if so. // Don't add to Q if so, as not needed later. if(packet[0] == swp.NFE) { // next frame in sequence? outfile = fopen("sentFile", "a"); fwrite(&packet[1], 1, n - H_SIZE, outfile); // needed for binary //printf("Received a packet: %d.\n", strlen(packet)+1); fclose(outfile); packetsWritten++; printf("Appended packet %u to file.\n", packet[0]); swp.NFE++; swp.LFR = (uint8_t)packet[0]; swp.LAF = (uint8_t)swp.LFR + WINDOW_SIZE; // Send the ACK. A packet with only the seqnum character. sendAck = 1; ackNum = packet[0]; clearBuffer(packet); } else { // Check if packet already in Q. for(i=0; i<WINDOW_SIZE; ++i) { if(swp.recvQ[i].isValid) { if(packet[0] == swp.recvQ[i].hdr.SeqNum) { inQ = 1; break; } } } if(inQ) { printf("Repeated packet %u discarded.\n", (uint8_t)packet[0]); } else { // add data to Q swp.recvQ[freeQSlot].hdr.SeqNum = (uint8_t)packet[0]; swp.recvQ[freeQSlot].isValid = 1; printf("Packet %u in window but out of sequence. Added to queue.\n", (uint8_t)packet[0]); freeQSlot = (freeQSlot + 1) % WINDOW_SIZE; } // Check if have lowest packet to append to file. for(i=0; i<WINDOW_SIZE; ++i) { if(swp.recvQ[i].isValid && !swp.recvQ[i].wasWritten) { if(swp.NFE == swp.recvQ[i].hdr.SeqNum) { outfile = fopen("sentFile", "a"); fwrite(&packet[1], 1, sizeof(packet) - 1, outfile); fclose(outfile); packetsWritten++; swp.recvQ[i].wasWritten = 1; printf("Wrote packet %u from the Q.\n", swp.NFE); // Send the ACK. A packet with only the seqnum character. sendAck = 1; ackNum = swp.NFE; swp.NFE++; // Source of failed error checking in demo??? (wasn't here) break; } } } } if (sendAck) { hdr[0] = ackNum; //hdr[1] = '\0'; printf("Sending ack %u.\n", hdr[0]); n = sendto(sockfd, &hdr[0], 1, 0, (struct sockaddr*)&serveraddr, sizeof(serveraddr)); printf("ACK send: n = %d, data[0] = %u\n", n, hdr[0]); if (n == -1) { printf("ACK for packet %u not sent.\n", hdr[0]); } else { printf("ACK for packet %u sent.\n", hdr[0]); } } } // Check if file write is complete. if ( packetsWritten == totalPackets ) { // TODO, leave until swp done transferComplete = 1; } inQ = 0; sendAck = 0; } } printf("Successfully downloaded a file from server.\n"); printf("Closing client.\n"); close(sockfd); return 0; }
C
#include <fcntl.h> #include <unistd.h> #include <stdlib.h> #define BUFSIZ 1024 int copy(int dst_fd, int src_fd); int main(int argc, char *argv[]) { int fd, result; if(argc == 1) { result = copy(STDOUT_FILENO, STDIN_FILENO); if(result < 0) { return result; } return 0; } while(--argc) { fd = open(*++argv, O_RDONLY); result = copy(STDOUT_FILENO, fd); if(result < 0) { return result; } result = close(fd); if(result < 0) { return result; } } } int copy(int dst_fd, int src_fd) { int n; char buf[BUFSIZ]; while((n = read(src_fd, buf, BUFSIZ)) > 0) write(dst_fd, buf, n); if(n < 0) { return n; } return 0; }
C
//TO CHECK WHETHER THE GIVEN NUMBER IS PRIME OR NOT. #include<stdio.h> void main() { int n,j,count=0; printf("enter the number : "); scanf("%d",&n); for(j=2;j<=n/2;j++) { if(n%j==0) { count=1; break; } } if(count==0) { printf("given number is a prime "); } else { printf("given number is not a prime"); } }
C
#include <stdio.h> #include <time.h> #include "rs232/rs232.h" #include "parser.h" #include "printer.h" #include "string.h" int parser_port = -1; int get_port_name() { clear_screen(); printf("Please enter the name of the serial port you want to use!\n"); char port_name[PORT_NAME_MAX_LEN]; fgets(port_name, PORT_NAME_MAX_LEN - 1, stdin); // Remove \r and \n characters for (int i = 0; i < PORT_NAME_MAX_LEN; i++) { if (port_name[i] == '\r' || port_name[i] == '\n') port_name[i] = '\0'; } // Find the index of that port parser_port = comFindPort(port_name); if (parser_port < 0) { printf("%s not exists!\n", port_name); return -1; } else { printf("%s port exists, saved.\n", port_name); } return 0; } int open_port() { clear_screen(); if (parser_port < 0) { printf("Port not set!\n"); return -1; } comClose(parser_port); if(!comOpen(parser_port, BAUD_RATE)) { printf("Port can not be opened. Try to set the port again!\n"); return -1; } else { printf("Port opened successfully!\n"); return 0; } } int close_port() { clear_screen(); if (parser_port < 0) { printf("Port not set!\n"); return -1; } comClose(parser_port); printf("Port closed.\n"); return 0; } int get_line_from_port(char *buff, int buff_len) { if (parser_port < 0) { printf("Port not set!\n"); return -1; } // Put data into the char ch; int i = 0; int bytes = comRead(parser_port, &ch, 1); // If there is no data on the port, exit if (bytes <= 0) { return 0; } // This loop will read until a \n character. If the buffer is too small, then // the characters will be discarded after the size limit is reached. while (ch != '\n') { // Check if there is enough space in the buffer if (i < (buff_len - 1)) { // Check if we are not near the end of the line (cr character) if (ch != '\r') { buff[i] = ch; i++; } } while (comRead(parser_port, &ch, 1) == 0); } // Put terminating zero at the end buff[i] = '\0'; return i; } int log_data() { // Check if port set up properly if (parser_port < 0) { printf("Port not set!\n"); return -1; } FILE * file; file= fopen("log.txt", "a"); // Get a line of data from the port // If there is no data on the port, then do nothing char buff[PORT_BUFFER_LEN]; if (get_line_from_port(buff, PORT_BUFFER_LEN) > 0) { // Put the data into the logfile //Printing thebuffer fprintf(file, "%s\n", buff); printf("%s\n",buff); } fclose(file); return 0; } void after_error() { FILE * file; file= fopen("log.txt", "r"); char printLine[100]; char* date; char* time; char* temperature; char* year; char* month; char* day; char* hour; char* min; char* sec; clear_screen(); printf(" Log file\n"); printf("==============================\n\n"); while(fgets(printLine, 100, file) != NULL) { date = strtok(printLine, " "); time = strtok(NULL, " "); temperature = strtok(NULL, " "); //Date tokens year = strtok(date, "."); month = strtok(NULL, "."); day = strtok(NULL, "."); //Time tokens hour = strtok(time, ":"); min = strtok(NULL, ":"); sec = strtok(NULL, ":"); int stringCount = 0; //Check temperature for (int i = 0; i < strlen(temperature) - 1; i++) { if(isdigit(temperature[i]) == 0) { stringCount++; } } //Test code for date filter if(strlen(year) <= 4 && atoi(year) <= 2018) { if(strlen(month) <= 2 && month[0] != '-' && atoi(month) <= 12) { if(strlen(day) <= 2 && day[0] != '-' && atoi(day) <= 31 && atoi(day) != 0) { if((stringCount == 0) || (temperature[0] == '-')) { if(hour[0] != '-' && atoi(hour) <= 23 && atoi(hour) != 0) { if(min[0] != '-' && atoi(min) <= 59 && atoi(min) != 0) { if(sec[0] != '-' && atoi(sec) <= 59 && atoi(sec) != 0) { printf("%s.%s.%s\t%s:%s:%s\t%s", year, month, day, hour, min, sec, temperature); } } } } } } } } fclose(file); } void averageByDay() { clear_screen(); FILE * file; file= fopen("log.txt", "r"); }
C
#include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { int fd = -1; // fd 就是file descriptor,文件描述符 char buf[100] = {0}; char writebuf[20] = "abcd"; int ret = -1; // 第一步:打开文件 fd = open("123.txt", O_RDWR | O_CREAT); //fd = open("a.txt", O_RDONLY); if (-1 == fd) // 有时候也写成: (fd < 0) { //printf("\n"); perror("文件打开错误"); // return -1; _exit(-1); } else { printf("文件打开成功,fd = %d.\n", fd); } ret = lseek(fd, 10, SEEK_SET); printf("lseek, ret = %d.\n", ret); #if 1 // 第二步:读写文件 // 写文件 ret = write(fd, writebuf, strlen(writebuf)); if (ret < 0) { //printf("write失败.\n"); perror("write失败"); _exit(-1); } else { printf("write成功,写入了%d个字符\n", ret); } #endif #if 1 // 读文件 ret = read(fd, buf, 20); if (ret < 0) { printf("read失败\n"); _exit(-1); } else { printf("实际读取了%d字节.\n", ret); printf("文件内容是:[%s].\n", buf); } #endif // 第三步:关闭文件 close(fd); _exit(0); }
C
#include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> int main(void) { int fd[2]; int nbytes; pid_t cpid; char base[] = "This is the base string.\n"; char extra[] = "This string should be appended to the base and returned to the parent.\n"; char buf[128]; pipe(fd); if ((cpid = fork()) == -1) { perror("fork"); return 1; } if (cpid > 0) { // Parent process closes 'read' side of pipe //close(fd[0]); // Send base string through 'write' side of pipe write(fd[1], base, (strlen(base)+1)); // Wait for child to finish wait(NULL); close(fd[1]); //TODO Read the final string back from the child process, and print it' read(fd[0], buf, strlen(base)+strlen(extra)+1); printf("Concatenated String: %s\n", buf); close(fd[0]); } else { // Child process closes the 'write' side of the pipe //close(fd[1]); // Read bytes from 'read' side of pipe read(fd[0], buf, sizeof(buf)); printf("Received string: %s", buf); close(fd[0]); //TODO Append the 'extra' string to the base string, and send the result // back to the parent process using pipes. strcat(buf, extra); close(fd[0]); write(fd[1], buf, strlen(buf)+1); close(fd[1]); } return 0; }
C
// // test_can_bus.c // CCanOpenStack // // Created by Timo Jääskeläinen on 20.10.2013. // Copyright (c) 2013 Timo Jääskeläinen. All rights reserved. // #include "test_can_bus.h" #include "can_bus.h" #include "log.h" #include "test_util.h" /****************************** Local Variables ******************************/ static uint16_t next_id = 0; static uint8_t next_len = 0; static uint8_t next_data[8]; static int error = 0; static uint8_t test_running = 0; /****************************** Local Prototypes *****************************/ static void send_message(uint16_t id, uint8_t len, uint32_t data); static void test_message_received_handler1(can_message *message); static void test_message_received_handler2(can_message *message); static void check_received_message(can_message *message, int handler_num); /****************************** Global Functions *****************************/ extern int test_can_bus_run(void) { test_running = 1; error |= can_bus_register_message_received_handler(test_message_received_handler1); error |= can_bus_register_message_received_handler(test_message_received_handler2); send_message(0x123, 4, 0x12345); send_message(0x456, 6, 0x98765); send_message(0x789, 8, 0x23452); send_message(0x123, 2, 0x3456); test_running = 0; return error; } /****************************** Local Functions ******************************/ static void send_message(uint16_t id, uint8_t len, uint32_t data) { next_id = id; next_len = len; for (int i = 0; i < len; i++) { next_data[i] = (data >> (i*8)) & 0xFF; } can_message msg = {.id = next_id, .data_len = next_len, .data = next_data}; can_bus_send_message(&msg); } static void test_message_received_handler1(can_message *message) { check_received_message(message, 1); } static void test_message_received_handler2(can_message *message) { check_received_message(message, 2); } static void check_received_message(can_message *message, int handler_num) { if (test_running) { if (message->id != next_id) { error = 1; log_write("test_can_bus: message received handler %d: wrong id, id:%Xh, len:%d, data:", handler_num, message->id, message->data_len); } if (!error) { if (message->data_len != next_len) { error = 1; log_write("test_can_bus: message received handler %d: wrong len, id:%Xh, len:%d, data:", handler_num, message->id, message->data_len); } } if (!error) { // Compare each byte in data for (int i = 0; i < message->data_len; i++) { if (message->data[i] != next_data[i]) { error = 1; log_write("test_can_bus: message received handler %d: wrong data, id:%Xh, len:%d, data:", handler_num, message->id, message->data_len); break; } } } if (!error) { log_write("test_can_bus: receive %d OK id:%Xh, len:%d, data:", handler_num, message->id, message->data_len); } print_message_data(message); log_write_ln(""); } }
C
#include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h> // in order to pass multiple arguments to a thread, it is better to create an argument structure struct thread_data { int thread_id; int sum; char *message; }; typedef struct thread_data thread_arg_struct; void *printHello(void *thread_arg){ thread_arg_struct *my_data; int taskid=0, sum=0; char hello_msg[255]; my_data = (thread_arg_struct *) thread_arg; taskid = my_data->thread_id; sum = my_data->sum; strcpy(hello_msg, my_data->message); printf("taskid = %d, sum = %d, message=%s\n", taskid, sum, hello_msg); } int main(void){ pthread_t thread; thread_arg_struct my_thread_data; my_thread_data.message = malloc(sizeof(char) * 255); my_thread_data.thread_id = 10; my_thread_data.sum = 35; my_thread_data.message = "hello world!"; pthread_t my_id = pthread_create(&thread, NULL, printHello, (void *) &my_thread_data); pthread_join(thread, NULL); pthread_exit(NULL); exit(0); }
C
#include <stdio.h> #include <cs50.h> int main(void) { // int n; // do // { // n = get_int("width: "); // } // while (n < 1); // //print the question marks 'n' times // for (int i = 0; i < n; i++) // { // printf("?"); // } // printf("\n"); for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { printf("#"); } printf("\n"); } }
C
#include<stdio.h> #include<conio.h> void main() { int a,n,rev=0; printf("enter the number"); scanf("%d",&n); while(n!=0) { a=n%10; n=n/10; rev=rev*10+a;} printf("%d",rev); }
C
#include <stdio.h> int main() { int i; scanf("%d", &i); do{ if(i%5==0) { printf("%d\n", i); } i--; } while (i>=0); }
C
/* * File: 4.10+4.11-PrintStars.c * ---------------------------- * This program prints 8 rows of stars. */ #include <stdio.h> #include "genlib.h" #include "simpio.h" /* constants */ #define rows 8 /* main program */ main() { /* 4.10 */ /* int i, j; for (i = 0; i < rows; i++) { for (j = 0; j <= i; j++) { printf("*"); } printf("\n"); } */ /* 4.11 */ int i, j, k, nstar, nblank; nblank = rows + 2; //parallel shift to the right for 3 blanks for (i = 0; i < rows; i++) { nstar = 2 * i + 1; for (j = 0; j < nblank; j++) { printf(" "); } for (k = 0; k < nstar; k++) { printf("*"); } printf("\n"); nblank--; } }
C
#include "a4.h" #include <stdio.h> #include <stdlib.h> #include <math.h> double comp_distance(const PIXEL *A, const PIXEL *B, int image_size) { double distance = 0; int i; for (i = 0; i < image_size; i++) { distance += (A[i].r - B[i].r) * (A[i].r - B[i].r); distance += (A[i].g - B[i].g) * (A[i].g - B[i].g); distance += (A[i].b - B[i].b) * (A[i].b - B[i].b); } distance = sqrt(distance); // printf("%lf\n", distance); return distance; } void comp_fitness_population(const PIXEL *image, Individual *individual, int population_size) { int imgsize = individual->image.width * individual->image.height; int i; for (i = 0; i < population_size; i++) { individual[i].fitness = comp_distance(image, individual[i].image.data, imgsize); } }
C
/* ------------------------------------------------------ */ /* FUNCTION dominance_count : */ /* Given two sorted (increasing) arrays, this function */ /* computes the number of pairs that satisfies f[i]>g[j]. */ /* This function is similar to coincidence_count(). */ /* */ /* Copyright Ching-Kuang Shene June/30/1989 */ /* ------------------------------------------------------ */ int dominance_count(int f[], int g[], int m, int n) { int index_f, index_g; int count; count = index_f = index_g = 0; while (index_f < m && index_g < n) if (f[index_f] <= g[index_g]) index_f++; else index_g++, count += m - index_f; return count; } /* ------------------------------------------------------ */ #include <stdio.h> void main(void) { int x[] = { 1, 2, 4, 7, 9, 12, 13, 15, 16, 20}; int nx = sizeof(x)/sizeof(int); int y[] = { 4, 5, 7, 8, 9, 10, 11, 13, 16, 19}; int ny = sizeof(y)/sizeof(int); int dominance_count(int [], int [], int, int), i; printf("\nDominance Count of two Increasing Arrays\n"); printf("\n # Array 1 Array 2"); printf("\n -- ------- -------"); for (i = 0; i < nx; i++) printf("\n%3d%10d%10d", i, x[i], y[i]); printf("\n\nThere are %d Dominance Pairs.", dominance_count(x, y, nx, ny)); } 
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include "hash_table.h" #define DEFAULT_NUM_BUCKETS 128 /* * Returns number of buckets in hash table * Number of buckets = lowest power of 2 greater than arrLen */ int getNumBuckets(int arrLen) { arrLen--; int numBuckets = 2; while(arrLen >>= 1) { numBuckets <<= 1; } return numBuckets; } /* * Simple hash function based on djb2 algorithm */ int hashFunction(char* key, int numBuckets) { // if y is a power of 2, x % y is the same as x & (y - 1) numBuckets--; int hash = 5381; for(int i = 0; key[i] != '\0'; i++) { hash = (((((hash << 5) & numBuckets) + hash) & numBuckets) + key[i]) & numBuckets; } return hash; } /* * Creates new hash table * Hashes elements of arr to their corresponding array indices * Returns hash table */ HashTable* initHashTable(int numElements) { // Initialize hash table int numBuckets = numElements == 0 ? DEFAULT_NUM_BUCKETS : getNumBuckets(numElements); HashEle** buckets = (HashEle**) malloc(numBuckets * (sizeof(HashEle*))); for(int i = 0; i < numBuckets; i++) { buckets[i] = NULL; } HashTable* hashTable = (HashTable*) malloc(sizeof(HashTable)); hashTable ->buckets = buckets; hashTable ->numBuckets = numBuckets; return hashTable; } void hashEleInTable(HashTable* hashTable, char* key, void* val) { HashEle* ele = (HashEle*) malloc (sizeof(HashEle)); ele ->key = key; ele ->val = val; int bucketNo = hashFunction(key, hashTable ->numBuckets); ele ->next = hashTable ->buckets[bucketNo]; hashTable ->buckets[bucketNo] = ele; } /* * Returns index of key in original array * Return -1 if key not present */ void* findEleInTable(HashTable* hashTable, char* key) { int bucketNo = hashFunction(key, hashTable ->numBuckets); HashEle* head = hashTable ->buckets[bucketNo]; while(head != NULL) { if (strcmp(head ->key, key) == 0) { return head ->val; } head = head ->next; } return NULL; } /* * Deallocates memory from hash table */ void freeHashTable(HashTable* hashTable) { for(int i = 0; i < hashTable ->numBuckets; i++) { HashEle* head = hashTable ->buckets[i]; while(head != NULL) { HashEle* temp = head; head = head ->next; free(temp); temp = NULL; } hashTable ->buckets[i] = NULL; } hashTable ->buckets = NULL; free(hashTable); } //debug void printHashTable(HashTable* hashTable) { for(int i = 0; i < hashTable ->numBuckets; i++) { printf("Bucket %d: ", i); HashEle* head = hashTable ->buckets[i]; while(head != NULL) { printf("%s ", head ->key); head = head ->next; } printf("\n"); } }
C
#include "comm.h" int mh_sendto(const char *dest_ipaddr, const char *send_buf, socklen_t send_len) { if (NULL==dest_ipaddr || NULL==send_buf || 0==send_len) { printf("mh_sendto() - Illegal dest_ipaddr/send_buf/send_len\n"); return -1; } SKADDRIN dest_addr; memset(&dest_addr, 0, sizeof (SKADDRIN)); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(COMM_PORT); dest_addr.sin_addr.s_addr = inet_addr(dest_ipaddr); int sockd = 0; if ((sockd=socket(AF_INET, SOCK_DGRAM, 0)) < 0) { perror("mh_sendto() - socket error "); return -1; } sendto(sockd, send_buf, send_len, 0, (SKADDR *) &dest_addr, sizeof (SKADDR)); } int mh_init_server_sock(short port, int type) { SKADDRIN server_addr; int server_sockd; memset(&server_addr, 0, sizeof (SKADDRIN)); server_addr.sin_family = AF_INET; server_addr.sin_port = htons(port); server_addr.sin_addr.s_addr = htonl(INADDR_ANY); if ((server_sockd=socket(AF_INET, type, 0)) < 0) { perror("socket error "); return -1; } int reuse = 1; if (setsockopt(server_sockd, SOL_SOCKET, SO_REUSEADDR, &reuse, (socklen_t) sizeof (reuse)) < 0) { perror("setsockopt error "); return -1; } if (bind(server_sockd, (SKADDR *) &server_addr, (socklen_t) sizeof (SKADDR)) < 0) { perror("bind error "); return -1; } return server_sockd; } int mh_init_server_tcp_sock(short port, int backlog) { printf("init tcp socket\n"); int server_sockd = 0; server_sockd = mh_init_server_sock(port, SOCK_STREAM); if (-1 == server_sockd) return -1; if (listen(server_sockd, backlog) < 0) { perror("listen error "); return -1; } return server_sockd; }
C
#include <stdio.h> #include <stdlib.h> #include "ejercicioUno.h" float aplicarDescuento(float precio) { float retorno = -1; retorno = precio *0.05; return retorno; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> int main(int argc, char **argv) { long int a = clock(); printf("clock() = %ld\n", a); return 0; }
C
#include <stdio.h> int main(){ int a,b; scanf("%d %d",&a,&b); if(a<b){ for(int i=a;i<=b;i++){ for(int j=0;j<i;j++){ printf("*"); } printf("\n"); } }else{ for(int i=a;i>=b;i--){ for(int j=0;j<i;j++){ printf("*"); } printf("\n"); } } return 0; }
C
/* Приведение типов Приведение типов работает и между целочисленными типа и числами с плавающей точкой. Например, если написать так: int a = 2.6; То получится, что слева стоит объект типа int, а справа - объект типа double. Число 2.6 не целое и не может сохранится в числе типа int, поэтому дробная часть просто отбрасывается. Получилось неявное приведение с потерей данных. Чтобы выявлять приведения с возможной потерей даный можно компилировать программу так: gcc -Wconversion 07cast.c Можно сделать явное приведение типов, указав компилятору, что вы хотите преобразавать один тип в другой: a = (int)2.6; Интересно, что если мы приводим число типа float к числу типа int, то может произойти потеря данных. Например, если мы преобразуем 2.6f из float в int. Но можно потерять данные и при приведении int во float. Например, если мы преобразуем число 1234567890 из int во float. */ #include <stdio.h> int main() { int a; a = 2.6; printf("%i\n", a); a = (int)2.6; printf("%i\n", a); float b; b = 1234567890; printf("%f\n", b); b = (float)1234567890; printf("%f\n", b); }
C
#ifndef T_MATRIX_H #define T_MATRIX_H #include "tVector.h" typedef struct { int capacity; int n, m; tVector** matrix; void* (*defValue)(); void (*tFree)(void*); } tMatrix; tMatrix* constructMatrix(int constColumns, void* (*defValue)(), void (*tFree)(void*)); int insertMatrix(tMatrix* mat, void *data, int pos_i, int pos_j, void* (*tCopy)(void *)); void printMatrix(tMatrix* mat, void (*tPrint)(void *)); void freeMatrix(tMatrix* mat); int addVectorToMatrix(tMatrix *mat, tVector *vec, void* (*tCopy)(void*)); void addRowMatrix(tMatrix *mat, void* (*tCopy)(void*)); void sortMatrix(tMatrix* mat, int (*comp)(const void *, const void *)); #endif
C
#include <stdio.h> #include <ctype.h> #include <stdlib.h> #include <string.h> #define TAMnome 100 #define TAMagenda 1000 typedef struct { int matricula; char nome[TAMnome]; int ddd; int numero; char tipo; } TipoAgenda; void cleanBuffer() { char cl; cl = getchar(); while (cl != '\n' && cl != EOF) cl = getchar(); } char menu() { char op; do { printf("\n# AGENDA TELEFONICA #\n"); printf("L- Listar nomes na agenda.\n"); printf("I- Inserir novo registro.\n"); printf("A- Apagar registro pelo nome.\n"); printf("B- Buscar telefone pelo nome.\n"); printf("O- Ordenar pelo nome.\n"); printf("S- Sair.\n"); printf("Digite sua escolha: "); __fpurge(stdin); scanf("%c", &op); op = toupper(op); } while ((op!='L') && (op!='I') && (op!='A') && (op!='B') && (op!='S') && (op!='O')); return op; } int main (int narg, char *argv[]) { TipoAgenda *agenda; TipoAgenda *novo[TAMagenda]; TipoAgenda *auxiliar3; int contador=0,auxiliar,auxiliar2,escolha,buscado; char opt,buffer[500],procurar[TAMnome],deletar[TAMnome]; FILE *fp; for (auxiliar=0; auxiliar<TAMagenda; auxiliar++) novo[auxiliar] = NULL; if (narg > 1) { fp = fopen(argv[1],"r"); if (fp == NULL) { fprintf(stderr, "Erro abrindo o arquivo.\n"); return EXIT_FAILURE; } while (!feof(fp)) { novo[contador]=(TipoAgenda*)malloc(sizeof(TipoAgenda)); agenda=novo[contador]; fscanf(fp,"%d\n", &(agenda->matricula)); fgets(buffer, TAMnome, fp); buffer[strlen(buffer)-1] = '\0'; strcpy(agenda->nome,buffer); fscanf(fp,"%d\n", &(agenda->ddd)); fscanf(fp,"%d\n", &(agenda->numero)); fscanf(fp,"%c\n", &(agenda->tipo)); contador ++; } fclose(fp); } do { escolha=menu(); switch(escolha) { case 'L': if (contador==0) { printf("\nAgenda vazia.\n"); } else { for (auxiliar=0; auxiliar<contador; auxiliar++) { if (novo[auxiliar] != NULL) { printf("\n%d\n", novo[auxiliar]->matricula); printf("%s\n", novo[auxiliar]->nome); printf("%d\n", novo[auxiliar]->ddd); printf("%d\n", novo[auxiliar]->numero); printf("%c\n", novo[auxiliar]->tipo); } } } break; case 'I': if (contador==TAMagenda) { printf("\nAgenda cheia.\n"); } else { auxiliar=0; while (novo[auxiliar] != NULL) auxiliar++; novo[auxiliar]=(TipoAgenda*)malloc(sizeof(TipoAgenda)); printf("Digite a matricula: "); scanf("%d", &(novo[auxiliar]->matricula)); cleanBuffer(); printf("Digite o nome: "); fgets(buffer, TAMnome, stdin); buffer[strlen(buffer)-1] = '\0'; strcpy(novo[auxiliar]->nome,buffer); printf("Digite o ddd: "); scanf("%d", &(novo[auxiliar]->ddd)); cleanBuffer(); printf("Digite o numero: "); scanf("%d", &(novo[auxiliar]->numero)); cleanBuffer(); printf("Digite o tipo: "); scanf("%c", &(novo[auxiliar]->tipo)); cleanBuffer(); printf("\nContato adicionado com sucesso.\n"); if (auxiliar==contador) contador++; } break; case 'A': buscado=0; cleanBuffer(); printf("Digite o nome: "); fgets(buffer, TAMnome, stdin); buffer[strlen(buffer)-1] = '\0'; strcpy(deletar,buffer); if (contador==0) printf("\nContato não encontrado.Agenda vazia.\n"); else { for(auxiliar=0; auxiliar<contador; auxiliar++) { if ((strcmp(novo[auxiliar]->nome,deletar))==0) { novo[auxiliar] = NULL; printf("\nContato apagado com sucesso.\n"); buscado=1; } } if (buscado==0) printf("\nContato não existe.\n"); } break; case 'B': buscado=0; cleanBuffer(); printf("Digite o nome: "); fgets(buffer, TAMnome, stdin); buffer[strlen(buffer)-1] = '\0'; strcpy(procurar,buffer); if (contador==0) printf("\nContato não encontrado.Agenda vazia.\n"); else { for(auxiliar=0; auxiliar<contador; auxiliar++) { if ((strcmp(novo[auxiliar]->nome,procurar))==0) { printf("\nContato encontrado:"); printf("\n%d\n", novo[auxiliar]->matricula); printf("%s\n", novo[auxiliar]->nome); printf("%d\n", novo[auxiliar]->ddd); printf("%d\n", novo[auxiliar]->numero); printf("%c\n", novo[auxiliar]->tipo); buscado=1; } } if (buscado==0) printf("\nContato não encontrado.\n"); } break; case 'O': for(auxiliar2=(contador-1); auxiliar2>=0; auxiliar2--) { for(auxiliar=0; auxiliar<auxiliar2; auxiliar++) { if (novo[auxiliar] != NULL) { if (strcmp(novo[auxiliar]->nome,novo[auxiliar+1]->nome)>0) { auxiliar3=novo[auxiliar]; novo[auxiliar]=novo[auxiliar+1]; novo[auxiliar+1]=auxiliar3; } } } } printf("\nLista ordenada.\n"); break; case 'S': break; } } while(escolha != 'S'); return EXIT_SUCCESS; }
C
/* Created by roberto on 29/8/20. */ #include "tester.h" void checkCreateTable(const char * tableName) /** * Tester method for createTable which initializes * a file to store data registers * @param tableName: file in which data will be stores * @param tableName: program structure that stores * a point to the tableName file */ { int num = 0; struct stat st; FILE * dataFileHandler; /* call createTable */ createTable(tableName); /* check file tableName has been created */ /* and first stored number if -1 */ dataFileHandler = fopen(tableName, "r"); fread(&num, sizeof(int), 1, dataFileHandler); if (num != -1){ printf("call to createTable failed\n"); printf("the first value stored in the file " "should be '-1' but is '%d'\n", num); exit(1); } /* check file size */ stat(tableName, &st); if (st.st_size!=sizeof(int)) { printf("call to createTable failed\n"); printf("the size of file %s should by %ld\n", tableName, sizeof(int)); exit(1); } printf("* checkcreateTable: OK\n"); fclose(dataFileHandler); }
C
#include <stdio.h> // int* readArray(int length){ int* array = malloc(length* sizeof(int)); for (int i=0; i<length; i++){ int input; printf("Enter a element of arrary: "); scanf("%d", &input); array[i] = input; } return array; } void swap(int *xp, int *yp){ int temp = *xp; *xp = *yp; *yp = temp; } void sortArray(int *array, int length){ for (int i=0; i < length-1; i++){ int min = i; for (int j = i+1; j<length; j++){ if (array[min] > array[j]){ min = j; } } if (min != i){ swap(&array[i], &array[min]); } } } void printArray(int *array, int length){ printf("[ "); int i; for (i =0; i<length-1; i++){ printf("%d, ", array[i]); } printf("%d ]", array[length-1]); } int main(){ int length; printf("Enter a array length: "); scanf("%d", &length); int* array = readArray(length); sortArray(array, length); printArray(array, length); free(array); } // a heap is an area of pre-reserved computer main storage ( memory ) //that a program process can use to store data in //some variable amount that won't be known until the program is running.
C
/*Задача 4. Напишете функция, която връща резултат a*2 + b*c.*/ #include<stdio.h> double calculation(void); int main(){ calculation(); return 0; } double calculation(void){ double a; double b; double c; printf("Please enter digit a = "); scanf("%lf", &a); printf("\nPlease enter a digit b = "); scanf("%lf", &b); printf("\nPlease enter a digit c = "); scanf("%lf", &c); double result = a*2 + b*c; return printf("\nThe result = a*2 + b*c = %lf", result); }
C
#ifndef MYY_SRC_WIDGETS_WIDGET_AREA_H #define MYY_SRC_WIDGETS_WIDGET_AREA_H 1 #include "myy/helpers/position.h" #include "myy/helpers/vector.h" #include <stdbool.h> struct widget_area { position_S upper_left; position_S bottom_right; }; typedef struct widget_area widget_area_t; __attribute__((unused)) static inline bool widget_area_contains( widget_area_t const area, position_S const pos) { return (area.upper_left.x <= pos.x) & (pos.x <= area.bottom_right.x) & (area.upper_left.y <= pos.y) & (pos.y <= area.bottom_right.y); } myy_vector_template(widget_areas, widget_area_t) __attribute__((unused)) static inline widget_area_t widget_area_struct_ulbr_S( position_S const upper_left, position_S const bottom_right) { widget_area_t area = { .upper_left = upper_left, .bottom_right = bottom_right }; return area; } #define widget_areas_for_each_containing(areas_name, area_name, posS, i_name, ...) {\ widget_area_t * __restrict const areas_data = \ myy_vector_widget_areas_data(areas_name);\ uintmax_t const areas_count =\ myy_vector_widget_areas_length(areas_name);\ for (uintmax_t i_name = 0; i_name < areas_count; i++) {\ widget_area_t area_name = areas_data[i]; \ if (widget_area_contains(area_name, posS)) __VA_ARGS__\ }\ }\ __attribute__((unused)) static inline void widget_areas_dump( myy_vector_widget_areas * __restrict const areas) { myy_vector_for_each_ptr( widget_area_t, area, in, areas, { LOG("[AREA] upper_left (%d,%d) - (%d,%d) bottom_right\n", area->upper_left.x, area->upper_left.y, area->bottom_right.x, area->bottom_right.y); } ); } #endif
C
#include <stdio.h> void printNaturalNumbers(int lowerLimit, int upperLimit); int main() { int lowerLimit, upperLimit; printf("Enter lower limit: "); scanf("%d", &lowerLimit); printf("Enter upper limit: "); scanf("%d", &upperLimit); printf("All natural numbers from %d to %d are: ", lowerLimit, upperLimit); printNaturalNumbers(lowerLimit, upperLimit); return 0; } void printNaturalNumbers(int lowerLimit, int upperLimit) { if(lowerLimit > upperLimit) return; printf("%d, ", lowerLimit); printNaturalNumbers(lowerLimit + 1, upperLimit); }
C
#include "game.h" static struct drop_table drop_table[] = { {90, 1, 10, NULL}, {10, 0, 0, create_random_armor}, {90, 0, 0, create_random_potion}, {0, 0, 0, NULL}, }; struct creature *create_bat() { int rc; struct creature *bat; bat = calloc(1, sizeof(*bat)); assert(bat); bat->color = BLUE; bat->symbol = 'b'; rc = asprintf(&bat->name, "a bat"); assert(rc != -1); bat->health = bat->max_health = 20; bat->mana = bat->max_mana = 0; bat->strength = 3; bat->intelligence = 3; bat->dexterity = 3; bat->level = 1; bat->experience = 20; bat->do_hurt = creature_hurt; bat->attack = creature_attack; bat->die = creature_die; bat->drop_table = drop_table; return bat; }
C
/* Title: Pointer Test Author: Haider Ali Punjabi Mail: me@haideralipunjabi.com Date: 12-07-2018 */ #include <stdio.h> #include <stdlib.h> int main() { int var; int* ptr; var = 3; ptr = &var; printf("Value of var before change = %d\n", var); printf("Address of var before change = %u\n", ptr); changeVal(ptr); printf("Value of var after change = %d\n", var); printf("Address of var after change = %u\n", ptr); } void changeVal(int* ptr){ (*ptr)++; }
C
#include "functions.h" #include <math.h> inline double sigmoid(double x) { return (double)1/((double)1+(double)exp(-x)); } double sigmoidExt(double x,int type) { /*0: ֵ 1:*/ if (type == FUNC_VALUE) { return (double)1/((double)1+(double)exp(-x)); } else { return (x) * ((double)1-x); } } int weightInit(BLOB_s *k) { double arr[][5]= { {0.1667,0.0971,0.0427,-0.0349,-0.1637}, { -0.0996,-0.0161,0.1081,0.1613,-0.0545}, {0.0396,-0.1783,0.1562,0.1544,0.1160}, {-0.0052,0.1190,0.0882,-0.0332,-0.1815}, {0.1449,-0.0205,-0.1199,0.1458,-0.1337} }; BLOB_DATA_PTR(k,ptr); int outputNum = k->numSize; int inputNum = k->channelSize; int sectionY = k->heightSize; int sectionX = k->widthSize; /*ʱ*/ CHECK_EXPR_RET(sectionY != 5,-1); CHECK_EXPR_RET(sectionX != 5,-1); for (int oy = 0;oy < outputNum;oy++) { for (int ix = 0;ix < inputNum;ix++) { for (int y = 0;y < sectionY;y++) { for (int x = 0;x < sectionX;x++) { ptr[oy][ix][y][x] = arr[y][x]; } } } } //printf("weightInit OK!\n"); return 0; } int biasInit(BLOB_s *b) { BLOB_DATA_PTR(b,ptr); for (int i_batch = 0;i_batch < b->numSize;i_batch++) { for (int i_num = 0;i_num < b->channelSize;i_num++) { for (int i_height = 0;i_height < b->heightSize;i_height++) { for (int i_width = 0;i_width < b->widthSize;i_width++) { ptr[i_batch][i_num][i_height][i_width] = 0; } } } } return 0; } double functionLoss1(BLOB_s *pError) { CHECK_EXPR_RET(pError == NULL,-1); double loss = 0.0; for (int i = 0;i < pError->count;i++) { loss += 0.5 * pError->data[i] * pError->data[i]; } loss /= pError->numSize; return loss; }
C
#include <stdio.h> #include "printSea.c" #include "check.c" #include "populate.c" //a ship can go over the left or right border and reappear //on the right or left border, respectively, //because the sea has to be considered as a cylinder //A ship cannot go from the upper border to the lower border, for the same reason int main() { int user_sea[100] = {0}; int comp_sea[100] = {0}; printf("Your sea\n\n"); printSea(user_sea); printf("\n\n"); printf("Computer's sea\n\n"); printSea(comp_sea); int xCoord = 0, yCoord = 0; int choice_dir = 0; int ship_size = 0; int flag = 1; int arr_pos = 0; for ( ship_size = 2; ship_size < 9; ship_size++ ) { flag = 1; while(flag == 1) { do { printf("Instert ship of size %d\n[x coordinate]\n", ship_size); scanf("%d", &xCoord); if(xCoord < 0 || xCoord >= 10 ) { printf("has to be 0-9\n"); } }while(xCoord < 0 || xCoord >= 10); do { printf("[y coordinate]"); scanf(" %d", &yCoord); if(yCoord < 0 || yCoord >= 10 ) { printf("has to be 0-9\n"); } }while(yCoord < 0 || yCoord >= 10); printf("what direction? [1:north; 2:south; 3:west; 4:east]"); scanf(" %d", &choice_dir); arr_pos = xCoord + yCoord * 10; //the actual position on the array, translated from coordinates flag = check(user_sea, arr_pos, choice_dir, ship_size); if ( flag == 0 ) { //a bit of code redundance here populate(user_sea, arr_pos, choice_dir, ship_size); } } printSea(user_sea); } return 0; }
C
#include <stdio.h> #include <cs50.h> #include <math.h> int main (void) { // Prompt user for $$ amount float f; int coins; do { f = get_float("How much $$: "); } while (f < 0); coins = (int)round(f*100); int counter_quarters; // Tallies number of quarters used if (coins / 25 > 0) { counter_quarters = coins / 25; } else { counter_quarters = 0; } // Tallies number of dimes used int mod_quarters = coins%25; int counter_dimes; if (mod_quarters / 10 > 0) { counter_dimes = mod_quarters / 10; } else { counter_dimes = 0; } // Tallies number of nickels used int mod_dimes = mod_quarters%10; int counter_nickels; if (mod_dimes / 5 > 0) { counter_nickels = mod_dimes / 5; } else { counter_nickels = 0; } // Tallies number of pennies used int mod_nickels = mod_dimes%5; int counter_pennies = mod_nickels; // Tallies and prints total int counter_total = counter_quarters + counter_dimes + counter_nickels + counter_pennies; printf("%i\n", counter_total); }
C
#include<stdio.h> void main() { int m, n, i, p, flag = 0; printf("Enter a Number: "); scanf("%d", &n); m = n/2; for (i = 2; i <= m; i++) { if (n%i == 0) { printf("%d is not a Prime Number",n); printf("\n %d times %d is %d" ,i, n/i, n); flag = 1; break; } } if (flag == 0) { printf("%d is Prime Number",n); } }
C
#include <stdlib.h> #include "holberton.h" /** * string_nconcat - function to concatenate 2 strings * @s1: first string * @s2: second string * @n: first n bytes of second string * Return: s */ char *string_nconcat(char *s1, char *s2, unsigned int n) { char *s3; unsigned int len1, len2; if (s1 == NULL) s1 = ""; if (s2 == NULL) s2 = ""; for (len1 = 0; *(s1 + len1); len1++)/* length of first string*/ {} for (len2 = 0; *(s2 + len2); len2++)/* length of second string*/ {} if (n < len2) { len2 = n; } s3 = malloc((len1 + len2 + 1) * sizeof(char)); if (s3 == NULL) { return (NULL); } for (len1 = 0; *(s1 + len1); len1++) { *(s3 + len1) = *(s1 + len1); } for (len2 = 0; len2 < n && *(s2 + len2); len1++, len2++) { *(s3 + len1) = *(s2 + len2); } *(s3 + len1) = '\0'; return (s3); }
C
#ifndef _PREDICATE_H #define _PREDICATE_H #include "arch.h" /* Compare two 64-bit words in constant-time */ #define CMP_LT_U64(a,b) \ (((((a)>>63U)^((b)>>63U)) &((((a)>>63U)-((b)>>63U))>>63U))\ ^ ((((a)>>63U)^((b)>>63U)^ONE64)\ &((((a)&((uint64_t)0x7FFFFFFFFFFFFFFF))\ -((b)&((uint64_t)0x7FFFFFFFFFFFFFFF)))>>63U))) /* Compare two 32-bit words in constant-time */ #define CMP_LT_U32(a,b) \ (((((a)>>31U)^((b)>>31U)) &((((a)>>31U)-((b)>>31U))>>31U))\ ^ ((((a)>>31U)^((b)>>31U)^ONE32)\ &((((a)&((uint32_t)0x7FFFFFFF))\ -((b)&((uint32_t)0x7FFFFFFF)))>>31U))) /* Compare two UINT in constant-time */ #define CMP_LT_UINT CONCAT(CMP_LT_U,NB_BITS_UINT) /* Constant-time version */ int PQCLEAN_GEMSSBLUE192_AVX2_ISZERO(const UINT *a, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_ISNOTZERO(const UINT *a, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_ISONE(const UINT *a, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL(const UINT *a, const UINT *b, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT(const UINT *a, const UINT *b, unsigned int size); #define f_CMP_GT(a,b,size) f_CMP_LT(b,a,size) /* Variable-time version */ int PQCLEAN_GEMSSBLUE192_AVX2_ISZERO_NOCST(const UINT *a, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_ISONE_NOCST(const UINT *a, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL_NOCST(const UINT *a, const UINT *b, unsigned int size); int PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT_NOCST(const UINT *a, const UINT *b, unsigned int size); #define f_CMP_GT_NOCST(a,b,size) f_CMP_LT_NOCST(b,a,size) /* Inlined version */ /* Equal to 0 */ #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO1_NOCST(a) ((a)[0]==0) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO2_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO1_NOCST(a)&&((a)[1]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO3_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO2_NOCST(a)&&((a)[2]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO4_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO3_NOCST(a)&&((a)[3]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO5_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO4_NOCST(a)&&((a)[4]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO6_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO5_NOCST(a)&&((a)[5]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO7_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO6_NOCST(a)&&((a)[6]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO8_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO7_NOCST(a)&&((a)[7]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISZERO9_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISZERO8_NOCST(a)&&((a)[8]==0)) /* Equal to 1 */ #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE1_NOCST(a) ((a)[0]==1) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE2_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE1_NOCST(a)&&((a)[1]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE3_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE2_NOCST(a)&&((a)[2]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE4_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE3_NOCST(a)&&((a)[3]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE5_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE4_NOCST(a)&&((a)[4]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE6_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE5_NOCST(a)&&((a)[5]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE7_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE6_NOCST(a)&&((a)[6]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE8_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE7_NOCST(a)&&((a)[7]==0)) #define PQCLEAN_GEMSSBLUE192_AVX2_ISONE9_NOCST(a) (PQCLEAN_GEMSSBLUE192_AVX2_ISONE8_NOCST(a)&&((a)[8]==0)) /* Equality */ #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL1_NOCST(a,b) ((a)[0]==(b)[0]) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL2_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL1_NOCST(a,b)&&((a)[1]==(b)[1])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL3_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL2_NOCST(a,b)&&((a)[2]==(b)[2])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL4_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL3_NOCST(a,b)&&((a)[3]==(b)[3])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL5_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL4_NOCST(a,b)&&((a)[4]==(b)[4])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL6_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL5_NOCST(a,b)&&((a)[5]==(b)[5])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL7_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL6_NOCST(a,b)&&((a)[6]==(b)[6])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL8_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL7_NOCST(a,b)&&((a)[7]==(b)[7])) #define PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL9_NOCST(a,b) (PQCLEAN_GEMSSBLUE192_AVX2_ISEQUAL8_NOCST(a,b)&&((a)[8]==(b)[8])) /* Comparison, less than */ #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT1_NOCST(a,b) ((a)[0]<(b)[0]) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT2_NOCST(a,b) (((a)[1]==(b)[1])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT1_NOCST(a,b)\ :((a)[1]<(b)[1])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT3_NOCST(a,b) (((a)[2]==(b)[2])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT2_NOCST(a,b)\ :((a)[2]<(b)[2])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT4_NOCST(a,b) (((a)[3]==(b)[3])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT3_NOCST(a,b)\ :((a)[3]<(b)[3])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT5_NOCST(a,b) (((a)[4]==(b)[4])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT4_NOCST(a,b)\ :((a)[4]<(b)[4])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT6_NOCST(a,b) (((a)[5]==(b)[5])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT5_NOCST(a,b)\ :((a)[5]<(b)[5])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT7_NOCST(a,b) (((a)[6]==(b)[6])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT6_NOCST(a,b)\ :((a)[6]<(b)[6])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT8_NOCST(a,b) (((a)[7]==(b)[7])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT7_NOCST(a,b)\ :((a)[7]<(b)[7])) #define PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT9_NOCST(a,b) (((a)[8]==(b)[8])?PQCLEAN_GEMSSBLUE192_AVX2_CMP_LT8_NOCST(a,b)\ :((a)[8]<(b)[8])) #endif
C
/** ** Вариант 41. ** Имеется матрица A размера n на m, состоящая из слов (в качестве элементов матрицы). ** Необходимо найти строку k матрицы A, такую что обращенное слово R(W(k)) совпадает с некоторым из слов W(i), i=0,...,n-1. ** А затем "прибавить" её ко всем остальным строкам матрицы, исключая её саму. ** "Сложение" найденной строки k и строки p (для каждого q = 0, ..., m-1) происходит вычеркиванием из слова A_pq букв слова A_kq. ** ** Параметры: ** int argc: количество аргументов командной строки; ** char *argv[]: массив аргументов командной строки. ** ** В нулевом аргументе функция получает имя исполняемого файла, в первом - имя входного файла. ** Функция проверяет ошибки чтения входного и выходного файлов. ** Размеры марицы считываются из входного файла, также проверяется считывание. ** Выделяется памят под марицу, а затем используются функции поиска строки и сложения строк. ** Конечная матрица печатается в выходной файл. ** ** Возращаемое значение: в случае успеха - 0, иначе - (-1). ** */ #include "libs.h" int main(int argc, char *argv[]) { int n, m; char **matrix; FILE *inp, *out; if ((inp = fopen(argv[1], "r")) == NULL) { printf("ERROR\n"); return -1; } if ((out = fopen("result.txt", "w")) == NULL) { printf("ERROR\n"); fclose(inp); return -1; } if(!fscanf(inp, "%d %d", &n, &m)){ printf("ERROR::read error n, m"); fclose(inp); fclose(out); return -1; } matrix = malloc(n * m * sizeof(*matrix)); read_string(inp); read_matrix(matrix, inp, n*m); sum(matrix, n, m, search(matrix, n, m)); print_matrix(matrix, n, m, out); for(int i = 0; i < n*m; i++) { free(matrix[i]); } free(matrix); fclose(inp); fclose(out); return 0; }
C
#include "test.h" #include <memory.h> #define _4bitstoascii(a) (a<10?a+48:a+55) #ifdef BIG_ENDIAN #error implement printHex #else static wchar_t* printHex(reg_t x, wchar_t * buffer) { const int s = sizeof(reg_t); wchar_t * buffercopy = buffer; unsigned char const * const c = (unsigned char const * const)(&x); int i = s-1; unsigned char byte; /*/remove leading zeroes*/ while (i > 0 && c[i] == 0) { i--; } for (; i >=0; --i) { byte = c[i] >> 4; *buffer = (wchar_t)_4bitstoascii(byte); ++buffer; byte = c[i] & 0xF; *buffer = (wchar_t)_4bitstoascii(byte); ++buffer; } *buffer = 0; return buffercopy; } #endif void dumpNumber(reg_t * A, _char_t* name, numsize_t ASize) { int charsize = ASize * sizeof(reg_t) * 2 + 1; int memsize = charsize * sizeof(_char_t); _char_t * buffer = (_char_t*)malloc(memsize); if (buffer == NULL) { _fprintf(stderr, STR("[ERROR] CANNOT DUMP NUMBER, NO MEMORY FOR MALLOC")); return; } FillHexString(buffer, charsize, A, ASize); _fprintf(stderr, STR("\n%s = \""), name); _fprintf(stderr, buffer); _fprintf(stderr, STR("\";\n")); free(buffer); } uint_fast32_t rand32(uint_fast64_t * const refState) { /* PCR random generator credit O'Neill, Melissa http://www.pcg-random.org/ */ static uint_fast64_t const multiplier = 6364136223846793005u; static uint_fast64_t const increment = 1442695040888963407u; /* Or an arbitrary odd constant*/ uint_fast64_t x; x = *refState; uint_fast8_t count = (uint_fast8_t)(x >> 59); *refState = x * multiplier + increment; x ^= x >> 18; x = x >> 27; return ((uint_fast32_t)x) >> count; } void randNum(uint_fast64_t * const refState, reg_t * const A, numsize_t size) { if (size == 0) return; /* PCR random generator credit O'Neill, Melissa http://www.pcg-random.org/ */ static uint_fast64_t const multiplier = 6364136223846793005u; static uint_fast64_t const increment = 1442695040888963407u; /* Or an arbitrary odd constant*/ numsize_t i; numsize_t sz = size * sizeof(reg_t) / sizeof(uint_fast32_t); uint_fast32_t * B = (uint_fast32_t *) A; uint_fast64_t x; uint_fast32_t y; uint_fast32_t z; for (i = 0; i < sz; i++) { x = *refState; uint_fast8_t count = (uint_fast8_t)(x >> 59); *refState = x * multiplier + increment; x ^= x >> 18; x = x >> 27; y = ((uint_fast32_t)x) >> count; z = ((uint_fast32_t)x) << (32 - count); B[i] = y | z; } if (B[size - 1] == 0) B[size - 1] = 1; } static void copystr(_char_t const * const src, _char_t* dest) { numsize_t i = 0; for (i = 0; i < MAXSTRING; ++i) { dest[i] = src[i]; if (dest[i] == 0) return; } } static void test_statistics_collection_ADD(test_statistics_collection * destination_array, test_statistics * result) { void* temp; if (destination_array->capacity == destination_array->count) { destination_array->capacity += 10; temp = (test_statistics**)realloc(destination_array->items, destination_array->capacity * sizeof(test_statistics*)); MY_ASSERT(temp, STR("CAN'T ALLOCATE MEMORY")); destination_array->items = temp; } destination_array->items[destination_array->count] = result; destination_array->count++; } static void test_statistics_collection_CLEAR(test_statistics_collection * array) { for (int i = 0; i < array->count; ++i) { free(array->items[i]); } free(array->items); array->items = NULL; array->capacity = array->count = 0; } void run_test_repeat(_result_t(*unit_test)(CLOCK_T* out_algorithmExecutionTiming, _operationdescriptor*, void* userData), _operationdescriptor* descriptor, _char_t const* const test_description, void* userData, unsigned int repeatCount, double operand1_size, double operand2_size ) { test_statistics * result = (test_statistics*)malloc(sizeof(test_statistics)); MY_ASSERT(result, NOMEM); copystr(test_description, result->test_description); unsigned int j; result->test_result = _OK; LOG_INFO(STR("%s on %s, operand sizes are [%.0f] and [%.0f], repeat [%d] times ..."), test_description, descriptor->implementation_description, operand1_size, operand2_size, repeatCount); CLOCK_T overall = precise_clock(); CLOCK_T cumulative = clock_zero(); CLOCK_T delta = cumulative; CLOCK_T feedbacktimeout = precise_clock(); for (j = 0; j < repeatCount; ++j) { result->test_result = unit_test(&delta, descriptor, userData); if (FAILED(result->test_result)) { break; } cumulative += delta; //assert(delta >= 0); if (seconds_from_clock(precise_clock() - feedbacktimeout) > 5.0) { LOG_INFO(STR("\tIT'S A LONG OPERATION: %d/%d"), j, repeatCount); feedbacktimeout = precise_clock(); } else if (seconds_from_clock(precise_clock() - overall) > MAX_OUTER_TIME_FOR_TESTING_SEC) { LOG_INFO(STR("\tOPERATION TIMEOUT")); break; } } if (FAILED(result->test_result)) { LOG_INFO(STR("...FAILED")); } else { LOG_INFO(STR("...PASSED")); } overall = precise_clock() - overall; result->outer_time_sec = seconds_from_clock(overall); result->inner_time_sec = seconds_from_clock(cumulative); result->number_of_iterations = j; result->operand1_size = operand1_size; result->operand2_size = operand2_size; if (result->inner_time_sec > 0) result->avg_operations_per_second = j / result->inner_time_sec; else result->avg_operations_per_second = 0; test_statistics_collection_ADD(&(descriptor->results), result); LOG_INFO(STR("cumulative inner time: %f sec, outer time: %f sec\n"), result->inner_time_sec, result->outer_time_sec); } void run_test_single(_result_t(*unit_test)(CLOCK_T * out_algorithmExecutionTiming, _operationdescriptor*, void * userData), _operationdescriptor* op, _char_t const * const test_description, void*userData, double operand1_size, double operand2_size) { test_statistics * result = (test_statistics*)malloc(sizeof(test_statistics)); MY_ASSERT(result, NOMEM); copystr(test_description, result->test_description); result->test_result = _OK; LOG_INFO(STR("%s on %s version"), test_description, op->implementation_description); CLOCK_T cumulative = clock_zero(); CLOCK_T overall = precise_clock(); result->test_result = unit_test(&cumulative, op, userData); if (FAILED(result->test_result)) { LOG_INFO(STR("...FAILED")); result->number_of_iterations = 0; } else { LOG_INFO(STR("...PASSED")); result->number_of_iterations = 1; } overall = precise_clock() - overall; result->operand1_size = operand1_size; result->operand2_size = operand2_size; result->outer_time_sec = seconds_from_clock(overall ); result->inner_time_sec = seconds_from_clock(cumulative); if (result->inner_time_sec > 0) result->avg_operations_per_second = result->number_of_iterations / result->inner_time_sec; else result->avg_operations_per_second = 0; test_statistics_collection_ADD(&(op->results), result); LOG_INFO(STR("")); } static int _summary( _char_t const * const impl, _char_t const * const func, test_statistics_collection const *const op, test_statistics_collection const *const referenceOp) { int i; int errCount = 0; for (i = 0; i < op->count; ++i) { struct _test_statistics * item = op->items[i]; struct _test_statistics * reference = referenceOp->items[i]; if (FAILED(item->test_result)) { errCount++; } double relative_inner_time = 0.0; double relative_outer_time = 0.0; if (reference->inner_time_sec != 0) relative_inner_time = item->inner_time_sec / reference->inner_time_sec; if (reference->outer_time_sec != 0) relative_outer_time = item->outer_time_sec / reference->outer_time_sec; _fprintf(stdout, STR("\"%s\"\t\"%s\"\t\"%s\"\t%E\t%E\t%E\t%E\t\"%s\"\t%E\t%E\t%E\t%E\n"), impl, func, item->test_description , item->inner_time_sec, item->outer_time_sec, item->number_of_iterations, item->avg_operations_per_second, (OK(item->test_result) ? STR("ok") : STR("failed")), relative_inner_time, relative_outer_time, item->operand1_size, item->operand2_size ); } return errCount; } int write_opsummary(_char_t * operatordescr, _operationdescriptor* descriptor, size_t count) { int errCount=0; _operationdescriptor* iterator = descriptor; int i ; for(i=0; i< count;++i) { errCount += _summary(iterator->implementation_description, operatordescr, &(iterator->results), &(descriptor->results)); iterator++; } return errCount; } void write_summary() { int errCount = 0; _fprintf(stdout, STR("\"Implementation\"\t\"Operation\"\t\"Test Description\"\t\"Inner Elapsed Seconds\"\t\"Outer Elapsed Seconds\"\t\"Number Of Iterations\"\t\"Average Op Per Second\"\t\"Result\"\t\"Relative inner time\"\t\"Relative outer time\"\t\"Operand1 Size\"\t\"Operand2 Size\"\n")); errCount += write_opsummary(STR("Addition"),arithmetic->sum, arithmetic->sumcount); errCount += write_opsummary(STR("Subtraction"), arithmetic->subtract, arithmetic->subtractcount); errCount += write_opsummary(STR("Multiplication"), arithmetic->multiply, arithmetic->multiplycount); errCount += write_opsummary(STR("Division"), arithmetic->divide, arithmetic->dividecount); _fprintf(stderr, STR("%d ERRORS FOUND"), errCount); } void cleanup_op(_operationdescriptor* descriptor, size_t count) { _operationdescriptor* iterator = descriptor; int i; for(i=0;i<count;++i) { test_statistics_collection_CLEAR(&(descriptor->results)); iterator++; } } void cleanup() { cleanup_op(arithmetic->sum, arithmetic->sumcount); cleanup_op(arithmetic->subtract, arithmetic->subtractcount); cleanup_op(arithmetic->multiply, arithmetic->multiplycount); cleanup_op(arithmetic->divide, arithmetic->dividecount); } #if defined(_WIN32) || defined(WIN32) CLOCK_T precise_clock() { unsigned long long o; if (QueryPerformanceCounter((LARGE_INTEGER*) &o) != 0) { return o; } return clock_zero(); } double seconds_from_clock(CLOCK_T clock) { unsigned long long o; if (QueryPerformanceFrequency( (LARGE_INTEGER*)&o ) == 0)return 0.0; double d = (double)(clock) /(double)o; assert(d >= 0); return d; } CLOCK_T clock_zero() { return 0ULL; } #else #warning maybe you want to define a better clock function CLOCK_T precise_clock() { return clock(); } double seconds_from_clock(CLOCK_T clock) { return clock / CLOCKS_PER_SEC; } CLOCK_T clock_zero() { return 0L; } #endif
C
// // main.c // baodaotanxianDFS // // Created by mingyue on 2022/4/23. // Copyright © 2022 Gmingyue. All rights reserved. // /** 10 10 6 8 1 2 1 0 0 0 0 0 2 3 3 0 2 0 1 2 1 0 1 2 4 0 1 0 1 2 3 2 0 1 3 2 0 0 0 1 2 4 0 0 0 0 0 0 0 0 1 5 3 0 0 1 2 1 0 1 5 4 3 0 0 1 2 3 1 3 6 2 1 0 0 0 3 4 8 9 7 5 0 0 0 0 0 8 7 8 6 0 1 2 0 0 0 0 0 0 0 0 1 0 38 */ #include <stdio.h> int a[51][51]; int book[51][51], n, m, sum; void dfs(int x, int y) { int next[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; int k, tx, ty; for (k = 0; k <= 3; k++) { tx = x + next[k][0]; ty = y + next[k][1]; if (tx < 1 || tx > n || ty < 1 || ty > m) { continue; } if (a[tx][ty] > 0 && book[tx][ty] == 0) { sum++; book[tx][ty] = 1; dfs(tx, ty); } } return; } int main(int argc, const char * argv[]) { int i, j, startX, startY; scanf("%d %d %d %d", &n, &m, &startX, &startY); for (i = 1; i <= n; i++) { for (j = 1; j <= m; j++) { scanf("%d", &a[i][j]); } } book[startX][startY] = 1; sum = 1; dfs(startX, startY); printf("%d\n", sum); getchar();getchar(); return 0; }
C
#include "monty.h" void (*get_function(char *s)) { instruction_t functions[] = { {"push", push}, {"pall", pall}, /*{"pint", pint}, {"pop", pop}, {"swap", swap}, {"add", add}, {"nop", nop},*/ {NULL, NULL} }; int i = 0; char *func; int argument; func = strtok(s, " \n"); while (func != NULL) { printf("From get function: %s\n", func); argument = atoi(strtok(NULL, " \n")); printf("From get fucntion: %d\n", argument); break; } while (functions[i].opcode != NULL) { if (functions[i].opcode == s) return (functions[i].f); i++; } return (NULL); }
C
/*Demo pre and post decrememt of unary operator*/ #include <stdio.h> int main() { int a = 5; int b = 5; printf("Post decrement %d pre decrement %d\n", a--, --b); printf("Post decrement %d pre decrement %d\n", a--, --b); printf("Post decrement %d pre decrement %d\n", a--, --b); printf("Post decrement %d pre decrement %d\n", a--, --b); printf("Post decrement %d pre decrement %d\n", a--, --b); return 0; }
C
/* Author Giuseppe Quartarone mat.: 408661 * Implementazione di un albero binario */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include "tree.h" #define DEBUG fprintf(stderr,"%s\n","eccomi") #define ABORT_1 "out of memory on malloc()" #define MACRO(x,y) if( x == NULL ){ fprintf(stderr,"%s\n",y); exit(EXIT_FAILURE);} #define NewNode new=(node_t *)malloc(sizeof(node_t)); MACRO(new,ABORT_1)\ new->key=(char *)malloc(sizeof(char)*strlen(key)+1); MACRO(new,ABORT_1)\ strcpy(new->key, key); \ new->data=data; \ new->left = NULL; \ new->right = NULL /* Aggiunge un nodo all'albero, se il nodo esiste gia` assegna a ret il suo puntatore. * Restituisce -1 in caso di errore 1 altrimenti */ int addNode(node_t **r, char *key, void *data, node_t **ret ){ node_t *new; node_t *att; att=*r; if(key == NULL || key =='\0') return -1; int i=0; while( att != NULL){ i = strcmp(key, att->key); if(i>0){ if(att->right != NULL ) att=att->right; else{ NewNode; att->right = new; return 1; } } else if(i<0){ if(att->left != NULL) att=att->left; else{ NewNode; att->left = new; return 1; } } else{ *ret=att; return 1; } } NewNode; *r=new; return 1; } /* Elimina un nodo dall'albero, restituice -1 in caso di errore 1 altrimenti */ int delNode(node_t **r, char *key){ if(r == NULL || key == NULL || key == '\0') return -1; node_t *canc, *prec, *att2, *prec2; int i; int type=0; canc=*r; prec=*r; while(canc != NULL && (i=strncmp(key,canc->key,MAXKEYLEN)) != 0){ if(i>0){ prec=canc; canc=canc->right; type=1; } else{ prec=canc; canc=canc->left; type=-1; } } if(canc == NULL) return -1; if(canc->right == NULL && canc->left == NULL){ // un solo nodo free(canc->data); free(canc); if(prec == canc) *r=NULL; return -1; } att2=canc->right; prec2=att2; while(att2->left != NULL){ prec2=att2; att2=att2->left; } att2->left=canc->left; if(prec2 != att2){ prec2->left = NULL; att2->right=canc->right; } if(canc = prec) *r=att2; else{ if(type == 1) prec->right = att2; else prec->left = att2; } free(canc->data); free(canc); return 1; } /* Ricerca un nodo e ne restituisce il suo puntatore, NULL in caso di errore */ node_t *findNode(node_t *r, char *key){ if(r == NULL || key == NULL || key == '\0') return NULL; node_t *att; att=r; int i=0; while( att != NULL && (i=strncmp(key,att->key,MAXKEYLEN)) != 0 ){ if(i>0) att=att->right; else att=att->left; } return att; } /* Stampa l'intero albero */ void printTree(node_t *r){ if(r != NULL){ printf("key: %s\n",r->key); printTree(r->left); printTree(r->right); } }
C
/************************************************************************************* * MIT License * * * * Copyright (C) 2017 Charly Lamothe, Doulkifouli Abdallah-Ali * * * * This file is part of CuttingStockProblem. * * * * Permission is hereby granted, free of charge, to any person obtaining a copy * * of this software and associated documentation files (the "Software"), to deal * * in the Software without restriction, including without limitation the rights * * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * * copies of the Software, and to permit persons to whom the Software is * * furnished to do so, subject to the following conditions: * * * * The above copyright notice and this permission notice shall be included in all * * copies or substantial portions of the Software. * * * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * * SOFTWARE. * *************************************************************************************/ #include "column.h" #include <stdlib.h> #include <string.h> double *column_create(int column_count, double value, int index) { double *column; column = (double *)malloc(column_count * sizeof(double)); memset(column, 0, column_count * sizeof(double)); column[index] = value; return column; } void column_print(double *columns, int column_count, FILE *fd) { int i; for (i = 0; i < column_count; i++) { fprintf(fd, "%f ", columns[i]); } } void columns_matrix_print(double **columns_matrix, int column_count, FILE *fd) { int i; for (i = 0; i < column_count; i++) { column_print(columns_matrix[i], column_count, fd); fprintf(fd, "\n"); } } void columns_matrix_destroy(double **columns_matrix, int column_count) { int i; if (columns_matrix) { for (i = 0; i < column_count; i++) { free((void *)columns_matrix[i]); } free((void *)columns_matrix); } } double **columns_matrix_compute(order **orders, int order_count, int max_width) { double **columns_matrix; int i; columns_matrix = (double **)malloc(order_count * sizeof(double *)); for (i = 0; i < order_count; i++) { if (orders[i]->width > max_width) { printf("[ERROR] Not correctly bound. The width must be less that that the maximal width.\n"); columns_matrix_destroy(columns_matrix, order_count); return NULL; } columns_matrix[i] = column_create(order_count, max_width / orders[i]->width, i); } return columns_matrix; }
C
/* Creator: Oleg Kryachun Date: 02/14/2019 Programming Assignment 3 CSE 222 Summary: This program implements a stack and queue with linked lists. The user can switch between stacks and queue, they can push, pop, or print numbers from the stack and queue. At the end of the program the memory is freed and program exits. */ #include <stdio.h> #include <stdlib.h> #include "stuff.h" int main(){ struct node *stack, *queue; //Initialize stack and queue queue = init(); stack = init(); //Start the program startStack(stack,queue); }
C
/** * @file List.h * @brief Creation of a generic (simply linked) List structure. * * To create a list, one must provide two functions (one function to * compare / order elements, one function to display them). Unlike arrays, * indices begins with 1. */ #ifndef __List_H #define __List_H #include <stdlib.h> #include "status.h" /** Typical simple link structure: a Node is a "value / next" pair * @param val pointer to resource * @param next pointer to next Node, 0 if none */ typedef struct Node { void *val; struct Node *next; } Node; /** Comparison function for list elements. * Must follow the "strcmp" convention: result is negative if e1 is less * than e2, null if they are equal, and positive otherwise. */ typedef int (*compFun) (void* e1, void* e2); /** Display function for list elements */ typedef void(*prFun) (void*); /** The list embeds a counter for its size and the two function pointers */ typedef struct List { int nelts; Node * head; compFun getComp; compFun addComp; prFun pr; } List; /** Empty List creation by dynamic memory allocation (O(1)). * @param getComp comparison function between elements (ala strcmp()) * @param addCompFun comparison function between elements when adding (ala strcmp()) * @param pr display function for list elements * @return a new (empty) list if memory allocation OK * @return 0 otherwise */ List* newList (compFun getCompfun, compFun addCompFun, prFun fun1); /** destroy the list by deallocating used memory (O(N)). * @param l the list to destroy */ void delList (List*); /** get the Nth element of the list (O(N)). * @param l the list * @param n the index of the element in list * @param e (out) the searched element * @return OK if element found * @return ERRINDEX if index out of list bounds */ status nthInList (List*,int,void**); /** add given element to given list according to compFun function (O(N)). * @param l the list (supposedly sorted according to compFun function) * @param e the element to add * @return ERRALLOC if memory allocation failed * @return ERRUNABLE if no comparison function has been provided * @return OK otherwise */ status addList (List*,void*); /** Insert element at a given position in the list (O(N)). * @param l the list to store the element in * @param p the position of the insertion point * @param e the element to insert * @return ERRINDEX if position is out of list bounds * @return ERRALLOC if memory allocation failed * @return OK otherwise */ status addListAt (List*,int,void*); /** remove the element located at a given position in list (O(N)). * @param l the list to remove the element from * @param p the position of the element to remove * @param e (out) the removed element * @return ERRINDEX if position is out of list bounds * @return OK otherwise */ status remFromListAt (List*,int,void**); /** remove given element from given list (O(N)). * implies the user has given a comparison function. * @param l the list to remove the element from * @param e the element to remove * @return ERRABSENT if element is not found in list * @return ERRUNABLE if no comparison function has been provided * @return OK otherwise */ status remFromList (List*,void*); /** display list elements as "[ e1 ... eN ]" (O(N)). * The display of the element is delegated to the prFun function * @param l the list to display. * @return ERRUNABLE if no comparison function has been provided * @return OK otherwise */ status displayList (List*); /** sequencially call given function with each element of given list (O(NxF)). * @param l the list * @param f the function */ void forEach (List*,void(*)(void*)); /** compute and return the number of elements in given list (O(1)). * @param l the list * @return the number of elements in given list */ int lengthList (List*); /** tests whether the list contains given element (O(N)). * @param l the list * @param e the searched element * @return 0 if element is not found in list * @return 1 if element is at the head of the list (no predecessor) * @return (a pointer to) the predecessor of the search element otherwise */ Node* isInList (List*,void*); /** tests whether the list contains given element, using a custom compare (O(N)). * @param list the list * @param pVoid the searched element * @param compareFun the function to compare elements * @return 0 if element is not found in list * @return 1 if element is at the head of the list (no predecessor) * @return (a pointer to) the predecessor of the search element otherwise */ Node *isInListComp(List *list, void *pVoid, compFun compareFun); #endif
C
#include <stdio.h> #include <string.h> #include "Pilha.h" #include "PilhaOperador.h" #include "PilhaOperando.h" double calculadora(double num1, double num2, char op); int ehOperador(char carac); int ehOperando(char carac); int main() { double num1, num2, result; char str[100], op; PilhaOperando* pilhaOperando = inicializaPilhaOperando(); PilhaOperador* pilhaOperador = inicializaPilhaOperador(); scanf("%[^\n]", str); for (int i = 0; i < strlen(str); i++) { result = 0; if (ehOperador(str[i])) pushPilhaOperador(pilhaOperador, str[i]); else if (ehOperando(str[i])) pushPilhaOperando(pilhaOperando, str[i] - 48); else if (str[i] == ')') { num1 = popPilhaOperando(pilhaOperando); num2 = popPilhaOperando(pilhaOperando); op = popPilhaOperador(pilhaOperador); result = calculadora(num1, num2, op); pushPilhaOperando(pilhaOperando, result); } } result = popPilhaOperando(pilhaOperando); printf("%lf\n", result); destroiPilhaOperador(pilhaOperador); destroiPilhaOperando(pilhaOperando); return 0; } double calculadora(double num1, double num2, char op) { if (op == '+') return num1 + num2; if (op == '-') return num1 - num2; if (op == '*') return num1 * num2; if (op == '/') return num1 / num2; } int ehOperador(char carac) { if (carac == '+' || carac == '-' || carac == '*' || carac == '/') return 1; return 0; } int ehOperando(char carac) { if (carac >= '0' && carac <= '9') return 1; return 0; }
C
/********************************************************************************************************************** * FILE DESCRIPTION * -----------------------------------------------------------------------------------------------------------------*/ /** \file Port.c * \brief Port driver * * \details Implemenation of the Port peripheral for TI microcontroller TM4C123GH6PM * * *********************************************************************************************************************/ /********************************************************************************************************************** * INCLUDES *********************************************************************************************************************/ #include "Registers_Ops.h" #include "TM4C123GH6PM_Registers.h" #include "Port.h" /********************************************************************************************************************** * LOCAL MACROS CONSTANT\FUNCTION *********************************************************************************************************************/ #define GET_PORT_BASE_ADDR(port) (PORT_BASE_ADDRESS[port]) /********************************************************************************************************************** * LOCAL DATA *********************************************************************************************************************/ static const uint32 PORT_BASE_ADDRESS[] = { 0x40004000, 0x40005000, 0x40006000, 0x40007000, 0x40024000, 0x40025000 }; /********************************************************************************************************************** * GLOBAL DATA *********************************************************************************************************************/ /********************************************************************************************************************** * LOCAL FUNCTION PROTOTYPES *********************************************************************************************************************/ /********************************************************************************************************************** * LOCAL FUNCTIONS *********************************************************************************************************************/ /********************************************************************************************************************** * GLOBAL FUNCTIONS *********************************************************************************************************************/ /****************************************************************************** * \Syntax : void Port_Init (void) * \Description : This function intialize the GPIO module * * \Sync\Async : Synchronous * \Reentrancy : Non Reentrant * \Parameters (in) : None * \Parameters (out): None * \Return value: : None *******************************************************************************/ void Port_Init() { uint8 u8PortNumber; uint8 u8PinPosition; uint8 u8LoopIndex; for(u8LoopIndex = 0; u8LoopIndex < PORT_PIN_CFG_SIZE; u8LoopIndex++) { u8PortNumber = Port_PinConfig[u8LoopIndex].u8Pin / 8; u8PinPosition = Port_PinConfig[u8LoopIndex].u8Pin % 8; /* Configure pin direction */ if(PORT_DIR_OUTPUT == Port_PinConfig[u8LoopIndex].u8PinDirection) { SET_BIT_REG(GPIODIR(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); } else if(PORT_DIR_INPUT == Port_PinConfig[u8LoopIndex].u8PinDirection) { CLR_BIT_REG(GPIODIR(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); } /* Configure port mode */ if(PORT_PIN_MODE_DIO != Port_PinConfig[u8LoopIndex].u8PinMode) { SET_BIT_REG(GPIOAFSEL(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); GPIOPCTL(GET_PORT_BASE_ADDR(u8PortNumber)) = GPIOPCTL(GET_PORT_BASE_ADDR(u8PortNumber)) | (Port_PinConfig[u8LoopIndex].u8PinMode << (4 * u8PinPosition)); } else { CLR_BIT_REG(GPIOAFSEL(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); } /* Set current */ switch (Port_PinConfig[u8LoopIndex].u8PinCurrent) { case PORT_PIN_2mA: SET_BIT_REG(GPIOR2R(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); break; case PORT_PIN_4mA: SET_BIT_REG(GPIOR4R(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); break; case PORT_PIN_8mA: SET_BIT_REG(GPIOR8R(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); break; default: break; } /* Set attach mode */ switch (Port_PinConfig[u8LoopIndex].u8PinAttach) { case PORT_ATTACH_PULLUP: SET_BIT_REG(GPIOPUR(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); break; case PORT_ATTACH_PULLDOWN: SET_BIT_REG(GPIOPDR(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); break; case PORT_ATTACH_OPENDRAIN: SET_BIT_REG(GPIOODR(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); break; default: break; } /* Enable GPIO digital I/O */ SET_BIT_REG(GPIODEN(GET_PORT_BASE_ADDR(u8PortNumber)) , u8PinPosition); } } /********************************************************************************************************************** * END OF FILE: Port.c *********************************************************************************************************************/
C
#include <stdio.h> #include <string.h> void palindromeDetactor(int n){ while (n--) { char s[10005]; int prev_ans = 0; scanf("%s" , s); for(int i = 0; i < strlen(s); i++){ int j = 0; int count_odd = 1; int count_even = 0; //odd while (i + j < strlen(s) && i - j >= 0) { if(s[i - j] == s[i + j]){ count_odd += 2; j++; } else break; } //even if(s[i] == s[i + 1]) count_even = 2; j = 0; while (s[i] == s[i + 1] && i + j + 1 < strlen(s) && i - j >= 0){ if(s[i - j] == s[i + j + 1]){ count_even += 2; j++; } else break; } //to get the longest palindrome if(count_even > count_odd){ if(prev_ans < count_even){ prev_ans = count_even; } } else{ if(prev_ans < count_odd){ prev_ans = count_odd; } } } printf("%d\n" , prev_ans - 2); } } int main(){ int n; scanf("%d" , &n); palindromeDetactor(n); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define CELULA_X 1 #define CELULA_Y 2 #define CELULA_NADA 0 typedef struct tabuleiro{ int dados[9]; }t_tabuleiro; t_tabuleiro cria_tabuleiro(){ int i; t_tabuleiro tab; for(i = 0; i< 9; i++){ tab.dados[i] = CELULA_NADA; } return tab; } void mostrar_tabuleiro(t_tabuleiro tab){ int i; for(i=0; i <=2; i++){ int dado = tab.dados[i]; if(dado == CELULA_X){ printf("X"); } if(dado == CELULA_Y){ printf("O"); } if(dado == CELULA_NADA){ printf("_"); } } printf("\n"); for(i=3; i <=5; i++){ int dado = tab.dados[i]; if(dado == CELULA_X){ printf("X"); } if(dado == CELULA_Y){ printf("O"); } if(dado == CELULA_NADA){ printf("_"); } } printf("\n"); for(i=6; i <=8; i++){ int dado = tab.dados[i]; if(dado == CELULA_X){ printf("X"); } if(dado == CELULA_Y){ printf("O"); } if(dado == CELULA_NADA){ printf("_"); } } printf("\n"); } void jogada_jogador(t_tabuleiro * tab){ int posicao; while(1){ printf("\nEscolha a posicao de 0 a 8: "); scanf("%d", &posicao); if(posicao >= 9 || tab->dados[posicao] != CELULA_NADA ){ printf("Posicao invalida selecione outra posicao"); } else { printf("Sua opcao foi colocada!\n"); tab->dados[posicao] = CELULA_X; break; } } } void jogada_computador(t_tabuleiro * tab){ int posicao; int r = rand() % 9; while(1){ if(tab->dados[r] == CELULA_NADA){ tab->dados[r] = CELULA_Y; break; }else { r = rand() % 9; } } } int verifica_ganhou_para(t_tabuleiro tab, int i){ if(tab.dados[0] == i && tab.dados[1] == i &&tab.dados[2] == i ){ return 1; } if(tab.dados[3] == i && tab.dados[4] == i &&tab.dados[5] == i ){ return 1; } if(tab.dados[6] == i && tab.dados[7] == i &&tab.dados[8] == i ){ return 1; } if(tab.dados[0] == i && tab.dados[4] == i &&tab.dados[8] == i ){ return 1; } if(tab.dados[2] == i && tab.dados[4] == i &&tab.dados[6] == i ){ return 1; } if(tab.dados[0] == i && tab.dados[3] == i &&tab.dados[6] == i ){ return 1; } if(tab.dados[1] == i && tab.dados[4] == i &&tab.dados[7] == i ){ return 1; } if(tab.dados[2] == i && tab.dados[5] == i &&tab.dados[8] == i ){ return 1; } return 0; } int verifica_velha(t_tabuleiro tab){ int i; for(i = 0;i<9; i++){ if(tab.dados[i] == CELULA_NADA){ return 0; } } return 1; } int verifica_acabou(t_tabuleiro tab){ if(verifica_ganhou_para(tab, CELULA_X)){ printf("parabens ganhou do bot no rng");//kkkkj return 1; } else if(verifica_ganhou_para(tab, CELULA_Y)){ printf("parabens perdeu do bot no rng");//kkkkjsoftint return 1; } else{ if(verifica_velha(tab)){ printf("todo mundo perdeu");//kkkkjsoftint return 1; } } return 0; } int main(void) { t_tabuleiro tab; tab = cria_tabuleiro(); srand(time(NULL)); mostrar_tabuleiro(tab); while(1){ jogada_jogador(&tab); mostrar_tabuleiro(tab); if(verifica_acabou(tab)){ break; } printf("\n================\n"); jogada_computador(&tab); mostrar_tabuleiro(tab); if(verifica_acabou(tab)){ break; } } return 0; }
C
/* ** EPITECH PROJECT, 2019 ** libmy ** File description: ** \nHello -> \0AHello */ #include "my.h" void showstr(char const *str) { for (int i = 0; str[i] != '\0'; i++) { if (str[i] < '!' || str[i] > '~') { my_putchar('\\'); if (str[i] < 16) { my_putchar('0'); } putnbr_base(str[i], "0123456789ABCDEF"); } else { my_putchar(str[i]); } } }
C
#include<stdio.h> int main() { int i,j,m,n; int mat[10][10]; printf("enter the num of rows:"); scanf("%d",&m); printf("enter the num of columns:"); scanf("%d",&n); printf("enter the elements of your matrix\n"); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { printf("\n mat[%d][%d]=",i,j); scanf("%d",&mat[i][j]); } } printf("the entered matrix is:\n"); for(i=1;i<=m;i++) { for(j=1;j<=n;j++) { printf("%d\t",mat[i][j]); } printf("\n\n"); } return 0; }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> struct foo { int a; char b; long c; struct rcu_head rcu; }; DEFINE_SPINLOCK(foo_mutex); struct foo __rcu *gbl_foo; void foo_update_a(int new_a) { struct foo *new_fp; struct foo *old_fp; new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL); spin_lock(&foo_mutex); old_fp = rcu_dereference_protected(gbl_foo, lockdep_is_held(&foo_mutex)); *new_fp = *old_fp; new_fp->a = new_a; rcu_assign_pointer(gbl_foo, new_fp); spin_unlock(&foo_mutex); synchronize_rcu(); kfree(old_fp); } int foo_get_a(void) { int retval; rcu_read_lock(); retval = rcu_dereference(gbl_foo)->a; rcu_read_unlock(); return retval; } void foo_reclaim(struct rcu_head *rp) { struct foo *fp = container_of(rp, struct foo, rcu); kfree(fp); } void foo_update_a2(int new_a) { struct foo *new_fp; struct foo *old_fp; new_fp = kmalloc(sizeof(*new_fp), GFP_KERNEL); spin_lock(&foo_mutex); old_fp = rcu_dereference_protected(gbl_foo, lockdep_is_held(&foo_mutex)); *new_fp = *old_fp; new_fp->a = new_a; rcu_assign_pointer(gbl_foo, new_fp); spin_unlock(&foo_mutex); call_rcu(&old_fp->rcu, foo_reclaim); } MODULE_LICENSE("Dual BSD/GPL"); static int rcu_test_init(void) { int a = 0; gbl_foo = kmalloc(sizeof(struct foo), GFP_KERNEL); foo_update_a2(1); a = foo_get_a(); printk(KERN_ALERT "rcu_test enter, %d\n", a); return 0; } static void rcu_test_exit(void) { printk(KERN_ALERT "rcu_test exit\n"); } module_init(rcu_test_init); module_exit(rcu_test_exit); MODULE_AUTHOR("mishuang"); MODULE_DESCRIPTION("A Sample Hello World Module"); MODULE_ALIAS("A Sample module");
C
/*compile-errors:*/ /*compile-result:1*/ /*save-event:compile*/ #include<stdio.h> int main() { int year; scanf("%d",&year);//accepting input if(year%4==0)//checking divisibility by 4 {/*divisible by 4*/ if(year%100==0) {/*divisible by 100*/ if(year%400==0) {/*divisible by 400*/ printf("Leap Year"); } else/*not divisible by 400 but by 4,100*/ { printf("Not Leap Year"); } } else {/*divisible by 4 but not by 100*/ printf("Leap Year"); } } else {/*not divisible by 4*/ printf("Not Leap Year"); } return 0; }
C
/**************************************************************************************************/ /* Copyright (C) mc2lab.com, SSE@USTC, 2014-2015 */ /* */ /* FILE NAME : menu.c */ /* PRINCIPAL AUTHOR : Mengning */ /* SUBSYSTEM NAME : menu */ /* MODULE NAME : menu */ /* LANGUAGE : C */ /* TARGET ENVIRONMENT : ANY */ /* DATE OF FIRST RELEASE : 2014/08/31 */ /* DESCRIPTION : This is a menu program */ /**************************************************************************************************/ /* * Revision log: * * Created by Mengning, 2014/08/31 * */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "linktable.h" #include "menu.h" tLinkTable * head = NULL; int Help(); int Quit(); #define CMD_MAX_LEN 1024 #define CMD_MAX_ARGV_NUM 32 #define DESC_LEN 1024 #define CMD_NUM 10 char prompt[CMD_MAX_LEN] = "Input Cmd >"; /* data struct and its operations */ typedef struct DataNode { tLinkTableNode * pNext; char* cmd; char* desc; int (*handler)(int argc, char *argv[]); } tDataNode; int SearchConditon(tLinkTableNode * pLinkTableNode,void * arg) { char * cmd = (char*)arg; tDataNode * pNode = (tDataNode *)pLinkTableNode; if(strcmp(pNode->cmd, cmd) == 0) { return SUCCESS; } return FAILURE; } /* find a cmd in the linklist and return the datanode pointer */ tDataNode* FindCmd(tLinkTable * head, char * cmd) { tDataNode * pNode = (tDataNode*)GetLinkTableHead(head); while(pNode != NULL) { if(!strcmp(pNode->cmd, cmd)) { return pNode; } pNode = (tDataNode*)GetNextLinkTableNode(head,(tLinkTableNode *)pNode); } return NULL; } /* show all cmd in listlist */ int ShowAllCmd(tLinkTable * head) { tDataNode * pNode = (tDataNode*)GetLinkTableHead(head); while(pNode != NULL) { printf(" * %s - %s\n", pNode->cmd, pNode->desc); pNode = (tDataNode*)GetNextLinkTableNode(head,(tLinkTableNode *)pNode); } return 0; } int Help(int argc, char *argv[]) { ShowAllCmd(head); return 0; } int SetPrompt(char * p) { if (p == NULL) { return 0; } strcpy(prompt,p); return 0; } /* add cmd to menu */ int MenuConfig(char * cmd, char * desc, int (*handler)(int, char **)) { tDataNode* pNode = NULL; if ( head == NULL) { head = CreateLinkTable(); pNode = (tDataNode*)malloc(sizeof(tDataNode)); pNode->cmd = "help"; pNode->desc = "Menu List"; pNode->handler = Help; AddLinkTableNode(head,(tLinkTableNode *)pNode); } pNode = (tDataNode*)malloc(sizeof(tDataNode)); pNode->cmd = cmd; pNode->desc = desc; pNode->handler = handler; AddLinkTableNode(head,(tLinkTableNode *)pNode); return 0; } /* Menu Engine Execute */ int ExecuteMenu() { /* cmd line begins */ while(1) { int argc = 0; char *argv[CMD_MAX_ARGV_NUM]; char cmd[CMD_MAX_LEN]; char *pcmd = NULL; printf("%s",prompt); /* scanf("%s", cmd); */ pcmd = fgets(cmd, CMD_MAX_LEN, stdin); if(pcmd == NULL) { continue; } /* convert cmd to argc/argv */ pcmd = strtok(pcmd," "); while(pcmd != NULL && argc < CMD_MAX_ARGV_NUM) { argv[argc] = pcmd; argc++; pcmd = strtok(NULL," "); } if(argc == 1) { int len = strlen(argv[0]); *(argv[0] + len - 1) = '\0'; } tDataNode *p = (tDataNode*)SearchLinkTableNode(head,SearchConditon,(void*)argv[0]); if( p == NULL) { continue; } printf("%s - %s\n", p->cmd, p->desc); if(p->handler != NULL) { p->handler(argc, argv); } } }
C
/** * * @file recuperaInfoR.c * * @brief Código que recuera la información de los recursos, crea un cola de ellos * @author AAFR */ #include "cac3.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int recuperaInfoRC(char * sarchivo); void liberaR(PRecurso pr); PRecurso creaR(int id, int estado_id, int municipio_id, int localidad_id, double lat, double lon, char * stipo); PRecurso insertaR(PRecurso pr, int id, int estado_id, int municipio_id, int localidad_id, double lat, double lon, char * stipo); PRecurso PRr = NULL; int cuentaRec; /** * @brief Función que recupera los recursos * @param sarchivo * @return */ int recuperaInfoRC(char * sarchivo) { cuentaRec = 0; PRecurso pr = PRr; int id, edo_id, mun_id, loc_id; double lat, lon; char stipo[20]; FILE *fh = fopen(sarchivo, "r"); while (!feof(fh)) { if (fscanf(fh, "%d %d %d %lf %lf %s %d", &edo_id, &mun_id, &loc_id, &lat, &lon, stipo, &id) != 7) break; if (pr == NULL && PRr == NULL) { PRr = creaR(id, edo_id, mun_id, loc_id, lat, lon, stipo); pr = PRr; } else { pr = insertaR(pr, id, edo_id, mun_id, loc_id, lat, lon, stipo); } } printf("cuentaRec: %d\n", cuentaRec); fclose(fh); return cuentaRec; } /** * @brief Función que inserta un recurso al final de la Cola de Recursos * @param pr * @param id * @param estado_id * @param municipio_id * @param localidad_id * @param lat * @param lon * @param stipo * @return PRecurso Puntero al recurso insertado */ PRecurso insertaR(PRecurso pr, int id, int estado_id, int municipio_id, int localidad_id, double lat, double lon, char * stipo) { pr->Pnext = creaR(id, estado_id, municipio_id, localidad_id, lat, lon, stipo); return pr->Pnext; } /** * @brief Función que crea un nodo Recurso * @param id * @param estado_id * @param municipio_id * @param localidad_id * @param lat * @param lon * @param stipo * @return */ PRecurso creaR(int id, int estado_id, int municipio_id, int localidad_id, double lat, double lon, char * stipo) { PRecurso pr = (PRecurso) malloc(sizeof (Recurso)); cuentaRec++; pr->id = id; pr->estado_id = estado_id; pr->municipio_id = municipio_id; pr->localidad_id = localidad_id; pr->lat = M_PI * lat / 180.0; pr->lon = M_PI * lon / 180.0; pr->stipo_infra = malloc(strlen(stipo) * sizeof (char)); strcpy(pr->stipo_infra, stipo); pr->Pnext = NULL; return pr; } /** * @brief Función que libera los recursos * @param pr */ void liberaR(PRecurso pr) { if (pr != NULL) { free(pr->stipo_infra); liberaR(pr->Pnext); cuentaRec--; free(pr); } }
C
#include <stdio.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> mode_t sixFourFour(); /* * FILE* fdopen(int fd, const char *mode); */ int main(int argc, char** argv) { if(argc != 2) { fprintf(stderr, "usage: ./fdopen <path>\n"); return 1; } int fd = open(argv[1], O_RDWR | O_CREAT, sixFourFour()); if(fd == -1) { perror("open"); return 1; } FILE *stream = fdopen(fd, "r+"); if(stream == NULL) { perror("fdopen"); return 1; } if(fclose(stream) != 0) { perror("fclose"); return 1; } } mode_t sixFourFour() { return S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; }
C
/* Encoder Card Interface. Sends commands (RF) via encoder card. Ported to QNX 4.01 3/31/92 by Eil. */ #include <assert.h> #include <conio.h> #include <i86.h> #include <sounds.h> #define CMD_DISCRETE 0 #define CMD_DATA_LSB 0x40 #define CMD_DATA_MSB 0x80 void strobe(unsigned int address, unsigned int data, int mode) { outp(0x3E8, (unsigned char)(address | ((data & 3) << 6))); outp(0x3E9, (unsigned char)(((data >> 2) & 0x3F) | (mode & 0xC0))); outp(0x3EA, 2); /* Key Xmit */ delay(150); /* Let xmitter come to full power */ outp(0x3EA, 3); /* Key Xmit + Larse */ delay(10); outp(0x3EA, 2); /* Key Xmit - Larse */ delay(150); /* Make sure command is transmitted */ outp(0x3EA, 0); /* Unkey Xmit */ } void send_cmd(unsigned int address, unsigned int data, int nbytes) { assert(nbytes == 1 || nbytes == 2); if (nbytes == 1) strobe(address, data, CMD_DISCRETE); else { strobe(address, data & 0xFF, CMD_DATA_LSB); strobe(address, (data>>8) & 0xFF, CMD_DATA_MSB); } PASS_TUNE; } void init_8255(void) { /* Initialize 8255 */ outp(0x3EB, 0x88); outp(0x3EA, 0); } /*int main(void) { unsigned int address, data; address = 027; for (data = 0;; data++) { if (kbhit()) break; send_cmd(address, data, 2); printf("Address: %o Data %04X\n", address, data); } while (kbhit()) getch(); } */
C
#include <winsock2.h> #include <stdio.h> #define PORT 1355 #define LEN 256 int main () { WSADATA wsaData; SOCKET ss; sockaddr_in in,from; char buf[LEN] = {0}; int namelen, len; WSAStartup(MAKEWORD(2,2), &wsaData); ss = socket(AF_INET, SOCK_DGRAM, 0); memset (&in, 0, sizeof(in)); in.sin_family = AF_INET; in.sin_port = htons(PORT); in.sin_addr.s_addr = inet_addr("127.0.0.1"); bind(ss, (sockaddr *)&in, sizeof(in)); memset (&from, 0, sizeof(from)); namelen = sizeof(from); /* recv buf */ len = recvfrom(ss, buf, LEN, 0, (sockaddr *)&from, &namelen); printf ("Recv:%s\n", buf); /* send buf */ sendto(ss, buf, sizeof(buf), 0, (sockaddr *)&from, sizeof(from)); WSACleanup(); }
C
/* ** EPITECH PROJECT, 2019 ** my_strdup.c ** File description: ** Dups a string */ #include <stdlib.h> #include "libmy.h" char *my_strdup(char *src) { char *dest = malloc(sizeof(char) * my_strlen(src) + 1); if (dest == NULL) return (NULL); my_strcpy(dest, src); return (dest); }
C
int printMatrix (float (*arrin), int dimx,int dimy){ int n = 0; int m = 0; for (n = 0; n < dimx ; n++){ for (m = 0 ; m < dimy ; m++){ printf("%8.3f ",arrin[dimy*n+m]); } printf("\n"); } return 0; } int ge_fw(float *matrix , int row, int col,float *matrix_out){ int w = 0; int i = 0; int small; int cycle = 0; float scale = 1; int check = 0; float *temp; temp = (float*)malloc(sizeof(float)*row*col); if (row>col){ small = col; } else { small = row; } if (matrix_out == NULL){ return -1; } if (matrix == NULL){ return -1; } if(sizeof(matrix[0]) != sizeof(float)){ return -1; } for (w=0; w < row;w++){ for (i = 0; i<col; i++){ matrix_out[w*col + i] = (float)matrix[w*col + i]; } } while (0==0) { for (w = cycle;w < row;w++){ if (matrix_out[w*col + cycle] != 0){ for (i=0; i< col;i++){ temp[w*col + i] = matrix_out[cycle*col + i]; } for (i= 0; i < col; i++){ matrix_out[cycle*col + i] = matrix_out[w*col + i]; } for (i=0;i<col; i++){ matrix_out[w*col +i] = temp[w*col + i]; } } } for (w = cycle+1; w < row;w++){ if (matrix_out[w*col + cycle]!=0){ scale = matrix_out[w*col + cycle]/matrix_out[cycle*col + cycle]; for (i=0;i<col;i++){ matrix_out[w*col + i] = matrix_out[w*col +i] -(scale*matrix_out[cycle*col + i]); } } } cycle = cycle + 1; if (cycle >= small){ free(temp); return 1; } } } int ge_bw(float *matrix , int row, int col,float *matrix_out){ int w = 0; int i = 0; int rank = 0; int cycle = 0; int check = 0; int small = 0; float scale = 1; float *temp; if (matrix_out == NULL){ return -1; } if (matrix == NULL){ return -1; } if(sizeof(matrix_out[0]) != sizeof(float)){ return -1; } temp = (float*)malloc(sizeof(float)*row*col); if (row>col){ small = col; } else { small = row; } for (w=0; w < row ;w++){ for (i = 0; i<col; i++){ matrix_out[w*col +i] = matrix[w*col +i]; } } for (w=0; w < row ;w++){ for (i = 0; i<col; i++){ if (matrix_out[w*col + i]>0){ if (matrix_out[w*col + i]<0.001){ matrix_out[w*col + i] = 0; } } else{ if (matrix_out[w*col + i]>-0.001){ matrix_out[w*col + i] = 0; } } matrix_out[w*col + i] = (float)matrix_out[w*col + i]; } } for (i=0;i<small;i++){ if (matrix_out[i*col +i] != 0){ rank = rank + 1; } } if (rank==0){ return -1; } while (0==0) { if (matrix_out[(rank-1)*col + (rank-1)] != 1){ scale = matrix_out[(rank-1)*col + (rank-1)]; for (i=0; i<col;i++){ matrix_out[(rank-1)*col +i] = matrix_out[(rank-1)*col +i]/scale ; } } for (w = rank-1; 0 < w;w = w-1){ if (matrix_out[(w-1)*col + (rank-1)]!=0){ scale = matrix_out[(w-1)*col + rank -1]; for (i=0;i<col;i++){ matrix_out[(w-1)*col + i] = matrix_out[(w-1)*col +i] -(scale*(matrix_out[(rank-1)*col + i])); } } } rank = rank - 1; if (rank == 0){ free(temp); return 0; } } }
C
#include "Header files/mesh.h" #include "Header files/matrix.h" #include <assert.h> #include <stdio.h> #include <stdlib.h> #include <math.h> vertex* meshNewVertex(mesh* M, float x, float y, float z) { // Luo uuden verteksin (pisteen avaruudessa) ja liittää sen malliin. // Tarkistaa, että malli ei ole tyhjä. assert(M != NULL); vertex* V = malloc(sizeof(vertex)); V->coords = newMatrix(4, 1); V->coords->values[0][0] = x; V->coords->values[1][0] = y; V->coords->values[2][0] = z; V->coords->values[3][0] = 1; V->world = NULL; V->NDC = NULL; V->window = NULL; V->next = NULL; V->prev = NULL; addVertex(M, V); return V; } void deleteVertex(vertex* V) { // Poistaa verteksin, tarkistaa, että annettu osoitin ei ole tyhjä. assert(V != NULL); vertex* Vnext = V->next; vertex* Vprev = V->prev; if(Vnext != NULL) { Vnext->prev = Vprev; } if(Vprev != NULL) { Vprev->next = Vnext; } deleteMatrix(V->coords); if(V->world != NULL) { deleteMatrix(V->world); } if(V->NDC != NULL) { deleteMatrix(V->NDC); } if(V->window != NULL) { deleteMatrix(V->window); } free(V); } polygon* meshNewPolygon(mesh* M, vertex* A, vertex* B, vertex* C) { // Luo uuden polygonin (kolmio kolmiulotteisessa avaruudessa). Tarkistaa, // että malli tai annetut pisteet eivät ole tyhjiä. assert(M != NULL && A != NULL && B != NULL && C != NULL); polygon* P = malloc(sizeof(polygon)); P->verts[0] = A; P->verts[1] = B; P->verts[2] = C; P->color = 0x00ffffff; P->normal = calculatePolygonNormal(P); P->next = NULL; P->prev = NULL; addPolygon(M, P); return P; } void deletePolygon(polygon* P) { // Poistaa polygonin, tarkistaa, että annettu osoitin ei ole tyhjä. assert(P != NULL); polygon* Pnext = P->next; polygon* Pprev = P->prev; if(Pnext != NULL) { Pnext->prev = Pprev; } if(Pprev != NULL) { Pprev->next = Pnext; } deleteMatrix(P->normal); free(P); } void setPolygonColor(polygon* P, Uint32 color) { // Asettaa polygonin värin, color-argumentti jakautuu neljään // kahdeksan bitin osaan, jotka kuvaavat punaisen, vihreän, // sinisen ja alpha-kanavan astetta. // Tarkistaa, että annettu polygoni ei ole tyhjä. assert(P != NULL); P->color = color; } matrix* calculatePolygonNormal(polygon* P) { // Laskee polygonin normaalin ja sijoittaa sen polygonin keskelle. // Verteksien tulee olla määritelty myötäpäivään pinnan normaalin // suhteen. Tarkistaa, että osoitin ei ole tyhjä. assert(P != NULL); matrix* u = newMatrix(3,1); matrix* v = newMatrix(3,1); // Määritellään vektorit u ja v, jotka määrittävät tason u->values[0][0] = P->verts[1]->coords->values[0][0] - P->verts[0]->coords->values[0][0]; u->values[1][0] = P->verts[1]->coords->values[1][0] - P->verts[0]->coords->values[1][0]; u->values[2][0] = P->verts[1]->coords->values[2][0] - P->verts[0]->coords->values[2][0]; v->values[0][0] = P->verts[2]->coords->values[0][0] - P->verts[0]->coords->values[0][0]; v->values[1][0] = P->verts[2]->coords->values[1][0] - P->verts[0]->coords->values[1][0]; v->values[2][0] = P->verts[2]->coords->values[2][0] - P->verts[0]->coords->values[2][0]; // Lasketaan normaali matrix* normal = newMatrix(4, 1); normal->values[0][0] = -u->values[1][0]*v->values[2][0] + u->values[2][0]*v->values[1][0]; normal->values[1][0] = -u->values[2][0]*v->values[0][0] + u->values[0][0]*v->values[2][0]; normal->values[2][0] = -u->values[0][0]*v->values[1][0] + u->values[1][0]*v->values[0][0]; normal->values[3][0] = 1; deleteMatrix(u); deleteMatrix(v); return normal; } matrix* calculatePolygonWorldNormal(polygon* P) { // Laskee polygonin normaalin tila-avaruudessa (world space) ja // sijoittaa sen polygonin keskelle. Verteksien tulee olla // määritelty myötäpäivään pinnan normaalin suhteen. Tarkistaa, // että osoitin ei ole tyhjä. assert(P != NULL); matrix* u = newMatrix(3,1); matrix* v = newMatrix(3,1); // Määritellään vektorit u ja v, jotka määrittävät tason u->values[0][0] = P->verts[1]->world->values[0][0] - P->verts[0]->world->values[0][0]; u->values[1][0] = P->verts[1]->world->values[1][0] - P->verts[0]->world->values[1][0]; u->values[2][0] = P->verts[1]->world->values[2][0] - P->verts[0]->world->values[2][0]; v->values[0][0] = P->verts[2]->world->values[0][0] - P->verts[0]->world->values[0][0]; v->values[1][0] = P->verts[2]->world->values[1][0] - P->verts[0]->world->values[1][0]; v->values[2][0] = P->verts[2]->world->values[2][0] - P->verts[0]->world->values[2][0]; // Lasketaan normaali matrix* normal = newMatrix(4, 1); normal->values[0][0] = -u->values[1][0]*v->values[2][0] + u->values[2][0]*v->values[1][0]; normal->values[1][0] = -u->values[2][0]*v->values[0][0] + u->values[0][0]*v->values[2][0]; normal->values[2][0] = -u->values[0][0]*v->values[1][0] + u->values[1][0]*v->values[0][0]; normal->values[3][0] = 1; deleteMatrix(u); deleteMatrix(v); return normal; } void calculateWorldCoordinates(polygon* P, matrix* worldTransform) { // Laskee polygonin verteksien oikeat koordinaatit globaalissa // avaruudessa. Tarkistaa, että annetut osoittimet eivät ole // tyhjiä. assert(P != NULL && worldTransform != NULL); int i = 0; for(i ; i < 3 ; i++) { // Poistetaan edellinen world-koordinaattivektori if(P->verts[i]->world != NULL) { deleteMatrix(P->verts[i]->world); P->verts[i]->world = NULL; } // Muunnetaan koordinaatit tila-avaruuteen (world space) P->verts[i]->world = matrixMultiply(worldTransform, P->verts[i]->coords); } } void calculateNormalizedDeviceCoordinates(polygon* P, matrix* fullTransform) { // Laskee polygonin verteksien koordinaatit näytöllä // (NDC = Normalized Device Coordinates). Tarkistaa, // että annetut osoittimet eivät ole tyhjiä. assert(P != NULL && fullTransform != NULL); int i = 0; for(i ; i < 3 ; i++) { // Poistetaan edellinen NDC-koordinaattivektori if(P->verts[i]->NDC != NULL) { deleteMatrix(P->verts[i]->NDC); P->verts[i]->NDC = NULL; } // Muunnetaan koordinaatit leikkausavaruuteen (clip space) P->verts[i]->NDC = matrixMultiply(fullTransform, P->verts[i]->coords); // Koordinaattien palauttaminen w = 1 avaruuteen, // ns. "Perspective divide" matrixMultiplyScalar(P->verts[i]->NDC, 1.0/P->verts[i]->NDC->values[3][0]); } } void deleteMesh(mesh* M) { // Poistaa mallin poistamalla kaikki sen polygonit ja verteksit. // Tarkistaa, että malli ei ole tyhjä. assert(M != NULL); polygon* P = M->polygons; while(P != NULL) { deletePolygon(P); P = P->next; } vertex* V = M->vertices; while(V != NULL) { deleteVertex(V); V = V->next; } free(M); } void addPolygon(mesh* M, polygon* P) { // Lisää polygonin P malliin M lisäämällä sen linkitetyn listan ensimmäiseksi. // Tarkistaa, että malli ja polygoni eivät ole tyhjiä. assert(M != NULL && P != NULL); polygon* P0 = M->polygons; if(P0 != NULL) { P0->prev = P; P->next = P0; } M->polygons = P; } void addVertex(mesh* M, vertex* V) { // Lisää verteksin V malliin M lisäämällä sen linkitetyn listan ensimmäiseksi. // Tarkistaa, että malli ja verteksi eivät ole tyhjiä. assert(M != NULL && V != NULL); vertex* V0 = M->vertices; if(V0 != NULL) { V0->prev = V; V->next = V0; } M->vertices = V; } vertex* meshGetVertex(mesh* M, int n) { // Palauttaa n:nnen verteksin mallin M verteksilistasta. Jos // n on suurempi kuin verteksien lukumäärä, palauttaa tyhjän osoittimen. // Jos n = 0, palauttaa viimeiseksi lisätyn. Tarkistaa, että malli // ei ole tyhjä ja n on positiivinen. assert(M != NULL && n >= 0); vertex* V = M->vertices; int i = 0; while(i < n) { if(V != NULL) { V = V->next; i++; } } return V; }
C
/* 二つの値を交換する関数形式マクロ */ #include<stdio.h> //(* ここに解答を書き加える *) #define swap(type, a,b) {type t; t = a; a = b; b = t;} int main(void) { int na,nb; puts("二つの整数を入力せよ."); printf("整数A:"); scanf("%d", &na); printf("整数B:"); scanf("%d", &nb); swap(int, na, nb); puts("\nAとBの値を交換"); printf("整数A=%d\n", na); printf("整数B=%d\n", nb); return (0); }
C
#include <fcntl.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> unsigned int len = 0; /* 1.用户输入数据 2.将输入数据保存至 file_1.txt 3.用户输入复制数据长度 4.将用户指定长度的数据从 file_1.txt 复制到 file_2.txt */ int main(void) { char file_name1[10] = {0}; char file_name2[10] = {0}; scanf("%s%s", file_name1, file_name2); // 1.打开两个文件 // 待复制文件1(只读) int fd1; fd1 = open(file_name1, O_RDONLY); if (fd1 == -1) { perror("open file1 failed"); return 1; } // 新文件2(复制文件。只写,不存在则创建,存在则清空) int fd2; fd2 = open(file_name2, O_WRONLY | O_CREAT | O_TRUNC, 0777); if (fd2 == -1) { perror("open file2 failed"); return 2; } // 2. 读取文件1,写入到文件2。循环多次操作。 char r_buf[100]; int n_read; while (1) { bzero(r_buf, sizeof(r_buf)); n_read = read(fd1, r_buf, sizeof(r_buf)); //读取100个字节(可能存在数据0('\0')) write(fd2, r_buf, n_read); if (n_read == 0) //如果成功读取到0个字节,说明已经读完该文件 { printf("Done\n"); break; } } //写入所有读取到的字节数(包括'\0') // 3.关闭两个文件 close(fd1); close(fd2); return 0; }
C
/// Obstacle (header) /// (c) 2017 Jani Nykänen #ifndef __OBSTACLE__ #define __OBSTACLE__ #include "../engine/sprite.h" #include "../engine/vector.h" #include "player.h" #include "stdbool.h" /// Obstacle object typedef struct { float x; /// X coordinate float y; /// Y coordinate VEC2 speed; /// Speed float startY; /// Starting y position float timer; /// Timer for special behavior SPRITE spr; /// Sprite int id; /// Obstacle id bool show; /// Is the object be drawn bool playZap; /// Play zap int dropping; /// If an apple } OBSCTALE; /// Init global obstacle variables void init_obstacles(); /// Remove obstacles from the screen void clear_obstacles(); /// Create a new obstacle /// < x X coordinate /// < y Y coordinate /// < id Obstacle id /// > A new plant OBSCTALE create_obstacle(float x, float y, int id); /// Get player collision /// < o Obstacle /// < pl Player void obs_on_player_collision(OBSCTALE* o, PLAYER* pl); /// Swap direction collision, horizontal /// < o Obstacle /// < x X coordinate /// < y Y coordinate /// < w Width /// < h Height void obs_swap_dir_horizontal(OBSCTALE* o, float x, float y, float w, float h); /// Swap direction collision, vertical /// < o Obstacle /// < x X coordinate /// < y Y coordinate /// < w Width /// < h Height void obs_swap_dir_vertical(OBSCTALE* o, float x, float y, float w, float h); /// Update an obstacle /// < o Obstacle to update /// > tm Time multiplier void obs_update(OBSCTALE* o, float tm); /// Draw an obstacle /// < o Obstacle to draw void obs_draw(OBSCTALE* o); #endif // __OBSTACLE__
C
/******************************************************************************* * Filename: file_utils.c * Author: Maxwell Goldberg * Last Modified: 03.17.17 * Description: Provides utilities for validating plain/ciphertext and key text * files. *******************************************************************************/ #include "file_utils.h" /******************************************************************************* * Function: validateFileReg() * Description: Determines whether or not a file is a regular file. * Parameters: struct stat *buf - A pointer to the file's filled in stat * struct. * Preconditions: None. * Returns: 0 if the file is a regular file, -1 otherwise. *******************************************************************************/ int validateFileReg(struct stat *buf) { /* Test the struct pointer */ if (!buf) { fprintf(stderr, "getFileSize: NULL FILE ptr arg\n"); return -1; } /* Use the POSIX S_ISREG macro to determine file regularity */ if (!S_ISREG(buf->st_mode)) { fprintf(stderr, "getFileSize: Not a regular file\n"); return -1; } return 0; } /******************************************************************************* * Function: validateFileChars() * Description: Validates the characters in a file. Files must contain only * upper case letters, spaces, and at most one POSIX line feed * at the end of the file. Determines the number of non-line feed * characters in the file. * Parameters: FILE *fptr - The file pointer. * Preconditions: None. * Returns: -1 if invalid characters are present. A nonnegative integer * representing the number of characters, otherwise. *******************************************************************************/ int validateFileChars(FILE *fptr) { int c; int count = 0; int newlineFound = 0; /* Test the file pointer */ if (!fptr) { fprintf(stderr, "validateFileChars: NULL FILE ptr arg\n"); return -1; } /* Increment the pointer until we hit EOF, storing each char in c */ while ((c = fgetc(fptr)) != EOF) { /* If we've found a newline before EOF, the newline is invalid. */ if (newlineFound) { fprintf(stderr, "Error: Input contains bad characters\n"); return -1; } if (c == '\n') { newlineFound = 1; } else { count++; } /* If the char isn't valid, return immediately */ if (!isupper(c) && c != ' ' && c != '\n') { fprintf(stderr, "Error: Input contains bad characters\n"); return -1; } } /* Check the final error value generated by fgetc to make sure we didn't * attempt to read past the maximum filestream offset */ if (ferror(fptr) != 0) { perror("validateFileChars: fgetc"); return -1; } /* Rewind the file pointer to the begining of the file */ rewind(fptr); return count; } /******************************************************************************* * Function: validateFile() * Description: Validates a single file. * Parameters: FILE *fptr - A pointer to the file. * Preconditions: None. * Returns: The number of non-line feed chars in the file on success, -1 * otherwise. *******************************************************************************/ int validateFile(FILE *fptr) { struct stat buf = {0}; int fd, size, status; /* Test the file pointer */ if (!fptr) { fprintf(stderr, "validateFile: NULL ptr argument\n"); return -1; } /* Get the file descriptor */ fd = fileno(fptr); if (fd == -1) { perror("getFileSize: fileno"); return -1; } /* Inform the stat struct */ status = fstat(fd, &buf); if (status == -1) { perror("getFileSize: fstat"); return -1; } /* Test file regularity */ status = validateFileReg(&buf); if (size == -1) { return -1; } /* Validate file characters */ size = validateFileChars(fptr); if (size == -1) { return -1; } return size; } /******************************************************************************* * Function: validateFiles() * Description: Validates text and key files, storing the number of characters * to be processed in each file in integers passed by pointer. * Parameters: FILE *ptextPtr - The text file pointer. * FILE *keyPtr - The key file pointer. * int *ptextSize - The text file size pointer. * int *keySize - The key file size pointer. * Preconditions: None. * Returns: 0 on success, -1 otherwise. *******************************************************************************/ int validateFiles(FILE *ptextPtr, FILE *keyPtr, int *ptextSize, int *keySize) { int status; /* Validate the text file */ *ptextSize = validateFile(ptextPtr); if (*ptextSize == -1) { return -1; } /* Validate the key file */ *keySize = validateFile(keyPtr); if (*keySize == -1) { return -1; } /* Ensure the key file has at least as many chars as the text file */ if (*ptextSize > *keySize) { fprintf(stderr, "Error: key is too short\n"); return -1; } return 0; }
C
#include <stdio.h> #include <string.h> void main() { int deptno, id; char ch; printf("Enter the id"); scanf("%d", &id); printf("Enter the deptNo"); scanf("%d",&deptno); printf("Enter designation code"); scanf("%c",&ch); ch=getchar(); printf("Employee with employee id %d",id); printf("is working in "); switch(deptno) { case 10: printf("\"Marketing\""); break; case 20: printf("\"Management\""); break; case 30: printf("\"Sales\" "); break; case 40: printf("\"Designing\" "); break; default: printf("\"No Exist\" "); } printf("Department as"); switch (ch) { case 'M': printf("\"Manager\" "); break; case 'S': printf("\"Supervisor\" "); break; case 's': printf("\"Security Officer\" "); break; case 'C': printf("\"Clerk\" "); break; default: printf("\"No Exist\" "); } }
C
#include <stdio.h> #include <math.h> int main() { int p,q,z; printf("Enter an Number & Power: "); scanf("%d %d",&p,&q); z= pow(p,q); printf("%d",z); }
C
#ifndef FILESYS_INODE_H #define FILESYS_INODE_H #include <stdbool.h> #include "filesys/off_t.h" #include "devices/block.h" #include "threads/synch.h" typedef struct buffer_block { void* data; bool free; bool dirty; bool accessed; block_sector_t sector; struct lock lock; } buffer_block; void buffer_init(void); void buffer_read(block_sector_t sector, void* buffer, int offset, int size); void buffer_write(block_sector_t sector, void* buffer, int offset, int size); void buffer_flush(void); int get_buffer_hit(void); int get_buffer_ac(void); /* On-disk inode. Must be exactly BLOCK_SECTOR_SIZE bytes long. */ struct inode_disk { int is_dir; /* Indicate whether inode is a directory. 1 = true; 0 otherwise.*/ off_t length; /* File size in bytes. */ unsigned magic; /* Magic number. */ block_sector_t direct[123]; /* Direct pointers. */ block_sector_t indirect; /* Indirect pointer. */ block_sector_t doubly_indirect; /* Doubly-indirect pointer. */ }; /* In-memory inode. */ struct inode { struct list_elem elem; /* Element in inode list. */ block_sector_t sector; /* Sector number of disk location. */ int open_cnt; /* Number of openers. */ bool removed; /* True if deleted, false otherwise. */ int deny_write_cnt; /* 0: writes ok, >0: deny writes. */ struct lock inode_lock; }; struct bitmap; void inode_init(void); bool inode_create(block_sector_t, off_t, int is_dir); struct inode* inode_open(block_sector_t); struct inode* inode_reopen(struct inode*); block_sector_t inode_get_inumber(const struct inode*); void inode_close(struct inode*); void inode_remove(struct inode*); off_t inode_read_at(struct inode*, void*, off_t size, off_t offset); off_t inode_write_at(struct inode*, const void*, off_t size, off_t offset); void inode_deny_write(struct inode*); void inode_allow_write(struct inode*); off_t inode_length(const struct inode*); bool inode_is_dir(struct inode* inode); #endif /* filesys/inode.h */
C
#include "common.h" #include <sys/stat.h> #include <fcntl.h> #include <dirent.h> int main(void) { DIR *pdir = NULL; struct dirent *p = NULL; pdir = opendir("."); if(pdir == NULL) err_sys("opendir error"); p = readdir(pdir); while(p != NULL) { printf("%s ", p->d_name); struct stat st; if(stat(p->d_name, &st) < 0) err_sys("stat error"); printf("%ld ", st.st_size); if(S_ISREG(st.st_mode)) printf("-\n"); if(S_ISDIR(st.st_mode)) printf("d\n"); p = readdir(pdir); } closedir(pdir); return 0; }
C
/****************************************************************************** * Filename: getAllMedicine.c * Author: 雷瑞祺 * License: MIT License * Purpose: handle get all medicine http request ******************************************************************************/ #include "database.h" #include <stdio.h> #include <stdlib.h> #include <sqlite3.h> #include <glib-object.h> #include <json-glib/json-glib.h> int post_exec(void *data, int col_count, char** col_contents, char** col_names) { JsonBuilder* builder = (JsonBuilder*)data; json_builder_begin_object(builder); while(col_count--) { json_builder_set_member_name(builder, *col_names); if((!strcmp(*col_names, "id")) || (!strcmp(*col_names, "number"))) { json_builder_add_int_value(builder, atoll(*col_contents)); } else if(!strcmp(*col_names, "price")) { json_builder_add_double_value(builder, atof(*col_contents)); } else { json_builder_add_string_value(builder, *col_contents); } col_names++, col_contents++; } json_builder_end_object(builder); return 0; } int main(int argc, char **argv) { sqlite3 *db; char *err_msg = NULL; int ret_code = 0; JsonBuilder *builder; JsonGenerator *generator; JsonNode *root_node; gchar* str; puts("Content-type: application/json\n"); ret_code = sqlite3_open(DATABASE, &db); if(ret_code) { fprintf(stderr, "Failed to open SQLite Database: %s\n", sqlite3_errmsg(db)); return 1; } builder = json_builder_new(); json_builder_begin_array(builder); ret_code = sqlite3_exec(db, "SELECT * FROM medicine", post_exec, builder, &err_msg); if(ret_code) { fprintf(stderr, "Failed to eval SQL: %s\n", err_msg); sqlite3_free(err_msg); return 1; } sqlite3_close(db); json_builder_end_array(builder); generator = json_generator_new(); root_node = json_builder_get_root(builder); json_generator_set_root(generator, root_node); str = json_generator_to_data(generator, 0); puts(str); g_free(str); json_node_free(root_node); g_object_unref(generator); g_object_unref(builder); return 0; }
C
/* * Migrated to Discover: Ta Quang Trung * Date: Nov 08, 2020 */ #include "discover.h" int* x,y; void f(int *m){ __assert_must_alias(m,&y); int *n; if(y==1){ n=&y; f(n); } } int main(){ x=&y; f(x); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/socket.h> #include <sys/types.h> #include <arpa/inet.h> #include <netinet/in.h> /* Thing to Research */ int main(int argc, char* agrv[]) { char address[] = "172.17.0.1"; // Creating a Socket int network_socket; // socket(domain of socket (generally AF_INET, a constant), TCP socket, protocol) network_socket = socket(AF_INET, SOCK_STREAM, 0); // Specifying an Address for the Socket (Address family is same as parameter one of socket()) struct sockaddr_in server_address; server_address.sin_family = AF_INET; // Specify the port, 9002 is random high port to avoid conflicts server_address.sin_port = htons(9001); // server_address holds information about the address // sin_addr is a structure itself that holds lots of data // s_addr is the real server address // INADDR_ANY is synonymous with 0.0.0.0 server_address.sin_addr.s_addr = inet_addr(address); // Returns an integer for error handling int connection_status = connect(network_socket, (struct sockaddr *) &server_address, sizeof(server_address)); // Error Handling if (connection_status == -1) { printf("There was an error making a connection to the remote socket.\n\n"); } // If we send data, we receive a response from the server in recv char server_response[256]; recv(network_socket, &server_response, sizeof(server_response), 0); // Printing the Server's Response printf("The server responded with: %s\n", server_response); // Avoiding data leaks close(network_socket); return 0; }
C
#include "delay.h" // 10ms for 12Mhz void Delay10mS(INT16U cnt) { while(cnt--) { Delay1mS(10); } } // 1ms for 12Mhz void Delay1mS(INT16U cnt) { INT16U i; while(cnt--) { for(i = 0;i < 705;i ++) { asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); } } } // 10us for 16Mhz void Delay10us(INT16U cnt) { INT16U i; while(cnt--) { for(i = 0;i < 20;i ++) { asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); asm("nop"); //asm("nop"); } } } // 1us for 16Mhz void Delay1us(INT16U cnt) { INT16U i; while(cnt--) { for(i = 0;i < 2;i ++) { asm("nop"); asm("nop"); asm("nop"); asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); //asm("nop"); } } }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> typedef uint8_t BYTE; BYTE buffer[512] = {0}; int main(int argc, char *argv[]) { //check for correct usage if (argc != 2) { fprintf(stderr, "Usage: recover filename\n"); return 1; } //save file name char *infile = argv[1]; //open memory card FILE *inptr = fopen(infile, "r"); //check if file can be open if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 2; } FILE *outptr = NULL; char filename[8]; int count = 0; //repeat until end of card: while (fread(buffer, 512, 1, inptr) == 1) { //check for JPEG if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) { if (outptr != NULL) { fclose(outptr); } sprintf(filename, "%03i.jpg", count); outptr = fopen(filename, "w"); count++; if (outptr != NULL) { fwrite(buffer, 512, 1, outptr); } } else { if (outptr != NULL) { fwrite(buffer, 512, 1, outptr); } } } fclose(inptr); fclose(outptr); return 0; }
C
#include<stdio.h> int main() { int a = 3; int b = 5; if(a>0) printf("3\n"); else printf("5"); return 0; }
C
/* Author: lmborba */ #include <stdio.h> #include <stdlib.h> typedef struct TURTLE { int nt; char nome[256]; } turtle; typedef struct LIST { turtle * turtl; struct LIST * next; } lturtle; void inserelista(turtle ** turt, lturtle ** lturt) { lturtle * aux; aux = (lturtle *) malloc(sizeof(lturtle)); aux->turtl = *turt; aux->next = *(lturt); *(lturt) = aux; return (void) 0; }; void limpalista(lturtle ** lturt, int b) { lturtle * aux, * aux2; aux = *(lturt); while (aux != NULL) { aux2 = aux; aux = aux->next; if (b) { free(aux2->turtl); }; free(aux2); }; *lturt = NULL; }; void deleteitem(lturtle * anterior) { lturtle * aux; aux = anterior->next; anterior->next = (anterior->next)->next; free(aux); }; turtle ** procurastr(char a[256],lturtle * lturt) { lturtle * aux; int i; for (aux = lturt;aux != NULL;aux = aux->next) { for (i=0;((a[i] == ((aux->turtl)->nome)[i]) && (a[i] != 0) && (((aux->turtl)->nome)[i] != 0));i++); if ((a[i] == 0) && (((aux->turtl)->nome)[i] == 0)) { return &(aux->turtl); }; }; return NULL; }; int main() { int i,j; int n,d; lturtle * aux2, * aux3; turtle * aux; lturtle * lista; lturtle * lista2; lturtle * lista3; lturtle * ant; lista = NULL; lista2 = NULL; lista3 = NULL; char str[256]; scanf("%d",&n); for (i=0;i<n;i++) { scanf("%d",&d); limpalista(&lista,1); limpalista(&lista2,0); fgets(str,256,stdin); for (j=0;j<d;j++) { aux = (turtle *) malloc(sizeof(turtle)); aux->nt = 0; fgets(aux->nome,256,stdin); inserelista(&aux,&(lista)); }; for (j=0;j<d;j++) { fgets(str,256,stdin); inserelista(procurastr(str,lista),&lista2); (lista2->turtl)->nt = j; }; aux2 = lista; aux3 = lista2; ant = NULL; while (aux2 != NULL) { if (aux3->turtl == aux2->turtl) { aux3 = aux3->next; }; aux2 = aux2->next; }; while(aux3 != NULL) { printf("%s",(aux3->turtl)->nome); aux3 = aux3->next; }; printf("\n"); }; return 0; };
C
/* // Sample code to perform I/O: #include <stdio.h> int main(){ int num; scanf("%d", &num); // Reading input from STDIN printf("Input number is %d.\n", num); // Writing output to STDOUT } // Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail */ // Write your code here #include <stdio.h> #include <stdlib.h> #include <string.h> int fillzeros(int num) { int power = 1; while(num > 0) { num = num/2; power *= 2; } return power; } void build(int tree[],int num,int n) { for(int i = 0;i < n;i++) { if(i < num) { tree[n + i - 1] = 1; } else { tree[n + i - 1] = 0; } } for(int i = n - 2;i >= 0;i--) { tree[i] = tree[2*i + 1] + tree[2*i + 2]; } } void printtree(int arr[],int n) { for(int i = 0;i < n;i++) { printf("%d ",arr[i]); } printf("\n"); } void update(int tree[],int n,int index) { if(tree[n + index - 1] == 0) { return ; } tree[n + index - 1] = 0; int parent = ((n + index - 2))/2; while(parent > 0) { tree[parent] -= 1; parent = (parent - 1)/2; } tree[0] -= 1; } int kthone(int tree[],int n,int k,int start,int end,int root) { if(k > tree[root] || start < 0 || end > n - 1) { return -1; } else if(k == tree[root] && start == end) { return end; } int mid = (start + end)/2; if(k > tree[2*root + 1]) { int right = kthone(tree,n,k - tree[2*root+1],mid+1,end,2*root+2); return right; } else { int left = kthone(tree,n,k,start,mid,2*root+1); return left; } } int main() { int num; scanf("%d",&num); int n = fillzeros(num); int *tree = malloc(sizeof(int)*(4*n)); build(tree,num,n); //printtree(tree,2*n-1); int queries; scanf("%d",&queries); while(queries--) { int query; scanf("%d",&query); if(query == 0) { int x; scanf("%d",&x); update(tree,n,x - 1); //printtree(tree,2*n - 1); } else { int x; scanf("%d",&x); int index = kthone(tree,n,x,0,n-1,0); if(index != -1) { printf("%d\n",index + 1); } else { printf("-1\n"); } } } return 0; }
C
/** * Projekt: Implementace interpretu imperativního jazyka IFJ14 */ /** * @file parserexpression.c * @author Martin Nosek (xnosek10) * @brief Zdrojový soubor pro parsovaní výrazu */ #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "parser.h" #include "parserexpression.h" #include "globalvariables.h" #include "tokens.h" #include "scanner.h" #include "errors.h" #include "3ak.h" #include "bst.h" #include "memoryallocation2.h" #include <limits.h> #define RULE_MAX_L 3 #define NUMBER_OF_RULES 17 typedef struct { sElemPtr Act; sElemPtr First; } tStack; void oInsertFirst(operListT *O){ O->next = operList; operList = O; } void oDeleteFirst(){ switch(operList->data->type) { case STRING_VARIABLE: if (operList->data->value.index >= actualFunction->stringVarCount && operList->data->value.index < stringCounter) --stringCounter; break; case REAL_VARIABLE: if (operList->data->value.index >= actualFunction->realVarCount && operList->data->value.index < realCounter) --realCounter; break; case INT_VARIABLE: if (operList->data->value.index >= actualFunction->intVarCount && operList->data->value.index < intCounter) --intCounter; break; default: break; } operList = operList->next; } void eInitStack (tStack *S) { S->Act = NULL; S->First = NULL; } /** * @brief Vyprázdní zásobník */ void eDisposeStack (tStack *S) { removeDSElem(INT_MAX); S->First = NULL; S->Act = NULL; } /** * @brief Vloží prvek s hodnotou val na vrchol zásobníku */ void eInsertFirst(tStack *S, int val){ sElemPtr newItem = getDSElem(1); newItem->data = val; newItem->ptr = S->First; S->First = newItem; } /** * @brief vymaže prvek zásobníku nejblíže vrcholu */ void eDeleteFirst (tStack *S) { if(S->First == NULL) return; S->First = S->First->ptr; removeDSElem(1); } /** * @brief Vrací terminál na zásobníku nejblíže vrcholu */ tokenTypeT top(tStack *S){ sElemPtr isterminal; isterminal = S->First; do { if((isterminal->data) > TOKENS_COUNT) isterminal = isterminal->ptr; else return (isterminal->data); }while(isterminal != NULL); errCode = SYNTAX_ERROR; fatalError("Syntakticka chyba\n"); } /** * @brief vrátí transformovanou hodnotu tokenu pro precedenční tabulku */ int transformTokenIndex(int x){ if (x<ID) { return x-1; }else if (x<INTEGER_TYPE) { return ID - 1; }else { return ID; } } /** * @brief vrátí true v případě, že na zásobníku je spracovatelný podvýraz */ bool expressionTop(tStack *S){ S->Act = S->First; if (S->Act->data == LEFT) return false; do{ if (S->Act->ptr->data == LEFT) return true; if (S->Act->ptr->data == DOLLAR) return false; S->Act = S->Act->ptr; }while(S->Act->data != DOLLAR); return false; } /** * @brief Vrátí true v případě, že operandy jsou kompaktibilní */ bool isCompatibleOper(operListT* op1, operListT* op2, int i){ if(i == 1 || i == 4 || i == 5) return((i==4 && op1->type == STRING_TYPE && op2->type == STRING_TYPE)||((op1->type == INTEGER_TYPE || op1->type == REAL_TYPE)&&(op2->type == INTEGER_TYPE||op2->type == REAL_TYPE))); else if(i == 2) return((op1->type == INTEGER_TYPE || op1->type == REAL_TYPE)&&(op2->type == INTEGER_TYPE||op2->type == REAL_TYPE)); else if( i>7 && i<14) return(op1->type == op2->type); else return((op1->type == op2->type)&&(op1->type == BOOLEAN_TYPE)); } void insertCode(instructionT instruction, operListT *op1, operListT *op2, operListT *dest){ last3ak->next = getDTAC(1); last3ak = last3ak->next; last3ak->instruction = instruction; if(op1 != NULL) last3ak->op1.varInfo = op1->data; if(op2 != NULL) last3ak->op2.varInfo = op2->data; if(dest != NULL) last3ak->dest.varInfo = dest->data; } /** * @brief Generuje kód pomocí funkce insertCode na základě aplikovaného pravidla */ void generateCode(int i){ operListT *op1 = NULL; operListT *op2 = NULL; switch(i){ case 0://NOT op1 = operList; if(op1->type != BOOLEAN_TYPE) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - NOT E\n"); } else { operListT* dest; if(op1->data->type == INT_CONSTANT) { dest = createOperBoolConst(!op1->data->value.intVal); } else { dest = createOperType(BOOLEAN_TYPE); insertCode(I_NOT, op1, op2, dest); } oDeleteFirst(); oInsertFirst(dest); } return; case 1://MULTIPLY op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E * E\n"); } else { oDeleteFirst(); oDeleteFirst(); operListT* dest; dest = (op1->type==REAL_TYPE||op2->type==REAL_TYPE) ? createOperType(REAL_TYPE) : createOperType(INTEGER_TYPE); insertCode(I_MULT, op1, op2, dest); oInsertFirst(dest); } return; case 2://DIVIDE op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E / E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(REAL_TYPE); oInsertFirst(dest); insertCode(I_DIV, op1, op2, dest); } return; case 3://AND op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E AND E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_AND, op1, op2, dest); } return; case 4://PLUS op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E + E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = (op1->type==REAL_TYPE||op2->type==REAL_TYPE) ? createOperType(REAL_TYPE) : ( op1->type == STRING_TYPE ? createOperType(STRING_TYPE) : createOperType(INTEGER_TYPE) ); oInsertFirst(dest); insertCode(I_ADD, op1, op2, dest); } return; case 5://MINUS op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - %s - %s\n", tokenRewrite[op1->type], tokenRewrite[op2->type]); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = (op1->type==REAL_TYPE||op2->type==REAL_TYPE) ? createOperType(REAL_TYPE) : createOperType(INTEGER_TYPE); oInsertFirst(dest); insertCode(I_SUB, op1, op2, dest); } return; case 6://OR op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E OR E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_OR, op1, op2, dest); } return; case 7://XOR op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E XOR E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_XOR, op1, op2, dest); } return; case 8://EQUAL op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E = E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_EQUAL, op1, op2, dest); } return; case 9://LESS op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E < E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_LESS, op1, op2, dest); } return; case 10://MORE op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E > E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_MORE, op1, op2, dest); } return; case 11://NOT_EQUAL op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E <> E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_NOT_EQUAL, op1, op2, dest); } return; case 12://LESS_OR_EQUAL op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E <= E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_LESS_OR_EQUAL, op1, op2, dest); } return; case 13://MORE_OR_EQUAL op2 = operList; op1 = op2->next; if(!isCompatibleOper(op1,op2,i)) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - E >= E\n"); } else { operListT* dest; oDeleteFirst(); oDeleteFirst(); dest = createOperType(BOOLEAN_TYPE); oInsertFirst(dest); insertCode(I_MORE_OR_EQUAL, op1, op2, dest); } return; case 16://unarni minus op1 = operList; if(op1->type != INTEGER_TYPE && op1->type != REAL_TYPE) { errCode = TYPE_ERROR; fatalError("Semantic error - uncompatible types - Unarni minus\n"); } else { operListT* dest; if(op1->data->type == INT_CONSTANT||op1->data->type == REAL_CONSTANT) { dest = (op1->data->type == INT_CONSTANT) ? createOperIntConst(op1->data->value.intVal * (-1)) : createOperRealConst(op1->data->value.realVal * (-1)); } else { op2 = createOperIntConst(0); dest = (op1->type == INTEGER_TYPE) ? createOperType(INTEGER_TYPE) : createOperType(REAL_TYPE); insertCode(I_SUB, op2, op1, dest); } oDeleteFirst(); oInsertFirst(dest); } return; default://PARENTHESIS nebo ID nejaky error return; } return; } /** * @brief Vrací true v případě, že transformace výrazu je v pravidlech. Zároveň generuje kód */ bool isInRules(tStack *S){ char stack[RULE_MAX_L+1]; stack[RULE_MAX_L] = '\0'; int x=RULE_MAX_L; S->Act = S->First; do{ --x; stack[x] = S->Act->data; S->Act = S->Act->ptr; }while (S->Act->data!=LEFT); for (int i = 0; i < NUMBER_OF_RULES; ++i) { if(!strcmp(&(stack[x]),expressionRuleTable[i])){ generateCode(i); return true; } } return false; } /** * @brief Vrátí true v případě, že funkce má správný počet správných parametrů */ bool validParameters(paramListItemT* params){ operListT * pom; if(params == NULL) pom = NULL; else { pom = createOperTypeEmpty(params->type); oInsertFirst(pom); } if(isExpression(pom)) { if(actToken.type == RIGHT_PARENTHESIS && params->next == NULL) return true; if(actToken.type == RIGHT_PARENTHESIS && params->next != NULL) { errCode = TYPE_ERROR; fatalError("Semantic error - malý počet parametrů\n"); } if(actToken.type == COMMA) { getToken(); return validParameters(params->next); } else return false; } else { return false; } } /** * @brief Vrátí true v případě, že příchozí posloupnost tokenů tvoří funkci */ bool isFunction(STFunctionT* function){ getToken(); if(actToken.type == RIGHT_PARENTHESIS) // funkce bez parametru { if(function->params->next != NULL) // pokud mela mit parametry { errCode = TYPE_ERROR; fatalError("Funkce se vola s nedostatecnym poctem parametru\n"); } return true; } return (validParameters(function->params->next)); } void insertCallCode(STFunctionT * function) { if(!isFunction(function)){ errCode = SYNTAX_ERROR; fatalError("Syntax error - chyba volani funkce\n"); } //generovani kodu pro I_CALL last3ak->next = getDTAC(1); last3ak = last3ak->next; last3ak->op1.function = function; paramListItemT* params = function->params->next; parameterT * parameters = NULL; parameterT * tmpPar; while(params != NULL) { tmpPar = getDParameter(1); tmpPar->next = parameters; tmpPar->data = operList->data; oDeleteFirst(); parameters = tmpPar; params = params->next; } last3ak->op2.parameters = parameters; if(!(strcmp(function->name, "length"))) { last3ak->instruction = I_CALL_LENGTH; last3ak->op1.varInfo = last3ak->op2.parameters->data; } else if(!(strcmp(function->name, "sort"))) last3ak->instruction = I_CALL_SORT; else if(!(strcmp(function->name, "find"))) last3ak->instruction = I_CALL_FIND; else if(!(strcmp(function->name, "copy"))) last3ak->instruction = I_CALL_COPY; else last3ak->instruction = I_CALL; operListT * pomOper = createOperType(function->params->type); last3ak->dest.varInfo = pomOper->data; oInsertFirst(pomOper); getToken(); // RIGHT_PARENTHESIS } //******************************************************** bool isExpression(operListT * retOper){ tStack stackE; eInitStack(&stackE); eInsertFirst(&stackE, DOLLAR); int a,b; do{ a = top(&stackE); b = actToken.type; int topTerminalS = transformTokenIndex(a); //topTerminalS hodnota terminálu na zásobníku nejblíže vrcholu pro precedenční tabulku int inToken = transformTokenIndex(b); //inToken hodnota tokenu pro precedencni tabulku if (precedentialTable[topTerminalS][inToken]==MIDDLE)//PÁROVÁNÍ ZÁVOREK { eInsertFirst(&stackE,b); getToken(); } else if (precedentialTable[topTerminalS][inToken]==LEFT)//SHIFT { if(inToken == ID-1) { operListT * pomOper = createOper(); if(pomOper==NULL) { STFunctionT * pomFunc = findFunction(actToken.value.idVal, functionTable); if(pomFunc == NULL) { errCode = UNDEFINED_ID; fatalError("Pokus o zavolani nedefinovane promenne.\n"); } else { getToken(); if(actToken.type == LEFT_PARENTHESIS) { insertCallCode(pomFunc); } else { errCode = 5; //TD fatalError("Semantic error"); } } } else if(b == ID) { char * name = actToken.value.idVal; getToken(); if(actToken.type == LEFT_PARENTHESIS) { STFunctionT * pomFunc = findFunction(name, functionTable); if(pomFunc == NULL) { errCode = UNDEFINED_ID; fatalError("Semantic error - volam funkci \"%s\", ktera neni definovana\n", name); } else { insertCallCode(pomFunc); } } else oInsertFirst(pomOper); } else { oInsertFirst(pomOper); getToken(); } eInsertFirst(&stackE, LEFT); eInsertFirst(&stackE, ID); } else { if(stackE.First->data == E) { int c = stackE.First->data; eDeleteFirst(&stackE); eInsertFirst(&stackE,LEFT); eInsertFirst(&stackE,c); eInsertFirst(&stackE,actToken.type); } else { eInsertFirst(&stackE, LEFT); eInsertFirst(&stackE, actToken.type); } getToken(); } } else if (precedentialTable[topTerminalS][inToken]==RIGHT)//APLIKACE PRAVIDLA { if(stackE.First->data != E && actToken.type == MINUS && stackE.First->data != ID) { eInsertFirst(&stackE, LEFT); eInsertFirst(&stackE, actToken.type); getToken(); } else { if (isInRules(&stackE)) { //vypis promennou globalnipromennapravidla – ergo vypiš nejpravější derivaci while(stackE.First->data != LEFT){ eDeleteFirst(&stackE); } stackE.First->data = E; } else { errCode = SYNTAX_ERROR; fatalError("Syntax error1\n"); } } } else if(precedentialTable[topTerminalS][inToken]==BLANK)//CHYBÍ PRECEDENČNÍ PRAVIDLO { errCode = SYNTAX_ERROR; fatalError("%s\nSyntax error2\n", tokenRewrite[actToken.type]); } else if(precedentialTable[topTerminalS][inToken]==FUNC) { break; } else { errCode = 99; fatalError("Unexpected fault - Expression parser\n"); } } while (top(&stackE) != TOKENS_COUNT || actToken.type < INTEGER_TYPE); if(retOper == NULL) { errCode = TYPE_ERROR; fatalError("Semantic error - nepsravny počet parametrů\n"); } if(retOper->type == ID) // muze to byt jakykoliv typ { retOper->type = operList->type; } else if(operList->type !=retOper->type) { errCode = TYPE_ERROR; fatalError("Nestejne typy pro prirazeni\n ocekavan: %s\n zadan: %s\n", tokenRewrite[retOper->type], tokenRewrite[operList->type]); } retOper->data = operList->data; // prehodim data u operandu oDeleteFirst(); return true; }
C
#include <conio.h> #include <stdio.h> #include <math.h> int main () { float x, fx, y, fy, z, a, a1, a2, a3; printf("enter x, y and z\n"); printf("x: "); scanf("%f", &fx); printf("y: "); scanf("%f", &y); printf("z: "); scanf("%f", &fy); x = fx*pow(10, -2); y = fy*pow(10, 3); a1 = pow(2, -x); a2 = sqrt(x+pow(fabs(y), 1/4)); a3 = pow(exp(x-1/sin(z)), 1/3); a = a1*a2*a3; // if (a == 1.26185) { printf("\nALL CORRECT\n\n"); } else { printf("ERROR \n"); //alexandr korolev } // printf("a = %f \n", a); getch(); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #define MAX 2 int main() { FILE *fp1, *fp2; int buf[MAX] = {10, 15}; fp1 = fopen("pap1.txt","w+"); fp2 = fopen("pap2.txt","w+"); fprintf(fp2,"%d%d",10,15); fwrite(buf,MAX,2,fp1); fclose(fp1); fclose(fp2); return 0; }
C
#include <stdio.h> int main(){ float x; for (x=0;x<=10;x++){ printf("%-3f | ",x); } puts("\n--------------------------------------------"); for (x=0;x<=10;x++){ printf("%+-3f | ",1/x); }}
C
#include<stdio.h> #include<stdlib.h> #include<time.h> int* intrev(int* src, int slen){ int* dst = src; int left = 0; int right = slen - 1; while(left <= right){ int tmp = src[left]; src[left] = src[right]; src[right] = tmp; left++; right--; } return dst; } int* plusOne(int* digits, int digitsSize, int* returnSize){ int* result = malloc(sizeof(int) * (digitsSize + 1)); int carry = 0; int cnt = 0; int i = digitsSize - 1, j = 0; while(i >= 0 || j >=0){ int bit1 = 0; if(i >= 0){ bit1 = digits[i--]; } int bit2 = 0; if(j >= 0){ bit2 = 1; j--; } int bit = (bit1 + bit2) % 10 + carry; carry = (bit1 + bit2) / 10; if(bit >= 10){ carry++; bit = bit % 10; } printf("%d %d %d %d\n", bit1, bit2, bit, carry); result[cnt++] = bit; } if(carry > 0){ result[cnt++] = carry; } *returnSize = cnt; intrev(result, cnt); return result; } int main(int argc, char* argv[]){ int* digits; int nums = 10; if(argc > 1){ nums = argc - 1; } digits = malloc(sizeof(int) * nums); if(argc > 1){ for(int i=0; i<nums; i++){ *(digits+i) = atoi(argv[i+1]); } } else { srand((unsigned)time(0)); for(int i=0; i<nums; i++){ *(digits+i) = rand() % 10; } } for(int i=0; i<nums; i++){ printf("%d ", *(digits+i)); } printf("\n"); int returnSize = 0; int* returns = plusOne(digits, nums, &returnSize); printf("%d \n", returnSize); for(int i=0; i<returnSize; i++){ printf("%d ", *(returns+i)); } printf("\n"); return 0; }
C
#include <stdio.h> void points (double x, double y, double u, double v, double a, double b) { double m1 = (y-v)/(x-u); double m2 = (y-b)/(x-a); if (m1-m2 < 1e-3) { printf(">>Points lie on the same line\n"); } else { printf(">> Points don't lie on the same line\n"); } } int main() { double x; double y; double u; double v; double a; double b; printf("Enter the points (x,y), (u,v) and (a,b)\n"); printf("x = "); scanf("%lf",&x); printf("y = "); scanf("%lf",&y); printf("u = "); scanf("%lf",&u); printf("v = "); scanf("%lf",&v); printf("a = "); scanf("%lf",&a); printf("b = "); scanf("%lf",&b); points(x,y,u,v,a,b); }
C
#include <raylib.h> #include <stdlib.h> #include <math.h> #define NUM_OF_RAYS 1080 #define MAX_STEPS 50 #define FRAMERATE 6000 typedef struct RayMarch { Vector2 pos; float distance; float angle; } RayMarch; typedef struct Sphere { Vector2 pos; float radius; } Sphere; typedef struct Plane { float value; bool isX; } Plane; float GetDist(Vector2 pos); int main(void) { const int screenWidth = 600; const int screenHeight = 600; float frayCount = (float) NUM_OF_RAYS; InitWindow(screenWidth, screenHeight, "2D Ray Marching"); RayMarch rays[NUM_OF_RAYS] = { 0 }; Sphere ball = { 0 }; Vector2 camera = (Vector2) { screenWidth/2, screenHeight/2 }; Plane floor = { 0 }; bool hit = false; bool drawCircle = false; bool drawPoints = false; bool help = false; bool zerothRay = false; bool lines = false; // Setup rays for (int i = 0; i < NUM_OF_RAYS; i++) { rays[i].pos = camera; rays[i].distance = 0.0f; rays[i].angle = (360.0f/frayCount) * i; } // Setup the Ball ball.pos = (Vector2) { screenWidth * 7/8, screenHeight/2 }; ball.radius = 50; //Setup Floor floor.isX = true; floor.value = screenHeight - 20; SetTargetFPS(FRAMERATE); while(!WindowShouldClose()) { // Update if(IsKeyDown(KEY_W)) camera.y--; if(IsKeyDown(KEY_S)) camera.y++; if(IsKeyDown(KEY_A)) camera.x--; if(IsKeyDown(KEY_D)) camera.x++; if(IsKeyPressed(KEY_R)) drawCircle = !drawCircle; if(IsKeyPressed(KEY_C)) drawPoints = !drawPoints; if(IsKeyPressed(KEY_H)) help = !help; if(IsKeyPressed(KEY_F)) zerothRay = !zerothRay; if(IsKeyPressed(KEY_E)) lines = !lines; if(IsMouseButtonDown(MOUSE_LEFT_BUTTON)) ball.pos = GetMousePosition(); if(IsMouseButtonDown(MOUSE_RIGHT_BUTTON)) camera = GetMousePosition(); // Draw BeginDrawing(); ClearBackground(BLACK); for (int i = 0; i < NUM_OF_RAYS; i++) { rays[i].distance = 0.0f; rays[i].pos = camera; hit = false; for (int j = 0; j < MAX_STEPS; j++) { // Calculate floor distance if (floor.isX) { rays[i].distance = abs(floor.value - rays[i].pos.y); } else if (!floor.isX) { rays[i].distance = abs(floor.value - rays[i].pos.y); } // Calculate ball distance and set if smaller if ((sqrt(pow(rays[i].pos.x - ball.pos.x, 2) + pow(rays[i].pos.y - ball.pos.y, 2)) - ball.radius) < rays[i].distance) { rays[i].distance = sqrt(pow(rays[i].pos.x - ball.pos.x, 2) + pow(rays[i].pos.y - ball.pos.y, 2)) - ball.radius; } // Draw if hit anything if(drawPoints) DrawPixel(rays[i].pos.x, rays[i].pos.y, GREEN); if(drawCircle) DrawCircleLines(rays[i].pos.x, rays[i].pos.y, rays[i].distance, (Color) { 255,255,255,50 }); if(zerothRay) { if(i == 0) { DrawPixel(rays[i].pos.x, rays[i].pos.y, GREEN); DrawCircleLines(rays[i].pos.x, rays[i].pos.y, rays[i].distance, (Color) { 255,255,255,50 }); }} if (rays[i].distance < 0.1f) { DrawPixel(rays[i].pos.x, rays[i].pos.y, RED); j = MAX_STEPS + 1; } // Add to pos rays[i].pos.x = (cos((PI/180) * rays[i].angle) * rays[i].distance) + rays[i].pos.x; rays[i].pos.y = (sin((PI/180) * rays[i].angle) * rays[i].distance) + rays[i].pos.y; } if(lines) { DrawLine(rays[i].pos.x, rays[i].pos.y, camera.x, camera.y, WHITE); } } if(help) { DrawText("WASD = Move Camera", 10, 40, 10, GREEN); DrawText("C = Draw points of each iteration", 10, 50, 10, GREEN); DrawText("R = Draw circle around each iteration of each ray", 10, 60, 10, GREEN); DrawText("H = Display this text", 10, 70, 10, GREEN); DrawText("F = Display circle and point of zeroth ray", 10, 80, 10, GREEN); DrawText("E = Draw rays as lines", 10, 90, 10, GREEN); DrawText("LMB = Move ball", 10, 100, 10, GREEN); DrawText("RMB = Move Camera", 10, 110, 10, GREEN); } DrawCircle(camera.x, camera.y, 2, PINK); DrawFPS(10,10); EndDrawing(); } CloseWindow(); return 0; }
C
#include "sort.h" /** * counting_sort - Counting sort implementation. * @array: Array to sort. * @size: Array's size. */ void counting_sort(int *array, size_t size) { int max = 0, i, total = 0; int *count_array = NULL, *copy_array = NULL; if (!array || size <= 1) return; for (i = 0; i < (int)size; i++) if (array[i] > max) max = array[i]; count_array = malloc(sizeof(int) * (max + 1)); copy_array = malloc(sizeof(int) * size); if (!count_array || !copy_array) { if (count_array) free(count_array); if (copy_array) free(copy_array); exit(1); } for (i = 0; i <= max; i++) count_array[i] = 0; for (i = 0; i < (int)size; i++) { copy_array[i] = array[i]; count_array[array[i]]++; } for (i = 0; i <= max; i++) { count_array[i] += total; total = count_array[i]; } print_array(count_array, max + 1); for (i = 0; i < (int)size; i++) { array[count_array[copy_array[i]] - 1] = copy_array[i]; count_array[copy_array[i]]--; } free(copy_array), free(count_array); }
C
/** @file * UART packet-based driver * * Recieve commands as simple byte-oriented packets. The first byte indicates the * length of the command to receieve, rest is the payload. * * Can be trivially extended with address byte as the first byte to make a simple * bus protocol that can handle upto 256 devices. * * @author Piotr S. Staszewski */ #include <stdint.h> #include <stdbool.h> #include <avr/interrupt.h> #include <util/delay.h> #include "uartcli.h" // Internal defines #define CLI_PRESCALE (((F_CPU / (16UL * CLI_BAUD))) - 1) //!< UART prescaler // Internal variables static volatile uint8_t cmdLen = 0; //!< Command length static volatile uint8_t cmdPtr = 0; //!< Pointer to current byte // Public variables volatile char cliBuffer[CLI_BUFSIZ]; volatile bool cliHasCmd = false; // Public routines /** Initialise the UART CLI. * Will setup the UART. */ void uartcli_init() { UCSRB = _BV(RXEN) | _BV(TXEN) | _BV(RXCIE); UCSRC = _BV(UCSZ0) | _BV(UCSZ1); UBRRH = (CLI_PRESCALE >> 8); UBRRL = CLI_PRESCALE; } /** Indicated ready to receive next command. * Has to be called after a command has been processed to enable * further processing. One should *never* clear cliHasCmd directly. * * @see cliBuffer * @see cliHasCmd */ void uartcli_next() { cliHasCmd = false; cmdLen = 0; cmdPtr = 0; UCSRB |= _BV(RXCIE); } /** Send signle byte over UART. * @param data The byte to send */ void uart_send_byte(uint8_t data) { loop_until_bit_is_set(UCSRA, UDRE); UDR = data; } /** Send character string over UART. * * @param str Pointer to the string to send */ void uart_write_str(char *str) { while (*str) uart_send_byte((uint8_t)*str++); } // Interrupt handlers /** UART Recieve interrupt handler. */ ISR(CLI_ISR) { if (cmdLen > cmdPtr) { cliBuffer[cmdPtr] = UDR; cmdPtr++; if (cmdLen == cmdPtr) { cliBuffer[cmdPtr] = 0; cliHasCmd = true; UCSRB &= ~_BV(RXCIE); } } else cmdLen = UDR; }
C
#include <stdio.h> /** * 위치 탐색 알고리즘 순차적 실행으로 검색 * 인자값 * ar[] = 탐색을 원하는 배열 입력 * len = 배열의 길이 * target = 찾고 싶은 값 */ int LSearch(int ar[], int len, int target){ /** for문의 실행 횟수를 구하기 위한 값 찾고 싶은 값의 위치 값이 된다. */ int i; /** 순차적 검색 */ for(i = 0; i < len; i++){ /** 배열의 값 비교 */ if(ar[i] == target){ return i; } } return -1; } int main(void){ /** 배열 선언 */ int arr[] = {3, 5, 2, 4, 9}; /** 찾고자 하는 값의 위치 값을 위한 변수 */ int idx; /** 위치값 찾기 */ /** sizeof(arr)/sizeof(int) 배열의 길이를 구하는 법 */ idx = LSearch(arr, sizeof(arr)/sizeof(int), 4); /** 원하는 값을 찾지 못했을 경우 */ if(idx == -1){ printf("Search Failed \r\n"); }else{ printf("Search Success ! index is %d \r\n", idx); } return 0; }
C
#include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <assert.h> #include <mpi.h> // Cartesian to linear #define to_lin(r, c, w) r * w + c #define MIN(a,b) ((a) < (b) ? (a) : (b)) #ifndef redis #define redis redistribute3 #endif //#define rprintf(format, ...) printf("[%d] " format, rank, __VA_ARGS__) /* Convert a global index into a local index (irrespective of which rank has the index) */ int global2local(int index_global, int nblock, int size) { int cur_block = index_global / (size * nblock); return nblock * cur_block + index_global % nblock; } /* Calculate which rank has the global index residing in its local index */ int global2rank(int index_global, int nblock, int size) { return (index_global / nblock) % size; } /* Calculate total number of elements on the local rank */ int local_size(int N, int nblock, int rank, int size) { // Total number of full blocks int full_blocks = N / nblock; // Minimum number of elements on each rank int min_elem = (full_blocks / size) * nblock; // Overlapping blocks int overlap = full_blocks % size; if (rank < overlap) { return min_elem + nblock; } else if (rank == overlap) { return min_elem + N % nblock; } else { return min_elem; } } int global2rank2d(int i_global, int j_global, int nblock, int pr, int pc) { return to_lin(global2rank(i_global, nblock, pr), global2rank(j_global, nblock, pc), pc); } int global2local2d(int N, int i_global, int j_global, int nblock, int pr, int pc) { return to_lin(global2local(i_global, nblock, pr), global2local(j_global, nblock, pc), local_size(N, nblock, global2rank(j_global, nblock, pc), pc)); } double *redistribute1(int N, double *A_in, int nblock_in, int nblock_out, int rank, int pr, int pc) { // Count the number of messages sent int ncomms = 0; // First we calculate the new (local) matrix size int rows_local = local_size(N, nblock_out, rank/pc, pr); int cols_local = local_size(N, nblock_out, rank%pc, pc); if (rank == 0) { printf("\nStart redistribute matrix from nb=%d to nb=%d\n", nblock_in, nblock_out); fflush(stdout); } #ifdef DEBUG MPI_Barrier(MPI_COMM_WORLD); printf(" [%2d] local rows %d\n", rank, rows_local); printf(" [%2d] local cols %d\n", rank, cols_local); fflush(stdout); #endif // Allocate memory for the new distributed matrix double *A_out = (double *)malloc(rows_local * cols_local * sizeof(double)); // align ranks MPI_Barrier(MPI_COMM_WORLD); double t0 = MPI_Wtime(); // Now all processors are ready for send/recv data for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Figure out which ranks has and which should have the given global index int rank_in = global2rank2d(i, j, nblock_in, pr, pc); int rank_out = global2rank2d(i, j, nblock_out, pr, pc); #ifdef DEBUG if (rank == 0) { printf("cell (%3d,%3d) %2d -> %2d\n", i, j, rank_in, rank_out); } #endif if (rank_in == rank) { // currently hosting rank has this row int idx_in = global2local2d(N, i, j, nblock_in, pr, pc); if (rank_out == rank) { // this rank also has the receive int idx_out = global2local2d(N, i, j, nblock_out, pr, pc); #ifdef DEBUG // Copy data printf(" [%2d] COPY %3d,%3d (%3d)\n", rank, i, j, idx_in); fflush(stdout); #endif // memcpy(&A_out[N * idx_out], &A_in[N * idx_in], sizeof(double)); A_out[idx_out] = A_in[idx_in]; } else { #ifdef DEBUG printf(" [%2d] SEND %3d,%3d (%3d) to %2d\n", rank, i, j, idx_in, rank_out); fflush(stdout); #endif MPI_Send(&A_in[idx_in], 1, MPI_DOUBLE, rank_out, 0, MPI_COMM_WORLD); } } else if (rank_out == rank) { // We already know that we *have* to post a recieve int idx_out = global2local2d(N, i, j, nblock_out, pr, pc); #ifdef DEBUG printf(" [%2d] RECV %3d,%3d (%3d) from %2d\n", rank, i, j, idx_out, rank_in); fflush(stdout); #endif MPI_Recv(&A_out[idx_out], 1, MPI_DOUBLE, rank_in, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } #ifdef DEBUGSLEEP usleep(250000); MPI_Barrier(MPI_COMM_WORLD); #endif ncomms++; } } // Final timing double t1 = MPI_Wtime(); MPI_Barrier(MPI_COMM_WORLD); if (rank == 0) { printf("Done redistributing matrix from nb=%d to nb=%d\n", nblock_in, nblock_out); fflush(stdout); } // Print timings, min/max double t = t1 - t0; MPI_Reduce(&t, &t0, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); MPI_Reduce(&t, &t1, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) { printf("#transactions: %d\n", ncomms); printf("Time min/max %12.8f / %12.8f ms\n", 1000 * t0, 1000 * t1); fflush(stdout); } return A_out; } double *redistribute2(int N, double *A_in, int nblock_in, int nblock_out, int rank, int pr, int pc) { // Count the number of messages sent int ncomms = 0; int rows_local_old = local_size(N, nblock_in, rank/pc, pr); int cols_local_old = local_size(N, nblock_in, rank%pc, pc); // First we calculate the new (local) matrix size int rows_local = local_size(N, nblock_out, rank/pc, pr); int cols_local = local_size(N, nblock_out, rank%pc, pc); if (rank == 0) { printf("\nStart redistribute matrix from nb=%d to nb=%d\n", nblock_in, nblock_out); fflush(stdout); } #ifdef DEBUG MPI_Barrier(MPI_COMM_WORLD); printf(" [%2d] local rows %d\n", rank, rows_local); printf(" [%2d] local cols %d\n", rank, cols_local); fflush(stdout); #endif // Allocate memory for the new distributed matrix double *A_out = (double *)malloc(rows_local * cols_local * sizeof(double)); // align ranks MPI_Barrier(MPI_COMM_WORLD); double t0 = MPI_Wtime(); // Now all processors are ready for send/recv data for (int i = 0; i < N;) { for (int j = 0; j < N;) { // Figure out which ranks has and which should have the given global index int rank_in = global2rank2d(i, j, nblock_in, pr, pc); int rank_out = global2rank2d(i, j, nblock_out, pr, pc); // Figure out how wide the current block is int next_div = MIN((j / nblock_in + 1) * nblock_in, (j / nblock_out + 1) * nblock_out); int width = MIN(N - j, next_div - j); #ifdef DEBUG if (rank == 0) { printf("cell (%3d,%3d) %2d -> %2d\n", i, j, rank_in, rank_out); } #endif if (rank_in == rank) { // currently hosting rank has this row int idx_in = global2local2d(N, i, j, nblock_in, pr, pc); if (rank_out == rank) { // this rank also has the receive int idx_out = global2local2d(N, i, j, nblock_out, pr, pc); #ifdef DEBUG // Copy data printf(" [%2d] COPY %3d,%3d (%3d)\n", rank, i, j, idx_in); fflush(stdout); #endif assert(idx_in + width <= cols_local_old * rows_local_old); assert(idx_out + width <= cols_local * rows_local); memcpy(&A_out[idx_out], &A_in[idx_in], width * sizeof(double)); } else { #ifdef DEBUG printf(" [%2d] SEND %3d,%3d (%3d) to %2d\n", rank, i, j, idx_in, rank_out); fflush(stdout); #endif assert(idx_in + width <= cols_local_old * rows_local_old); MPI_Send(&A_in[idx_in], width, MPI_DOUBLE, rank_out, 0, MPI_COMM_WORLD); } } else if (rank_out == rank) { // We already know that we *have* to post a recieve int idx_out = global2local2d(N, i, j, nblock_out, pr, pc); #ifdef DEBUG printf(" [%2d] RECV %3d,%3d (%3d) from %2d\n", rank, i, j, idx_out, rank_in); fflush(stdout); #endif assert(idx_out + width <= cols_local * rows_local); MPI_Recv(&A_out[idx_out], width, MPI_DOUBLE, rank_in, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE); } #ifdef DEBUGSLEEP usleep(250000); MPI_Barrier(MPI_COMM_WORLD); #endif j += width; ncomms++; } i++; } // Final timing double t1 = MPI_Wtime(); MPI_Barrier(MPI_COMM_WORLD); if (rank == 0) { printf("Done redistributing matrix from nb=%d to nb=%d\n", nblock_in, nblock_out); fflush(stdout); } // Print timings, min/max double t = t1 - t0; MPI_Reduce(&t, &t0, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); MPI_Reduce(&t, &t1, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) { printf("#transactions: %d\n", ncomms); printf("Time min/max %12.8f / %12.8f ms\n", 1000 * t0, 1000 * t1); fflush(stdout); } return A_out; } double *redistribute3(int N, double *A_in, int nblock_in, int nblock_out, int rank, int pr, int pc) { // Count the number of messages sent int ncomms = 0; int rows_local_old = local_size(N, nblock_in, rank/pc, pr); int cols_local_old = local_size(N, nblock_in, rank%pc, pc); // First we calculate the new (local) matrix size int rows_local = local_size(N, nblock_out, rank/pc, pr); int cols_local = local_size(N, nblock_out, rank%pc, pc); if (rank == 0) { printf("\nStart redistribute matrix from nb=%d to nb=%d\n", nblock_in, nblock_out); fflush(stdout); } #ifdef DEBUG MPI_Barrier(MPI_COMM_WORLD); printf(" [%2d] local rows %d\n", rank, rows_local); printf(" [%2d] local cols %d\n", rank, cols_local); fflush(stdout); #endif // Allocate memory for the new distributed matrix double *A_out = (double *)malloc(rows_local * cols_local * sizeof(double)); MPI_Request *reqs = malloc(sizeof(MPI_Request) * (cols_local_old + cols_local)); MPI_Status *stats = malloc(sizeof(MPI_Status) * (cols_local_old + cols_local)); // align ranks MPI_Barrier(MPI_COMM_WORLD); double t0 = MPI_Wtime(); // Now all processors are ready for send/recv data for (int i = 0; i < N;) { int req_count = 0; for (int j = 0; j < N;) { // Figure out which ranks has and which should have the given global index int rank_in = global2rank2d(i, j, nblock_in, pr, pc); int rank_out = global2rank2d(i, j, nblock_out, pr, pc); // Figure out how wide the current block is int next_div = MIN((j / nblock_in + 1) * nblock_in, (j / nblock_out + 1) * nblock_out); int width = MIN(N - j, next_div - j); #ifdef DEBUG if (rank == 0) { printf("cell (%3d,%3d) %2d -> %2d\n", i, j, rank_in, rank_out); } #endif if (rank_in == rank) { // currently hosting rank has this row int idx_in = global2local2d(N, i, j, nblock_in, pr, pc); if (rank_out == rank) { // this rank also has the receive int idx_out = global2local2d(N, i, j, nblock_out, pr, pc); #ifdef DEBUG // Copy data printf(" [%2d] COPY %3d,%3d (%3d)\n", rank, i, j, idx_in); fflush(stdout); #endif assert(idx_in + width <= cols_local_old * rows_local_old); assert(idx_out + width <= cols_local * rows_local); memcpy(&A_out[idx_out], &A_in[idx_in], width * sizeof(double)); } else { #ifdef DEBUG printf(" [%2d] SEND %3d,%3d (%3d) to %2d\n", rank, i, j, idx_in, rank_out); fflush(stdout); #endif assert(idx_in + width <= cols_local_old * rows_local_old); MPI_Isend(&A_in[idx_in], width, MPI_DOUBLE, rank_out, 0, MPI_COMM_WORLD,&reqs[req_count]); req_count++; } } else if (rank_out == rank) { // We already know that we *have* to post a recieve int idx_out = global2local2d(N, i, j, nblock_out, pr, pc); #ifdef DEBUG printf(" [%2d] RECV %3d,%3d (%3d) from %2d\n", rank, i, j, idx_out, rank_in); fflush(stdout); #endif assert(idx_out + width <= cols_local * rows_local); MPI_Irecv(&A_out[idx_out], width, MPI_DOUBLE, rank_in, 0, MPI_COMM_WORLD,&reqs[req_count]); req_count++; } #ifdef DEBUGSLEEP usleep(250000); MPI_Barrier(MPI_COMM_WORLD); #endif j += width; ncomms++; } MPI_Waitall(req_count,reqs,stats); i++; } free(reqs); free(stats); // Final timing double t1 = MPI_Wtime(); MPI_Barrier(MPI_COMM_WORLD); if (rank == 0) { printf("Done redistributing matrix from nb=%d to nb=%d\n", nblock_in, nblock_out); fflush(stdout); } // Print timings, min/max double t = t1 - t0; MPI_Reduce(&t, &t0, 1, MPI_DOUBLE, MPI_MIN, 0, MPI_COMM_WORLD); MPI_Reduce(&t, &t1, 1, MPI_DOUBLE, MPI_MAX, 0, MPI_COMM_WORLD); if (rank == 0) { printf("#transactions: %d\n", ncomms); printf("Time min/max %12.8f / %12.8f ms\n", 1000 * t0, 1000 * t1); fflush(stdout); } return A_out; } int main(int argc, char *argv[]) { // Initialize MPI MPI_Init(&argc, &argv); // Query size and rank int rank, size; MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &size); // No buffering of stdout setbuf(stdout, NULL); if (argc < 6) { printf("Requires 5 inputs:\n"); printf(" N : matrix size\n"); printf(" Pc : number of processors in the 2D column layout\n"); printf(" Pr : number of processors in the 2D row layout\n"); printf(" NB1 : block-size 1\n"); printf(" NB2 : block-size 2\n"); // Quick exist since the arguments are inconsistent MPI_Finalize(); return 1; } // Read arguments int N = atoi(argv[1]); int pc = atoi(argv[2]); int pr = atoi(argv[3]); int nblock_1 = atoi(argv[4]); int nblock_2 = atoi(argv[5]); // Check that Pc * Pr == size if (pr * pc != size) { printf("Please correct input!\n"); printf(" Pc * Pr != size\n"); printf(" %d * %d != %d\n", pr, pc, size); // Quick exist since the arguments are inconsistent MPI_Finalize(); return 1; } if (rank == 0) { printf("Arguments:\n"); printf(" N = %d\n", N); printf(" nblock_1 = %d\n", nblock_1); printf(" nblock_2 = %d\n", nblock_2); printf("MPI processors: %d\n", size); } // Initialize a matrix with *random* data double *A_dense = NULL; if (rank == 0) { // allocate and initialize A_dense = (double *)malloc(N * N * sizeof(double)); // Consecutive numbers (linear matrix index) for (int i = 0; i < N * N; i++) { A_dense[i] = i; } printf("Done initializing matrix on root node\n"); fflush(stdout); } // Distribute the first (dense) matrix double *A_1 = redis(N, A_dense, N, nblock_1, rank, pr, pc); // Redistribute to the next level double *A_2 = redis(N, A_1, nblock_1, nblock_2, rank, pr, pc); // if (rank == 0) { // for ( int i = 0 ; i < N * N ; i++ ) { // printf(" %f%s", A_dense[i], i % N == N - 1 ? "\n" : ""); // } // fflush(stdout); // } // Clean-up memory free(A_1); // Redistribute to the local one again to check we have done it correctly double *A_final = redis(N, A_2, nblock_2, N, rank, pr, pc); // Clean-up memory free(A_2); if (rank == 0) { for (int i = 0; i < N * N; i++) { if (fabs(A_dense[i] - A_final[i]) > 0.1) { printf("Error on index %3d %5.1f %5.1f\n", i, A_dense[i], A_final[i]); } } } // Clean-up memory! if (A_final != NULL) free(A_final); if (A_dense != NULL) free(A_dense); MPI_Finalize(); }
C
#include "holberton.h" #include <stdlib.h> #include <stdio.h> /** * _strlen - length of string * *@str: pointer to a string * * Return: int, length */ int _strlen(char *str) { int i = 0; while (str[i] != '\0') i++; return (i); } /** * argstostr - concatenates all the arguments of the program * * @ac: int * @av: pointer to a pointer to a char * * Return: pointer to a char */ char *argstostr(int ac, char **av) { char *s = '\0'; int len = 0; int stockAc = ac; int i = 0; int j = 0; int k = 0; if (ac == 0 || av == NULL) return (NULL); while (ac--) { len += _strlen(av[ac]); } s = malloc(sizeof(char) * (len + stockAc + 1)); if (s == NULL) return (NULL); for (i = 0; i < stockAc; i++) { for (j = 0; j < _strlen(av[i]); j++) { *(s + k) = av[i][j]; k++; } *(s + k) = '\n'; k++; } return (s); }
C
// Street of the Merchants, Verhedin // Thorn@ShadowGate // 001027 // New City, Verhedin #include <std.h> #include "/d/tsarven/include/southern.h" #include "/d/verhedin/include/city.h" inherit ROOM; void create() { room::create(); set_light(2); set_short("%^BOLD%^YELLOW%^Street of the Merchants, Verhedin%^RESET%^"); set_long( @VERHEDIN %^BOLD%^YELLOW%^Street of the Merchants, Verhedin%^RESET%^ This is a cobblestonned street that appears to run north-south though the city. You notice that there is a fair amount of traffic in this area, which looks to be a shopping district filled with stores. To the south, you see that this street intersects with another, wider street running perpendicular to this one. Across that street, you see a %^BOLD%^WHITE%^magnificent white marble temple%^RESET%^ with a %^YELLOW%^BOLD%^golden dome%^RESET%^ rise high above the city. At this end of the street, you can see the bank on the west side, a building that would be considered impressive in its own right if it hadn't been placed so close to the grand temple. On the east side are a number of more humble shops, most notably a tailor shop. You see a signpost. You can go north or south down the street from here. VERHEDIN ); set_exits(([ "north" : VNEW+"som8", "south" : VNEW+"iw12", "east" : VNEW+"tailor", "west" : VNEW+"bank" ])); set_listen("default","This is a fairly busy area, but it is ordered and there is little noise."); set_smell("default","There is a faint smell of incense coming from the south."); set_items( ([ "signpost" : "It reads in Elven and Common: %^BOLD%^Street of the Merchants%^RESET%^", "temple" : "The temple appears to be a work of art unsurpassed by anything else in " "this part of the city. Nearly 5 stories high, not including the dome, the " "temple seems to be built as much for defense as worship. You can " "even see men in golden armor and white cloaks on the walls standing " "guard at certain intervals. Although you can't make it out from here " "there is evidence that there are some fine carvings and decorative work " "gracing the blindingly white exterior. Around the temple is what appears to " "be some well manicured trees and bushes, perhaps even flowers." ]) ); } void reset(){ ::reset(); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <ctype.h> #include <string.h> int main() { int becoan; for(becoan = 1; becoan <= 33; becoan++){ printf("The becoan is avaliable %d times \n\n", becoan); } float black; for(black = 5; black <= 22; black++){ printf("The black monster is coming %.2f rounds \n\n", black); } int blue; blue = black >= becoan; for(blue = 5;blue <=15; blue++){ printf("Goodbye \n"); } return 0; }
C
/* * wytar.c * Lucas Manker * 3/7/20 * COSC 3750 * Homework 6 * * mimics tar */ #include<stdio.h> #include<tar.h> #include "wytar.h" #include<stdlib.h> #include<unistd.h> #include<dirent.h> #include<sys/stat.h> #include<sys/types.h> #include<pwd.h> #include<grp.h> #include<time.h> struct tar_header* makeHeader(char *file); void processDir(char* dir); void processFile(char* file); void extraction(char* dir, char* target); int main(int argc, char** argv){ int flags[3]; flags[0] = 0; flags[1] = 0; flags[2] = 0; int optionsFlag = 0; int i; for(i = 1; i < argc; i++){ const char first = argv[i][0]; char *perCh; perCh = strchr(&first, '-'); size_t num = perCh-&first; if(num < 2 && !optionsFlag && i < 4 && !flags[2]){ int j; for(j = 1; j < strlen(argv[i]); j++){ const char next = argv[i][j]; char *peChc; peChc = strchr(&next, 'c'); size_t cSize = peChc - &next; char *peChx; peChx = strchr(&next, 'x'); size_t xSize = peChx - &next; char *peChf; peChf = strchr(&next, 'f'); size_t fSize = peChf - &next; if(cSize < 2){ if(flags[1]) printf("incompatible flags\n"); else flags[0] = 1; } else if(xSize < 2){ if(flags[0]) printf("incompatible flags\n"); else flags[1] = 1; } else if(fSize < 2){ if(flags[2]){ printf("more than one instance of -f found\n"); exit(1); } else flags[2] = 1; } else{ printf("%.*s command not found\n",1,&next); exit(1); } } } else if(flags[0] && flags[2] && !optionsFlag){ printf("target file for compression is %s\n", argv[i]); optionsFlag = 1; } else if(flags[1] && flags[2] && !optionsFlag){ if(!argv[i+1]){ printf("Specify an output file\n"); exit(2); } else{ extraction(argv[i], argv[i+1]); break; } } else{ DIR *d; d = opendir(argv[i]); if(!d){ if(access(argv[i], F_OK) != -1){ processFile(argv[i]); } else{ printf("wytar: cannot access '%s': No Such file or " "directory\n", argv[i]); } } else{ processDir(argv[i]); } } } if((!flags[0] || !flags[1]) && !flags[2]){ printf("incorrect options\nusage: \n-x extract \n-c create archive\ \n-f filename to process\n"); } return 0; } void processDir(char* direct){ printf("processing directory %s\n", direct); struct dirent *dir; DIR *d; d = opendir(direct); while((dir=readdir(d)) != NULL){ const char firstLet = dir->d_name[0]; char *perCh; perCh = strchr(&firstLet, '.'); size_t num = perCh - &firstLet; if(num > 2){ DIR *tempD; char *fullPath = (char*) malloc(2+strlen(direct) + strlen(dir->d_name)); strcpy(fullPath, direct); strcat(fullPath, dir->d_name); tempD = opendir(fullPath); if(!tempD){ strcat(fullPath,"\0"); processFile(fullPath); free(fullPath); } else { strcat(fullPath,"/"); processDir(fullPath); free(fullPath); } } } } void processFile(char* file){ printf("processing file %s\n", file); } void extraction(char* dir, char* target){ printf("extracting file: %s\n", dir); printf("target of extraction: %s\n", target); } struct tar_header* makeHeader(char *file){ struct tar_header *header = (struct tar_header *)\ malloc(sizeof(struct tar_header)); setfields(header); return header; }
C
#include <stdio.h> int main (void) { int integer = 42; float singlePrecision = 2.2; double doublePrecision = 3.31223344556677; char singleChar = 'J'; printf("your int: %d cast to a float: %f \n", integer , (float)integer); printf("your int: %d cast to a char: %c \n", integer, (char)integer); printf("your float: %f cast to a double: %lf \n", singlePrecision, (double)singlePrecision); printf("your double: %lf cast to a float: %f \n", doublePrecision, (float)doublePrecision); printf("your char: %c cast to an int: %d \n", singleChar, (int)singleChar); printf("33 cast to a char: %c \n", (char)33); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> bool isZero (double value); int solveLinear(double a, double b, double* root); int solveQuadratic(double a, double b, double c, double* root1, double* root2); int testQuad(double a, double b, double c, int num, double root1, double root2); int testLin(double a, double b, int num, double root); double getnum(); const double eps = 1e-7; // a < eps => a = 0 const int noRoots = -1; const int infRoots = -2; const double epsIgnore = 1e-4; // diifference between coeffs when a is considered 0 int main() { double a = 0;// ax^2 + bx + c = 0 double b = 0; double c = 0; double root1 = 0; double root2 = 0; testQuad(3, 4, 2, noRoots, 0, 0); testQuad(5, 8, -9, 2, 0.762049935, -2.362049935); testQuad(1, 0, -4, 2, -2, 2); testQuad(1, 6, 9, 1, -3, 0); testQuad(1, 0, 0, 1, 0, 0); testLin(0, 0, infRoots, 0); testLin(0, 2, noRoots, 0); testLin(-3, 9, 1, 3); printf("Equation solver 1.0 by Me: \"Solve your equation absolutely free\"\n" "Enter coeffs. for your equation (ax^2 + bx + c = 0)\n"); printf("a = "); a = getnum(); printf("b = "); b = getnum(); printf("c = "); c = getnum(); if ( ((fabs(a / b) < epsIgnore) && (fabs(a / c) < epsIgnore)) || ((fabs(a / b) < epsIgnore) && isZero(c) && !isZero(b)) || ((fabs(a / c) < epsIgnore) && isZero(b) && !isZero(a)) || isZero(a) ) solveLinear( b, c, &root1 ); else solveQuadratic( a, b, c, &root1, &root2 ); printf("\nYour equation is solved\n"); return 0; } bool isZero (double value) { return ( fabs(value) < eps ); } int solveLinear (double a, double b, double* root) { // ax + b = 0 printf("Solving linear equation: %gx + (%g) = 0\n", a, b); if ( isZero(a) && isZero(b) ) { printf ("\nInfinite number of roots\n"); return infRoots; } else if ( (isZero(a)) && ( !isZero(b) ) ) { printf ("\nThere are no roots\n"); return noRoots; } else { *root = -b / a; if (isZero(*root)) *root = 0; printf ("\nRoot of the equation is: %g\n", *root); return 1; } } int solveQuadratic (double a, double b, double c, double* root1, double* root2) { // ax^2 + bx + c = 0 printf("Solving quadratic equation: %gx^2 + %gx + %g = 0\n", a, b, c); double dis = pow(b, 2) - 4*a*c; if ( dis < - eps ){ printf("\nDiscriminant below zero, no roots\n"); return noRoots; } else if ( isZero(dis) ) { *root1 = -b/(2*a); if (isZero(*root1)) *root1 = 0; printf("\nDiscriminant is zero, one root: %g\n", *root1); return 1; } else { *root1 = (-b + sqrt(dis))/(2*a); if (isZero(*root1)) *root1 = 0; *root2 = (-b - sqrt(dis))/(2*a); if (isZero(*root2)) *root2 = 0; printf("\nDiscriminant more than zero, two roots: %g, %g\n", *root1, *root2); return 2; } } int testQuad (double a, double b, double c, int num, double root1, double root2) { double gotRoot1 = 0; double gotRoot2 = 0; int res = solveQuadratic( a, b, c, &gotRoot1, &gotRoot2 ); if ( (res == num) && ((isZero(root1 - gotRoot1) && isZero(root2 - gotRoot2)) || (isZero(root1 - gotRoot2) && isZero(root2 - gotRoot1)))) { printf("Test %lg, %lg, %lg is SUCCESSFUL\n\n", a, b, c); return 0; } else { printf("Test %lg, %lg, %lg is FAILED. Expected num = %d, root1 = %lg, root2 = %lg. " "Got num = %d, root1 = %lg, root2 = %lg\n\n", a, b, c, num, root1, root2, res, gotRoot1, gotRoot2); return 1; } } int testLin (double a, double b, int num, double root) { double gotRoot = 0; int res = solveLinear( a, b, &gotRoot); if ( (res == num) && (isZero(root - gotRoot)) ) { printf("Test %lg, %lg is SUCCESSFUL\n\n", a, b); return 0; } else { printf("Test %lg, %lg is FAILED. Expected num = %d, root = %lg. " "Got num = %d, root = %lg\n\n", a, b, num, root, res, gotRoot); return 1; } } double getnum(){ double tnum = 0; int res = scanf("%lg", &tnum); while ( res == 0 ) { while ( getchar() != '\n' ); printf("\nEnter correct number...\n"); res = scanf("%lg", &tnum); } return tnum; }
C
#include "BlueTooth.h" /************************************************************************** ߣī˹Ƽ ҵԱС꣺https://moebius.taobao.com/ **************************************************************************/ #define MAXQSIZE 32 int QueueSize; LinkQueue *Uart_Queue; #define bufferLenth 50 extern char uartbuffer[bufferLenth]; int bufferPosition = 0; //======================================================================== // void InitQueue() { Uart_Queue = (LinkQueue*)malloc(sizeof(LinkQueue)); Uart_Queue->Hand = (QNode*)malloc(sizeof(QNode)); Uart_Queue->Tail = Uart_Queue->Hand; if (!Uart_Queue->Hand) printf("Er 0001: Init queue error!\r\n"); Uart_Queue->Hand->next = NULL; } //======================================================================== // void InQueue(u8 Data) //ͷ巨 { if (QueueSize >= MAXQSIZE) { printf("Er 0002: Queue overflow!\r\n"); return; } else { QNode* NewNode = (QNode*)malloc(sizeof(QNode)); NewNode->data = Data; NewNode->next = Uart_Queue->Hand; Uart_Queue->Hand = NewNode; QueueSize++; } } //======================================================================== // u8 OutQueue() { QNode* Temp; Temp = Uart_Queue->Hand; if (Uart_Queue->Hand == Uart_Queue->Tail) { printf("Er 0002: Queue empty!\r\n"); return 0; } while (Temp->next != Uart_Queue->Tail) { Temp = Temp->next; } Temp->next = NULL; free(Uart_Queue->Tail); Uart_Queue->Tail = Temp; QueueSize--; return Temp->data; } //======================================================================== //ǷΪ u8 InspectQueue() { if(Uart_Queue->Tail == Uart_Queue->Hand) return 0; else return 1; } ////======================================================================== //// //void PrintQueue() //{ // int cnt = 0; // QNode* Temp; // Temp = Uart_Queue->Hand; // // memset(uartbuffer,0,sizeof(uartbuffer)); // while (Temp->next != NULL) // { // uartbuffer[cnt++] = Temp->data; //// printf("%c, ",Temp->data); // Temp = Temp->next; // } // printf("%s",uartbuffer); //} void USART2_Send_Data(u8 Dat) { USART_SendData(USART2,Dat); while(USART_GetFlagStatus(USART2, USART_FLAG_TC) != SET); USART_ClearFlag(USART2,USART_FLAG_TC); } /******************************************************************************* * : USART1_Init * : USART1ʼ * : bound: * : *******************************************************************************/ void USART2_Init(u32 bound) { //GPIO˿ GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA,ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO,ENABLE); //ʱ /* GPIOģʽIO */ GPIO_InitStructure.GPIO_Pin=GPIO_Pin_2;//TX //PA2 GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz; GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP; // GPIO_Init(GPIOA,&GPIO_InitStructure); /* ʼIO */ GPIO_InitStructure.GPIO_Pin=GPIO_Pin_3;//RX //PA3 GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING; //ģ GPIO_Init(GPIOA,&GPIO_InitStructure); /* ʼGPIO */ //USART1 ʼ USART_InitStructure.USART_BaudRate = bound; // USART_InitStructure.USART_WordLength = USART_WordLength_8b; //ֳΪ8λݸʽ USART_InitStructure.USART_StopBits = USART_StopBits_1; //һֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No; //żУλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//Ӳ USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //շģʽ USART_Init(USART2, &USART_InitStructure); //ʼ1 USART_Cmd(USART2, ENABLE); //ʹܴ1 USART_ClearFlag(USART2, USART_FLAG_TC); USART_ITConfig(USART2, USART_IT_RXNE, ENABLE); //ж //USART_ITConfig(USART2, USART_IT_IDLE, ENABLE); //ж //Usart1 NVIC NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; //1жͨ NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=2; //ռȼ3 NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; //ȼ3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQͨʹ NVIC_Init(&NVIC_InitStructure); //ָIJʼVICĴ // InitQueue(); } /******************************************************************************* * : USART1_IRQHandler * : USART1жϺ * : * : *******************************************************************************/ void USART2_IRQHandler(void) //1жϷ { // ITStatus status; // status = if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) //ж //if(USART_GetITStatus(USART2, USART_IT_IDLE) != RESET) //ж { //InQueue(USART_ReceiveData(USART2)); uartbuffer[bufferPosition] = USART_ReceiveData(USART2); bufferPosition++; if (bufferPosition >= (bufferLenth-1)){ bufferPosition = 0; } } }
C
#include <stdio.h> #include <stdlib.h> /* Board is an 8-element array of ints, organize 0-based indexes * like this: * * 0 1 2 * 3 4 5 * 6 7 8 * */ int winning_triads[8][3] = { {0,1,2}, {3,4,5}, {6,7,8}, {0,3,6}, {1,4,7}, {2,5,8}, {0,4,8}, {2,4,6} }; int find_winner(int board[]); /* if computer wins 1, if humn -1, 0 no win */ int move_remaining(int board[]); /* 1 if a legal move remains, 0 otherwise */ int computer_moves(int board[]); /* determine computer's next move */ int get_human_move(int board[]); /* get an int between 0 and 8 inclusive */ void print_board(int board[]); int main(int ac, char **av) { int goes_first = -1; int board[9]; int winner = 0; int new_move; int i; if (ac > 1) { if (av[1][0] == 'h' || av[1][0] == 'H') goes_first = -1; else if (av[1][0] == 'c' || av[1][0] == 'C') goes_first = 1; } printf("0 1 2\n3 4 5\n6 7 8\n"); for (i = 0; i < 9; ++i) board[i] = 0; if (goes_first == -1) printf("\nHuman plays first, X, computer plays 2nd, O\n"); else printf("\nComputer plays first, 0, human plays 2nd, X\n"); /* Duff-like device. */ switch (goes_first) { do { case -1: new_move = get_human_move(board); /* human's next move */ board[new_move] = -1; /* Human is minimizer */ winner = find_winner(board); if (winner) break; case 1: new_move = computer_moves(board); board[new_move] = 1; /* Computer maximises */ winner = find_winner(board); if (winner) break; print_board(board); } while (0 == winner && move_remaining(board)); } switch (winner) { case -1: printf("\nHuman wins.\n"); break; case 1: printf("\nComputer wins\n"); break; default: printf("\nCat got the game\n"); break; } print_board(board); return 0; } int move_remaining(int board[]) { int i, legal_move_left = 0; for (i = 0; i < 9; ++i) { if (board[i] == 0) { legal_move_left = 1; break; } } return legal_move_left; } int find_winner(int board[]) { int i; int winner = 0; for (i = 0; i < 8; ++i) { int sum; int *triad = winning_triads[i]; sum = board[triad[0]] + board[triad[1]] + board[triad[2]]; if (sum == 3) winner = 1; else if (sum == -3) winner = -1; } return winner; } int corners[] = {0, 2, 6, 8}; int sides[] = {1, 3, 5, 7}; int computer_moves(int board[]) { int i; /* fill in any wins */ for (i = 0; i < 8; ++i) { int sum; int *triad = winning_triads[i]; sum = board[triad[0]] + board[triad[1]] + board[triad[2]]; if (sum == 2) { int j; for (j = 0; j < 3; ++j) { if (board[triad[j]] == 0) return triad[j]; } } } /* block any 2-in-a row */ for (i = 0; i < 8; ++i) { int sum; int *triad = winning_triads[i]; sum = board[triad[0]] + board[triad[1]] + board[triad[2]]; if (sum == -2) { int j; for (j = 0; j < 3; ++j) { if (board[triad[j]] == 0) return triad[j]; } } } /* Move to center if possible */ if (board[4] == 0) return 4; /* Move to a corner if possible */ for (i = 0; i < 3; ++i) if (board[corners[i]] == 0) return corners[i]; /* Move to a side if possible */ for (i = 0; i < 3; ++i) if (board[sides[i]] == 0) return sides[i]; return -1; } void print_board(int board[]) { printf("%c %c %c\n%c %c %c\n%c %c %c\n", (board[0] == -1? 'X': (board[0] == 0? '_': 'O')), (board[1] == -1? 'X': (board[1] == 0? '_': 'O')), (board[2] == -1? 'X': (board[2] == 0? '_': 'O')), (board[3] == -1? 'X': (board[3] == 0? '_': 'O')), (board[4] == -1? 'X': (board[4] == 0? '_': 'O')), (board[5] == -1? 'X': (board[5] == 0? '_': 'O')), (board[6] == -1? 'X': (board[6] == 0? '_': 'O')), (board[7] == -1? 'X': (board[7] == 0? '_': 'O')), (board[8] == -1? 'X': (board[8] == 0? '_': 'O')) ); } int get_human_move(int board[]) { char buffer[16]; int new_move = -1; /* human's next move */ while (new_move == -1) { int candidate; printf("Your move > "); fgets(buffer, sizeof(buffer), stdin); printf("\n"); candidate = strtol(buffer, NULL, 10); if (0 <= candidate && 9 > candidate && board[candidate] == 0) { new_move = candidate; break; } else { if (0 > candidate || 9 <= candidate) fprintf(stderr, "Valid move between 0 and 8\n"); if (board[candidate] != 0) fprintf(stderr, "That spot is taken\n"); } } return new_move; }
C
/** * @brief It defines a player * * @file player.h * @author David Ramirez * @version 1.0 * @date 08/02/2019 */ #ifndef PLAYER_H #define PLAYER_H #include "types.h" typedef struct _Player Player; Player* player_create(Id id); STATUS player_destroy(Player* player); STATUS player_set_name(Player* player, char* name); STATUS player_set_location(Player* player, Id location); STATUS player_set_ported_object(Player* player, Id ported_object); Id player_get_id(Player* player); const char * player_get_name(Player* player); Id player_get_location(Player* player); Id player_get_ported_object(Player* player); STATUS player_print(Player* player); #endif
C
#include <stdio.h> int main(void) { int n, m; scanf("%d %d", &n, &m); int a[m]; for (int i = 0; i < m; i++) { scanf("%d", &a[i]); n -= a[i]; } if (n < 0) { n = -1; } printf("%d\n", n); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { /*Faa um programa que leia a idade de uma pessoa expressa em anos, meses e dias e escreva a idade dessa pessoa expressa apenas em dias. Considerar ano com 365 dias e ms com 30 dias.*/ int ano, mes, dia, dias; printf("Digite sua idade:"); scanf("%d",&ano); printf("\nDigite o total de meses:"); scanf("%d",&mes); printf("\nDigite o total de dias:"); scanf("%d",&dia); dias = (ano*365) + (mes*30) + dia; printf("\nSua idade total expressa em dias: %d",dias); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int main(int argc, char* argv[]){ int pfd[2]; if(pipe(pfd) < 0){ perror("pipe"); exit(1); } pid_t pid; if((pid = fork()) < 0){ perror("fork"); exit(1); } if(pid > 0){ // 父进程 close(pfd[1]); int ret; char buf[256]; while((ret = read(pfd[0], buf, sizeof(buf))) != 0){ write(STDOUT_FILENO, buf, ret); } close(pfd[0]); } else{ // 子进程 int fd; char buf[256]; int ret; close(pfd[0]); if((fd = open(argv[1], O_RDONLY)) < 0){ perror("open"); exit(1); } while((ret = read(fd, buf, sizeof(buf))) != 0){ write(pfd[1], buf, ret); } close(fd); close(pfd[1]); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> void main( ) { char c[128]; int a,b; srand(time(NULL)); // 乱数の準備 while ( 1 ) { printf("\n*******サイコロを振ります。*******\n0を入力すると終了します。\n好きな数字を入力してください: "); gets(c); a=atoi(c); if ( a==0 ) break; b=rand( )%5+1; // 乱数発生 printf(" >>> "); switch ( (a+b)%6 ) { case 0: printf("\n+--------+\n| |\n| ● |\n| |\n+--------+\n"); break; case 1: printf("\n+--------+\n| ● |\n| |\n| ● |\n+--------+\n"); break; case 2: printf("\n+--------+\n| ● |\n| ● |\n| ● |\n+--------+\n"); break; case 3: printf("\n+--------+\n| ● ● |\n| |\n| ● ● |\n+--------+\n"); break; case 4: printf("\n+--------+\n| ● ● |\n| ● |\n| ● ● |\n+--------+\n"); break; case 5: printf("\n+--------+\n| ● ● |\n| ● ● |\n| ● ● |\n+--------+\n"); break; } printf("\n"); } }