language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> void main() { int minute,hour,minu; scanf("%d",&minute); hour=minute/60; minu=minute%60; printf("%d %d",hour,minu); }
C
#include <stdlib.h> #include <stdio.h> #include "linkList.h" /* * @brief This function is to initialize * the structure of linkList. * * @return *plinkList */ linkList *createdLinkList(){ linkList *plinkList = malloc(sizeof(linkList)); plinkList->head = NULL; plinkList->tail = NULL; plinkList->length = 0; return plinkList; } /* * @brief This function is to initialize * the structure of listElement. * * @return *thisElement */ listElement *createdElement(){ listElement *thisElement = malloc(sizeof(listElement)); thisElement->indexNum = 0; thisElement->next = NULL; return thisElement; } /* * @brief This function is to link the linklist and listElement * and form a list whenever a new element added to the list. * */ void addList(listElement *newElement, linkList *newlinkElement){ if (newElement == NULL){ printf("error\n"); return; } if (newlinkElement->head == NULL && newlinkElement->tail == NULL){ newlinkElement->head = newElement; newlinkElement->tail = newElement; } else{ newlinkElement->tail->next = newElement; newlinkElement->tail = newElement; } (newlinkElement->length)++; newElement->indexNum = newlinkElement->length; } /* * @brief This function is to delete the first * node of the linked list and free it. */ void deleteFirstNode(listElement *firstElement, linkList *link){ if (link->head == NULL && link->tail == NULL){ firstElement = NULL; printf("No node needs to be freed"); } else { if (link->head->next == NULL){ link->head = NULL; link->tail = NULL; } else{ link->head->indexNum = link->head->next->indexNum; link->head = link->head->next; free(firstElement); } } } /* * @brief This function is to delete a node * of the linked list and free it. * * @except first and last node */ void deleteOneNode(listElement *element, linkList *link){ listElement *tempNode; tempNode = link->head; if (link->head == NULL && link->tail == NULL){ element = NULL; printf("No node needs to be freed"); } else{ while(tempNode->next != element) { tempNode = tempNode->next; } if(tempNode->next == NULL) { printf("\n Given node is not present in the Linked List"); return; } tempNode->next = tempNode->next->next; free(element); } } /* * @brief This function is to delete the last * node of the linked list and free it. */ void deleteLastNode(listElement *lastElement, linkList *link){ listElement *tempNode; tempNode = link->head; if (link->head == NULL && link->tail == NULL){ lastElement = NULL; printf("\nNo node needs to be freed\n"); } else{ while(tempNode->next != lastElement) { tempNode = tempNode->next; } if(link->head->next == NULL) { printf("\n Given node is not present in Linked List\n"); return; } link->tail->indexNum = tempNode->indexNum; link->tail = tempNode; free(lastElement); } }
C
#define _GNU_SOURCE #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <stdint.h> #include <string.h> #include <stdbool.h> #include <unistd.h> #include <sys/mman.h> #include <time.h> #include <assert.h> #include "../include/custom_timing.h" void time_handler1(size_t timer_id, void* callbackData); void PrintData(void); extern unsigned int sleep(unsigned int __seconds); /******************************/ /* Enter values for constants */ /******************************/ const int policyRT = SCHED_FIFO; // Sets the scheduling policy attribute of the RT enabled thread. Options: SCHED_FIFO, SCHED_RR, and SCHED_OTHER const int cpuRT = 1; // Sets the CPU core affinity for the RT enabled thread. In a 2 core cRIO the options are 0 and 1 const double cycleTime = 500; // Cycle time in Hz const int runSec = 15; // Sets the time window for the loops to be run within // Initialize global variables char errBuff[2048] = { '\0' }; int timerCount; double totalTime, avgTime, maxTime, minTime; struct timespec prevTime = {0}, startTime = {0}; int main() { int i, timerRT, timerStandard; double actualCycleTime, expectedTimePerLoop = 1/cycleTime*1000; // Print input parameters to console printf("\n********* Input Parameters *********\n"); if (policyRT == 0) { printf("RT thread policy: Other\n"); } else if (policyRT == 1){ printf("RT thread policy: FIFO\n"); } else if (policyRT == 2){ printf("RT thread policy: Round-robin\n"); } printf("RT thread CPU core: %d\n", cpuRT); printf("Cycle time: %5.2f Hz\n", cycleTime); printf("Run time per thread: %d sec\n", runSec); // ************************************************** // RT priority loop thread // ************************************************** // Initialize the timer module with RT priority if (initializeRT(policyRT, cpuRT)) { printf("create pthread failed\n"); return 1; } // Assign initial values to previously initialized variables minTime = 10000; maxTime = 0; totalTime = 0; timerCount= 0; // Get current value of clock CLOCK_MONOTONIC and stores it in StartTime clock_gettime(CLOCK_MONOTONIC, &startTime); // Create a timer and assigns its file descriptor to timer1 printf("\n********* RT Priority Thread *********\n"); timerRT = start_timer(expectedTimePerLoop, time_handler1, TIMER_PERIODIC, NULL); // Wait before stopping the timer sleep(runSec); // Stop the timer, delete it, and print timer data to the console stop_timer(timerRT); finalize(); PrintData(); // ************************************************** // Standard priority thread // ************************************************** // Initialize the timer module with standard priority if (initializeStandard()) { printf("create pthread failed\n"); return 1; } // Reassign initial values to previously initialized variables minTime = 10000; maxTime = 0; totalTime = 0; timerCount= 0; // Get current value of clock CLOCK_MONOTONIC and stores it in StartTime clock_gettime(CLOCK_MONOTONIC, &startTime); // Creates a timer and assigns its file descriptor to timer1 printf("********* Standard Priority Thread *********\n"); timerStandard = start_timer(expectedTimePerLoop, time_handler1, TIMER_PERIODIC, NULL); // Wait before stopping the timer sleep(runSec); // Stop the timer, delete it, and print timer data to the console stop_timer(timerStandard); finalize(); PrintData(); return 0; } // Creates a timer and calculates its stats for minimum, maximum, and average time void time_handler1(size_t timer_id, void* callbackData) { struct timespec currentTime, tempTimeUsed; double timeUsed; double expectedTimePerLoop = 1/cycleTime*1000; // Get current value of clock CLOCK_MONOTONIC and stores it in currentTime clock_gettime(CLOCK_MONOTONIC, &currentTime); if (timerCount == 0) { prevTime = startTime; printf("\n"); } // Calculate the time used tempTimeUsed = diff(prevTime, currentTime); timeUsed = tempTimeUsed.tv_sec + (double) tempTimeUsed.tv_nsec / 1000000.0; prevTime = currentTime; if (timerCount > 1) { // Calculate average time totalTime = totalTime + timeUsed; avgTime = totalTime / timerCount; // Save the minimum time and print to console if (timeUsed < minTime) { minTime = timeUsed; } // Save the maximum time and print to console if (timeUsed > maxTime){ maxTime = timeUsed; } } timerCount++; } // Prints timer data to the console void PrintData(void) { float actualCycleTime; printf("Minimum Time: %2.3f ms\n", minTime); printf("Maximum Time: %2.3f ms\n", maxTime); printf("Average Time: %2.3f ms\n", avgTime); actualCycleTime = (float)(timerCount + 1) / runSec; printf("Frequency: %5.3f Hz\n\n", actualCycleTime); }
C
#include "ADC.h" static volatile uint16_t ADC_val = 0; static volatile uint8_t ADC_cnt = 0; static volatile uint16_t ADC_result = 0; void ADC_init() { /*Vref = AVCC*/ ADMUX |= _BV(REFS0); /*MUX3..0 = ADC6*/ ADMUX |= _BV(MUX2) | _BV(MUX1); /*ADC interrupt enable*/ ADCSRA |= _BV(ADIE); /*ADC enabled*/ ADCSRA |= _BV(ADEN); /*ADC frequency div. factor = 64*/ ADCSRA |= _BV(ADPS2) | _BV(ADPS1); /*ADC start conversion*/ ADCSRA |= _BV(ADSC); } uint8_t ADC_val_nearby(float val, float deviation){ uint16_t lower = (uint16_t)(val - deviation * val); uint16_t higher = (uint16_t)(val + deviation * val); uint16_t ADC_at_res = ADC_result; if (ADC_at_res > higher || ADC_at_res < lower) return 0; else return 1; return 0; } ISR(ADC_vect){ ADC_val += ADC; ADC_cnt++; if(ADC_cnt == 2){ ADC_cnt = 0; ADC_result = ADC_val / 2; ADC_val = 0; } ADMUX ^= _BV(MUX0); ADCSRA |= _BV(ADSC); }
C
#include <stdio.h> #define SERIAL_BUFFER_SIZE 16 #define SERIAL_BUFFER_SIZE_MASK (SERIAL_BUFFER_SIZE -1) struct serial_buffer { unsigned char head; unsigned char tail; unsigned char data[SERIAL_BUFFER_SIZE]; }; void debug_print_fifo( struct serial_buffer *fifo) { unsigned char i; printf("\nhead: %2d tail %2d Data:",fifo->head,fifo->tail); for (i=0 ; i < SERIAL_BUFFER_SIZE ; i++) { printf(" %02x", fifo->data[i]); } printf("\n"); } char fifo_putchar(struct serial_buffer *fifo) { unsigned char tail=fifo->tail; printf("printing chars\n"); if (fifo->head != tail) { tail++; tail&=SERIAL_BUFFER_SIZE_MASK; if (putchar(fifo->data[tail])) { tail&=SERIAL_BUFFER_SIZE_MASK; /* wrap around if neededd */ fifo->tail=tail; debug_print_fifo(fifo); return 1; } } return 0; } /* print into circular buffer */ /* TODO: check if local var head speed up function */ char print_fifo(const unsigned char *s, struct serial_buffer *fifo) { unsigned char head=fifo->head; char c; while ( ( c = *s++ ) ) { head++; head&=SERIAL_BUFFER_SIZE_MASK; /* wrap around if neededd */ printf("pf head: %2d tail %2d\n",head,fifo->tail); if (head != fifo->tail) { /* space left ? */ fifo->data[head]=c; } else { return -1; } } fifo->head=head; /* only store new pointer if all is OK */ return 1; } int main( int argc,const char* argv[]) { struct serial_buffer fifo; char ret; fifo.head=0; fifo.tail=0; debug_print_fifo(&fifo); ret=print_fifo("Hello world !\n",&fifo); debug_print_fifo(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=print_fifo("Der Hund.\n",&fifo); // debug_print_fifo(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); ret=fifo_putchar(&fifo); printf("ret: %d\n",ret); return 0; }
C
#include <stdio.h> #include <math.h> #include <float.h> #define N 10000 int main(void) { int k, i = 0, ind; double t, s, h, x, err; h = 10*M_PI/N; for(i = 0; i <=N; i++) { x = i*h; s = 0.; t = 1.; k = 0; while(fabs(t) >= fabs(s)*FLT_EPSILON) { s += t; t = -t*x*x/((k+1)*(k+2)); k += 2; } err = (s - cos(x) / cos(x)); ind = 0; if(fabs(err) > FLT_EPSILON) ind = 1; printf("%+le %+le %+le %d \n", x, s, err, ind); } return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { FILE* f; char msj[10]="hola a todos"; f=fopen("mihtml.html","w"); /**Estatico*/ if(f!=NULL) { // fprintf(f,"<html><head> Hola </head></html>"); // mensaje hardcodeado fprintf(f,"<head><html>"); fprintf(f,msj);// parte variable del mensaje que quiero mostrar fprintf(f,"</head></html>"); // ejemplo para escribir cierre y apertura de los tags fclose(f); } return 0; }
C
/* * life.c - Conway's Game of Life * * Read about the game at https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life * * compile with * mygcc life.c -lcurses -o life * run with * ./life [startboard.txt] * where the optional file has lines of text containing only the letter 'O' * and spaces, and no line longer than the width of the window. * * Tap any key to step from one generation to the next. * Use ^C to quit. * * This program serves as an example of * - the use of the ncurses library (search for CURSES) * - the allocation and use of a 2-dimensional array of char * - the use of fgets() to read lines from a file * * David Kotz, May 2017 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <ncurses.h> // CURSES // size of board, initialized to initial window size static int NROWS; static int NCOLS; /* characters representing live and dead cells */ static const char LIVECELL = 'O'; static const char DEADCELL = ' '; /* Local function prototypes */ static void initialize_curses(); static char** new_board(void); static void load_simple_board(char** board); static void load_board(char** board, FILE *fp); static void display_board(char** board, int generation); static void evolve(char** now, char** next); static int numNeighbors(char** now, const int x, const int y); static int neighbor(char** now, const int x, const int y); /* ***************** main ********************** */ int main(int argc, char* argv[]) { int generation = 0; // count the generations FILE* fp = NULL; // the file with the initial board if (argc > 1) { if ( (fp = fopen(argv[1], "r")) == NULL) { fprintf(stderr, "%s: cannot open '%s'\n", argv[0], argv[1]); } } // initialize curses library initialize_curses(); // CURSES // initialize and display the board char** board1 = new_board(); if (fp == NULL) { load_simple_board(board1); } else { load_board(board1, fp); fclose(fp); } display_board(board1, generation++); getch(); // pause until keystroke // CURSES // initialize a second board char** board2 = new_board(); // evolve life forward while(1) { // from board1 to board2 evolve(board1, board2); display_board(board2, generation++); getch(); // pause until keystroke // CURSES // from board2 to board1 evolve(board2, board1); display_board(board1, generation++); getch(); // pause until keystroke // CURSES } endwin(); // CURSES // I don't bother to free malloc'd memory because exit is via ^C } /* ************ initialize_curses *********************** */ /* * initialize curses // CURSES everywhere in this function */ static void initialize_curses() { // initialize the screen - which defines LINES and COLS initscr(); // cache the size of the window in our global variables // (this is a macro, which is why we don't need & before the variables.) getmaxyx(stdscr, NROWS, NCOLS); cbreak(); // actually, this is the default noecho(); // don't show the characters users type // I like yellow on a black background start_color(); init_pair(1, COLOR_YELLOW, COLOR_BLACK); attron(COLOR_PAIR(1)); } /* ************ new_board *********************** */ /* * allocate and erase a new board - fill with DEADCELL */ static char** new_board(void) { // allocate a 2-dimensional array of NROWS x NCOLS char** board = calloc(NROWS, sizeof(char*)); char* contents = calloc(NROWS * NCOLS, sizeof(char)); if (board == NULL || contents == NULL) { fprintf(stderr, "cannot allocate memory for board\r\n"); exit(1); } // set up the array of pointers, one for each row for (int y = 0; y < NROWS; y++) { board[y] = contents + y * NCOLS; } // fill the board with empty cells for (int y = 0; y < NROWS; y++) { for (int x = 0; x < NCOLS; x++) { board[y][x] = DEADCELL; } } return board; } /* ************ load_simple_board *********************** */ /* * Load the board with a simple pattern */ static void load_simple_board(char** board) { if (NCOLS >= 4) { for (int y = 0; y < NROWS; y++) { strncpy(board[y], " OOO", 4); } } } /* ************ load_board *********************** */ /* * Load the board from a file. All lines in the file should * have only DEADCELL or LIVECELL characters. */ static void load_board(char** board, FILE* fp) { const int size = NCOLS+2; // include room for \n\0 char line[size]; // a line of input int y = 0; // read each line and copy it to the board while ( fgets(line, size, fp) != NULL && y < NROWS) { int len = strlen(line); if (line[len-1] == '\n') { // normal line len--; // don't copy the newline } else { // overly wide line len = NCOLS; fprintf(stderr, "board line %d too wide for screen; truncated.\r\n", y); for (char c = 0; c != '\n' && c != EOF; c = getc(fp)) ; // scan off the excess part of the line } strncpy(board[y++], line, len); } if (!feof(fp)) { fprintf(stderr, "board too big for screen; truncated to %d lines\r\n", y); } } /* ************ display_board *********************** */ /* * Display the board onto the screen; notice we just copy all chars * of the board to the screen, then let curses figure out what to paint. */ static void display_board(char** board, int generation) { for (int y = 0; y < NROWS; y++) { for (int x = 0; x < NCOLS; x++) { move(y,x); // CURSES addch(board[y][x]); // CURSES } } mvprintw(0,0, "Generation %d", generation); // CURSES refresh(); // CURSES } /* ************ evolve ************** */ /* Produce the next board from the current board, * according to the rules: * * Every cell interacts with its eight neighbours, which are the cells * that are horizontally, vertically, or diagonally adjacent. At each * step in time, the following transitions occur: * * Any live cell with fewer than two live neighbours dies, as if caused * by underpopulation. * * Any live cell with two or three live neighbours lives on to the next * generation. * * Any live cell with more than three live neighbours dies, as if by * overpopulation. * * Any dead cell with exactly three live neighbours becomes a live cell, * as if by reproduction. * * From https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life#Rules */ static void evolve(char** now, char** next) { // Compute a new cell value for every cell, by counting its neighors // and following the above rules. for (int y = 0; y < NROWS; y++) { for (int x = 0; x < NCOLS; x++) { int neighbors = numNeighbors(now, y, x); if (now[y][x] == LIVECELL) { // cell currently live if (neighbors < 2 || neighbors > 3) { next[y][x] = DEADCELL; } else { next[y][x] = LIVECELL; } } else { // cell currently empty if (neighbors == 3) { next[y][x] = LIVECELL; } else { next[y][x] = DEADCELL; } } } } } /* ************** numNeighbors *************** */ /* * Return the count of neighbors for this cell, * respecting the boundaries of the board. */ static int numNeighbors(char** now, const int y, const int x) { return neighbor(now, y-1, x-1) + // above left neighbor(now, y-1, x-0) + // above neighbor(now, y-1, x+1) + // above right neighbor(now, y-0, x-1) + // left neighbor(now, y-0, x+1) + // right neighbor(now, y+1, x-1) + // below left neighbor(now, y+1, x-0) + // below neighbor(now, y+1, x+1); // below right } // return 0 or 1, whether there is a neighbor at the given position static int neighbor(char** now, const int y, const int x) { if (y < 0 || y >= NROWS || x < 0 || x >= NCOLS) { return 0; // out of bounds; implicitly no neighbor } else { if (now[y][x] == LIVECELL) { return 1; // neighbor! } else { return 0; // no neighbor } } }
C
#include "header.h" /* MAKE TREE */ void makeTree(char c, tree *T){ simpul *node; node = (simpul *) malloc(sizeof (simpul)); node->info = c; node->right = NULL; node->left = NULL; (*T).root = node; } /* ADD */ //=== right ===// void addRight(char c, simpul *root){ count_root++; if(root->right == NULL){ /*jika sub pohon kanan kosong*/ simpul *node; node = (simpul *) malloc(sizeof (simpul)); node->info = c; node->right = NULL; node->left = NULL; root->right = node; }else{ printf("sub pohon kanan telah terisi\n"); } } //=== left ===// void addLeft(char c, simpul *root){ count_root++; if(root->left == NULL){ /*jika sub pohon kanan kosong*/ simpul *node; node = (simpul *) malloc(sizeof (simpul)); node->info = c; node->right = NULL; node->left = NULL; root->left = node; }else{ printf("sub pohon kiri telah terisi\n"); } } /* DEL */ //=== right ===// void delRight(simpul *root){ count_root--; if((root->right->right == NULL) && (root->right->left == NULL)){ simpul *node = root->right; root->right = NULL; free(node); }else{ printf("punteun teu tiasa dihapus da gaduh budak\n"); } } //=== left ===// void delLeft(simpul *root){ count_root--; if((root->left->right == NULL) && (root->left->left == NULL)){ simpul *node = root->left; root->left = NULL; free(node); }else{ printf("punteun teu tiasa dihapus da gaduh budak\n"); } } /* PRINT */ //=== preorder ===// void printTreePreOrder(simpul *root){ if(root != NULL){ printf("%c", root->info); count1++; if(count1 < count_root){ printf(" - "); } printTreePreOrder(root->left); printTreePreOrder(root->right); } } //=== inorder ===// void printTreeInOrder(simpul *root){ if(root != NULL){ printTreeInOrder(root->left); printf("%c", root->info); count2++; if(count2 < count_root){ printf(" - "); } printTreeInOrder(root->right); } } //=== postorder ===// void printTreePostOrder(simpul *root){ if(root != NULL){ printTreePostOrder(root->left); printTreePostOrder(root->right); printf("%c", root->info); count3++; if(count3 < count_root){ printf(" - "); } } } /* COPY */ void copyTree(simpul *root1, simpul **root2){ if(root1 != NULL){ (*root2) = (simpul *) malloc(sizeof (simpul)); (*root2)->info = root1->info; //cek kiri if(root1->left != NULL){ copyTree(root1->left, &(*root2)->left); }else{ (*root2)->left = NULL; } //cek kanan if(root1->right != NULL){ copyTree(root1->right, &(*root2)->right); }else{ (*root2)->right = NULL; } } } /* ISEQUAL */ int isEqual(simpul *root1, simpul *root2){ int hasil = 1; if((root1 != NULL)&&(root2 != NULL)){ if(root1->info != root2->info){ hasil = 0; }else{ isEqual(root1->left, root2->left); isEqual(root1->right, root2->right); } }else{ hasil = 0; } return hasil; }
C
#include "utils.h" /** * Implementing a 0-indexed heap * Needed for efficient implementation of event priority queue * to simulate when events like a process arriving or the CPU finishing * computing a process happens */ struct EventHeap *createPriorityQueue(int capacity) { struct EventHeap *priority_queue = malloc(sizeof(struct EventHeap)); priority_queue->arr = malloc(capacity * sizeof(struct Event)); priority_queue->num_events = 0; priority_queue->capacity = capacity; return priority_queue; } void destroyPriorityQueue(struct EventHeap *priority_queue) { free(priority_queue->arr); free(priority_queue); } int isPriorityQueueEmpty(struct EventHeap *priority_queue) { return priority_queue->num_events == 0; } void insertEvent(struct EventHeap *priority_queue, int time, enum EventType event_type, struct ProcessInfo *pinfo) { priority_queue->arr[priority_queue->num_events].time = time; priority_queue->arr[priority_queue->num_events].event_type = event_type; priority_queue->arr[priority_queue->num_events].pinfo = pinfo; heapifyUp(priority_queue, priority_queue->num_events); ++priority_queue->num_events; } struct Event *getEarliestEvent(struct EventHeap *priority_queue) { return priority_queue->arr; } void popEarliestEvent(struct EventHeap *priority_queue) { priority_queue->arr[0] = priority_queue->arr[priority_queue->num_events - 1]; --priority_queue->num_events; heapifyDown(priority_queue, 0); } void heapifyUp(struct EventHeap *priority_queue, int index) { int parent_index = (index - 1) / 2; if (compareEvents(&(priority_queue->arr[index]), &(priority_queue->arr[parent_index])) < 0) { // Swap the event up then continue heapifying up struct Event temp = priority_queue->arr[index]; priority_queue->arr[index] = priority_queue->arr[parent_index]; priority_queue->arr[parent_index] = temp; heapifyUp(priority_queue, parent_index); } } void heapifyDown(struct EventHeap *priority_queue, int index) { int left_index = index * 2 + 1; int right_index = index * 2 + 2; int min_index; if (left_index >= priority_queue->num_events) return; else if (right_index >= priority_queue->num_events) min_index = left_index; else if (compareEvents(&(priority_queue->arr[left_index]), &(priority_queue->arr[right_index])) < 0) min_index = left_index; else min_index = right_index; if (compareEvents(&(priority_queue->arr[min_index]), &(priority_queue->arr[index])) < 0) { // swap event[index] for event[min_index], then heapify down from min_index struct Event temp = priority_queue->arr[index]; priority_queue->arr[index] = priority_queue->arr[min_index]; priority_queue->arr[min_index] = temp; heapifyDown(priority_queue, min_index); } } int compareEvents(struct Event *event1, struct Event *event2) { // Sort by event time first, // then event type if the 2 events have the same time // then the process remaining execution time if the event types are both PROCESS_ARRIVE if (event1->time != event2->time) return event1->time - event2->time; if (event1->event_type != event2->event_type) return event1->event_type - event2->event_type; if (event1->event_type == PROCESS_ARRIVE) return event1->pinfo->remaining_execution_time - event2->pinfo->remaining_execution_time; return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/file.h> #include <fcntl.h> #define MEMSZ 200 * 1024 * 1024 int main( int argc, char **argv ) { int fd; char *p, *path = getenv("PATH_INFO"); if( path && strncmp( path, "/lock", 5 ) == 0 ){ if( ( fd = open("/tmp/loadtest.lock", O_CREAT|O_WRONLY, 0666) ) < 0 ){ perror("open"); return -1; } if( flock(fd, LOCK_EX) < 0 ){ perror("open"); return -1; } } p = malloc(MEMSZ); bzero(p, MEMSZ); printf( "Content-type: text/html\n\nOK\n" ); return 0; }
C
#include <stdio.h> int main (){ int arr[2][3][5]={2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60}; int l,m,n; for(l=0; l<2;l++){ for(m=0;m<3;m++){ for(n=0;n<5;n++){ printf("Arreglos [%d][%d][%d]: %d\n", l,m,n,arr[l][m][n]); } } } return 0; }
C
#include <stdio.h> #include "sorts.h" int main(int argc, char *argv[]){ int a[6] = {2,6,3,4,5,1}; int b[6]; int c[6]; for(int q = 0; q < 6;q++){ b[q] = a[q]; c[q] = a[q]; } List nList = create_list(a,6); merge_sort_list(&nList); ListNode *trav = nList.head; while(trav != NULL){ printf("%d", trav -> value); trav = trav -> next; } empty_list(&nList); BST nBst = create_bst(b,6); tree_sort_array(b,6); printf("\n"); for(int k = 0; k < 6; k++){ printf("%d", b[k]); } empty_bst(&nBst); quick_sort_array(c,6); printf("\n"); for(int k = 0; k < 6;k++){ printf("%d", c[k]); } return EXIT_SUCCESS; }
C
#include "../include/table_operations.h" #include "../include/jhash.h" #include <sys/time.h> /******************************五元组精确匹配********************************/ unsigned int get_tuple_hash(five_tuple_info tuple,unsigned int length) { unsigned int a[3]; a[0] = tuple.dst_ip; a[1] = tuple.src_ip; a[2] = (tuple.dst_port<<16)|tuple.src_ip; return jhash2(a,3,VOICE_HASH_GOLDEN_INTERER)&(length-1); } table_operations init_index_table(unsigned int tablesize) { table_operations tops; tops.tablesize = tablesize; tops.idle_id_count = tablesize; htitem **ht = (htitem **)calloc(tablesize,sizeof(htitem*)); for(int i =0;i<tablesize;i++) { ht[i]=(htitem *)malloc(sizeof(htitem)); memset(ht[i],0,sizeof(htitem)); } tops.index_table = ht; LinkedList head = NULL; head = tailInsert(&head,tablesize); tops.idle_id_table = head; return tops; } int search_index_table(table_operations tablename, five_tuple_info md) { unsigned int index = get_tuple_hash(md,tablename.tablesize); htitem *tmp = tablename.index_table[index]; while (tmp->next) { tmp = tmp->next; if(cmp_tuples(&md,&(tmp->md))) { //tmp->entry_info.hit_count++; return tmp->id; } } return -1; } int cmp_tuples(five_tuple_info *key1,five_tuple_info *key2) { u8 *m1 = (u8 *)key1; u8 *m2 = (u8 *)key2; u8 diffs = 0; int i = 0; while(i<13 && diffs == 0) { diffs |= (m1[i] ^ m2[i]); i++; } return diffs == 0; } int insert_new_entry(table_operations *tablename, five_tuple_info md) { int pos; if(tablename->idle_id_count == 0) { printf("FULL!\n"); return -1; } else { //find pos to insert LinkedList p = tablename->idle_id_table->next->next; pos = p->data; //write in index table // index_table_entry temp; // struct timeval start; // gettimeofday(&start,NULL); // temp.time = start; // temp.valid = 1; // temp.hit_count = 0; //update idle id count tablename->idle_id_count --; //update idle id table deleteK(tablename->idle_id_table,1); unsigned int index = get_tuple_hash(md,tablename->tablesize);//获取哈希值即桶的位置 //printf("hashvalue: %d pos: %d\n",index,pos); htitem *tmp = tablename->index_table[index]; while (tmp->next) { tmp = tmp->next; } tmp->next=(htitem *)malloc(sizeof(htitem)); tmp->next->md = md; tmp->next->id = pos; //tmp->next->entry_info = temp; tmp->next->next = NULL; return pos; } } int insert_new_entry_to_pos(table_operations *tablename, five_tuple_info md,int pos) { if(tablename->idle_id_count == 0) { printf("FULL!\n"); return -1; } else { //find pos to insert int x_pos = findX(tablename->idle_id_table,pos); if(x_pos == -1) { printf("This Pos is INAVALIDABLE!\n"); return -1; } else { deleteK(tablename->idle_id_table,x_pos); } //write in index table // index_table_entry temp; // struct timeval start; // gettimeofday(&start,NULL); // temp.time = start; // temp.valid = 1; // temp.hit_count = 0; //update idle id count //tablename->idle_id_count --; //update idle id table //deleteK(tablename->idle_id_table,1); unsigned int index = get_tuple_hash(md,tablename->tablesize);//获取哈希值即桶的位置 printf("hashvalue: %d pos: %d\n",index,pos); htitem *tmp = tablename->index_table[index]; while (tmp->next) { tmp = tmp->next; } tmp->next=(htitem *)malloc(sizeof(htitem)); tmp->next->md = md; tmp->next->id = pos; //tmp->next->entry_info = temp; tmp->next->next = NULL; return pos; } } int delete_entry(table_operations *tablename, five_tuple_info md) { int tablesize = tablename->tablesize; unsigned int index = get_tuple_hash(md,tablesize); htitem *tmp = tablename->index_table[index]; while (tmp->next) { tmp = tmp->next; if(cmp_tuples(&md,&(tmp->md))) { int id = tmp->id; //tmp->entry_info.valid = 0; tablename->idle_id_count++; add(tablename->idle_id_table,tablesize-1,id); return 0; } } printf("NO Entry!\n"); return -1; } int delete_all_entry(table_operations *tablename) { int size = tablename->tablesize; htitem *tmp,*p; for(int i = 0;i<size;i++) { tmp = tablename->index_table[i]->next; while (tmp) { p = tmp->next; add(tablename->idle_id_table,size-1,tmp->id); free(tmp); tablename->idle_id_count ++; tmp = p; } tablename->index_table[i]->next = NULL; } return 0; } unsigned int get_idle_entry_num(table_operations tablename) { return tablename.idle_id_count; } int get_table_entry_num(table_operations *tablename) { return (tablename->tablesize)-(tablename->idle_id_count); } void print_entry_info(table_operations tablename) { int size = tablename.tablesize; htitem *tmp; for(int i = 0;i<size;i++) { tmp = tablename.index_table[i]; printf("Indextable[%d]\n",i); while (tmp->next) { tmp = tmp->next; five_tuple_info md = tmp->md; //struct timeval time = tmp->entry_info.time; //int count = tmp->entry_info.hit_count; printf("==========================================================\n"); //printf("Valid: %d\n",tmp->entry_info.valid); printf("Tuples Value: %x %d %x %d %d\n",md.src_ip,md.src_port,md.dst_ip,md.dst_port,md.proto); printf("Index: %d\n",tmp->id); //printf("Time: %s",ctime((time_t *)&(time.tv_sec))); //printf("HitCounter: %d\nID:%d\n",count,tmp->id); printf("==========================================================\n"); } } } void free_index_table(table_operations *tablename) { int length = tablename->tablesize; for(int i = 0;i<length;i++) { free(tablename->index_table[i]); } free(tablename->index_table); free_list(tablename->idle_id_table); } /******************************带掩码精确匹配********************************/ table_operations_mask init_index_table_m(unsigned int tablesize) { table_operations_mask tops; tops.tablesize = tablesize; tops.idle_id_count = tablesize; index_table_entry_mask *index_table = (index_table_entry_mask *)calloc(tablesize, sizeof(index_table_entry_mask)); tops.index_table = index_table; LinkedList head = NULL; head = tailInsert(&head,tablesize); tops.idle_id_table = head; return tops; } int search_index_table_m(table_operations_mask tablename, five_tuple_info md) { int tablesize = tablename.tablesize; for (int i = 0; i < tablesize; i++) { if(cmp_tuples_mask(&md,&(tablename.index_table[i].rule))&&tablename.index_table[i].valid) { return i; } else { continue; } } return -1; } int cmp_tuples_mask(five_tuple_info *key,tuple_rule *rule) { five_tuple_info *value = &(rule->value); five_tuple_info *mask = &(rule->mask); u8 *m1 = (u8 *)value; u8 *m2 = (u8 *)key; u8 *m3 = (u8 *)mask; u8 diffs = 0; int i = 0;//*cnt = sizeof(struct flow)/4; while(i<13 && diffs == 0) { diffs |= (m1[i] ^ m2[i])&m3[i]; i++; } return diffs == 0; } int insert_new_entry_m(table_operations_mask *tablename,tuple_rule rule) { if(tablename->idle_id_count == 0) { printf("FULL!\n"); return 0; } else { //find pos to insert LinkedList p = tablename->idle_id_table->next->next; int pos = p->data; //printf("____%d\n",pos); //write in index table index_table_entry_mask temp; temp.rule = rule; struct timeval start; gettimeofday(&start,NULL); temp.valid = 1; temp.index = pos; tablename->index_table[pos] = temp; //update idle id count tablename->idle_id_count --; //update idle id table deleteK(tablename->idle_id_table,1); return pos; } } //插入新的表项掩码规则至指定位置 int insert_new_entry_to_pos_m(table_operations_mask *tablename,tuple_rule rule,int pos) { if(tablename->idle_id_count == 0) { printf("FULL!\n"); return 0; } else { //find pos to insert int x_pos = findX(tablename->idle_id_table,pos); if(x_pos == -1) { printf("This Pos is INAVALIDABLE!\n"); return -1; } else { deleteK(tablename->idle_id_table,x_pos); } //LinkedList p = tablename->idle_id_table->next->next; //int pos = p->data; //printf("____%d\n",pos); //write in index table index_table_entry_mask temp; temp.rule = rule; struct timeval start; gettimeofday(&start,NULL); temp.valid = 1; temp.index = pos; tablename->index_table[pos] = temp; //update idle id count tablename->idle_id_count --; //update idle id table //deleteK(tablename->idle_id_table,1); return pos; } } int delete_entry_m(table_operations_mask *tablename,tuple_rule rule) { int tablesize = tablename->tablesize; int id = 0; for (int i = 0; i < tablesize + 1; i++) { if(i == tablesize) { id = -1; } else { if(cmp_tuples(&(tablename->index_table[i].rule.mask),&(rule.mask))&&cmp_tuples(&(tablename->index_table[i].rule.value),&(rule.value))) { id = i; break; } else { continue; } } } //printf("delete pos: %d\n",id); if(id == -1) { printf("No entry!"); return -1; } else { tablename->index_table[id].valid = 0; // idle 操作 tablename->idle_id_count++; add(tablename->idle_id_table,tablesize-1,id); return 0; } } unsigned int get_idle_entry_num_m(table_operations_mask tablename) { return tablename.idle_id_count; } int get_table_entry_num_m(table_operations_mask *tablename) { return (tablename->tablesize)-(tablename->idle_id_count); } void print_entry_info_m(table_operations_mask tablename,int entry_id) { index_table_entry_mask temp = tablename.index_table[entry_id]; five_tuple_info md = temp.rule.value; five_tuple_info md1 = temp.rule.mask; printf("==========================================================\n"); printf("Valid: %d\n",temp.valid); printf("Tuples Value: %x %d %x %d %d\n",md.src_ip,md.src_port,md.dst_ip,md.dst_port,md.proto); printf("Tuples Mask: %x %d %x %d %d\n",md1.src_ip,md1.src_port,md1.dst_ip,md1.dst_port,md1.proto); //printf("Time: %s",ctime((time_t *)&(time.tv_sec))); printf("==========================================================\n"); //print(tablename.idle_id_table); } int delete_all_entry_m(table_operations_mask *tablename) { int size = tablename->tablesize; for(int i = 0;i<size;i++) { index_table_entry_mask *tmp = &(tablename->index_table[i]); if(tmp->valid == 1) { tmp->valid = 0; add(tablename->idle_id_table,size-1,tmp->index); tablename->idle_id_count++; } } return 0; } void free_index_table_m(table_operations_mask *tablename) { int length = tablename->tablesize; for(int i = 0;i<length;i++) { free(&(tablename->index_table[i])); } free_list(tablename->idle_id_table); } /******************************链表相关操作********************************/ //头插法 LinkedList headInsert(LinkedList *L,unsigned int tablesize){ LinkedList p,s; (*L) = s = (LinkedList)malloc(sizeof(LNode)); s->next = NULL; int num = 0; while(num < tablesize){ p = (LinkedList)malloc(sizeof(LNode)); p->data = num; p->next = s->next; s->next = p; num ++; } return s; } //尾插法 LinkedList tailInsert(LinkedList *L,unsigned int tablesize){ LinkedList p,s; int num = 0; int count = -1; (*L) = s = (LinkedList)malloc(sizeof(LNode)); s->next = NULL; while(num < tablesize+1){ p = (LinkedList)malloc(sizeof(LNode)); p->data = count; p->next = NULL; s->next = p; s = p; num ++; count++; } return (*L); } //给第k给结点之后增加一个值x void add(LinkedList L, int k, int x){ int num; LinkedList p,s; p = L->next; for(int i=1; i<k; i++){ p = p->next; } s = (LinkedList)malloc(sizeof(LNode)); s->data = x; s->next = p->next; p->next = s; } //删除第k个结点 void deleteK(LinkedList L, int k){ LinkedList p,q; p = L->next; for(int i=1; i<k-1; i++){ p = p->next; } q = p->next; p->next = q->next; free(q); } //更改第k个结点的值为x void update(LinkedList L, int k, int x){ LinkedList p = L->next; for(int i=1; i<k; i++){ p = p->next; } p->data = x; } //查询第k个结点的值 int getK(LinkedList L, int k){ LinkedList p = L->next; for(int i=1; i<k; i++){ p = p->next; } return p->data; } //输出链表所有值 void print(LinkedList L){ LinkedList p = L->next; while(p){ printf("%d\t", p->data); p = p->next; } printf("\n"); } int findX(LinkedList L,int x) { LinkedList p = L->next; int pos = 0; while(p->next) { if(p->data == x) { return pos; } pos ++; p = p->next; } return -1; } void free_list(LinkedList L) { LinkedList p,q; p = L->next; while(p) { q = p->next; free(p); p = q; } free(L); }
C
/*---------------------------------------------------------------------------------------------------------------------------------------------------------- DaysConvert.c Program to convert days into years, months and days DIVYA RAJ K 09-09-2018 -----------------------------------------------------------------------------------------------------------------------------------------------------------*/ #include<stdio.h> main() { int Days,Years,Months,NumDays; system("clear"); printf("Program to convert days into years, months and days\n\n"); printf("Enter the total number of days:\n"); scanf("%d",&Days); NumDays=Days; Years=Days/365; Days=Days%365; Months=Days/30; Days=Days%30; printf("\n%d days = %d years %d months and %d days",NumDays,Years,Months,Days); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_find_min_elem_to_put_in_b.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rkhelif <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/19 19:32:52 by rkhelif #+# #+# */ /* Updated: 2021/08/22 21:15:16 by rkhelif ### ########.fr */ /* */ /* ************************************************************************** */ #include "push_swap.h" void ft_find_min_elem_to_put_in_b(t_list **list1, t_list **list2, void (**ptr)(t_list **list1, t_list **list2)) { t_list *temp; t_list *min; int count1; int count2; count1 = 0; count2 = 0; temp = *list1; min = ft_find_min_elem_list(list1); if (temp->nbr == min->nbr) return (ft_action(list1, list2, ptr, PB)); while (temp != NULL && temp->nbr != min->nbr && ++count1 != -1) temp = temp->next; count2++; temp = ft_find_last_elem_list(list1); while (temp != NULL && temp->nbr != min->nbr) { count2++; temp = temp->prev; } if (count1 <= count2) ft_action(list1, list2, ptr, RA); else ft_action(list1, list2, ptr, RRA); }
C
Escreva um programa que pede ao utilizador um valor N correspondente a um certo período de tempo em segundos. O programa deverá apresentar no output esse período de tempo no formato HH:MM:SS. Sugestão: utilize o operador que calcula o resto da divisão (%). Input: 96 Output: Horas: 0 Minutos:1 Segundos: 36 #include <stdio.h> #include <stdio.h> int main() { int N, hora, min, sec; scanf("%d",&N); hora = N/3600; min = (N -(3600*hora))/60; sec= (N -(3600*hora)-(min*60)); printf("Horas: %d Minutos:%d Segundos: %d\n",hora,min,sec); return 0; }
C
/* * ===================================================================================== * * Filename: console.c * * Description: Command console with interpreter * * Version: 1.0 * Created: 西元2020年06月05日 14時04分41秒 * Revision: none * Compiler: gcc * * Author: Lai Liang-Wei (), [email protected] * Organization: * * ===================================================================================== */ #include <ctype.h> #include <fcntl.h> #include <inttypes.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <console.h> #include "scaleoutmanager.h" /* global variable */ static cmd_ptr cmd_list = NULL; static param_ptr param_list = NULL; static bool quit_flag = false; static char *prompt = "CMD> "; static bool prompt_flag = true; static bool block_flag = false; /* Implement RIO package */ #define RIO_BUFSIZE 8192 /* Allow file size */ static char linebuf[RIO_BUFSIZE]; typedef struct _RIO rio_obj, *rio_ptr; struct _RIO { int fd; /* File descriptor */ int cnt; /* Unread bytes in internal buffer */ char *bufptr; /* Next unread byte in internal buffer */ char buf[RIO_BUFSIZE]; /* Internal buffer */ rio_ptr prev; /* Next element in stack */ }; static rio_ptr buf_stack = NULL; static char linebuf[RIO_BUFSIZE]; int fd_max = 0; bool push_file(char *filename) { int fd = filename ? open(filename, O_RDONLY) : STDIN_FILENO; if (fd < 0) return false; if (fd > fd_max) fd_max = fd; rio_ptr riop = malloc(sizeof(rio_obj)); if (!riop) return false; riop->fd = fd; riop->cnt = 0; riop->bufptr = riop->buf; riop->prev = buf_stack; buf_stack = riop; return true; } void pop_file() { if (buf_stack) { rio_ptr file = buf_stack; buf_stack = buf_stack->prev; close(file->fd); free(file); } } static bool do_quit_cmd(int argc, char *argv[]); static bool do_help_cmd(int argc, char *argv[]); void init_cmd() { cmd_list = NULL; param_list = NULL; buf_stack = NULL; add_cmd("quit", do_quit_cmd, " | Exit program"); add_cmd("help", do_help_cmd, " | Show documentation"); } void add_cmd(char *name, cmd_function operation, char *documentation) { cmd_ptr next_cmd = cmd_list; cmd_ptr *last_cmd = &cmd_list; while (next_cmd && strcmp(name, next_cmd->name) > 0) { last_cmd = &next_cmd->next; next_cmd = next_cmd->next; } cmd_ptr new = (cmd_ptr) malloc(sizeof(cmd_obj)); if (new == NULL) abort; new->name = name; new->operation = operation; new->documentation = documentation; new->next = next_cmd; *last_cmd = new; } void add_param(char *name, int *pval, param_function setter, char *documentation) { param_ptr next_param = param_list; param_ptr *last_param = &param_list; while (next_param && strcmp(name, next_param->name) > 0) { last_param = &next_param->next; next_param = next_param->next; } param_ptr new = malloc(sizeof(param_obj)); if (new == NULL) abort(); new->name = name; new->setter = setter; new->documentation = documentation; new->next = next_param; *last_param = new; } static char **parse_args(char *line, int *argcp) { char *scan = line; char c = 0; int argc = 0; bool skipping = true; int len = strlen(line); char *buf = malloc(len + 1); char *current = buf; /* Split line into sevral componien */ while ((c = *scan++) != '\0') { if (isspace(c)) { if (!skipping) { *current++ = '\0'; skipping = true; } } else { if (skipping) { argc++; skipping = false; } *current++ = c; } } char **argv = calloc(argc, sizeof(char *)); current = buf; for (int i = 0; i < argc; i++) { argv[i] = malloc(strlen(current) + 1); if (argv[i] == NULL) return NULL; strncpy(argv[i], current, strlen(current) + 1); current += strlen(argv[i]) + 1; } free(buf); *argcp = argc; return argv; } static bool interpret_cmda(int argc, char *argv[]) { bool ok = true; if (argc == 0) return true; cmd_ptr cmdp = cmd_list; while (cmdp && strcmp(cmdp->name, argv[0]) != 0) cmdp = cmdp->next; if (cmdp != NULL) { ok = cmdp->operation(argc, argv); if (!ok) { printf("cmd:%s operfail", cmdp->name); } } else { printf("Unknown command \'%s\'\n", argv[0]); ok = false; } return ok; } static bool interpret_cmd(char *cmdline) { if (!cmdline) return true; int argc = 0; char **argv = parse_args(cmdline, &argc); bool ok = interpret_cmda(argc, argv); for (int i = 0; i < argc; i++) free(argv[i]); free(argv); return ok; } void quit_helper(cmd_function qfunc) {} /* Built-in commands */ static bool do_quit_cmd(int argc, char *argv[]) { bool ok = true; cmd_ptr cmdp = cmd_list; while (cmdp) { cmd_ptr old = cmdp; cmdp = cmdp->next; free(old); } param_ptr paramp = param_list; while (paramp) { param_ptr old = paramp; paramp = paramp->next; free(old); } while (buf_stack) pop_file(); quit_flag = true; return ok; } static bool do_help_cmd(int argc, char *argv[]) { if (argc == 1) { cmd_ptr cmdp = cmd_list; printf("Commands:\n"); while (cmdp) { printf("\t%s\t%s\n", cmdp->name, cmdp->documentation); cmdp = cmdp->next; } param_ptr paramp = param_list; printf("Options:\n"); while (paramp) { printf("\t%d\t%s\n", paramp->name, paramp->documentation); paramp = paramp->next; } } return true; } bool finish_check() {} static char *readline() { int cnt = 0; char *lbufp = linebuf; char c; if (!buf_stack) return NULL; for (cnt = 0; cnt < RIO_BUFSIZE - 2; cnt++) { if (buf_stack->cnt <= 0) { buf_stack->cnt = read(buf_stack->fd, buf_stack->buf, RIO_BUFSIZE); /* Read will save offset */ buf_stack->bufptr = buf_stack->buf; if (buf_stack->cnt <= 0) { /* got EOF */ pop_file(); // why? if (cnt > 0) { *lbufp++ = '\n'; *lbufp++ = '\0'; return linebuf; } return NULL; } } c = *buf_stack->bufptr++; *lbufp++ = c; buf_stack->cnt--; if (c == '\n') break; } if (c != '\n') // Hit buffer limit *lbufp++ = '\n'; *lbufp++ = '\0'; return linebuf; } bool readReady() { for (int i = 0; buf_stack && i < buf_stack->cnt; i++) { if (buf_stack->bufptr[i] == '\n') { return true; } } return false; } static bool cmd_done() { return !buf_stack || quit_flag; } static int cmd_select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout) { char *cmdline; while (!block_flag && readReady()) { cmdline = readline(); interpret_cmd(cmdline); } if (cmd_done()) return 0; int infd; fd_set local_readset; if (!block_flag) { if (!readfds) readfds = &local_readset; infd = buf_stack->fd; FD_SET(infd, readfds); if (infd == STDIN_FILENO && prompt_flag) { printf("%s", prompt); fflush(stdout); } if (infd >= nfds) nfds = infd + 1; } if (nfds == 0) return 0; int result = select(nfds, readfds, writefds, exceptfds, timeout); if (result <= 0) return result; infd = buf_stack->fd; if (readfds && FD_ISSET(infd, readfds)) { /* Commandline input available */ FD_CLR(infd, readfds); result--; cmdline = readline(); if (cmdline) interpret_cmd(cmdline); } return result; } bool start_console(char *infile_name) { if (!push_file(infile_name)) { printf("faild to push \'%s\' at start", infile_name); return false; } while (!cmd_done()) cmd_select(0, NULL, NULL, NULL, NULL); return true; } bool get_int(char *vname, int *loc) { char *end = NULL; long int v = strtol(vname, &end, 0); if (v == LONG_MIN || *end != '\0') return false; *loc = (int) v; return true; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_cconv.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: cfarjane <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/05/24 18:12:08 by cfarjane #+# #+# */ /* Updated: 2018/09/05 14:29:34 by cfarjane ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/libft.h" static int ft_cconv_next(int ret, t_flags *flag, va_list ap) { ret = print_zero_char(flag, ret); if (flag->minus == 1) ret = print_minus_char((char)va_arg(ap, int), flag, ret); else { ft_putchar((char)va_arg(ap, int)); ret++; } return (ret); } int print_minus_wchar(wchar_t wc, t_flags *flag) { int ret; ret = 0; ft_putwchar(wc); if (flag->minus == 1 && flag->width > 0) ft_putnchar(' ', flag->width - ft_wcharlen(wc)); else ret = 1; if (flag->width > ft_wcharlen(wc)) ret += flag->width; else ret += ft_wcharlen(wc); return (ret); } int print_minus_char(char c, t_flags *flag, int ret) { ft_putchar(c); if (flag->minus == 1 && flag->width > 0) { ret++; ret += ft_putnchar(' ', flag->width - 1); } else ret = 1; return (ret); } int width_char(t_flags *flag, int ret) { if (flag->width > 1 && flag->minus == 0) { if (flag->zero == 0 && flag->pre == 0) { ft_putnchar(' ', flag->width - 1); ret += (flag->width - 1); } else ret += print_zero_char(flag, ret); } return (ret); } int ft_cconv(char *format, va_list ap, t_flags *flag) { wchar_t wchar; int ret; ret = 0; wchar = 0; ret += width_char(flag, ret); if (flag->length == 0 && *format == 'c') ret = ft_cconv_next(ret, flag, ap); else if ((flag->length == 1 && *format == 'c') || *format == 'C') { wchar = va_arg(ap, wchar_t); ret = print_zero_char(flag, ret); if (flag->minus == 1) ret += print_minus_wchar(wchar, flag); else { if (wchar < 0 || (wchar > 55295 && wchar < 57344) || wchar > 1114111) ret = -1; else ret += ft_putwchar(wchar); } } return (ret); }
C
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <time.h> #include <stdlib.h> void selection_Sort(int* arr, int size) { int min = 0; for (int i = 0; i < size; i++) { min =i; for (int j = i; j < size; j++) { if (arr[min] > arr[j]) min = j; } int temp = arr[i]; arr[i] = arr[min]; arr[min] = temp; } return; } int main() { FILE* fp = fopen("lab1.data.txt", "r"); if (fp == NULL) { printf("cannot open file\n"); return; } int n; double duration; clock_t start; fscanf(fp,"%d", &n); int* arr = (int*)malloc(sizeof(int) * n); // Ҵ for (int i = 0; i < n; i++) { fscanf(fp,"%d", &arr[i]); } // Input : --- for (int i = 0; i < n; i++) { if (i == 0) { printf("Input: "); } printf("%d", arr[i]); if (i != n - 1) { printf(", "); } } printf("\n"); // long repetitions = 0; start = clock(); do { repetitions++; selection_Sort(arr, n); } while (clock() - start < 1000); duration = ((double)(clock() - start)) / CLOCKS_PER_SEC; printf("\n"); printf("\n"); //Sorted: --- for (int i = 0; i < n; i++) { if (i == 0) { printf("Sorted: "); } printf("%d", arr[i]); if (i != n - 1) { printf(", "); } } printf("\n"); //ð printf("ð : %lf\n", duration/repetitions); free(arr); return 0; }
C
/* Firmware for Serial-CV converter board. * http://www.fetchmodus.org/projects/serialcv/ * Written in 2013 by Nick Ames <[email protected]>. * Placed in the Public Domain. */ #include <avr/interrupt.h> #include <stdbool.h> #define F_CPU 8000000UL #include <util/delay.h> #include <stdint.h> /* This program receives commands over RS-232 (9600 baud, 8N1) on pin * PB3. (As the attiny25 lacks a UART, this is done in software.) * It communicates with an MCP4716/4726 DAC over I2C on pins * PB2 (SCL) and PB0 (SDA). This is also performed in software. */ /* Each command consists of two bytes, containing the desired voltage word and * a shutdown bit. If the shutdown bit is 1, the voltage word is ignored, and * the DAC is put into a high-Z mode. When shutdown, the DAC can be overridden * by another controller. * Command Format (V# = voltage word bit, S = shutdown bit, X = don't care): * 1st byte 2nd byte * MSB LSB MSB LSB * V11 V10 V9 V8 V7 V6 V5 1 X S V4 V3 V2 V1 V0 0 */ /* MCP4716/4726 I2C Address */ #define I2C_ADDR 0b1100000 /* Set the DAC output voltage. * This re-enables the DAC after shutdown. */ void voltage(uint16_t voltage_word); /* Shutdown the DAC, putting its output in a Hi-Z mode. */ void shutdown_dac(void); /* Receive a byte over the RS-232 connection. * Blocks until a byte has been received. */ uint8_t get_byte(void); int main(void){ /* Setup pins. */ PORTB = 1 & ~_BV(PB0) & ~_BV(PB2); /* Setup timer and interrupts for RS-232 */ GIMSK |= _BV(PCIE); /* Enable Pin Change Interrupt. */ PCMSK = _BV(PCINT3); /* Enable PCINT3. */ GTCCR |= _BV(TSM) | _BV(PSR0); /* Stop timer 0. */ TCNT0 = 0; /* Reset timer 0. */ TCCR0B |= _BV(CS01); /* Set timer 0 clock to 1Mhz (system clock/8). */ TIMSK |= _BV(OCIE0A); /* Enable timer interrupts. */ sei(); /* Enable interrupts. */ uint8_t first, second; uint16_t dac_word; shutdown_dac(); first = get_byte(); while(1){ if(first & 0x01){ second = get_byte(); if(second & 0x01){ first = second; continue; } else { if(second & 0x40){ shutdown_dac(); } else { dac_word = (second & 0x3E) >> 1; dac_word |= (first & 0xFE) << 4; voltage(dac_word); } } } first = get_byte(); } return 0; } #define SDA_H DDRB &= ~_BV(PB0) #define SDA_L DDRB |= _BV(PB0) #define SCL_H DDRB &= ~_BV(PB2) #define SCL_L DDRB |= _BV(PB2) #define I2C_DELAY 2 /* Half of SCL period, in us. */ /* Send a byte over I2C. SCL should be low before calling this function. * The MSB is the first bit to be transmitted. */ void send_byte(uint8_t byte){ uint8_t i; for(i=0;i<8;i++){ _delay_us(I2C_DELAY); if(0x80 & byte){ SDA_H; } else { SDA_L; } byte <<= 1; SCL_H; _delay_us(I2C_DELAY); SCL_L; } _delay_us(I2C_DELAY); SCL_H; /* ACK bit. */ _delay_us(I2C_DELAY); SCL_L; } /* Send a two-byte command to the DAC, with the R/W bit set to write. */ void send_cmd(uint8_t first, uint8_t second){ SCL_H; _delay_us(I2C_DELAY); SDA_H; _delay_us(I2C_DELAY); /* Start condition: */ SDA_L; _delay_us(I2C_DELAY); SCL_L; send_byte(I2C_ADDR << 1); send_byte(first); send_byte(second); /* Stop condition: */ SCL_H; _delay_us(I2C_DELAY); SDA_H; _delay_us(I2C_DELAY); } /* Set the DAC output voltage. * This re-enables the DAC after shutdown. */ void voltage(uint16_t voltage_word){ send_cmd(voltage_word >> 8, 0xFF & voltage_word); } /* Shutdown the DAC, putting its output in a Hi-Z mode. */ void shutdown_dac(void){ send_cmd(0x30, 0); } /* Received byte. */ volatile uint8_t rs232_byte; /* If 1, a new byte has been received. */ volatile uint8_t rs232_byte_ready; /* Receive a byte over the RS-232 connection. * Blocks until a byte has been received. */ uint8_t get_byte(void){ while(!rs232_byte_ready){ /* Wait for a new byte to arrive. */ } rs232_byte_ready = 0; return rs232_byte; } /* Buffer for received byte. */ volatile uint8_t rs232_buffer; /* Bit (0-7) currently being received. */ volatile uint8_t rs232_bit; /* Adjust the bit periods (or calibrate the RC oscillator) to get good reception. * These period are for a clock frequency of 8.07 Mhz. * The CLKOUT fuse bit is helpful in determining your AVR's clock. */ /* Time between bit samples, in uS. */ #define rs232_period 96 /* 1.5 * rs232_period. */ #define rs232_period_and_half 146 ISR(PCINT0_vect){ if(!(PINB & _BV(PB3))){ /* Falling edge */ OCR0A = rs232_period_and_half; GTCCR = 0; /* Start timer 0. */ GIMSK &= ~_BV(PCIE); /* Disable PCINT. */ } } ISR(TIM0_COMPA_vect){ rs232_buffer |= (((PINB & _BV(PB3)) != 0)) << rs232_bit; GTCCR |= _BV(TSM) | _BV(PSR0); /* Stop timer 0. */ TCNT0 = 0; /* Reset timer 0. */ GTCCR = 0; /* Start timer 0. */ OCR0A = rs232_period; rs232_bit++; if(9 == rs232_bit){ rs232_byte = rs232_buffer; rs232_byte_ready = 1; rs232_buffer = 0; rs232_bit = 0; GTCCR |= _BV(TSM) | _BV(PSR0); /* Stop timer 0. */ TCNT0 = 0; /* Reset timer 0. */ GIMSK |= _BV(PCIE); /* Enable PCINT. */ } }
C
//includes #include <stdio.h> #define FILAS 6 #define COLUMNAS 1 //---------MAIN------------ int main() { int filas = FILAS; int coef = COLUMNAS; for(int a=0; a<filas; a++) { for(int b=0; b <= a; b++) { if (b==0 || a==0) { coef = 1; } else { coef = coef*(a-b+1)/b; } printf("%d ", coef); } printf("\n"); } return 0; }
C
/********************************************************/ /*************** AUTHOR :ELabbas salah ****************/ /*************** DATE : 10 NOV 2020 ****************/ /*************** SWC : ARM STDTYPE ****************/ /*************** VERSION : V1.1 ****************/ /********************************************************/ #ifndef STD_TYPE_H_ #define STD_TYPE_H_ //boolleen #define FALSE 0 #define TRUE 1 #define NULL ((void *)0) /* Void */ typedef void Void; /* Typedef opertor */ #define __SIZEOF(DataType) sizeof(DataType) /* unsigned Type */ typedef unsigned char u8; // 0 ...... 255// typedef unsigned short int u16; // 0 ...... 65536 // typedef unsigned long int u32; // 0 ...... 4294967296 // typedef unsigned long long int u64; // 0 ...... 18446744073709551615 // typedef float f32; //4 Byte typedef double f64; //8 Byte /* signed Type */ typedef signed char s8; // -128 ...... +127 // typedef signed short int s16; // -32768 ...... +32767 // typedef signed long int s32; // -2147483648 ...... +2147483647 // typedef signed long long int s64; // -9223372037709551618 ...... +9223372037709551617 // /* ERROR STATUS CHECK */ typedef enum{ ERROR_POSITIVE= 0, ERROR_NEGATIVE= -1 }CheckError; #endif
C
/* Horner's rule, 霍纳法则, 求多项式值的一个快速算法,算法复杂度O(n)。 原理:F(x) = a0+a1*x^1+...+an*x^n = ((an*x+a{n-1})*x+a{n-2}...)x+a0 */ #include<stdio.h> int horner(const int A[], int N, int x) { int fx = 0; int i; for(i=N-1;i>=0;--i) fx = A[i] + fx * x; return fx; } int main() { int A[4]={1,2,3,4},N=4,x=2; printf("when x=%d,1+2*x+3*x^2+4*x^3=%d\n", x, horner(A, N, x)); return 0; }
C
/* ███████████ ██████ █████ ████████ ░░███░░░░░███ ░░██████ ░░███ ███░░░░███ ░███ ░███ ████████ ██████ █████ ████ ░███░███ ░███ ░░░ ░███ ░██████████ ░░███░░███ ███░░███░░███ ░███ ░███░░███░███ ██████░ ░███░░░░░░ ░███ ░░░ ░███ ░███ ░███ ░███ ░███ ░░██████ ░░░░░░███ ░███ ░███ ░███ ░███ ░███ ░███ ░███ ░░█████ ███ ░███ █████ █████ ░░██████ ░░███████ █████ ░░█████░░████████ ░░░░░ ░░░░░ ░░░░░░ ░░░░░███ ░░░░░ ░░░░░ ░░░░░░░░ ███ ░███ ░░██████ ░░░░░░ ██████████ █████ █████ █████ ░░███░░░░███ ░░███ ░░███ ░░███ ░███ ░░███ ██████ ███████ ██████ █████ ░███ ░███ ░███ ░███ ░░░░░███ ░░░███░ ███░░███ ███░░ ░███ ░███ ░███ ░███ ███████ ░███ ░███ ░███░░█████ ░███ ░███ ░███ ███ ███░░███ ░███ ███░███ ░███ ░░░░███ ░███ ░███ ██████████ ░░████████ ░░█████ ░░██████ ██████ █████ █████ ░░░░░░░░░░ ░░░░░░░░ ░░░░░ ░░░░░░ ░░░░░░ ░░░░░ ░░░░░ */ /* Prof. Crispina Ramos TEMA: Métodos y algoritmos de estructuras de datos complejas OBJETIVOS: -Algoritmo de ordenamiento y su eficiencia Quicksort vs Heapsort */ #include <stdio.h> #include <stdlib.h> #include <string.h> // #include <time.h> #include <windows.h> #include "Funs_Ayudas.h" // funciones que son comunes entre archivos #include "Algoritmo_De_Ordenamientos.h" // Llaman a los dos algoritmos de ordenamiento // Funcion que crea y genera un archivo para registrar // las acciones del programa void printLog(char text[300]) { char NombreArch[300]; sprintf(NombreArch, "resultados/output.log"); // crea la carpeta y guarda la informacion para ver despues escribirArchivo(NombreArch, text); } // Funcion que crea un archivo excel con los datos del algoritmo de turno void printResult(char *cNom_Algorit, int nTam, double tTiempoEjec, int nInter) { char NombreArch[300]; sprintf(NombreArch, "resultados/resultados.csv"); // crea la carpeta y guarda la informacion char log[300]; char logt[300]; if (nTam > 10) { sprintf(log, "%d, %f, %i, %s", nTam, tTiempoEjec, nInter, cNom_Algorit); escribirArchivo(NombreArch, log); } else { if (strcmp(cNom_Algorit, "quickSort") == 0) sprintf(logt, "%s, %s, %s, %s \n", "tam del arreglo", "tiempo", "intercambio", "Nombre de algoritmo"); sprintf(log, "%d, %f, %i, %s", nTam, tTiempoEjec, nInter, cNom_Algorit); strcat(logt, log); escribirArchivo(NombreArch, logt); } } // Funcion que crea un archivo excel con los datos del algoritmo de turno void printMuestra(char *cNom_Algorit, int nTam, int *arrNumeros, const char *modo) { char NombreArch[300]; sprintf(NombreArch, "resultados/C_muestra_%s.csv", cNom_Algorit); // crea la carpeta y guarda la informacion char log[3000] = " "; char logtemp[300] = " "; strcpy(log, modo); strcat(log, "\n"); for (int i = 0; i < nTam; i++) { if (i < nTam - 1) { sprintf(logtemp, "%d, ", arrNumeros[i]); } else if (i == nTam - 1) { sprintf(logtemp, "%d\n", arrNumeros[i]); } strcat(log, logtemp); } escribirArchivo(NombreArch, log); strcpy(log, ""); } void CompaAlgorit(char *cNom_Algorit, int nTam, int *arrNumeros) { char log[300]; int nInter = 0; sprintf(log, "----------------------------------------------------------------"); printLog(log); sprintf(log, "Lenguaje C"); printLog(log); sprintf(log, "Nombre del algoritmo: %s", cNom_Algorit); printLog(log); sprintf(log, "TAmaño del Arreglo: %d", nTam); printLog(log); LARGE_INTEGER frequency; LARGE_INTEGER t1, t2; double tTiempoEjec; QueryPerformanceFrequency(&frequency); if (nTam == 10 || nTam == 100) printMuestra(cNom_Algorit, nTam, arrNumeros, "original"); if (strcmp(cNom_Algorit, "heapSort") == 0) { QueryPerformanceCounter(&t1); heapSort(arrNumeros, nTam, &nInter); } else if (strcmp(cNom_Algorit, "quickSort") == 0) { QueryPerformanceCounter(&t1); quickSort(0, nTam - 1, arrNumeros, &nInter); // arreglado daba basura } QueryPerformanceCounter(&t2); tTiempoEjec = (float)(t2.QuadPart - t1.QuadPart) / frequency.QuadPart; sprintf(log, "La tarea del algoritmo ha tomado %f segundos", tTiempoEjec); printLog(log); printResult(cNom_Algorit, nTam, tTiempoEjec, nInter); nInter = 0; if (nTam == 10 || nTam == 100) printMuestra(cNom_Algorit, nTam, arrNumeros, "ordenado"); } //Leer números del archivo y almacenarlo en una matriz en la memoria void LeerNumeroArchivo(int nTam, int *arrNumeros) { int i = 0; char fileArchivo[] = "numeros.txt"; char str[10000]; FILE *file; file = fopen(fileArchivo, "r"); if (file) { while (i < nTam && fscanf(file, "%s", str) != EOF) { arrNumeros[i] = atoi(str); i++; } fclose(file); } } int main(int argc, char const *argv[]) { int nAlgoritmo = 0, nTam = 0, nIncreTam = 0, nIncreTamAux = 1; // genera numeros al azar GeneradorDeNumeros(); char cNom_Algorit[50]; // almacena los nombres de los algoritmos int *arrNumeros; // arreglo dinamico // Ciclo que aumenta el tamaño del areglo de 10 en 10 for (nIncreTam = 10, nIncreTamAux = 1, nTam = 10; nTam <= 1000000; nTam += nIncreTam) { // condicion para incrementar el tamaño // del arreglo de 10 en 10 modificando nIncreTam if (nIncreTamAux % 10 == 0) { nIncreTamAux = 1; nIncreTam = nIncreTam * 10; } // Ciclo for{} realiza los dos algoritmos con el mismo tamaño de arreglo // automaticamente uno seguido de otro con for (nAlgoritmo = 0; nAlgoritmo < 2; nAlgoritmo++) { strcpy(cNom_Algorit, (nAlgoritmo == 0) ? "quickSort" : "heapSort"); // Se crea un arreglo de tamaño dinamico para los // diferentes casos arrNumeros = (int *)malloc(sizeof(int) * nTam); // Leer números del archivo LeerNumeroArchivo(nTam, arrNumeros); // Ejecutar algoritmo de ordenación // dependiendo de el algoritmo CompaAlgorit(cNom_Algorit, nTam, arrNumeros); printf("Algoritmo %-10s Porcesos completos [%-7i/%i]\n", cNom_Algorit, nTam, 1000000); // muestra progreso } nIncreTamAux++; } free(arrNumeros); return 0; exit(1); //cerrado automatico }
C
/* ============================================================================ Name : Clase_Array.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "utn.h" #define CANTIDAD_EDADES 5 int main(void) { int arrayEdades[CANTIDAD_EDADES]; int resultado; for(int i=0; i<CANTIDAD_EDADES; i++){ _getNumero(&arrayEdades[i], "Edad?", "", 0, 150, 2); } utn_maximo(arrayEdades, 5, &resultado); printf("%d",resultado); return EXIT_SUCCESS; }
C
#include <std.h> #include "../yntala.h" inherit CROOM; void create(){ ::create(); set_property("indoors",1); set_property("light",-1); set_property("no_teleport",1); set_travel(RUBBLE); set_terrain(ROCKY); set_name("%^RESET%^%^ORANGE%^The edge of an underground spring"); set_short("%^RESET%^%^ORANGE%^The edge of an underground spring"); set_long("%^RESET%^%^ORANGE%^This is a narrow, %^BOLD%^%^BLACK%^dark, %^RESET%^%^ORANGE%^cavern that abruptly ends" " to the east. Smooth cave walls arch up into a high ceiling, where you can" " just make out the %^RESET%^faint glow %^ORANGE%^of hanging %^RESET%^stalactites, %^ORANGE%^giving hint as to " " where the steady drip of %^BLUE%^cold water %^ORANGE%^comes from. %^ORANGE%^The cavern floor" " is really uneven and difficult to maneuver due to the many large, %^CYAN%^water-filled %^ORANGE%^holes and" " abundance of large rocks and boulders laying about. Almost completely hidden by the %^BOLD%^%^BLACK%^shadows, " "%^RESET%^%^ORANGE%^a gushing, underground %^CYAN%^waterfall %^ORANGE%^dives into a large pool of %^BLUE%^dark water" " %^ORANGE%^at the caverns edge.\n"); set_smell("default","%^ORANGE%^The caverns carry with them a light, musty smell along with the faint scent of bat guano.%^RESET%^"); set_listen("default","%^CYAN%^The sound of dripping water echoes through the cavern."); set_items(([ ({"floor","cave floor"}):"%^RESET%^%^ORANGE%^The cave floor is rocky and uneven. Puddles of water fill small holes in the %^BOLD%^%^BLACK%^rocks.%^RESET%^", ({"shadow","shadows"}):"%^BOLD%^%^BLACK%^Shadows line the edges of the cave, making it difficult to see what may be hiding there.", "cracks":"%^RESET%^Cracks line the floor and walls here, making a good place for small creatures to hide.", ({"puddles","puddles of water"}):"%^BLUE%^Puddles of stagnant, smelly water fill small holes in the cave floor.", "rocks":"%^RESET%^Rocks and large boulders of various sizes lay about the cave.", ({"walls","cave walls"}):"%^RESET%^%^BLUE%^The cavern walls are smooth to the touch. Small %^RESET%^stalagnites %^RESET%^can be seen hanging from the ceiling.", "ceiling":"%^BOLD%^%^BLACK%^It is difficult to see the ceiling from here, and the %^RESET%^faint glow %^BOLD%^%^BLACK%^%^of %^RESET%^stalagnites %^BOLD%^%^BLACK%^can barely be made out.%^RESET%^", "water":"%^RESET%^%^CYAN%^The waters edge here is stagnate and unmoving, though appears to be fairly deep.%^RESET%^", ])); set_search("shadows","%^BOLD%^%^BLACK%^You sigh in relief as you search the shadows and find nothing.%^RESET%^"); set_exits(([ "pool":INRMS+"hid2", "west":INRMS+"hid4" ])); }
C
#include "stdio.h" /* Partial low? high? sum = 55 */ int main() { int low, high, result = 0; scanf("%d\n", &low); scanf("%d", &high); for (int i = low; i <= high; i++) { result += i; } printf("low? high? sum = %d", result); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int raio; float raioquadr; printf("Insira o valor do raio do circulo: "); scanf("%d", &raio); raioquadr = raio*raio; printf("Raio do circulo: %d", raio); printf("Area do circulo correspondente: %.2f", 3.14*raioquadr); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strlcat.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: nghebreh <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/07/03 19:13:57 by nghebreh #+# #+# */ /* Updated: 2021/07/03 19:14:00 by nghebreh ### ########.fr */ /* */ /* ************************************************************************** */ unsigned int ft_strlen(char *str) { unsigned int count; count = 0; while (str[count] != '\0') count++; return (count); } unsigned int ft_strlcat(char *dest, char *src, unsigned int size) { char *dst; char *src_start; unsigned int dst_length; unsigned int available; dst = dest; src_start = src; available = size; while (available-- != 0 && *dst != '\0') dst++; dst_length = dst - dest; available = size - dst_length; if (available == 0) return (dst_length + ft_strlen(src)); while (*src != '\0') { if (available > 1) { *dst++ = *src; available--; } src++; } *dst = '\0'; return (dst_length + (src - src_start)); }
C
#include <stdio.h> int main(int argc, char const *argv[]) { int input, enter; scanf("%d\n", enter); scanf("%d\n", input); printf("输出的值是%d\n", input + enter); return 0; }
C
/* K&R Exercise 3-1 p. 58 */ /* Our binary search makes two tests inside the loop, when one * would suffice (at the price of more tests outside). Write a * version with only one test inside the loop and measure the * difference in run-time. */ #include <stdio.h> #define LENGTH 100000 int binsearch(int x, int v[], int n); int binsearch2(int x, int v[], int n); int ops1 = 0; /* The number of operations performed by the binsearch loop */ int ops2 = 0; /* The number of operations performed by the binsearch2 loop */ int main() { extern int ops1, ops2; int a[LENGTH]; int s = 1; int i,j; for (i=0; i<LENGTH; ++i) { a[i] = i+1; } i = binsearch(s, a, LENGTH); j = binsearch2(s, a, LENGTH); switch(i) { case -1: printf("binsearch: Could not find %d in array! (%d operations were performed)\n", s, ops1); break; default: printf("binsearch: Found %d at index %d. (%d operations were performed)\n", s, i, ops1); break; } switch(j) { case -1: printf("binsearch2: Could not find %d in array! (%d operations were performed)\n", s, ops2); break; default: printf("binsearch2: Found %d at index %d. (%d operations were performed)\n", s, i, ops2); break; } } /* binsearch: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch(int x, int v[], int n) { extern int ops1; int low, high, mid; low = 0; high = n-1; while (low <= high) { ++ops1; mid = (low+high) / 2; if (x < v[mid]) { ++ops1; high = mid - 1; } else if (x > v[mid]) { ++ops1; low = mid + 1; } else { return mid; } } return -1; /* no match */ } /* binsearch2: find x in v[0] <= v[1] <= ... <= v[n-1] */ int binsearch2(int x, int v[], int n) { extern int ops2; int low, high, mid; low = 0; high = n-1; while (low <= high) { ++ops2; mid = (low+high) / 2; if (x < v[mid]) { ++ops2; high = mid - 1; } else { ++ops2; low = mid + 1; } } if (x == mid) { return mid; } else { return -1; /* no match */ } }
C
#include <stdio.h> #include <string.h> #include <rsl.h> void dump_radar_header(FILE *output, const Radar *const r) { char radar_type[sizeof(r->h.radar_type)]; strncpy(radar_type, r->h.radar_type, sizeof(radar_type)); fprintf(output, "Radar [%p]:\nType: %s\nTimestamp: %02d/%02d/%d [M/D/Y] %d:%d:%f\n\n", r, radar_type, r->h.month, r->h.day, r->h.year, r->h.hour, r->h.minute, r->h.sec); } int usage(int argc, char *argv[]) { fprintf(stderr, "%s <radar binary>\n", argv[0]); return 1; } int main(int argc, char *argv[]) { if (argc < 2) { return usage(argc, argv); } Radar *rad = RSL_anyformat_to_radar(argv[1]); if (rad == NULL) { fprintf(stderr, "Not any matching format\n"); return 2; } else { printf("It's something\n"); dump_radar_header(stdout, rad); return 0; } }
C
#include <stdio.h> int lower_one_mask(int n) { unsigned a=~0x00; a=a<<n; a=~a; printf("%.x\n",a); } int main(void) { // your code goes here lower_one_mask(17); return 0; }
C
# include <stdio.h> # include <stdlib.h> # include <string.h> # include "Listas_enlazadas.h" /**************************************************************** * Programa: lab_03_recursividad_07.c * * Objetivo: Escriba una función recursiva llamada sumaLista que * retorne la suma de los elementos de una lista de enteros L. * * Fecha Creación: 02/05/2017 Fecha última actualización: 02/05/2017 * * Autor/Grupo: Waldo Peyrau Morales * * Asignatura: Estructura de datos INS127 Sección: 651 * *****************************************************************/ int sumaLista(Nodo*,int); int main(int argc, char *argv[]){ int suma; Lista *A = crearLista(); insertarElemento(A,11); insertarElemento(A,14); insertarElemento(A,54); insertarElemento(A,14); insertarElemento(A,67); suma=sumaLista(A->ini,A->tam); printf("%d",suma); } int sumaLista(Nodo *n, int tam){ if (tam == 1){ return n->dato->num; }else{ return (n->dato->num + sumaLista(n->sgte,tam-1)); } }
C
#include "sh.h" char *check_is_alias(t_42sh *sh, char *str) { int i; t_alias *start; char *to_return; i = 0; start = sh->alias->begin; if (sh->alias->size == 0) return (NULL); while (i < sh->alias->size) { if (ft_strequ(start->to_sub, str) == 1) { to_return = ft_strdup(start->sub); return (to_return); } start = start->next; i++; } return (NULL); } int check_is_builtin(t_42sh *sh, char *str) { int i; i = 0; while (sh->builtin[i]) { if (ft_strequ(sh->builtin[i], str) == 1) return (1); i++; } return (0); } void get_type(t_42sh *sh) { int i; char *to_print; i = 1; while (i < sh->argv->size) { if ((to_print = check_is_alias(sh, sh->argv->argv[i])) != NULL) { ft_putstr(sh->argv->argv[i]); ft_putstr(" is an alias for "); ft_putendl(to_print); ft_strdel(&to_print); } else if (check_is_builtin(sh, sh->argv->argv[i]) == 1) { ft_putstr(sh->argv->argv[i]); ft_putendl(" is a shell builtin"); } else if ((to_print = check_access(sh, i)) != NULL) { ft_putstr(sh->argv->argv[i]); ft_putstr(" is "); ft_putendl(to_print); ft_strdel(&to_print); } else { ft_putstr("42sh: type: "); ft_putstr(sh->argv->argv[i]); ft_putendl(": not found"); } i++; } } void builtin_type(t_42sh *sh) { if (sh->argv->size == 1) return ; else get_type(sh); }
C
#include <stdio.h> #define EURO 68.27 #define POUND 80.05 #define DOLLAR 61.60 int main(void) { char currency; double value; printf("Enter value and currency (d - dollars, e - euros, p - pounds): "); if (scanf("%lf %c", &value, &currency) != 2) { fprintf(stderr, "Error: Invalid type of Input\n"); fprintf(stderr, "Fix: Enter a double and a char\n"); return 1; } if (value < 0) { fprintf(stderr, "Error: value cannot be nagative\n"); fprintf(stderr, "Fix: Try enter a positive double value\n"); return 1; } switch (currency) { case 'e': printf("%.2lf(e) == %.2lf(r)\n", value, value * EURO); break; case 'd': printf("%.2lf(d) == %.2lf(r)\n", value, value * DOLLAR); break; case 'p': printf("%.2lf(p) == %.2lf(r)\n", value, value * POUND); break; default: printf("Sorry, I do not know this currency '%c'\n", currency); break; } return 0; }
C
#include<stdio.h> void main() { int x[5]={30,40,37,23,50},i,y; printf("enter the value of y\n:"); scanf("%d",&y); for(i=0;i<5;i++) { if(x[i]==y) break; } if(i<5) printf("found"); else printf("not found"); }
C
#include <stdio.h> int sort(int val1, int val2, int val3, int val4, int val5, int val6, int val7, int val8, int val9, int val10); //prototype function int main() { int num1, num2, num3, num4, num5, num6; int num7, num8, num9, num10; printf("Please input 10 numbers:\n"); scanf("%d", &num1); scanf("%d", &num2); scanf("%d", &num3); scanf("%d", &num4); scanf("%d", &num5); scanf("%d", &num6); scanf("%d", &num7); scanf("%d", &num8); scanf("%d", &num9); scanf("%d", &num10); sort(num1, num2, num3, num4, num5, num6, num7, num8, num9, num10); } int sort(int val1, int val2, int val3, int val4, int val5, int val6, int val7, int val8, int val9, int val10) { int tmp, sortFlag; sortFlag = 0; if (val1 > val2) { tmp = val1; val1 = val2; val2 = tmp; sortFlag = 1; } if (val2 > val3) { tmp = val2; val2 = val3; val3 = tmp; sortFlag = 1; } if (val3 > val4) { tmp = val3; val3 = val4; val4 = tmp; sortFlag = 1; } if (val4 > val5) { tmp = val4; val4 = val5; val5 = tmp; sortFlag = 1; } if (val5 > val6) { tmp = val5; val5 = val6; val6 = tmp; sortFlag = 1; } if (val6 > val7) { tmp = val6; val6 = val7; val7 = tmp; sortFlag = 1; } if (val7 > val8) { tmp = val7; val7 = val8; val8 = tmp; sortFlag = 1; } if (val8 > val9) { tmp = val8; val8 = val9; val9 = tmp; sortFlag = 1; } if (val9 > val10) { tmp = val9; val9 = val10; val10 = tmp; sortFlag = 1; } if (sortFlag == 1) { sort(val1, val2, val3, val4, val5, val6, val7, val8, val9, val10); } else { printf("Smallest: %d\n", val1); printf("Biggest: %d\n", val10); } }
C
/** * \file * \brief Implementation of the ADC on the PRG_G board. * \author Erich Styger, [email protected] * * This module implements the ADC (Analog to Digital Converter) driver. */ #ifndef SRC_ADC_H_ #define SRC_ADC_H_ #include <stdint.h> /** @addtogroup ADC * @{ */ /** \brief Selection of sensors */ typedef enum { ADC_LIGHT_SENSOR, /**< Light sensor */ ADC_HALL_SENSOR /**< Hall sensor */ } ADC_SensorE; /*! * \brief Returns the measured voltage of the ADC in milli-Volts * \param sensor sensor to measure * \return milli-volts of the sensor */ uint32_t ADC_GetMilliVoltage(ADC_SensorE sensor); /*! * \brief Initializes the ADC driver */ void ADC_Init(void); /** * @} */ #endif /* SRC_ADC_H_ */
C
/**** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** ** Version 2, December 2004 ** ** Copyright (C) 2013 Kristiyan Peychev <[email protected]> ** ** ** ** Everyone is permitted to copy and distribute verbatim or modified ** ** copies of this license document, and changing it is allowed as long ** ** as the name is changed. More info about the license at ** ** http://www.wtfpl.net/ ** ** ** ** DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE ** ** TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION ** ** 0. You just DO WHAT THE FUCK YOU WANT TO. ** ** **/ #include <dirent.h> #include <string.h> #include <stdlib.h> #include <stdio.h> int getCommandsFromDIR(DIR *dp, char **cp, short writeFromWhere){ struct dirent *ep; short num_written = writeFromWhere, recurse = 0; if (dp != NULL) { while ((ep = readdir(dp))) { if (ep->d_type == DT_REG || ep->d_type == DT_LNK) { sprintf(*(cp + num_written), "%s%c", ep->d_name, 0x0); num_written++; } else { } } } else ; return (num_written - writeFromWhere); } int readPATH(char **dirs){ int i = 0, j = 0, k = 0; char buffer[256], *pathval = getenv("PATH"); while (*(pathval + i)) { if (*(pathval + i) == ':') { *(buffer + k) = 0; k++; k = 0; *(dirs + j) = (char *) malloc(64 * sizeof(char)); strcpy(*(dirs + j), buffer); memset(buffer, 0, 256); j++; i++; continue; } *(buffer + k) = *(pathval + i); i++; k++; } return j; } char **getCommands(int *totWrit){ char **dirs = malloc(24 * sizeof(char *)), **commands; int totalWritten = 0, size = 8120, i = 0, somecount = 0; if ((somecount = readPATH(dirs)) < 0) { fprintf(stdout, "lolish: Error reading PATH!\n"); return NULL; } commands = (char **) malloc(size * sizeof(char *)); for (i = 0; i < size; i++) *(commands+i) = (char *) malloc(48 * sizeof(char)); DIR *dp; i = 0; while (i < somecount) { dp = opendir(*(dirs + i)); if (dp == NULL) { fprintf(stdout, "lolish: Failed in reading %s\n", *(dirs + i)); i++; continue; } totalWritten += getCommandsFromDIR(dp, commands, totalWritten); closedir(dp); i++; } *totWrit = totalWritten; return commands; }
C
/** * @file sol_1.c * @author LiYu87 ([email protected]) * @brief 24. Swap Nodes in Pairs * @date 2021.04.27 * * Time Complexity: O(n) * Space Complexity: O(n) * * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ #include <stdlib.h> struct ListNode* swapPairs(struct ListNode* head) { if (head == NULL) { return head; } struct ListNode* p; struct ListNode* q; int tmp; p = head; while (1) { if (p == NULL) { break; } if (p->next == NULL) { break; } p = p; q = p->next; tmp = p->val; p->val = q->val; q->val = tmp; p = q->next; } return head; }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct livros /*dados do livro*/ { char titulo[60]; char autor[20]; int qtd_biblioteca, qtd_emprest, ano_publi; }livros; typedef struct registro /*ficha do livro*/ { char titulo[60]; char autor[20]; int ano_p; }registro; int inserindo(livros book[200], int tam, int i, registro reg) /*cadastro dos livros*/ { if(i < tam) { //printf("tam: %d %d", tam, i); if ((reg.titulo != book[i].titulo) && (reg.autor != book[i].autor) && (reg.ano_p != book[i].ano_publi)) { strcpy(book[i].titulo, reg.titulo); strcpy(book[i].autor, reg.autor); book[i].ano_publi = reg.ano_p; return printf("\n ########### Livro sendo cadastrado #############\n\n"); /*espaço*/ } else if ((strcmp(reg.titulo, book[i].titulo) == 0) && (strcmp(reg.autor, book[i].autor) == 0) && (reg.ano_p == book[i].ano_publi) ) /*já tem registro*/ { book[i].qtd_biblioteca += 1; return printf("\n ######## Inserindo mais uma unidade ########## \n\n"); } inserindo(book, tam, i+1, reg); } } int ler_livro(registro *reg, int *tam) { fflush(stdin); printf("----------> Insira o Título do livro <--------------- \n"); getchar(); //scanf("%[^\n]", reg.titulo); fgets(reg->titulo, 60, stdin); printf("\n----------> Insira o autor do livro <---------------- \n"); // scanf("%[^\n]", reg.autor); fgets(reg->autor, 20, stdin); printf("\n------> Insira o ano de publicação do livro <-------- \n"); scanf("%d", &reg->ano_p); *tam += 1; } int status_livro(livros book[200], registro reg, int i, int tam) /*ver a quantidade que ainda tem disponivel*/ { if (book->qtd_biblioteca < 0) /*não possui livros*/ { printf("############ Livro indisponível ###############\n"); } else { if (i < tam) { if ((strcmp(reg.titulo, book[i].titulo) == 0) && (strcmp(reg.autor, book[i].autor) == 0) && (reg.ano_p == book[i].ano_publi)) { if (book[i].qtd_biblioteca <= 0) /*precisa ter um volume na bib*/ { return printf("Apenas volume leitura disponível\n"); } else return printf("Quantidade disponível: %d\n", book[i].qtd_biblioteca); } else return printf("Não existe volume cadastrado\n"); status_livro(book, reg, i+1, tam); } } } int empresta_livro(livros book[200], registro reg, int i, int tam) { if (book->qtd_biblioteca <= 0) /*não possui livros*/ { printf("############ Livro indisponível ###############\n"); } else { if (i < tam) { //printf("AQUI\n"); if ((strcmp(reg.titulo, book[i].titulo) == 0) && (strcmp(reg.autor, book[i].autor) == 0) && (reg.ano_p == book[i].ano_publi)) { book[i].qtd_emprest += 1; book[i].qtd_biblioteca -= 1; return printf("-----> Empréstimo finalizado <------\n"); } else return printf("------------> Livro não cadastrado <---------- \n"); empresta_livro(book, reg, i+1, tam); } } } int sistema(registro reg, int tam, int action, livros book[200], int count) { if (count > 0) { ler_livro(&reg, &tam); } if (action == 1) /*cadastro do livro*/ { inserindo(book, tam, 0, reg); } else if (action == 2) { status_livro(book, reg, 0, tam); } else if (action == 3) { empresta_livro(book, reg, 0, tam); } printf("Insira o que deseja fazer:\n [0] Finalizar\n [1] Cadastro de livro\n [2] Status do livro\n [3] Pegar emprestado\n\n"); scanf("%d", &action); if (action != 0) { sistema(reg, tam, action, book, count+1); } } int main() { livros book[200]; registro reg; int action = 0; int tam; printf("\n---------> Sistema de livros da biblioteca <----------\n\n"); printf("Insira o que deseja fazer:\n [0] Finalizar\n [1] Cadastro de livro\n [2] Status do livro\n [3] Pegar emprestado\n"); scanf("%d", &action); if (action != 0) { ler_livro(&reg, &tam); } sistema(reg, tam, action, book, 0); return 0; }
C
#include<stdio.h> void main() { int a,b,c,d; unsigned u; a=12;b=-24;u=10; c=a+u,d=b+u; printf("%d+%d=%d\n,%d+%d=%d",a,u,c,b,u,d); }
C
/* Date : 11-1-2021 Aim : Min and max out of array Source : c patterns app */ #include <stdio.h> void main() { int arr[] = {18, 29, 36, 6, 92, 14, 46, 76, 34, 67}; int min, max, i; max = arr[0]; min = arr[0]; for(i = 0; i < 10; i++) { if(arr[i] < min) min = arr[i]; if(arr[i] > max) max = arr[i]; } printf("\n%d", min); printf("\n%d", max); }
C
#include "ai_header.h" struct tree_node* create_node(int **map, int intree, int winorlose, int minmax_or_leaf) { struct tree_node *node = (struct tree_node*)malloc(sizeof(struct tree_node)); if (node == NULL) return NULL; node->map = map; node->evaluation_value = 9999; node->is_in_tree = intree; node->min_or_max_or_leaf = minmax_or_leaf; node->is_it_winorlose = winorlose; node->child1 = NULL; node->child2 = NULL; node->child3 = NULL; node->child4 = NULL; node->child5 = NULL; node->child6 = NULL; node->child7 = NULL; node->next_sibling = NULL; return node; } /*i made tree structure function - create_node, insert_child. In insert_child function, it automatically creates nodes, makes maps and inerts it into child nodes so you do not need to make child map using malloc. you can make all 7 child nodes just uning insert_child function passing only argument as root node But it can have some child nodes as empty node which has not_intree flag and null value on map pointer when child can not have a place to put stone any more*/ void insert_child(struct tree_node *root, int minmax_or_leaf) { if (root->is_in_tree == FALSE || root->is_it_winorlose == TRUE) { root->child1 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); root->child2 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); root->child3 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); root->child4 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); root->child5 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); root->child6 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); root->child7 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); connect_siblings(root); } else { int **child_map1 = duplicate_root_map(root->map); int **child_map2 = duplicate_root_map(root->map); int **child_map3 = duplicate_root_map(root->map); int **child_map4 = duplicate_root_map(root->map); int **child_map5 = duplicate_root_map(root->map); int **child_map6 = duplicate_root_map(root->map); int **child_map7 = duplicate_root_map(root->map); int result; // 1 -> can move, 0 -> can not move, 2 -> state is win or lose result = modify_child_map(child_map1, 1, minmax_or_leaf); if (result == 1) root->child1 = create_node(child_map1, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child1 = create_node(child_map1, TRUE, TRUE, LEAF); else { free_map(child_map1); root->child1 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } result = modify_child_map(child_map2, 2, minmax_or_leaf); if (result == 1) root->child2 = create_node(child_map2, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child2 = create_node(child_map2, TRUE, TRUE, LEAF); else { free_map(child_map2); root->child2 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } result = modify_child_map(child_map3, 3, minmax_or_leaf); if (result == 1) root->child3 = create_node(child_map3, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child3 = create_node(child_map3, TRUE, TRUE, LEAF); else { free_map(child_map3); root->child3 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } result = modify_child_map(child_map4, 4, minmax_or_leaf); if (result == 1) root->child4 = create_node(child_map4, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child4 = create_node(child_map4, TRUE, TRUE, LEAF); else { free_map(child_map4); root->child4 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } result = modify_child_map(child_map5, 5, minmax_or_leaf); if (result == 1) root->child5 = create_node(child_map5, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child5 = create_node(child_map5, TRUE, TRUE, LEAF); else { free_map(child_map5); root->child5 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } result = modify_child_map(child_map6, 6, minmax_or_leaf); if (result == 1) root->child6 = create_node(child_map6, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child6 = create_node(child_map6, TRUE, TRUE, LEAF); else { free_map(child_map6); root->child6 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } result = modify_child_map(child_map7, 7, minmax_or_leaf); if (result == 1) root->child7 = create_node(child_map7, TRUE, FALSE, minmax_or_leaf); else if (result == 2) root->child7 = create_node(child_map7, TRUE, TRUE, LEAF); else { free_map(child_map7); root->child7 = create_node(NULL, FALSE, FALSE, minmax_or_leaf); } connect_siblings(root); } } int** duplicate_root_map(int **root_map) { int **child_map = (int**)malloc(sizeof(int*) * 6); int i, k; for (i = 0; i < 6; i++) child_map[i] = (int*)malloc(sizeof(int) * 7); for (i = 0; i < 6; i++) { for (k = 0; k < 7; k++) { child_map[i][k] = root_map[i][k]; } } return child_map; } int modify_child_map(int **child_map, int number, int minmax_or_leaf) { number--; int i; for (i = 0; i < 6; i++) { if (child_map[i][number] == 0) { #ifdef DEPTH2 if (minmax_or_leaf == MIN) child_map[i][number] = 2; else if (minmax_or_leaf == MAX || minmax_or_leaf == LEAF) child_map[i][number] = 1; #endif // DEPTH2 #ifdef DEPTH3 if (minmax_or_leaf == MIN || minmax_or_leaf == LEAF) child_map[i][number] = 2; else if (minmax_or_leaf == MAX) child_map[i][number] = 1; #endif // DEPTH3 #ifdef DEPTH4 if (minmax_or_leaf == MIN) child_map[i][number] = 2; else if (minmax_or_leaf == MAX || minmax_or_leaf == LEAF) child_map[i][number] = 1; #endif // DEPTH4 #ifdef DEPTH5 if (minmax_or_leaf == MIN || minmax_or_leaf == LEAF) child_map[i][number] = 2; else if (minmax_or_leaf == MAX) child_map[i][number] = 1; #endif // DEPTH5 #ifdef DEPTH6 if (minmax_or_leaf == MIN) child_map[i][number] = 2; else if (minmax_or_leaf == MAX || minmax_or_leaf == LEAF) child_map[i][number] = 1; #endif // DEPTH6 //it can move and retun 1 as success if (decide_win_or_lose_or_continue(child_map) == CONTINUE) return 1; else //it is the case that it doesn;t need to make child nodes because after modifiying map, state of map is win or lose. return 2; } if (i == 5) { /*it can not move because vertical row is full so return 0 as fail and do not make map (free map in upper function and set is_it_in_tree varibale as FALSE in child node)*/ return 0; } } } void mem_free_tree(struct tree_node *root) { if (root->child1 == NULL&&root->child2 == NULL&&root->child3 == NULL&&root->child4 == NULL&& root->child5 == NULL&&root->child6 == NULL&&root->child7 == NULL) { if (root->map != NULL) free_map(root->map); free(root); return; } mem_free_tree(root->child1); mem_free_tree(root->child2); mem_free_tree(root->child3); mem_free_tree(root->child4); mem_free_tree(root->child5); mem_free_tree(root->child6); mem_free_tree(root->child7); if (root->map != NULL) free_map(root->map); free(root); } void free_map(int **map) { int i; for (i = 0; i < 6; i++) { free(map[i]); } free(map); } void connect_siblings(struct tree_node *root) { root->child1->next_sibling = root->child2; root->child2->next_sibling = root->child3; root->child3->next_sibling = root->child4; root->child4->next_sibling = root->child5; root->child5->next_sibling = root->child6; root->child6->next_sibling = root->child7; }
C
#include <math.h> #include "Trig.h" #include "MathConstants.h" double Sec(const double x_rads) { //Secant if (cos(x_rads) != 0) { return 1 / cos(x_rads); } else { return -9999999999999; } } double Cosec(const double x_rads) { //Cosecant if (sin(x_rads) != 0) { return 1 / sin(x_rads); } else { return -9999999999999; } } double Cotan(const double x_rads) { //Cotangent if (tan(x_rads) != 0) { return 1 / tan(x_rads); } else { return -9999999999999; } } double ArcSec(const double x_rads) { //Inverse Secant return atan(x_rads / sqrt(x_rads * x_rads - 1)) + Sign(x_rads - 1) * (PI / 2); } double ArcCosec(const double x_rads) { //Inverse Cosecant return atan(x_rads / sqrt(x_rads * x_rads - 1)) + Sign(x_rads - 1) * (PI / 2); } double ArcCotan(const double x_rads) { //Inverse Cotangent return atan(x_rads) + (PI / 2); } double Csch(const double x_rads) { //Calculates hyperbolic cosecant of x_rads return 1 / sinh(x_rads); } double Sech(const double x_rads) { //Calculates hyperbolic secant of x_rads return 1 / cosh(x_rads); } double Coth(const double x_rads) { //Calculates hyperbolic cotangent of x_rads return 1 / tanh(x_rads); } int Sign(const double x) { return x / fabs(x); }
C
#include <stdio.h> #include <conio.h> #include <stdbool.h> int main(){ int cari,low,high,tm; bool berhenti; berhenti = false; int arr[9] = {3, 9, 11, 12, 15, 17, 23, 31, 35}; int n = sizeof(arr)/sizeof(arr[0]); int c; printf("Indeks\t: "); for (c=0;c<n;c++){ printf("%d\t ",c); } printf("\nNilai\t: "); for (c=0;c<n;c++){ printf("%d\t ",arr[c]); } printf("\nMasukkan angka yang dicari : "); scanf("%d",&cari); low = 0; high = (n-1); int posisi; while(berhenti != true){ posisi = ((cari - arr[low])/(arr[high]-arr[low]))*(high-low)+low; printf("loop ke-%d\n",posisi+1); //indeks 1 nilai 9 //pos= ((9-3)/(35-3))*(8-0)+0 //pos= ((6)/(32))*8+0 //pos= 1,5 ~> 1 //nilai 13 //loop 1 //pos= ((13-3)/(35-3))*(8-0)+0 //pos= ((10)/(32))*8 //pos= 2,5 ~> 2 (arr[2]=11) //loop 2 low = pos+1 //pos= ((13-12)/(35-12))*(8-3)+3 // ((1)/(23))*5+3 // 3,217 ~> 3 (arr[3]=12) //dst. if(arr[posisi] == cari){ printf("%d terdapat pada indeks ke %d",cari,posisi); berhenti = true; //jika sudah memnuhi aaka akan keluar dari while } else if(arr[posisi] < cari){ printf("%d < %d\n",arr[posisi],cari); //hanya untuk cek loop low = posisi + 1; } else{ //terjadi saat if atau else if tidak terpenuhi atau data yang dimasukkan tidak ada printf("\nData tidak ada"); berhenti = true; } } }
C
/* 2/10/15 Stefan Countryman * * A program for timing various looped operations on Unix-like machines. * * Most timing functionality is copied straight from RDM's real_time_clock. * * The program will print the results in CSV format. The user should run the * program and append each new line to the file timing-results-o0.csv if * compiled with -O0 optimization or timing-results-o3.csv if compiled with * -O3 optimization. * * The Mac OS X implementation came from gist/github.com/jbenet/1087739 * This code uses the real time clock feature. These clocks return times in * nanoseconds. * * On Linux, compile with * gcc -o real_time_clock real_time_clock.c -lrt * * (The -lrt flag links in the real-time libraries.) * On Mac, compile with * gcc -o real_time_clock real_time_clock.c * */ /* author: jbenet os x, compile with: gcc -o testo test.c linux, compile with: gcc -o testo test.c -lrt */ #include <time.h> #include <sys/time.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #ifdef __MACH__ #include <mach/clock.h> #include <mach/mach.h> #endif void current_utc_time(struct timespec *ts) { #ifdef __MACH__ // OS X does not have clock_gettime, use clock_get_time clock_serv_t cclock; mach_timespec_t mts; host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); clock_get_time(cclock, &mts); mach_port_deallocate(mach_task_self(), cclock); ts->tv_sec = mts.tv_sec; ts->tv_nsec = mts.tv_nsec; #else clock_gettime(CLOCK_REALTIME, ts); #endif } /* The size of the a & b arrays, for section (c) */ const int absize = 20020; /* The number of operations in each loop */ const int nops = 10000; /* The number of results to print out */ const int nprint = 8; /* The seed to start the random number sequence */ const int seed = 1234; int main() { double a[absize], b[absize], c[nops]; int i; struct timespec tstart, tstop; struct timespec ts; current_utc_time(&ts); /* Initialize random floating point values */ srand48(seed); for ( i = 0; i < nops; i++ ) { a[i] = fabs(drand48()); // make a[i]>0 for (h) b[i] = drand48(); } /* Initialize timing variables */ tstart.tv_sec = 0; tstart.tv_nsec = 0; tstop.tv_sec = 0; tstop.tv_nsec = 0; /* Time each operation */ // a current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] = a[i] * b[i]; } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // b current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] += a[i] * b[i]; } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // c current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] += a[i] * b[2*i + 20]; } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // d current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] = a[i] / b[i]; } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // e current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] += a[i] / b[i]; } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // f current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] = sin(a[i]); } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // g current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] = exp(a[i]); } current_utc_time(&tstop); printf("%lu,", tstop.tv_nsec - tstart.tv_nsec); // h current_utc_time(&tstart); for ( i = 0; i < nops; i++ ) { c[i] = sqrt(a[i]); } current_utc_time(&tstop); /* Replace final comma with newline character */ printf("%lu\n", tstop.tv_nsec - tstart.tv_nsec); return 0; }
C
#include <stdio.h> /*/ 19. Faa um algoritmo que leia dois valores inteiros (X e Y) e mostre todos os nmeros primos entre X e Y. /*/ int main(){ int x,y, cont, ax, i; printf("Digite um valor X:"); scanf("%d", &x); printf("Digite um valor Y:"); scanf("%d", &y); if (y<x){ ax = x; x = y; y = ax; } for (;x<=y;x++){ cont=0; for (i=2;i<=(x-1);i++){ if (x%i==0){ cont += 1; } } if (cont>=1){ // printf ("%d nao e primo\n", x); }else{ printf ("%d e primo\n", x); } } return 0; }
C
#ifndef TERMINAL_H #define TERMINAL_H #include <stddef.h> #include <stdint.h> /* Hardware text mode color constants. */ enum vga_color { COLOR_BLACK = 0, COLOR_BLUE = 1, COLOR_GREEN = 2, COLOR_CYAN = 3, COLOR_RED = 4, COLOR_MAGENTA = 5, COLOR_BROWN = 6, COLOR_LIGHT_GREY = 7, COLOR_DARK_GREY = 8, COLOR_LIGHT_BLUE = 9, COLOR_LIGHT_GREEN = 10, COLOR_LIGHT_CYAN = 11, COLOR_LIGHT_RED = 12, COLOR_LIGHT_MAGENTA = 13, COLOR_LIGHT_BROWN = 14, COLOR_WHITE = 15, }; uint8_t make_color(enum vga_color fg, enum vga_color bg); void terminal_initialize(); void terminal_setcolor(uint8_t color); void terminal_putentryat(char c, uint8_t color, size_t x, size_t y); void terminal_putchar(char c); void terminal_writestring(char *s); void terminal_writeint(uint16_t i); void terminal_writeint32(uint32_t i); void terminal_writehex(uint16_t i); void terminal_writehex32(uint32_t i); void terminal_writehex64(uint64_t i); #endif
C
#include <stdio.h> int main123() { int arr[9] = { 1, 3, 5, 2, 1, 2, 4, 3, 4 }; int res = 0; int i; for (i = 0; i < 9; i++) { res ^= arr[i]; } printf("%d\n", res); return 0; }
C
// Program2, Blaise Takushi CS344, OSUID: 932347942, [email protected] #include <ctype.h> #include <dirent.h> #include <limits.h> #include <pthread.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include <unistd.h> #include <libgen.h> //Initialize Mutex pthread_mutex_t mutex1; //Struct for room struct Room { char name[20]; char roomType[20]; int numberConnections; char connections[6][15]; }; //Hardcoded room names and room types char* roomNames[10] = {"Death", "Life", "Purge", "Horror", "Lights", "Cowards", "Winners", "Losers", "Midnight", "Weirdos"}; char* types[3] = {"START_ROOM", "MID_ROOM", "END_ROOM"}; char* openFolder(); char* getFirstRoom(); void gameLoop(); void switchRoom(char* roomName, struct Room* room1); void printTime(); void thread(); void* timeFile(); //Function to open correct rooms directory and return folder name (string) char* openFolder() { char targetDir[40] = "takushib.rooms."; static char newDir[100]; int newestDirTime = -1; memset(newDir, '\0', sizeof(newDir)); FILE* filep; DIR* dirToCheck; struct dirent *fileInDir; struct stat dirStats; //Open current directory dirToCheck = opendir("."); //Get the most recent directory if (dirToCheck > 0) { while ((fileInDir = readdir(dirToCheck)) != NULL) { if (strstr(fileInDir->d_name, targetDir) != NULL) { stat(fileInDir->d_name, &dirStats); if ((int)dirStats.st_mtime > newestDirTime) { newestDirTime = (int)dirStats.st_mtime; memset(newDir, '\0', sizeof(newDir)); strcpy(newDir, fileInDir->d_name); } } } } closedir(dirToCheck); // return the folder name return newDir; } //function that returns the name of the Start room char* getFirstRoom() { struct dirent* search; DIR* currentFolder; char currentLine[75]; char fileName[50]; char* folderName = openFolder(); //Variables to hold the sscanf results char stringCheck1[20], stringCheck2[20], stringCheck3[20]; static char startRoom[50]; FILE* fileP; if((currentFolder = opendir(folderName)) == NULL) { perror("Unable to find folder"); return ""; } else { //While the current folder isn't empty, search through each room file while((search = readdir(currentFolder)) != NULL) { int i = 0; for(i = 0; i < 10; i++) { //if the name of the file is in the hardcoded list, continue if(strcmp(search -> d_name, roomNames[i])) { sprintf(fileName, "./%s/%s", folderName, search->d_name); //open the room file fileP = fopen(fileName, "r"); //iterate through each line until the last one which holds the room type while(fgets(currentLine, 75, fileP) != NULL) { sscanf(currentLine, "%s %s %s", stringCheck1, stringCheck2, stringCheck3); } //if the room type is start room, save it to a variable if(!strcmp(stringCheck3, "START_ROOM")) { strcpy(startRoom, search -> d_name); break; } } } } closedir(currentFolder); return startRoom; } } //function that takes a room and sets all it's field to the room it's switching to void switchRoom(char* roomName, struct Room* room1) { FILE* fileP; char fileName[50]; char Folder[50]; int i; char stringCheck1[20], stringCheck2[20], stringCheck3[20]; //set all the connections to nothing for(i = 0; i < room1->numberConnections; i++) { strcpy(room1->connections[i],""); } //reset the number of connections so that it can be built up later room1->numberConnections = 0; sprintf(Folder, "%s", openFolder()); //build up file path string sprintf(fileName, "./%s/%s", Folder, roomName); fileP = fopen(fileName, "r"); if(fileP == NULL) { perror("Could not open file"); return; } char currentLine[75]; fgets(currentLine, 75, fileP); int n = sscanf(currentLine, "%s %s %s", stringCheck1, stringCheck2, stringCheck3); strcpy(room1->name, stringCheck3); //while in the file, scan each line and set connections and types while(fgets(currentLine, 75, fileP) != NULL) { sscanf(currentLine, "%s %s %s", stringCheck1, stringCheck2, stringCheck3); if(strcmp(stringCheck1,"CONNECTION") == 0) { //set connections and increment count strcpy(room1->connections[room1->numberConnections], stringCheck3); room1->numberConnections = room1->numberConnections + 1; } else if(strcmp(stringCheck1,"ROOM") == 0 && strcmp(stringCheck2,"TYPE:") == 0) { //set type strcpy(room1->roomType, stringCheck3); } } return; } //gameLoop function that runs the actual game. void gameLoop() { char* firstRoom; //variable to store the path of the user, set number of steps to 0 char userPath[50][15]; int numberSteps = 0; int finished = 0; char userInput[50]; //if for some reason the first room is null, exit the game. if (strcmp(getFirstRoom(), "") == 0) { exit(1); } //get the name of the first room firstRoom = getFirstRoom(); struct Room* room = malloc(sizeof(struct Room)); //build room struct for the first room switchRoom(firstRoom, room); int i; do { if(strcmp(userInput, "time") != 0) { //print current location and connections printf("CURRENT LOCATION: %s\n", room->name); printf("POSSIBLE CONNECTIONS: %s", room->connections[0]); i = 1; for(i = 1; i < room->numberConnections; i++) { printf(", %s", room->connections[i]); } printf(".\n"); } printf("WHERE TO >"); //get user input and store in variable scanf("%s", userInput); //if the user input is time, start second thread and print the time if(strcmp(userInput, "time") == 0) { //start thread and print the time thread(); printTime(); } else { int checker = 0; i = 0; //check if user input is a valid connection for(i = 0; i < room->numberConnections; i++) { if(strcmp(userInput,room->connections[i]) == 0) { checker = 1; } } //if the user input isn't valid, print error statement if(checker != 1) { printf("\nHUH? I DON'T UNDERSTAND THAT ROOM. TRY AGAIN.\n\n"); } else { //if the input is valid, change the room struct and print fields switchRoom(userInput, room); strcpy(userPath[numberSteps], userInput); numberSteps = numberSteps + 1; printf("\n"); if(strcmp(room->roomType,"END_ROOM") == 0) { finished = 1; free(room); } } } } while(finished == 0); //print congratulatory message printf("\nYOU HAVE FOUND THE END ROOM. CONGRATULATIONS!\nYOU TOOK %d STEPS. YOUR PATH TO VICTORY WAS:\n", numberSteps); int k; //print user path for(k = 0; k < numberSteps; k++) { printf("%s\n", userPath[k]); } } //printTime function that opens the time file and prints the time void printTime() { char timeBuffer[50]; char time1[20], time2[20], time3[20], time4[20], time5[20]; FILE* currentTimeFile; currentTimeFile = fopen("./currentTime.txt", "r"); //print error if time file is empty if(currentTimeFile == NULL) { perror("Unable to open time File"); } else { fgets(timeBuffer, 75, currentTimeFile); //scan the line and place into char array sscanf(timeBuffer, "%s %s %s %s %s", time1, time2, time3, time4, time5); //if the first number is 0, set it to a space as shown in the instructions if(time1[0] == '0') { time1[0] = ' '; } //change the AM and PM to lowercase as shown in instructions time1[5] = tolower(time1[5]); time1[6] = tolower(time1[6]); //print time to terminal printf("\n%s %s %s %s %s\n\n", time1, time2, time3, time4, time5); fclose(currentTimeFile); } } //timeFile function that creates/updates time file with the current time void* timeFile() { time_t t = time(0); struct tm* info; //get local time info = localtime(&t); FILE* currentTimeFile; currentTimeFile = fopen("currentTime.txt", "w+"); char timeBuffer[50]; //format the time to match the string shown in the instructions strftime (timeBuffer, sizeof(timeBuffer), "%I:%M%p, %A, %B %d, %Y", info); fputs(timeBuffer, currentTimeFile); fclose(currentTimeFile); return ""; } //thread function that initializes a new thread void thread() { int result; pthread_t thread1; pthread_mutex_init(&mutex1, NULL); //lock the first thread pthread_mutex_lock(&mutex1); //create new thread that calls the timeFile function result = pthread_create(&thread1, NULL, timeFile, NULL); if(result != 0) { perror("Could not create thread"); } //unlock main thread pthread_mutex_unlock(&mutex1); //destroy thread pthread_mutex_destroy(&mutex1); sleep(1); } int main() { //run game loop function until user wins gameLoop(); return 0; }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <sys/mman.h> #include <sys/time.h> #include <time.h> #include <pthread.h> #include <stdlib.h> #define KERRW_IOC_READ 0 #define KERRW_IOC_WRITE 1 #define KERRW_IOC_READ16 10 #define KERRW_IOC_WRITE16 11 #define KERRW_IOC_READ8 20 #define KERRW_IOC_WRITE8 21 #define KERRW_IOC_DIRECTREAD8 70 #define KERRW_IOC_DIRECTWRITE8 71 #define KERRW_IOC_READ_CP0 2 #define KERRW_IOC_WRITE_CP0 3 #define KERRW_IOC_READ_PCICONF_8 30 #define KERRW_IOC_WRITE_PCICONF_8 31 #define KERRW_IOC_READ_PCICONF_16 40 #define KERRW_IOC_WRITE_PCICONF_16 41 #define KERRW_IOC_READ_PCICONF_32 50 #define KERRW_IOC_WRITE_PCICONF_32 51 #define KERRW_IOC_READ_PCIBASE 60 #define KERRW_IOC_WRITE_PCIBASE 61 void PrintUsage(char * name) { printf("Usage:\n"); printf("01. %s r32 <address> [num] ---- read the val(u32) from kernel address\n", name); printf("02. %s w32 <address> <value> [num] ---- write the val(u32) to kernel address\n", name); printf("03. %s r16 <address> [num] ---- read the val(u16) from kernel address\n", name); printf("04. %s w16 <address> <value> [num] ---- write the val(u16) to kernel address\n", name); printf("05. %s r8 <address> [num] ---- read the val(u8) from kernel address\n", name); printf("06. %s w8 <address> <value> [num] ---- write the val(u8) to kernel address\n", name); printf("07. %s dr8 <address> [num] ---- read the val(u8) from address\n", name); printf("08. %s dw8 <address> <value> [num] ---- write the val(u8) to address\n", name); printf("09. %s v ---- see the version\n", name); } int main(int argc, char* argv[]) { int fd; int i; int ret; unsigned int adwParams[20]; int width; int num = 1; if ((argc == 2) && (strcmp(argv[1], "v") == 0)) { printf("%s, regeditor V1.00\n", argv[0]); printf("Compile date and time: %s %s\n", argv[0], __DATE__, __TIME__ ); return 0; } fd = open("/dev/ker_r_w", O_RDWR); if (fd < 0) { fd = open("/dev/ker_rw", O_RDWR); if (fd < 0) { printf("can't open /dev/ker_r_w: %d\n", fd); return 0; } } if (argc < 2) { goto err; } for (i = 0; i < 3; i++) { adwParams[i] = ~0UL; } for (i = 2; i < argc; i++) { adwParams[i - 2] = strtoul(argv[i], 0, 0); } if (!strcmp(argv[1], "r32")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { adwParams[1] = 1; } adwParams[2] = adwParams[1]; for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_READ, adwParams))) { printf("Error, can't Read Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { printf("Reg: 0x%08x, Value: 0x%08x\n", adwParams[0], adwParams[1]); adwParams[0] += 4; } } } else if (!strcmp(argv[1], "w32")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { goto err; } if (adwParams[2] == ~0UL) { adwParams[2] = 1; } for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_WRITE, adwParams))) { printf("Error, can't Write Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { adwParams[0] += 4; } } } else if (!strcmp(argv[1], "r16")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { adwParams[1] = 1; } adwParams[2] = adwParams[1]; for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_READ16, adwParams))) { printf("Error, can't Read Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { printf("Reg: 0x%08x, Value: 0x%08x\n", adwParams[0], adwParams[1]); adwParams[0] += 4; } } } else if (!strcmp(argv[1], "w16")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { goto err; } if (adwParams[2] == ~0UL) { adwParams[2] = 1; } for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_WRITE16, adwParams))) { printf("Error, can't Write Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { adwParams[0] += 4; } } } else if (!strcmp(argv[1], "r8")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { adwParams[1] = 1; } adwParams[2] = adwParams[1]; for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_READ8, adwParams))) { printf("Error, can't Read Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { printf("Reg: 0x%08x, Value: 0x%08x\n", adwParams[0], adwParams[1]); adwParams[0] += 4; } } } else if (!strcmp(argv[1], "w8")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { goto err; } if (adwParams[2] == ~0UL) { adwParams[2] = 1; } for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_WRITE8, adwParams))) { printf("Error, can't Write Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { adwParams[0] += 4; } } } else if (!strcmp(argv[1], "dr8")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { adwParams[1] = 1; } adwParams[2] = adwParams[1]; for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_DIRECTREAD8, adwParams))) { printf("Error, can't Read Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { printf("Reg: 0x%08x, Value: 0x%08x\n", adwParams[0], adwParams[1]); adwParams[0] += 4; } } } else if (!strcmp(argv[1], "dw8")) { if (adwParams[0] == ~0UL) { goto err; } if (adwParams[1] == ~0UL) { goto err; } if (adwParams[2] == ~0UL) { adwParams[2] = 1; } for (i = 0; i < adwParams[2]; i++) { if ((ret = ioctl(fd, KERRW_IOC_DIRECTWRITE8, adwParams))) { printf("Error, can't Write Reg: 0x%x, ret: %d\n", adwParams[0], ret); return 0; } else { adwParams[0] += 4; } } } else { PrintUsage(argv[0]); } return 0; err: PrintUsage(argv[0]); return 0; }
C
/* 画一个长方形 */ #include<stdio.h> int main(void){ int row; int column; puts("让我们来画一个长方形。"); printf("一边:"); scanf("%d",&row); printf("另一边"); scanf("%d",&column); for(int i=0; i<column;i++){ for(int m=0 ;m<row; m++){ printf("*"); } printf("\n"); } }
C
#include "lem_in.h" int type_num_ants(char *str) { if (if_is_digit_str(str)) if (count_ants(str)) return (1); return (0); } int type_room(char *str) { char **s; unsigned long int len; if (!str) return (0); s = ft_strsplit(str, ' '); len = two_dem_strlen(s) - 1; if (len != 3) { free_twodem_str(s); return (0); } if (if_is_alnum_str(s[0])) { if (if_is_digit_sign_str(s[1]) && if_is_digit_sign_str(s[2])) { if (limit_int(atoi_lemin(s[1])) && limit_int(atoi_lemin(s[2]))) { free_twodem_str(s); return (1); } } } free_twodem_str(s); return (0); } int type_start_end(char *str) { if (!strcmp(str, "##start") || !strcmp(str, "##end")) return (1); return (0); } int type_connect(char *str) { char **s; unsigned long int len; s = ft_strsplit(str, '-'); len = two_dem_strlen(s) - 1; if (len == 2) { if (if_is_alnum_str(s[0]) || if_is_alnum_str(s[1])) { free_twodem_str(s); return (1); } } free_twodem_str(s); return (0); } int type_comment(char *str) { if (*str == '#' && (ft_strcmp(str, "##start") && ft_strcmp(str, "##end"))) return (1); return (0); }
C
#include <stdio.h> #include "myArray.c" int Partition_Lamuto(int A[], int lower_bound, int upper_bound); int Partition(int A[], int lower_bound, int upper_bound); void QuickSort(int A[], int lower_index, int higher_index) { if (lower_index < higher_index) { // int border = Partition_Lamuto(A, lower_index, higher_index); // QuickSort(A, lower_index, border-1); int border = Partition(A, lower_index, higher_index); QuickSort(A, lower_index, border); QuickSort(A, border +1 , higher_index); } } int Partition(int A[], int lower_bound, int upper_bound) { int i, j, pivot; pivot = A[(lower_bound + (upper_bound - lower_bound) / 2)]; // pivot = A[upper_bound]; i = lower_bound; j = upper_bound; while (1) { while (A[i] < pivot) i++; while (A[j] > pivot) j--; if (i >= j) { // if(pivot == A[i]) printf("Pivot index in I A[%d]=%d But J -- %d \n", i, pivot, j); // else if(pivot == A[j]) printf("Pivot index in J A[%d]=%d But I -- %d \n", j, pivot, i); // else printf("Pivot index in none : I -- %d, j--%d, pivot--%d \n", i, j, pivot); return j; } swap(&A[i++], &A[j--]); } } int Partition_Lamuto(int A[], int lower_bound, int upper_bound){ int pivot = A[ lower_bound + (upper_bound-lower_bound) /2 ]; // int pivot = A[upper_bound]; int i, j; i = j = lower_bound; for(j=lower_bound; j<upper_bound; j++){ if(A[j]<pivot) { swap(&A[i], &A[j]); i++; } } swap(&A[i], &A[upper_bound]); return i; } int main() { int A[] = {10, 5, 6, 20}, size; size = sizeof(A) / sizeof(*A); // int B[] = {10, 5, 6, 20}; A[] = {1, 34, 54, 3, 45, 2, 22, 36, 0} // printf("size %d \n",size); pArray(A, size); QuickSort(A, 0, size - 1); pArray(A, size); }
C
/******************************************************************* * Cellular Automaton *******************************************************************/ #include "mex.h" // #include "matrix.h" #include "math.h" /******************************************************************* * global parameters list *******************************************************************/ double *out_cell; double *in_cell; int m; int n; int st_n =0; int st_d; int st_s; int st_i; double s2d_rate; //S -> D ĸ double i2d_rate; //I->Dĸ double s2i_rate; //S->Iĸ double xy_range; //ԴķΧ,ͨŰ뾶 double k; //ھӽڵIڵĸ /******************************************************************* * UTIL function list *******************************************************************/ void dump_param() { static int i = 0; if (i != 0) return; ++i; mexPrintf("m*n=%d*%d\n", m, n); mexPrintf("xy_range=%f\n", xy_range); mexPrintf("st_n=%d\n", st_n); mexPrintf("st_d=%d\n", st_d); mexPrintf("st_s=%d\n", st_s); mexPrintf("st_i=%d\n", st_i); mexPrintf("s2d_rate=%f\n", s2d_rate); mexPrintf("i2d_rate=%f\n", i2d_rate); mexPrintf("s2i_rate=%f\n", s2i_rate); } double myrand() { double r; static int i = 0; if (i == 0) { srand(time(0)); i = 1; mexPrintf("set srand only once\n"); } r = rand(); return r / RAND_MAX; r = rand() % 10000; return r / 10000.0f; } int statisticsNeighborStatus(int x, int y, int st) { int k = 0; int i,j; int x0,x1,y0,y1; x0 = x - xy_range; x1 = x + xy_range; y0 = y - xy_range; y1 = y + xy_range; if (x0 < 0) x0 = 0; if (x1 >= m) x1 = m - 1; if (y0 < 0) y0 = 0; if (y1 >= n) y1 = n - 1; for ( i = x0; i <= x1; ++i) { for ( j = y0; j <= y1; ++j) { if ((int)in_cell[i*n+j] == st) { ++k; } } } return k; } /******************************************************************* * S status change function list *******************************************************************/ int func_S_status_change(int x, int y) { int k = statisticsNeighborStatus(x, y, st_i); double s2i_rate_all = 1-pow((1 - s2i_rate), k); double r = myrand(); int st; if (r < s2d_rate) { st = st_d; } else if (r < s2i_rate_all + s2d_rate) { st = st_i; } else { st = st_s; } return st; } /******************************************************************* * I status change function list *******************************************************************/ int func_I_status_change() { int st; if (myrand() < i2d_rate) { st = st_d; } else { st = st_i; } return st; } /******************************************************************* * UPDATE STATUS function list *******************************************************************/ void UpdateCaStatus() { int i,j, k; double r; for (i = 1; i < m-1; ++i) { //mexPrintf("\n"); for (j = 1; j < n-1; ++j) { //mexPrintf("%d,",in_cell[i*n+j]); if ((int)in_cell[i*n+j] == st_s) { out_cell[i*n+j] = func_S_status_change(i,j); } else if ((int)in_cell[i*n+j] == st_i) { out_cell[i*n+j] = func_I_status_change(); } else if ((int)in_cell[i*n+j] == st_d) { out_cell[i*n+j] = st_d; } else { out_cell[i*n+j] = st_n; } } } } /******************************************************************* * MAIN function *******************************************************************/ void mexFunction(int nlhs,mxArray *plhs[],int nrhs,const mxArray *prhs[]) { //mexPrintf("\nThere are %d right-hand-side argument(s).", nrhs); //die_rate,xy_range,st_d,st_s,st_i //size of input in_cell=mxGetPr(prhs[0]); xy_range =mxGetScalar(prhs[1]); st_n =mxGetScalar(prhs[2]); st_d = mxGetScalar(prhs[3]); st_s = mxGetScalar(prhs[4]); st_i = mxGetScalar(prhs[5]); s2d_rate = mxGetScalar(prhs[6]); i2d_rate = mxGetScalar(prhs[7]); s2i_rate = mxGetScalar(prhs[8]); m = mxGetM(prhs[0]); n = mxGetN(prhs[0]); dump_param(); plhs[0]=mxCreateDoubleMatrix(m,n, mxREAL); //outputd pointer out_cell=mxGetPr(plhs[0]); memcpy(out_cell, in_cell, m * n *sizeof(int)); //mexPrintf("%f\n",myrand()); //call subfunction UpdateCaStatus(); }
C
// // ArrayList.c // ListMain // // Created by 김영후 on 2014. 12. 27.. // Copyright (c) 2014년 Hoo. All rights reserved. // #include "ArrayList.h" /* * 리스트 초기화 */ void ListInit(List * plist) { plist->numOfData = 0; // 리스트에 저장된 데이터의 수는 0 plist->curPosition = -1; // 현재 아무 위치도 가리키지 않음 } /* * 데이터 저장 */ void LInsert(List * plist, LData data) { if (plist->numOfData >= LIST_LEN) { // 예외 처리 puts("배열길이를 초과하여 더이상 저장할 수 없습니다."); return; } plist->arr[plist->numOfData] = data; // 데이터 저장 (plist->numOfData)++; // 저장된 데이터의 수 증가 } /* * 첫 번째 조회 */ int LFirst(List * plist, LData * pdata) { if (plist->numOfData == 0) { // 예외 처리 return FALSE; } (plist->curPosition) = 0; // 참조 위치 초기화(첫 번째 데이터의 참조를 의미한다) *pdata = plist->arr[0]; // pdata가 가리키는 공간에 데이터 저장 return TRUE; } /* * 두 번째 이후의 조회 */ int LNext(List * plist, LData * pdata) { if (plist->curPosition >= plist->numOfData-1) { // 예외 처리 return FALSE; } (plist->curPosition)++; *pdata = plist->arr[plist->curPosition]; return TRUE; } /* * 데이터 삭제 */ LData LRemove(List * plist) { int i; int rpos = plist->curPosition; int num = plist->numOfData; LData removedData = plist->arr[rpos]; for (i = rpos; i < num-1; i++) { plist->arr[i] = plist->arr[i+1]; } (plist->numOfData)--; (plist->curPosition)--; return removedData; } /* * 전체 데이터 개수 */ int LCount(List * plist) { return plist->numOfData; }
C
#ifndef __datetime__ #define __datetime__ #include <stdio.h> #include <string.h> #include <stdlib.h> typedef struct { int year,month,day,hour,min,seg; }datetime_t; //Inicializa la estructura int datetime_create(datetime_t *self); //Setea fecha y hora int datetime_setdatetime(datetime_t *self, char* datetime); //Devuelve el valor de los segundos int datetime_getsecond(datetime_t *self, int *second); //Devuelve la fecha y hora int datetime_getdatetime(datetime_t *self, char* datetime,size_t length); //Devuelve la fecha int datetime_getdate(datetime_t *self, char* date,size_t length); //Devuelve el dia int datetime_getday(datetime_t *self, int *day); //Incrementa un minuto int datetime_minuteincrease(datetime_t *self); //Incrementa una hora int datetime_hourincrease(datetime_t *self); //Incrementa un dia int datetime_dayincrease(datetime_t *self); //Incrementa un mes int datetime_monthincrease(datetime_t *self); //Incrementa un anio int datetime_yearincrease(datetime_t *self); //Destruye la estructura int datetime_destroy(datetime_t *self); #endif
C
#include "stdlib.h" int containsFive(int n) { while(n != 0) { if(abs(n % 10) == 5) { return 1; } n /= 10; } return 0; } int dontGiveMeFive(int start, int end) { int total = 0; for(int i = start; i <= end; i++) { if(containsFive(i) == 0){ total++; } } return total; }
C
#ifndef __FILE_H__ #define __FILE_H__ typedef struct Directory { // The name of the directory char *name; // TODO: The list of files of the current directory struct FolderChain *folders; // TODO: The list of directories of the current directory struct FileChain *files; // The parent directory of the current directory (NULL for the root directory) struct Directory *parentDir; } Directory; typedef struct File { // The name of the file char *name; // The size of the file int size; // The content of the file char *data; // The directory in which the file is located Directory *dir; } File; typedef struct FolderChain { Directory *dir; struct FolderChain *next; } FolderChain; typedef struct FileChain { File *file; struct FileChain *next; } FileChain; #endif /* __FILE_H__ */
C
/* 인접 행렬로 표현된 그래프를 입력받아서 인접 리스트로 변환하는 C함수로 작성하라. */ #include<stdio.h> #include<malloc.h> #define MAX_VERTICES 50 #define MATRIC_VERTICES 6 typedef struct GraphNode{ int vertex; int weight; struct GraphNode *link; }GraphNode; typedef struct GraphType{ int n; GraphNode *adjList[MAX_VERTICES]; }GraphType; void init(GraphType *g, int n){ if(n <= MAX_VERTICES){ g->n = n; for(int i=0; i<n; i++){ g->adjList[i] = NULL; } } else { printf("Input of vertices is too big.\n"); } } void insertEdge(GraphType *g, int u, int v, int weight){ if(u < g->n && v < g->n){ GraphNode *newNode = (GraphNode *)malloc(sizeof(GraphNode)); newNode->vertex = v; newNode->weight = weight; newNode->link = g->adjList[u]; g->adjList[u] = newNode; } else { printf("wrong vertex.\n"); } } void display(GraphType g){ for(int i=0; i<g.n; i++){ GraphNode *p = g.adjList[i]; printf("%d : ", i); while(p != NULL){ printf("%d ", p->vertex); p = p->link; } printf("\n"); } } void main() { GraphType test1; int adjMat[MATRIC_VERTICES][MATRIC_VERTICES] = { {0, 50, 45, 10, 0, 0}, {0, 0, 10, 15, 0, 0}, {0, 0, 0, 0, 30, 0}, {20, 0, 0, 0, 15, 0}, {0, 20, 35, 0, 0, 0}, {0, 0, 0, 0, 3, 0} }; init(&test1, MATRIC_VERTICES); for(int i=0; i<MATRIC_VERTICES; i++){ for(int j=0; j<MATRIC_VERTICES; j++){ if (adjMat[i][j] != 0) { insertEdge(&test1, i, j, adjMat[i][j]); } } } display(test1); }
C
#ifndef BST_H_ #define BST_H_ #include <stdio.h> #include <stdlib.h> #include "structures.h" #include "data.h" #include "stack.h" #include "queue.h" // create a new leaf and return it struct leaf* createLeaf(struct data *d); // create a new Tree struct tree* createTree(); // Insert a new node into tree void insertBst(struct tree *t,struct data *d); void insertBst_r(struct leaf* current,struct leaf* newLeaf); // Print all the node of Tree in InOrder sequence void inOrderBst(struct tree *t); void inOrderBst_r(struct leaf *current); // Find out sum of all the nodes in tree float totalSum(struct tree *t); float totalSum_r(struct leaf* current); // void breathFirstBst(struct tree *t); // Print all the nodes of tree in PreOrder sequence void preOrderBst(struct tree *t); void preOrderBst_r(struct leaf *lf); // Print all the nodes of Tree in PostOrder sequence void postOrderBst(struct tree *t); void postOrderBst_r(struct leaf *lf); // recursively find out the node with largest value and return it struct data* getMaxData(struct tree *tr); struct data* getMaxData_r(struct leaf* lf); // recursively find out the node with smallest value and return it struct data* getMimData(struct tree *tr); struct data* getMimData_r(struct leaf* lf); // return height of BST int getBstHeight(struct tree *tr); int getBstHeight_r(struct leaf* lf); // Print out all of the elements whose sum is greater than begin and less than end in inOrde sequence void printInRange(struct tree *tr, float begin, float end); void printInRange_r(struct leaf* lf, float begin,float end); // Check whether BST is a complete BST (all of the leaves terminate at the same level) int isCompleteBst(struct tree *tr); int isCompleteBst_r(struct leaf* lf); // Check Whether BST is a Full BST (every node has 2 children except for the leaves) int isFullBst(struct tree *tr); int isFullBst_r(struct leaf *lf); // Create a mirror image of BST void reverseBST(struct tree *t); void reverseBST_r(struct leaf *lf); // return sum of all the leaves of BST float sumLeaves(struct tree *t); float sumLeaves_r(struct leaf *lf); // Print BST in Breadth First Order void printBreadthFirstSearch(struct tree *t); // Print BST in Depth First Order void printDepthFirstSearch(struct tree *t); // Free all the memory allocated by tree void cleanBST(struct tree *t); void cleanBST_r(struct leaf *lf); int isBST(struct tree *t); float isBST_r(struct leaf *n); #endif
C
/*Binary Search Recursion*/ #include<stdio.h> int BinarySearch(int [], int, int, int); int main() { int n,data; int place; printf("Enter the Number: "); scanf("%d", &data); int A[13] = {1,4,6,8,10,25,67,78,98,100,201,403,607}; place = BinarySearch(A, data, 0, 12); printf("The index is: %d and position is: %d", place, place+1); } int BinarySearch(int A[], int data, int left, int right) { int mid; mid = (left + right) / 2; while(left<=right) { if(data==A[mid]) return mid; else if(data>A[mid]) return BinarySearch(A, data, mid+1,right); else return BinarySearch(A, data, left, mid-1); } return -1; }
C
/* * plus_one.c * * Created on: Apr 29, 2018 * Author: Harsh */ #include <stdio.h> #include <stdlib.h> #include "_linked_list.h" /** * Definition for singly-linked list.*/ struct ListNode { int val; struct ListNode *next; }; /* Method 1: Iterative + Reversal 1. Reverse the linked list 2. Add 1 and carry forward the carry to reset of the linke dlist 3. Reverse the result list again Time Complexity = 3*O(n) ~~ O(n) Method 2 : Recursion */ typedef struct ListNode node; node* plusOneRecursively(node* head, int* carry){ if (head == NULL){ return NULL; } int sum; int add; node* result = (node*)malloc(sizeof(node)); result->next = plusOneRecursively(head->next, carry); // add 1 to current node and propagated carry sum = head->val + *carry; *carry = sum / 10; sum = sum % 10; result->val = sum; //printf("Carry = %d\n", *carry); return result; } struct ListNode* plusOne(struct ListNode* head) { int carry = 1; node* res = plusOneRecursively(head, &carry); if(head->val != 0 && res->val == 0){ node* newNode = (node*)malloc(sizeof(node)); newNode->val = 1; newNode->next = res; return newNode; } else{ return res; } }
C
#include <X11/X.h> #include "tool_freehand.h" #include "tool.h" #include "network.h" #include <X11/Xlib.h> void tool_freehand(tool_freehand_context_t *context, canvas_event_t event) { if(event.type == ButtonPress) { context->is_painting = True; ll_point_clear(context); context->head->point.x = event.x; context->head->point.y = event.y; } else if(event.type == ButtonRelease && context->is_painting == True) { context->is_painting = False; tool_freehand_paint(context); ll_point_clear(context); } else if(event.type == MotionNotify && context->is_painting == True) { XPoint p; p.x = event.x; p.y = event.y; ll_point_add(context, p); } } void tool_freehand_paint(tool_freehand_context_t *context) { /* We create a temporary image that is the result of the mouse movements */ char *imageInitData = malloc(context->repaint_context->canvas->width * context->repaint_context->canvas->height * sizeof(int)); int *p = (int *) imageInitData; for(int i = 0; i < context->repaint_context->canvas->width * context->repaint_context->canvas->height; ++i) *p++ = 0x00000000; /* Make it all black at first */ XImage *image = XCreateImage(context->repaint_context->display, context->repaint_context->visual, DEFAULT_DEPTH, ZPixmap, 0, imageInitData, context->repaint_context->canvas->width, context->repaint_context->canvas->height, 32, 0); ll_point_t *ptr = context->head; /* Paint white lines on the temporary image */ while(ptr->next != NULL) { ll_point_t *next = (ll_point_t *) ptr->next; if(next->next == NULL) break; int start_x = ptr->point.x; int start_y = ptr->point.y; int end_x = next->point.x; int end_y = next->point.y; int thickness = context->repaint_context->thickness; draw_line_on_image(image, thickness, TMP_COLOR, start_x, start_y, end_x, end_y); ptr = (ll_point_t *) ptr->next; } process_image(context->repaint_context, image); XDestroyImage(image); /* This also free()s the data! */ } /* Linked list functions */ void ll_point_add(tool_freehand_context_t *context, XPoint p) { ll_point_t *tmp; tmp = context->head; while(tmp->next != NULL) { tmp = (ll_point_t *) tmp->next; } tmp->next = malloc(sizeof(ll_point_t)); tmp->point = p; tmp = (ll_point_t *) tmp->next; tmp->next = NULL; } void ll_point_clear(tool_freehand_context_t *context) { ll_point_t *tmp = context->head; context->head = malloc(sizeof(ll_point_t)); context->head->next = NULL; while(tmp->next != NULL) { /* FIXME!!! Really? Really?!? Have I thought this through? */ ll_point_t *tmp2 = tmp; tmp = (ll_point_t *) tmp->next; free(tmp2); } }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> #include<string.h> double Manhattan_Dist(double vectx[], double vecty[], int n) //Function to calculate Manhattan Distance { double man_dist = 0; for (int i=0; i<n; i++) { man_dist = man_dist + fabs(vectx[i] - vecty[i]); } return floor((floor(man_dist*1e5)*1e-5+1e-5)*1e4)*1e-4; } double Euclidean_Dist(double vectx[], double vecty[], int n) //Function to calculate Euclidean Distance { double euc_dist = 0; for (int i=0; i<n; i++) { euc_dist = euc_dist + pow((vectx[i]- vecty[i]), 2); } euc_dist = sqrt(euc_dist); return floor((floor(euc_dist*1e5)*1e-5+1e-5)*1e4)*1e-4; } double Chebyshev_Dist(double vectx[], double vecty[], int n) //Function to calculate Chebysev Distance { double che_dist = 0; for (int i=0; i<n; i++) { if (che_dist < fabs(vectx[i] - vecty[i])) { che_dist = fabs(vectx[i] - vecty[i]); } } return floor((floor(che_dist*1e5)*1e-5+1e-5)*1e4)*1e-4; } double KL_Divergence(double vectx[], double vecty[], int n) //Function to calculate KL Divergence { double div = 0; for (int i=0; i<n; i++) { div = div + (vectx[i]*log(vectx[i]/vecty[i])); } return div; } double KL_Dist(double vectx[], double vecty[], int n) //Function to calculate KL Distance { return floor((floor((KL_Divergence(vectx, vecty, n) + KL_Divergence(vecty, vectx, n))*1e5)*1e-5+1e-5)*1e4)*1e-4; } double JS_Divergence(double vectx[], double vecty[], int n) //Function to calculate JS Divergence { double avg[n]; for (int i=0; i<n; i++) { avg[i] = (vectx[i] + vecty[i])/2; } return (KL_Divergence(vectx, avg, n) + KL_Divergence(vecty, avg, n))/2; } double JS_Dist(double vectx[], double vecty[], int n) //Function to calculate JS Distance { double div = JS_Divergence(vectx, vecty, n); return floor((floor(sqrt(div)*1e5)*1e-5+1e-5)*1e4)*1e-4; } int main() { int n; //size of vectors scanf("%d",&n); int p1, p2; //to detect "-1" char c; //to detect "," double vectx[n]; //Array of first-vectors double vecty[n]; //Array of second-vectors scanf("%d",&p1); if(p1 != -1) { printf("-1\n"); return 0; } for(int i=0; i<n-1; i++) { scanf("%lf%c",&vectx[i],&c); if(c != ',' || vectx[i] <= 0) //detecting "," and sign of vectors { printf("-1\n"); return 0; } } scanf("%lf",&vectx[n-1]); if(vectx[n-1] <= 0) { printf("-1\n"); return 0; } scanf("%d",&p2); if(p2 != -1) { printf("-1\n"); return 0; } for(int j=0; j<n-1; j++) { scanf("%lf%c",&vecty[j],&c); if(c != ',' || vecty[j] <= 0) //detecting "," and sign of vectors { printf("-1\n"); return 0; } } scanf("%lf",&vecty[n-1]); if(vecty[n-1] <= 0) { printf("-1\n"); return 0; } char arr[5]; // to detect last "-1" as a delimiter fgets(arr, 5, stdin); if(arr[1] != '-' || arr[2] != '1') // checking characters separately { printf("-1\n"); return 0; } double sumx = 0, sumy = 0; for (int i=0; i<n; i++) //Sums for Normalisation { sumx = sumx + vectx[i]; sumy = sumy + vecty[i]; } for (int i=0; i<n; i++) //Vectors after Normalisation { vectx[i] = vectx[i]/sumx; vecty[i] = vecty[i]/sumy; } printf("%.4lf,%.4lf,%.4lf,%.4lf,%.4lf\n", Manhattan_Dist(vectx, vecty, n), Euclidean_Dist(vectx, vecty, n), Chebyshev_Dist(vectx, vecty, n), KL_Dist(vectx, vecty, n), JS_Dist(vectx, vecty, n)); return 0; }
C
#include "linear_allocator.h" #include <stdio.h> #include <stdlib.h> #define ALLOCATED_MEMORY_SIZE 100 #define CHUNK_SIZE 23 int main(int argc, char *argv[]) { linear_allocator_t allocator; void *mem; allocator = linear_allocator_new(ALLOCATED_MEMORY_SIZE); while (mem = linear_allocator_alloc(allocator, CHUNK_SIZE)) { printf("Memory chunk size %d allocated at adress %p\n", CHUNK_SIZE, mem); } puts("Memory out, dealocating allocator"); linear_allocator_free(&allocator); return EXIT_SUCCESS; }
C
/***************************************************************** * Author: Joseph DePrey * Description: adventure.c provides an interface for playing a game using * the most recently generated rooms from buildrooms.c * In the game, the player will begin in the "starting room" and will win * the game automatically upon entering the "ending room", which causes the * game to exit, displaying the path taken by the player. * During the game, the player can also enter a command that returns the * current time *****************************************************************/ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <unistd.h> #include <sys/stat.h> #include <dirent.h> #include <pthread.h> // Buffer for max length of room names #define NAME_LENGTH 10 // Constants provided by program specifications #define NUM_ROOMS 7 // Max number of outgoing connections (amount is random) between each room #define MAX_CONN 6 #define DIR_PREFIX "depreyj.rooms" #define ROOM_ERROR "HUH? I DON’T UNDERSTAND THAT ROOM. TRY AGAIN." #define TIME_FILENAME "currentTime.txt" enum roomType {START_ROOM, MID_ROOM, END_ROOM}; // Room info struct Room { char *name; enum roomType type; int connections[MAX_CONN]; }; // Global mutex for time thread pthread_mutex_t time_mutex; /******************Function Declarations**********************/ void getLatestRoomDir(char roomDir[]); void readRooms(struct Room roomList[], char roomDir[], char *visited[]); void gameOn(struct Room roomList[], char *visited[]); void *writeTime(); void readTime(); /************************************************************ *********************** MAIN ******************************* *************************************************************/ int main(void){ // Array of pointers to Rooms to hold data read from files struct Room roomList[NUM_ROOMS]; // Array of Room names already read in from files char **visited; visited = malloc(NUM_ROOMS * sizeof(char*)); for (int i = 0; i < NUM_ROOMS; i++){ visited[i] = malloc((NAME_LENGTH+1) * sizeof(char)); } // Get most recent room directory char roomDir[30]; getLatestRoomDir(roomDir); // Read all files in room directory readRooms(roomList, roomDir, visited); // Finally, play the game gameOn(roomList, visited); return(0); } /************************************************************ * Get most recent room directory from same directory as game * Return directory name as pointer to char *************************************************************/ void getLatestRoomDir(char roomDir[]){ DIR *d; // stat struct to hold directory info struct stat sb; // Used to sort folders by time int latest = 0; memset(roomDir, '\0', 30); struct dirent *dir; d = opendir("./"); if (d) { while ((dir = readdir(d)) != NULL) { // Match dir names with our room dir prefix if(strstr(dir->d_name, DIR_PREFIX) != NULL){ // Get dir stats stat(dir->d_name, &sb); // Find the most recently created dir if (((int) sb.st_mtime) > latest){ latest = (int) sb.st_mtime; strcpy(roomDir, dir->d_name); } } } } else { printf("Directory is empty. Please run buildrooms program before playing."); } closedir(d); } /************************************************************ * Read room data from files in room directory * Store room data in array of pointers to Room structs *************************************************************/ void readRooms(struct Room roomList[], char roomDir[], char *visited[]){ // Open latest room directory DIR *d; FILE *fp; int i, j; int roomCount = 0; char roomFilePath[100]; memset(roomFilePath, '\0', strlen(roomFilePath)); // Use these with fscanf because each file has only three fields per line // e.g. ROOM, NAME, desert char field1[NAME_LENGTH]; char field2[NAME_LENGTH]; char field3[NAME_LENGTH]; struct dirent *dir; d = opendir(roomDir); // Open all files in current Room directory and put filenames in array if (d) { // Make sure we get files, not . and .. readdir(d); readdir(d); printf("%s",roomDir); while((dir = readdir(d)) != NULL){ // Put filenames in array for later use // memset(visited[roomCount], '\0', NAME_LENGTH); strcpy(visited[roomCount], dir->d_name); roomCount++; } } else { fprintf(stderr, "Unable to open dir %s\n", roomDir); exit(1); } // Open all named room files and get Room struct data for (i = 0; i < roomCount; i++){ // Create path for room file by combining the current Room directory and filename sprintf(roomFilePath, "%s/%s", roomDir, visited[i]); // Open room file for reading fp = fopen(roomFilePath, "r"); if (fp == NULL){ fprintf(stderr, "Unable to open file %s\n", roomFilePath); exit(1); } // Get room name from file strcpy(roomList[i].name, visited[i]); // Set all connections to 0 (no connections by default) for (j = 0; j < NUM_ROOMS; j++){ roomList[i].connections[j] = 0; } // Load connections and type from every room file // Attempt to use fscanf to read data from room file while(fscanf(fp, "%s %s %s", field1, field2, field3) != EOF){ if(strncmp(field2, "NAME", 4) == 0) { // Skip over the name value which we already have } else if(strncmp(field2, "TYPE", 4) == 0) { if(strncmp(field3, "START_ROOM", 10) == 0) { roomList[i].type = START_ROOM; } else if(strncmp(field3, "MID_ROOM", 8) == 0) { roomList[i].type = MID_ROOM; } else if(strncmp(field3, "END_ROOM", 8) == 0) { roomList[i].type = END_ROOM; } } else if (strncmp(field1, "CONNECTION", 10) == 0){ // Set up room connections for (j = 0; j < NUM_ROOMS; j++){ if(strcmp(field3, visited[j]) == 0){ roomList[i].connections[j] = 1; } } } } fclose(fp); } // Close room directory closedir(d); } /************************************************************ * Start the game *************************************************************/ void gameOn(struct Room roomList[], char *visited[]){ pthread_t time_thread; // Start Second Thread running pthread_create(&time_thread, NULL, writeTime, NULL); // Mutex lock it pthread_mutex_init(&time_mutex, NULL); pthread_mutex_lock(&time_mutex); // User input must be shorter than room names char buffer[NAME_LENGTH]; // Current connection int currConn = 0; int i = 0; int j; int index = -1; // Set up default path int path[14] = {-1}; int pathCount = 0; // Room struct for current room struct Room *currRoom = NULL; // Get START_ROOM do { if(roomList[i].type == START_ROOM) { currRoom = &roomList[i]; } i++; } while((currRoom == NULL) && (i < NUM_ROOMS)); // Let user continue looking for other rooms while(currRoom->type != END_ROOM){ printf("CURRENT LOCATION: %s\n", currRoom->name); printf("POSSIBLE CONNECTIONS:"); // Print connections // Reset to 0 currConn = 0; for(j = 0; j < NUM_ROOMS; j++) { if(currRoom->connections[j] == 1) { if(currConn == 0) { printf(" %s", visited[j]); } else { printf(", %s", visited[j]); } currConn++; } } printf(".\n"); Input: printf("WHERE TO? >"); fgets(buffer, NAME_LENGTH, stdin); // Span the string until newline, set index at newline to null buffer[strcspn(buffer, "\n")] = 0; // Check if user entered valid Room name for(j = 0; j < NUM_ROOMS; j++) { if(strcmp(visited[j], buffer) == 0) { index = j; } } // Check if entered room is a connection if(currRoom->connections[index] == 1) { currRoom = &roomList[index]; path[pathCount] = index; pathCount++; } else if (strcmp("time", buffer) == 0){ // Unlock a mutex pthread_mutex_unlock(&time_mutex); // Join() on second thread pthread_join(time_thread, NULL); // writeTime(); // Lock mutex again pthread_mutex_lock(&time_mutex); // Spawn second thread again pthread_create(&time_thread, NULL, writeTime, NULL); readTime(); goto Input; } else { printf("\n%s\n", ROOM_ERROR); } } if(currRoom->type == END_ROOM) { printf("YOU HAVE FOUND THE END ROOM. CONGRATULATIONS!\n"); printf("YOU TOOK %d STEPS. YOUR PATH TO VICTORY WAS:\n", pathCount); for(i = 0; i < pathCount; i++) { printf("%s\n", visited[path[i]]); } } // Kill second (time) thread pthread_detach(time_thread); pthread_cancel(time_thread); } /************************************************************ * Write current time to currentTime.txt file *************************************************************/ void *writeTime(){ // Attempt to lock mutex pthread_mutex_lock(&time_mutex); // Time variables time_t rawtime; struct tm *info; char timeBuffer[80] = {0}; // Output file pointer FILE *fp = NULL; time(&rawtime); info = localtime(&rawtime); strftime(timeBuffer, 80, "%l:%M%p, %A, %B %d, %Y", info); fp = fopen(TIME_FILENAME, "w"); if (fp == NULL){ fprintf(stderr, "Unable to open file %s for writing.\n", TIME_FILENAME); exit(1); } fprintf(fp, "%s", timeBuffer); fclose(fp); // Unlock mutex pthread_mutex_unlock(&time_mutex); return NULL; } /************************************************************ * Read current time from currentTime.txt file and print it *************************************************************/ void readTime(){ FILE *fp2 = NULL; // Time test char line[80]; fp2 = fopen(TIME_FILENAME, "r"); if (fp2 < 0){ fprintf(stderr, "Unable to open file %s for reading.\n", TIME_FILENAME); exit(1); } while (fgets(line, sizeof(line), fp2) != NULL) { printf("\n%s\n", line); } fclose(fp2); }
C
#include "mesin_kar.h" /** * Menghitung jumlah kemunculan karakter pada suatu pita karakter * needle merupakan huruf yang akan dihitung * filename merupakan nama file * Fungsi mengembalikan jumlah karakter yang muncul pada pita karakter */ /* State Mesin */ extern char CC; extern boolean EOP; /* pada implementasi (mesin_kar.c), perlu ditambahkan variabel static global yang menyimpan pembacaan file pita. */ void START(char* filename) /* Mesin siap dioperasikan. Pita disiapkan untuk dibaca. Karakter pertama yang ada pada pita posisinya adalah pada jendela. filename merupakan nama file yang berisi pita karakter I.S. : sembarang F.S. : CC adalah karakter pertama pada pita Jika CC != MARK maka EOP akan padam (false) Jika CC = MARK maka EOP akan menyala (true) */ { pita = fopen(filename,"r"); ADV(); } void ADV() /* Pita dimajukan satu karakter. I.S. : Karakter pada jendela = CC, CC != MARK F.S. : CC adalah karakter berikutnya dari CC yang lama, CC mungkin = MARK Jika CC = MARK maka EOP akan menyala (true) */ { retval = fscanf(pita,"%c",&CC); if (IsEOP) { fclose(pita); } } char GetCC() /* Mengembalikan karakter yang sedang terbaca di jendela. I.S. : Karakter pada jendela = CC, CC != MARK F.S. : mengembalikan karakter yang sedang terbaca di jendela */ { i = 0; while ((CC != MARK) && (CC != BLANK)){ C } } boolean IsEOP() /* Mengecek apakah pita telah selesai dibaca I.S. : Pita telah terbaca F.S. : Menegmbalikan true jika pita telah selesai terbaca, false jika sebaliknya */ { if (CC == MARK){ return true } } int count_char(char needle, char *filename) { int count = 0; START(filename); while (!IsEOP()) { if (GetCC() == needle) { count++; } ADV(); } return count; }
C
/* Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Example 4: Input: x = 0 Output: 0 Constraints: -231 <= x <= 231 - 1 */ int reverse(int x){ if (x < -2147483648 || x > 2147483647) { return 0; } int digit = 0; int out = 0; while (x != 0){ if (out < -2147483648/10 || out > 2147483647/10){ return 0; } digit = x % 10; out = 10*out + digit; x = x/10; } return out; }
C
#ifndef __LIST__H__ #define __LIST__H__ /* Définition d'un Booléen */ typedef enum { false, true }Bool; /* Définition d'une Liste */ typedef struct ListElement { int value; struct ListElement *next; }ListElement, *List; /* Prototypes */ List new_list(void); Bool is_empty_list(List li); void print_list(List li); int list_length(List li); List push_back_list(List li, int x); List push_front_list(List li, int x); List pop_back_list(List li); List pop_front_list(List li); List clear_list(List li); #endif
C
// Owner: Costa // Exercise: formula_bhaskara // Created in 11/01/2018 10:11:16 #include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ double a, b, c; scanf("%lf %lf %lf", &a, &b, &c); double r1 = 0; double r2 = 0; double bhask = b*b -4*a*c; if(bhask < 0 || a == 0.0){ printf("Impossivel calcular\n"); return 0; } //printf("%lf ", bhask); r1 = ( -b + sqrt(bhask) ) / (2*a); r2 = ( -b - sqrt(bhask) ) / (2*a); printf("R1 = %.5lf\n", r1); //printf("%lf %lf %lf %lf", 34.0/2*a, -b, -sqrt(bhask), 2*a); printf("R2 = %.5lf\n", r2); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <math.h> #include "pe12.h" #include "pe13.h" #include "pe14.h" extern int random_s(void); extern void setNext(void); extern void reverse(void); void readLine(int argv, char * args[]); void showArray(double targer[], int size); int main(int argv, char * args[]) { //getCharNum(); //readLine(argv, args); //copyFile_s(); //showFile(argv, args); //appendFile(argv, args); //showFileText(argv, args); // addWord(); //showBitmap_s(); //showBookList(); //getDaysInYear(); //readFileToStruct(); //test(); //assignSeatsSys(); //assignFlight(); double source[100]; double targer[100]; rand(time(0)); int i; for (i = 0; i < 100; i++) { source[i] = i; } transform(source, targer, 100, sin); showArray(targer, 100); transform(source, targer, 100, cos); printf("==================================================\n"); showArray(targer, 100); transform(source, targer, 100, tan); printf("==================================================\n"); showArray(targer, 100); return 0; } void showArray(double targer[], int size) { static int i = 0; for (i = 0; i < size; i++) { printf("%+6.3lf ", targer[i]); if ((i + 1) % 10 == 0) { putchar('\n'); } } }
C
#include<stdio.h> int main() { int a[2][2]; int b[2][2]; int i,j; printf("MATRIX A :"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { scanf("%d",&a[i][j]); } } for(i=0;i<2;i++) { for(j=0;j<2;j++) { printf("%d\t",a[i][j]); } printf("\n"); } printf("Transpose of matrix :\n"); for(i=0;i<2;i++) { for(j=0;j<2;j++) { b[i][j]=a[j][i]; printf("%d\t",b[i][j]); } printf("\n"); } }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> //дһMaxȽĽϴֵ int Max(int x, int y) { if (x > y) { printf("ϴֵa=%d\n", x); } if (x < y) { printf("ϴֵb=%d\n", y); } if (x==y) { printf("\n"); } return 0; } int main() { int a = 0; int b = 0; printf("a\n"); scanf("%d", &a); //ȡaֵ printf("b\n"); scanf("%d", &b); //ȡbֵ Max(a, b); //Max return 0; }
C
/** * Ce programme montre comment il est possible de faire jouer de la musique à * votre programme. * * Cette démonstration utilise les fonctions suivantes : * *------------------------------------------------------------------------------ * MLV_init_audio : Cette fonction initialise la libraire MLV pour pouvoir jouer * de la musique et des sons. * * Cette fonction renvoie 0 si l'infrastructure audio a été * correctement initialisé, renvoie -1 sinon. * * int MLV_init_audio(); * *------------------------------------------------------------------------------ * MLV_free_audio : Ferme proprement les différents périphériques audios. * * void MLV_free_audio(); * *------------------------------------------------------------------------------ * MLV_load_music : Charge un ficher contenant de la musique en mémoire. * * Cette fonction prends en paramètre le chemin d'acces du * fichier contenant la musique et renvoie un pointeur vers * l'espace mémoire où a été chargé la musique. * * Les formats de fichier acceptés sont le .ogg, .mp3, .wav, * etc... * * Cette fonctione renvoie un pointeur vers la musique chargée * en mémoire, ou NULL si la librairie n'a pas réussi à charger * la musique en mémoire. * * MLV_Music* MLV_load_music( * const char* file_music Chemin d'accès vers un fichier contenant * de la musique. * ); * *------------------------------------------------------------------------------ * MLV_free_music : Ferme un morceau de musique chargé en mémoire. * * void MLV_free_music( * MLV_Music* music Le morceau de musique à fermer * ); * *------------------------------------------------------------------------------ * MLV_play_music : Joue une musique qui est chargée en mémoire. * * void MLV_play_music( * MLV_Music* music, Le morceau de musique à jouer. * float volume, Le volume sonore. * int loop Le nombre de fois que le morceau doit être * joué. Si loop est strivtement négatif, le * morceau sera joué indéfiniment. * ); * *------------------------------------------------------------------------------ * Arrête toutes les musiques. * * void MLV_stop_music(); * *------------------------------------------------------------------------------ * * Pour plus d'information tapez la commande : * man MLV_audio.h * */ #include <MLV/MLV_all.h> // // Attention ! // Pour pouvoir compiler ce programme sous windows et sous macintosh, // il faut, pour la déclaration du main, respecter strictement la syntaxe // suivante : // int main( int argc, char *argv[] ){ // // Initialise l'infrastructure son de la librairie MLV. // MLV_init_audio( ); // // Charge en mémoire un fichier contenant un morceau de musique. // MLV_Music* music = MLV_load_music( "fugue.ogg" ); // // Joue la musique chargée en mémoire. // MLV_play_music( music, 1.0, -1 ); // // Attend 20 seconde avant la fin du programme. // MLV_wait_seconds( 20 ); // // Arrête toutes les musiques en cours d'exécution. // MLV_stop_music(); // // Ferme les morceaux de musiques qui ont été ouverts. // MLV_free_music( music ); // // Arrête l'infrastructure son de la librairie MLV. // MLV_free_audio(); return 0; } /* * This file is part of the MLV Library. * * Copyright (C) 2010,2011,2012,2013 Adrien Boussicault, Marc Zipstein * * * This Library is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This Library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this Library. If not, see <http://www.gnu.org/licenses/>. */
C
#include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <traildb.h> #include "tdb_test.h" static tdb *make_tdb(const char *root, const uint64_t *tstamps, uint32_t num, int should_fail) { static uint8_t uuid[16]; const char *fields[] = {}; tdb_cons* c = tdb_cons_init(); test_cons_settings(c); uint64_t zero = 0; uint32_t i; assert(tdb_cons_open(c, root, fields, 0) == 0); for (i = 0; i < num; i++) assert(tdb_cons_add(c, uuid, tstamps[i], fields, &zero) == 0); assert(tdb_cons_finalize(c) == (should_fail ? TDB_ERR_TIMESTAMP_TOO_LARGE: 0)); tdb_cons_close(c); if (!should_fail){ tdb* t = tdb_init(); assert(tdb_open(t, root) == 0); return t; }else return NULL; } int main(int argc, char** argv) { /* small min_timestamp, large max_timedelta, sorted */ const uint64_t TSTAMPS1[] = {1, 2, 3, UINT32_MAX, UINT32_MAX + 1LLU, TDB_MAX_TIMEDELTA - 10, TDB_MAX_TIMEDELTA - 9, TDB_MAX_TIMEDELTA - 8}; /* large min_timestamp, small max_timedelta, reverse order */ const uint64_t TSTAMPS2[] = {TDB_MAX_TIMEDELTA - 1, TDB_MAX_TIMEDELTA - 3, TDB_MAX_TIMEDELTA - 5}; /* this should not fail */ const uint64_t TSTAMPS3[] = {10, TDB_MAX_TIMEDELTA + 9}; /* this should fail */ const uint64_t TSTAMPS4[] = {10, TDB_MAX_TIMEDELTA + 11}; /* this should fail */ const uint64_t TSTAMPS5[] = {TDB_MAX_TIMEDELTA + 1}; const tdb_event *event; uint64_t i, num_events = sizeof(TSTAMPS1) / sizeof(TSTAMPS1[0]); tdb *db = make_tdb(getenv("TDB_TMP_DIR"), TSTAMPS1, num_events, 0); tdb_cursor *cursor = tdb_cursor_new(db); assert(tdb_get_trail(cursor, 0) == 0); for (i = 0; (event = tdb_cursor_next(cursor)); i++) assert(event->timestamp == TSTAMPS1[i]); assert(i == num_events); tdb_close(db); tdb_cursor_free(cursor); num_events = sizeof(TSTAMPS2) / sizeof(TSTAMPS2[0]); db = make_tdb(getenv("TDB_TMP_DIR"), TSTAMPS2, num_events, 0); cursor = tdb_cursor_new(db); assert(tdb_get_trail(cursor, 0) == 0); for (i = 1; (event = tdb_cursor_next(cursor)); i++) /* reverse order */ assert(event->timestamp == TSTAMPS2[num_events - i]); assert(i == num_events + 1); tdb_close(db); tdb_cursor_free(cursor); num_events = sizeof(TSTAMPS3) / sizeof(TSTAMPS3[0]); db = make_tdb(getenv("TDB_TMP_DIR"), TSTAMPS3, num_events, 0); cursor = tdb_cursor_new(db); assert(tdb_get_trail(cursor, 0) == 0); for (i = 0; (event = tdb_cursor_next(cursor)); i++) assert(event->timestamp == TSTAMPS3[i]); assert(i == num_events); tdb_close(db); tdb_cursor_free(cursor); make_tdb(getenv("TDB_TMP_DIR"), TSTAMPS4, sizeof(TSTAMPS4) / sizeof(TSTAMPS4[0]), 1); make_tdb(getenv("TDB_TMP_DIR"), TSTAMPS5, sizeof(TSTAMPS5) / sizeof(TSTAMPS5[0]), 1); return 0; }
C
/* You can produce input and output in more ways than with the scanf() and printf() functions. You can use these simple functions to build powerful data-entry routines of your own. Functions explained here are a little easier to use, and they provide some capabilities that scanf() and printf() dont offer. */ // PUTCHAR() AND GETCHAR() /* getchar() gets a single character from the keyboard. putchar() sends a single character to the screen. You can use them just about anytime you want to print or input a single character into a variable. // IMAGE LINK EXPLANATION https://learning.oreilly.com/library/view/c-programming-absolute/9780133149869/graphics/18fig01.jpg */ /* TIP: Always include the stdio.h header file when using this chapters I/O (Input/Output)functions, just as you do for printf() and scanf(). */ //------------------------------------------------------------------------------------------------------------------------ /* The following program prints C is fun, one character at a time, using putchar() to print each element of the character array in sequence. Notice that strlen() is used to ensure that the for doesnt output past the end of the string. */ // Example program #1 from Chapter 18 of Absolute Beginner's Guide // to C, 3rd Edition // File Chapter18ex1.c /* This program is nothing more than a simple demonstration of the putchar() function. */ // putchar() is defined in stdio.h, but string.h is needed for the // strlen() function #include <stdio.h> #include <string.h> main() { int i; char msg[] = "C is fun"; for (i = 0; i < strlen(msg); i++) { putchar(msg[i]); //Outputs a single character } putchar('\n'); // One line break after the loop is done. return(0); } /* The getchar() function returns the character input from the keyboard. Therefore, you usually assign the character to a variable or do something else with it. You can put getchar() on a line by itself, like this: getchar(); // Does nothing with the character you get However, most C compilers warn you that this statement is rather useless. The getchar() function would get a character from the keyboard, but then nothing would be done with the character. */
C
#include<stdio.h> int main() { int t,x,y,n; scanf("%d",&t); while(t) { t=t-1; scanf("%d%d",&x,&y); if(x==y) { if(x%2==0) n=2*x; else n=2*x-1; printf("%d\n",n); } else if(x==y+2) { if(x%2==0) n=x+y; else n=x+y-1; printf("%d\n",n); } else printf("No Number\n"); } return 0; }
C
void main(void) { int w; scanf("%d",&w); int day[]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int d=12+w,i; for(i=1;i<=12;i++) { d=d+day[i-1]; if(d%7==5) printf("%d\n",i); } }
C
#include <stdio.h> #include <stdlib.h> int main() { int i, n, dim, *dec; setlocale(0, "rus"); printf("Введите размер массива: "); scanf("%d", &n); printf("Введите диапазон случайных чисел: "); scanf("%i", &dim); srand(time(0)); dec = malloc(n * sizeof(int)); printf("Сгенерированный массив:\n"); for (i = 0; i < n; i++) { dec[i] = rand() % dim; printf("%d ", dec[i]); } putchar('\n'); int k = 0; while (dim) { dim=dim/2; k++; } // printf("%i", k); char * mass; mass = malloc(n*k*sizeof(char)); int a = 0; for (int i = 0; i < n; i++) { for (int j = k*(i+1)-1; j >= k*i ; j--) { a = dec[i]%2; dec[i] = dec[i] / 2; mass[j] = a ==1 ? '1' : '0'; } } for (int i = 0; i < n*k; i++) { if (i%k == 0 && i !=0) printf(" "); printf("%c",mass[i]); } free(dec); system("pause"); return 0; }
C
#include <stdlib.h> #include <assert.h> struct list_elem { size_t size; int free; struct list_elem *prev; struct list_elem *next; }; struct list { struct list_elem head; struct list_elem tail; }; void list_init (struct list *list); void list_insert (struct list_elem *before, struct list_elem *elem); void list_push_back (struct list *list, struct list_elem *elem); struct list_elem * list_remove (struct list_elem *elem);
C
int hash(char s[]) { char *p; int h = 0; for(p = s;*p;p++) { h = h*3 + *p; } return h; }
C
/* 15: 鿴 ύ ͳ ʱ: 1000ms ڴ: 65536kB , ΪһУ֮һոֿ һУһ 10 20 56 56 */ #include <stdio.h> int main() { int a,b,c,v; scanf("%d %d %d",&a,&b,&c); v=a>b?a:b; if (v<c) v=c; printf ("%d",v); return 0; }
C
#include<stdio.h> struct da { int max[10],a1[10],need[10],before[10],after[10]; }p[10]; void main() { int i,j,k,l,r,n,tot[10],av[10],cn=0,cz=0,temp=0,c=0; printf("\nENTER THE NO. OF PROCESSES: "); scanf("%d",&n); printf("ENTER THE NO. OF RESOURCES: "); scanf("%d",&r); for(i=0;i<n;i++) { printf("PROCESS %d \n",i+1); for(j=0;j<r;j++) { printf("MAXIMUM VALUE FOR RESOURCE %d: ",j+1); scanf("%d",&p[i].max[j]); } for(j=0;j<r;j++) { printf("ALLOCATED FROM RESOURCE %d: ",j+1); scanf("%d",&p[i].a1[j]); p[i].need[j]=p[i].max[j]-p[i].a1[j]; } } for(i=0;i<r;i++) { printf("ENTER TOTAL VALUE OF RESOURCE %d: ",i+1); scanf("%d",&tot[i]); } for(i=0;i<r;i++) { for(j=0;j<n;j++) temp=temp+p[j].a1[i]; av[i]=tot[i]-temp; temp=0; } printf("\nRESOURCES ALLOCATED NEEDED TOTAL AVAIL "); for(i=0;i<n;i++) { printf("\n P%d \t",i+1); for(j=0;j<r;j++) printf("%d",p[i].max[j]); printf("\t"); for(j=0;j<r;j++) printf("%d",p[i].a1[j]); printf("\t"); for(j=0;j<r;j++) printf("%d",p[i].need[j]); printf("\t"); for(j=0;j<r;j++) { if(i==0) printf("%d",tot[j]); } printf(" "); for(j=0;j<r;j++) { if(i==0) printf("%d",av[j]); } } printf("\n\nAVAIL BEFORE\t AVAIL AFTER "); for(l=0;l<n;l++) { for(i=0;i<n;i++) { for(j=0;j<r;j++) { if(p[i].need[j] >av[j]) cn++; if(p[i].max[j]==0) cz++; } if(cn==0 && cz!=r) { for(j=0;j<r;j++) { p[i].before[j]=av[j]-p[i].need[j]; p[i].after[j]=p[i].before[j]+p[i].max[j]; av[j]=p[i].after[j]; p[i].max[j]=0; } printf("\n P %d \t",i+1); for(j=0;j<r;j++) printf("%d",p[i].before[j]); printf("\t"); for(j=0;j<r;j++) printf("%d",p[i].after[j]); cn=0; cz=0; c++; break; } else { cn=0;cz=0; }}} if(c==n) printf("\nTHE ABOVE SEQUENCE IS A SAFE SEQUENCE\n"); else printf("\nDEADLOCK OCCURED\n"); }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: AaronHenry * * Created on April 30, 2017, 4:52 PM */ #include <stdio.h> #include <stdlib.h> struct character{ char* name; int level; int health; int placeInTree; }; struct node{ struct character person; char color; struct node *child[2]; }node; struct node *root = NULL; struct node * createNode(char* name) { struct node *newnode; newnode = (struct node *)malloc(sizeof(struct node)); newnode->person.name = name; newnode->person.level = 5; newnode->person.health = 100; newnode->color = 'R'; newnode->child[0] = newnode->child[1] = NULL; /* link[0] - Left Child; link[1] - Right Child */ return newnode; } void case3(struct node* move,struct node* list[], int k, struct node* yPtr, int dir[]){ move = list[k - 2]; yPtr->color = 'B'; move->color = 'R'; move->child[1] = yPtr->child[0]; yPtr->child[0] = move; if (move == root) { root = yPtr; } else { list[k - 3]->child[dir[k - 3]] = yPtr; } } void case2(struct node* move,struct node* list[], int k, struct node* yPtr){ move = list[k - 1]; yPtr = move->child[1]; move->child[1] = yPtr->child[0]; yPtr->child[0] = move; list[k - 2]->child[0] = yPtr; } void case1(struct node* list[], int k, struct node* yPtr){ list[k - 2]->color = 'R'; list[k - 1]->color = yPtr->color = 'B'; k = k -2; } void insertion (struct character person) { struct node *list[98], *hold, *newnode, *move, *ptr; int dir[98], k = 0, index; hold = root; //set root if (!root) { root = createNode(person.name); root->color = 'B'; return; } list[k] = root; dir[k++] = 0; while (hold != NULL) { if (hold->person.name == person.name) { printf("you have multiple %s's thats not allowed\n",person.name); return; } index = ((int)person.name - (int)hold->person.name) > 0 ? 1 : 0; list[k] = hold; hold = hold->child[index]; dir[k++] = index; } list[k - 1]->child[index] = newnode = createNode(person.name); while ((k >= 3) && (list[k - 1]->color == 'R')) { if (dir[k - 2] == 0) { ptr = list[k - 2]->child[1]; if (ptr != NULL && ptr->color == 'R') { case1(list,k,ptr); } else { if (dir[k - 1] == 0) { ptr = list[k - 1]; } else { case2(move, list, k, ptr); } case3(move, list, k, ptr, dir); break; } } else { ptr = list[k - 2]->child[0]; if ((ptr != NULL) && (ptr->color == 'R')) { case1(list,k,ptr); } else { if (dir[k - 1] == 1) { ptr = list[k - 1]; } else { case2(move, list, k, ptr); } case3(move, list, k, ptr, dir); break; } } } root->color = 'B'; } void print(struct node* head, int level) { if (head == NULL) return; if (level == 1) printf("%s-%c: Health: %d, Level: %d\n ", head->person.name, head->color, head->person.health,head->person.level); else if (level > 1) { print(head->child[0], level-1); print(head->child[1], level-1); } } void printLevelOrder(struct node* head) { int i; for (i=1; i<=8; i++) { print(head, i); } } /* * */ struct character winOrLose(int outcome, struct node* currentBoss){ if(outcome == 1){ return currentBoss->child[1]; }else if(outcome == 0){ return currentBoss->child[0]; } } int main(int argc, char** argv) { int numOfPeople=1; printf("# of ppl: "); scanf("%d", &numOfPeople); int i=0; char* name;// = malloc(sizeof(char*)); struct character person; for(i = 0; i<numOfPeople;i++){ name = malloc(sizeof(char*)); printf("Name: "); scanf("%s", name); person.name = name; person.level = (int)name; insertion(person); free(name); } struct character person1; struct character person2; person1.name = "aaron"; person1.level = (int) "aaron"; person2.name = "Bob"; person2.level = (int) "Bob"; insertion(person1); insertion(person2); printLevelOrder(root); return (EXIT_SUCCESS); }
C
/* $Id: xutf8.h,v 1.1 2015/06/15 04:50:41 gremlin Exp $ */ #ifndef XUTF8_H_ #define XUTF8_H_ #include "xstr.h" #ifdef __cplusplus extern "C" { #endif /* Return number of byte the unicode code point occupied. * Return 0 if the string is not encoded as valid utf8. */ size_t xutf8_cstr_to_code(const char *s, int *pcode); size_t xutf8_xstr_to_code(const xstr_t *xs, int *pcode); /* Return number of byte writen to the buf. * Return 0 if the code is not a valid unicode code point. */ size_t xutf8_cstr_from_code(char *buf, int code); /* Return number of unicode code point in the utf8 string. */ size_t xutf8_cstr_count(const char *s, char **end/*NULL*/); size_t xutf8_xstr_count(const xstr_t *s, xstr_t *end/*NULL*/); #ifdef __cplusplus } #endif #endif
C
#include "core/pt.h" /* * Return the distance in tiles between two ships. * This will mostly be used in hit chance calculations. */ int calc_dist (const struct pt thisCoord, const struct pt otherCoord) { int x = thisCoord.x - otherCoord.x; int y = thisCoord.y - otherCoord.y; if(x < 0) x = -x; if(y < 0) y = -y; return x + y; }
C
10 /* Nonzero -- yields a true result */ !10 /* Yields a false (logically opposite) result */ int a = 10, b = 5, c = 0; a && b /* True -- both are nonzero */ a && c /* False -- one operand is zero */ a || c /* True -- one operand is nonzero */ int a = 10, b = 5; int i = 2, j = 9; a > b && i < j /* True */ a < b || i > j /* False */ (a > b || i > j) && a < i /* False */ a > b || i > j && a < i /* True */ int x = 8000; char zed = 'z'; int avg = (3 + 11 + 21 + 66)/2; int diff = a - b;
C
/* * procExit.c -- * * Routines to terminate and detach processes, and to cause a * process to wait for the termination of other processes. This file * maintains a monitor to synchronize between exiting, detaching, and * waiting processes. The monitor also synchronizes access to the * dead list. * * Copyright 1986, 1988, 1991 Regents of the University of California * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appear in all copies. The University of California * makes no representations about the suitability of this * software for any purpose. It is provided "as is" without * express or implied warranty. * * Proc table fields managed by this monitor: * * 1) exitFlags is managed solely by this monitor. * 2) When a process is about to exit the PROC_DYING flag is set * in the genFlags field. * 3) The only way a process can go to the exiting and dead states * is through using routines in this file. * * To avoid deadlock, obtain the monitor lock before locking a pcb. * * A process can be in one of several states: * * PROC_READY: It is ready to execute, at least as far as * Sprite is concerned. Whether it is actually * running is up to the kernel. * PROC_WAITING: It is waiting for an event to occur. * PROC_EXITING: It has finished executing but the PCB is kept around * until the parent waits for it via Proc_Wait or dies * via Proc_Exit. * PROC_DEAD: It has been waited on and the PCB is attached to * the Dead list. * PROC_SUSPENDED It is suspended from executing. * PROC_UNUSED: There is no process using this PCB entry. * * In addition, the process may have the following attributes: * * PROC_DETACHED: It is detached from its parent. * PROC_WAITED_ON: It is detached from its parent and its parent * knows about it. This attribute implies PROC_DETACHED * has been set. * PROC_SUSPEND_STATUS: * It is suspended and its parent has not waited on it * yet. In this case it isn't detached. * PROC_RESUME_STATUS: * It has been resumed and its parent has not waited on * it yet. In this case it isn't detached. * * These attributes are set independently of the process states. * * The routines in this file deal with transitions from the * RUNNING state to the EXITING and DEAD states and methods to * detach a process. * * State and Attribute Transitions: * The following tables show how a process changes attributes and states. * * * Legend: * ATTRIBUTE1 -> ATTRIBUTE2: * --------------------------------------------------------------------- * who "routine it called to change attribute" comments * * * * Attached -> Detached * --------------------------------------------------------------------- * current process Proc_Detach * * Detached -> Detached and Waited on * --------------------------------------------------------------------- * parent Proc_Wait WAITED_ON attribute set when * parent finds child is detached. * * Attached or Detached -> Detached and Waited on * --------------------------------------------------------------------- * parent Proc_ExitInt parent exiting, child detached. * * * * * Legend: * STATE1 -> STATE2: (attributes before transition) * --------------------------------------------------------------------- * who "routine it called to change state" comments * * * RUNNING -> EXITING: (attached or detached but not waited on) * RUNNING -> DEAD: (detached and waited on) * --------------------------------------------------------------------- * current process Proc_Exit normal termination. * kernel Proc_ExitInt invalid process state found or * process got a signal * * EXITING -> DEAD: (attached or detached or detached and waited on) * --------------------------------------------------------------------- * last family member to exit Proc_ExitInt * parent Proc_Wait parent waiting for child to exit * parent Proc_ExitInt parent exiting but did not * wait on child. * * DEAD -> UNUSED: * --------------------------------------------------------------------- * The Reaper Proc_Reaper kernel process to clean the * dead list. */ #ifndef lint static char rcsid[] = "$Header: /user5/kupfer/spriteserver/src/sprited/proc/RCS/procExit.c,v 1.19 92/07/16 18:06:50 kupfer Exp $ SPRITE (Berkeley)"; #endif /* not lint */ #include <sprite.h> #include <ckalloc.h> #include <mach.h> #include <mach_error.h> #include <spriteTime.h> #include <status.h> #include <user/sig.h> #include <proc.h> #include <procInt.h> #include <sig.h> #include <spriteSrvServer.h> #include <sync.h> #include <sys.h> #include <timerTick.h> #include <utils.h> #include <vm.h> #include <user/vmStat.h> #define min(a,b) ((a) < (b) ? (a) : (b)) static Sync_Lock exitLock = Sync_LockInitStatic("Proc:exitLock"); #define LOCKPTR &exitLock /* * When a process is put into the PROC_DEAD state, it is put on a linked * list, so that the pcb can be reused. This reclamation can only happen * at certain times to avoid races between process destruction and process * requests. */ static List_Links deadProcessListHdr; #define deadProcessList (&deadProcessListHdr) /* * Shared memory. */ extern int vmShmDebug; #ifndef lint #define dprintf if (vmShmDebug) printf #else /* lint */ #define dprintf printf #endif /* lint */ /* Forward references: */ static ReturnStatus CheckPidArray _ARGS_((Proc_ControlBlock *curProcPtr, Boolean returnSuspend, int numPids, Proc_PID *pidArray, Proc_LockedPCB **procPtrPtr)); static void UpdateChildCpuUsage _ARGS_(( Proc_ControlBlock *parentProcPtr, Proc_ControlBlock *exitProcPtr)); extern ReturnStatus DoWait _ARGS_((Proc_ControlBlock *curProcPtr, int flags, int numPids, Proc_PID *newPidArray, ProcChildInfo *childInfoPtr)); static Proc_State ExitProcessInt _ARGS_(( Proc_ControlBlock *exitProcPtr, Boolean migrated, Boolean contextSwitch)); static ReturnStatus FindExitingChild _ARGS_(( Proc_ControlBlock *parentProcPtr, Boolean returnSuspend, int numPids, Proc_PID *pidArray, ProcChildInfo *infoPtr)); static ReturnStatus LookForAnyChild _ARGS_((Proc_ControlBlock *curProcPtr, Boolean returnSuspend, Proc_LockedPCB **procPtrPtr)); static void ProcPutOnDeadList _ARGS_((Proc_ControlBlock *procPtr)); static void SendSigChild _ARGS_((ClientData data, Proc_CallInfo *callInfoPtr)); static void WakeupMigratedParent _ARGS_((Proc_PID pid)); /* *---------------------------------------------------------------------- * * ProcExitInit -- * * Initialization for this monitor. * * Results: * None. * * Side effects: * Initializes the list of dead processes. * *---------------------------------------------------------------------- */ void ProcExitInit() { List_Init(deadProcessList); } /* *---------------------------------------------------------------------- * * Proc_RawExitStub -- * * MIG stub for when a user process has decided it wants to be an * ex-process. * * Results: * Returns MIG_NO_REPLY, so that no reply message is sent to the * client process. * * Side effects: * Sets the PROC_NO_MORE_REQUESTS flag for the process, so that the * process will exit when all the RPC bookkeeping is done. * *---------------------------------------------------------------------- */ kern_return_t Proc_RawExitStub(serverPort, status) mach_port_t serverPort; /* system request port */ int status; /* UNIX exit status code */ { Proc_ControlBlock *procPtr = Proc_GetCurrentProc(); kern_return_t kernStatus; #ifdef lint serverPort = serverPort; #endif Proc_Lock(procPtr); /* * Freeze the thread, so that it can't run after its reply message is * destroyed. */ kernStatus = thread_suspend(procPtr->thread); if (kernStatus != KERN_SUCCESS) { printf("Proc_RawExitStub: can't suspend thread for pid %x: %s.\n", procPtr->processID, mach_error_string(kernStatus)); } procPtr->genFlags |= PROC_NO_MORE_REQUESTS; procPtr->termReason = PROC_TERM_EXITED; procPtr->termStatus = status; procPtr->termCode = 0; Proc_Unlock(Proc_AssertLocked(procPtr)); return MIG_NO_REPLY; } /* *---------------------------------------------------------------------- * * Proc_Exit -- * * The current process has decided to end it all voluntarily. * Call an internal procedure to do the work. * * Results: * None. This routine should NOT return! * * Side effects: * None. * *---------------------------------------------------------------------- */ void Proc_Exit(status) int status; /* Exit status from caller. */ { Proc_ExitInt(PROC_TERM_EXITED, status, 0); /* * Proc_ExitInt should never return. */ } /* *---------------------------------------------------------------------- * * Proc_ExitInt -- * * Internal routine to handle the termination of a process. It * determines the process that is exiting and then calls * ProcExitProcess to do the work. This routine does not return. * If the process is foreign, ProcRemoteExit is called to handle * cleanup on the home node of the process, then ProcExitProcess * is called. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void Proc_ExitInt(reason, status, code) int reason; /* Why the process is dying: EXITED, SIGNALED, DESTROYED */ int status; /* Exit status or signal # or destroy status */ int code; /* Signal sub-status */ { register Proc_ControlBlock *curProcPtr; curProcPtr = Proc_GetActualProc(); if (curProcPtr == (Proc_ControlBlock *) NIL) { panic("Proc_ExitInt: bad procPtr.\n"); } #ifdef SPRITED_MIGRATION if (curProcPtr->genFlags & PROC_FOREIGN) { ProcRemoteExit(curProcPtr, reason, status, code); } #endif #ifdef SPRITED_PROFILING if (curProcPtr->Prof_Scale != 0) { Prof_Disable(curProcPtr); } #endif if (curProcPtr->genFlags & PROC_DEBUGGED) { /* * If a process is being debugged then force it onto the debug * list before allowing it to exit. Note that Proc_SuspendProcess * will unlock the PCB. */ Proc_Lock(curProcPtr); Proc_SuspendProcess(Proc_AssertLocked(curProcPtr), TRUE, reason, status, code); } if (sys_ErrorShutdown) { /* * Are shutting down the system because of an error. In this case * don't close anything down because we want to leave as much state * around as possible. */ Proc_ContextSwitch(PROC_DEAD); } ProcExitProcess(curProcPtr, reason, status, code, TRUE); panic("Proc_ExitInt: Exiting process still alive!!!\n"); } /* *---------------------------------------------------------------------- * * ExitProcessInt -- * * Do monitor level exit stuff for the process. * * Results: * None. * * Side effects: * The process is locked. If it doesn't context switch, it is left * locked. * *---------------------------------------------------------------------- */ ENTRY static Proc_State ExitProcessInt(exitProcPtr, foreign, contextSwitch) register Proc_ControlBlock *exitProcPtr; /* The exiting process. */ Boolean foreign; /* TRUE => foreign process. */ Boolean contextSwitch; /* TRUE => context switch. */ { register Proc_ControlBlock *procPtr; Proc_State newState = PROC_UNUSED; register Proc_PCBLink *procLinkPtr; #if !defined(CLEAN) && defined(SPRITED_MIGRATION) Timer_Ticks ticks; #endif LOCK_MONITOR; Proc_Lock(exitProcPtr); exitProcPtr->genFlags |= PROC_DYING; #ifdef SPRITED_MIGRATION if (exitProcPtr->genFlags & PROC_MIG_PENDING) { /* * Someone is waiting for this guy to migrate. Let them know that * the process is dying. */ exitProcPtr->genFlags &= ~PROC_MIG_PENDING; ProcMigWakeupWaiters(); } #endif /* * If the parent is still around, add the user and kernel cpu usage * of this process to the parent's summary of children. * If we're detached, don't give this stuff to the parent * (it might not exist.) Keep track of global usage if we're local. */ if (!(exitProcPtr->genFlags & PROC_FOREIGN)) { if (!(exitProcPtr->exitFlags & PROC_DETACHED)) { register Proc_ControlBlock *parentProcPtr; parentProcPtr = Proc_GetPCB(exitProcPtr->parentID); if (parentProcPtr != (Proc_ControlBlock *) NIL) { UpdateChildCpuUsage(parentProcPtr, exitProcPtr); } } #if !defined(CLEAN) && defined(SPRITED_MIGRATION) Timer_AddTicks(exitProcPtr->kernelCpuUsage.ticks, exitProcPtr->userCpuUsage.ticks, &ticks); ProcRecordUsage(ticks, PROC_MIG_USAGE_TOTAL_CPU); /* * Record usage for just the amount of work performed after the * first eviction. */ if (exitProcPtr->migFlags & PROC_WAS_EVICTED) { if (proc_MigDebugLevel > 4) { printf("ExitProcessInt: process %x was evicted. Used %d ticks before eviction, %d total.\n", exitProcPtr->processID, exitProcPtr->preEvictionUsage.ticks, ticks); } Timer_SubtractTicks(ticks, exitProcPtr->preEvictionUsage.ticks, &ticks); ProcRecordUsage(ticks, PROC_MIG_USAGE_POST_EVICTION); exitProcPtr->migFlags &= ~PROC_WAS_EVICTED; } #endif /* !CLEAN && SPRITED_MIGRATION */ } /* * Make sure there are no lingering interval timer callbacks associated * with this process. * * Go through the list of children of the current process to * make them orphans. When the children exit, this will typically * cause them to go on the dead list directly. */ if (!foreign) { ProcDeleteTimers(Proc_AssertLocked(exitProcPtr)); while (!List_IsEmpty(exitProcPtr->childList)) { procLinkPtr = (Proc_PCBLink *)List_First(exitProcPtr->childList); procPtr = procLinkPtr->procPtr; List_Remove((List_Links *) procLinkPtr); if (procPtr->state == PROC_EXITING) { /* * The child is exiting waiting for us to wait for it. */ ProcPutOnDeadList(procPtr); } else { /* * Detach the child so when it exits, it will be * put on the dead list automatically. */ procPtr->exitFlags = PROC_DETACHED | PROC_WAITED_ON; } } } /* * If the debugger is waiting for this process to return to the debug * state wake it up so that it will realize that the process is dead. */ if (exitProcPtr->genFlags & PROC_DEBUG_WAIT) { ProcDebugWakeup(); } #ifdef SPRITED_MIGRATION /* * If the process is still waiting on an event, this is an error. * [For now, flag this error only for foreign processes in case this * isn't really an error after all.] */ if (foreign && (exitProcPtr->currCondPtr != NULL)) { if (proc_MigDebugLevel > 0) { panic( "ExitProcessInt: process still waiting on condition.\n"); } else { printf( "Warning: ExitProcessInt: process still waiting on condition.\n"); } } #endif /* SPRITED_MIGRATION */ /* * If the current process is detached and waited on (i.e. an orphan) then * one of two things happen. If the process is a family head and its list * of family members is not empty then the process is put onto the exiting * list. Otherwise the process is put onto the dead list since its * parent has already waited for it. */ if (((exitProcPtr->exitFlags & PROC_DETACHED) && (exitProcPtr->exitFlags & PROC_WAITED_ON)) || foreign) { ProcPutOnDeadList(exitProcPtr); newState = PROC_DEAD; } else { Proc_ControlBlock *parentProcPtr; #ifdef DEBUG_PARENT_PID int hostID; hostID = Proc_GetHostID(exitProcPtr->parentID); if (hostID != rpc_SpriteID && hostID != 0) { panic("ExitProcessInt: parent process (%x) is on wrong host.\n", exitProcPtr->parentID); goto done; } #endif DEBUG_PARENT_PID parentProcPtr = Proc_GetPCB(exitProcPtr->parentID); if (parentProcPtr == (Proc_ControlBlock *) NIL) { panic("ExitProcessInt: no parent process (pid == %x)\n", exitProcPtr->parentID); goto done; } if (parentProcPtr->state != PROC_MIGRATED) { Sync_Broadcast(&parentProcPtr->waitCondition); } else { WakeupMigratedParent(parentProcPtr->processID); } /* * Signal the parent later on, when not holding the exit monitor * lock. */ Proc_CallFunc(SendSigChild, (ClientData)exitProcPtr->parentID, time_ZeroSeconds); newState = PROC_EXITING; } done: if (contextSwitch) { Proc_Unlock(Proc_AssertLocked(exitProcPtr)); UNLOCK_MONITOR_AND_SWITCH(newState); panic("ExitProcessInt: Exiting process still alive\n"); } else { UNLOCK_MONITOR; } return(newState); } /* *---------------------------------------------------------------------- * * ProcExitProcess -- * * Internal routine to handle the termination of a process, due * to a normal exit, a signal or because the process state was * inconsistent. The file system state associated with the process * is invalidated. Any children of the process will become detatched. * * Warning: this function should be called only once for a given * process. * * Results: * None. * * Side effects: * The PCB entry for the process is modified to clean-up FS * state. The specified process may be placed on the dead list. * If thisProcess is TRUE, a context switch is performed. If not, * then the exit is being performed on behalf of another process. * *---------------------------------------------------------------------- */ void ProcExitProcess(exitProcPtr, reason, status, code, thisProcess) register Proc_ControlBlock *exitProcPtr; /* Exiting process; should * be locked if not the * current process */ int reason; /* Why the process is dieing: * EXITED, SIGNALED, * DESTROYED */ int status; /* Exit status, signal # or * destroy status. */ int code; /* Signal sub-status */ Boolean thisProcess; /* TRUE => context switch */ { register Boolean foreign; int currHeapPages; /* num. of mapped heap pages */ int currStackPages; foreign = (exitProcPtr->genFlags & PROC_FOREIGN); /* * Decrement the reference count on the environment. */ if (!foreign && exitProcPtr->environPtr != (Proc_EnvironInfo *) NIL) { ProcDecEnvironRefCount(exitProcPtr->environPtr); } /* * If the process is being killed off by another process, it should * already be locked. Also, it shouldn't be in the middle of a * request, since we can't synchronize with the thread handling the * request inside the server. */ if (thisProcess) { Proc_Lock(exitProcPtr); } else { if (!(exitProcPtr->genFlags & PROC_LOCKED)) { panic("ProcExitProcess: process isn't locked.\n"); } if (exitProcPtr->genFlags & PROC_BEING_SERVED) { panic("ProcExitProcess: active process is being killed.\n"); } } /* * If the process was already marked with PROC_NO_MORE_REQUESTS, then * the code that set the flag should have also filled in the * termination information. (XXX Ugly.) * This is so that a user process can be marked as "about to exit" * (e.g., Proc_Kill, Proc_RawExitStub), clean up from a current request * (e.g., free request buffers), and then exit while getting the exit * status codes right. */ if (exitProcPtr->genFlags & PROC_NO_MORE_REQUESTS) { /* sanity check */ if (exitProcPtr->termReason < PROC_TERM_EXITED || exitProcPtr->termReason > PROC_TERM_DESTROYED) { panic("ProcExitProcess: bogus termination reason.\n"); } } else { exitProcPtr->genFlags |= PROC_NO_MORE_REQUESTS; exitProcPtr->termReason = reason; exitProcPtr->termStatus = status; exitProcPtr->termCode = code; } /* * Some instrumentation. Figure out how many pages had to get faulted * back in again because the heap and stack segments were destroyed and * then recreated when the process last did an exec. For each segment, * this is the smaller of {the current number of pages, the number of * pages at exec time}. */ if (exitProcPtr->taskInfoPtr != NULL) { currHeapPages = (exitProcPtr->taskInfoPtr->vmInfo.heapInfoPtr == NULL ? 0 : Vm_ByteToPage(exitProcPtr->taskInfoPtr-> vmInfo.heapInfoPtr->length)); currStackPages = (exitProcPtr->taskInfoPtr->vmInfo.stackInfoPtr == NULL ? 0 : Vm_ByteToPage(exitProcPtr->taskInfoPtr-> vmInfo.stackInfoPtr->length)); vmStat.swapPagesWasted += min(currHeapPages, exitProcPtr->taskInfoPtr-> vmInfo.execHeapPages); vmStat.swapPagesWasted += min(currStackPages, exitProcPtr->taskInfoPtr-> vmInfo.execStackPages); } if (exitProcPtr->genFlags & PROC_USER) { ProcFreeTaskThread(Proc_AssertLocked(exitProcPtr)); } /* * Native Sprite had to do the Fs_CloseState in two phases. * Because in the Sprite server the VM code is divorced from * specific processes, we can do it in one shot. */ if (exitProcPtr->fsPtr != (struct Fs_ProcessState *) NIL) { Fs_CloseState(Proc_AssertLocked(exitProcPtr),0); Fs_CloseState(Proc_AssertLocked(exitProcPtr),1); } Proc_Unlock(Proc_AssertLocked(exitProcPtr)); /* * Remove the process from its process family. (Note that migrated * processes have family information on the home node.) */ if (!foreign) { ProcFamilyRemove(exitProcPtr); } Proc_SetState(exitProcPtr, ExitProcessInt(exitProcPtr, foreign, thisProcess)); } /* *---------------------------------------------------------------------- * * Proc_Reaper -- * * Cleans up the state information kept in the PCB for dead processes. * Processes get put on the dead list after they exit and someone has * called Proc_Wait to wait for them. Detached processes * are put on the dead list when they call Proc_Exit or Proc_ExitInt. * * Results: * None. * * Side effects: * Virtual memory and Mach state for processes on the list is * deallocated. The PCB is marked as unused. * *---------------------------------------------------------------------- */ ENTRY void Proc_Reaper() { Proc_ControlBlock *procPtr; /* a dead process */ List_Links *itemPtr; LOCK_MONITOR; LIST_FORALL(deadProcessList, itemPtr) { List_Remove(itemPtr); procPtr = ((Proc_PCBLink *)itemPtr)->procPtr; Proc_Lock(procPtr); if (procPtr->genFlags & PROC_USER && procPtr->taskInfoPtr != NULL) { panic("Proc_Reaper: process wasn't cleaned up properly.\n"); } ProcFreePCB(Proc_AssertLocked(procPtr)); } UNLOCK_MONITOR; } /* *---------------------------------------------------------------------- * * Proc_DetachInt -- * * The given process is detached from its parent. * * Results: * SUCCESS - always returned. * * Side effects: * PROC_DETACHED flags set in the exitFlags field for the process. * *---------------------------------------------------------------------- */ ENTRY void Proc_DetachInt(procPtr) register Proc_ControlBlock *procPtr; { Proc_ControlBlock *parentProcPtr; LOCK_MONITOR; /* * If the process is already detached, there's no point to do it again. * The process became detached by calling this routine or its parent * has died. */ if (procPtr->exitFlags & PROC_DETACHED) { UNLOCK_MONITOR; return; } procPtr->exitFlags |= PROC_DETACHED; /* * Wake up the parent in case it has called Proc_Wait to * wait for this child (or any other children) to terminate. */ parentProcPtr = Proc_GetPCB(procPtr->parentID); if (parentProcPtr->state == PROC_MIGRATED) { WakeupMigratedParent(parentProcPtr->processID); } else { Sync_Broadcast(&parentProcPtr->waitCondition); } /* * Signal the parent later on, when not holding the exit monitor * lock. */ Proc_CallFunc(SendSigChild, (ClientData)parentProcPtr->processID, time_ZeroSeconds); UNLOCK_MONITOR; } /* *---------------------------------------------------------------------- * * Proc_InformParent -- * * Tell the parent of the given process that the process has changed * state. * * Results: * None. * * Side effects: * Status bit set in the exit flags. * *---------------------------------------------------------------------- */ ENTRY void Proc_InformParent(procPtr, childStatus) register Proc_LockedPCB *procPtr; /* Process whose parent to * inform of state change. */ int childStatus; /* PROC_SUSPEND_STATUS | * PROC_RESUME_STATUS */ { Proc_ControlBlock *parentProcPtr; Boolean foreign = FALSE; LOCK_MONITOR; /* * If the process is already detached, then there is no parent to tell. */ if (procPtr->pcb.exitFlags & PROC_DETACHED) { UNLOCK_MONITOR; return; } /* * Wake up the parent in case it has called Proc_Wait to * wait for this child (or any other children) to terminate. Also * clear the suspended and waited on flag. * * For a foreign process, just send a signal no matter what, since it * can go to an arbitrary node. Also, do RPC's using a callback so * the monitor lock isn't held during the RPC. */ if (procPtr->pcb.genFlags & PROC_FOREIGN) { foreign = TRUE; } if (!foreign) { parentProcPtr = Proc_GetPCB(procPtr->pcb.parentID); Sync_Broadcast(&parentProcPtr->waitCondition); } Proc_CallFunc(SendSigChild, (ClientData)procPtr->pcb.parentID, time_ZeroSeconds); procPtr->pcb.exitFlags &= ~PROC_STATUSES; procPtr->pcb.exitFlags |= childStatus; UNLOCK_MONITOR; } /* *---------------------------------------------------------------------- * * SendSigChild -- * * Send a SIG_CHILD signal to the given process. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ /* ARGSUSED */ static void SendSigChild(data, callInfoPtr) ClientData data; Proc_CallInfo *callInfoPtr; /* passed in by callback routine */ { (void)Sig_Send(SIG_CHILD, SIG_NO_CODE, (Proc_PID)data, FALSE, (Address)0); } /* *---------------------------------------------------------------------- * * Proc_Detach -- * * The current process is detached from its parent. Proc_DetachInt called * to do most work. * * Results: * SUCCESS - always returned. * * Side effects: * Statuses set in the proc table for the process. * *---------------------------------------------------------------------- */ ReturnStatus Proc_Detach(status) int status; /* Detach status from caller. */ { register Proc_ControlBlock *procPtr; procPtr = Proc_GetEffectiveProc(); if (procPtr == (Proc_ControlBlock *) NIL) { panic("Proc_Detach: procPtr == NIL\n"); } /* * The following information is kept in case the parent does a * Proc_Wait on this process. */ Proc_Lock(procPtr); procPtr->termReason = PROC_TERM_DETACHED; procPtr->termStatus = status; procPtr->termCode = 0; Proc_Unlock(Proc_AssertLocked(procPtr)); Proc_DetachInt(procPtr); return(SUCCESS); } /* *---------------------------------------------------------------------- * * Proc_WaitStub -- * * MIG interface to Proc_Wait. * * Results: * Returns KERN_SUCCESS. Fills in the Sprite status code * from Proc_Wait and the "pending signals" flag. * * Side effects: * See Proc_Wait. * *---------------------------------------------------------------------- */ kern_return_t Proc_WaitStub(serverPort, numPids, pidArray, flags, procIDPtr, reasonPtr, procStatusPtr, subStatusPtr, usageAddr, statusPtr, sigPendingPtr) mach_port_t serverPort; /* server request port */ int numPids; /* number of pids in pidArray */ vm_address_t pidArray; /* array of pids to look at (maybe nil) */ int flags; Proc_PID *procIDPtr; /* OUT: pid for the child that changed state */ int *reasonPtr; /* OUT: reason for state change */ int *procStatusPtr; /* OUT: status code for state change (e.g., * Unix exit status) */ int *subStatusPtr; /* OUT: substatus code for state change */ vm_address_t usageAddr; /* OUT: resource usage info for child * (maybe nil, if info isn't desired) */ ReturnStatus *statusPtr; /* OUT: Sprite status code for the call * (SUCCESS, etc.) */ boolean_t *sigPendingPtr; /* OUT: is there a signal pending */ { #ifdef lint serverPort = serverPort; #endif *statusPtr = Proc_Wait(numPids, (Proc_PID *)pidArray, flags, procIDPtr, reasonPtr, procStatusPtr, subStatusPtr, (Proc_ResUsage *)usageAddr); *sigPendingPtr = Sig_Pending(Proc_GetCurrentProc()); return KERN_SUCCESS; } /* *---------------------------------------------------------------------- * * Proc_Wait -- * * Returns information about a child process that has changed state to * one of terminated, detached, suspended or running. If the * PROC_WAIT_FOR_SUSPEND flag is not set then info is only returned about * terminated and detached processes. If the PROC_WAIT_BLOCK flag is * set then this function will wait for a child process to change state. * * A terminated process is a process that has ceased execution because * it voluntarily called Proc_Exit or was involuntarily killed by * a signal or was destroyed by the kernel for some reason. * A detached process is process that has called Proc_Detach to detach * itself from its parent. It continues to execute until it terminates. * * Results: * PROC_INVALID_PID - a process ID in the pidArray was invalid. * SYS_INVALID_ARG - the numPids argument specified a negative * number of pids in pidArray, or numPids * valid but pidArray was USER_NIL * SYS_ARG_NOACCESS - an out parameter was inaccessible or * pidArray was inaccessible. * * Side effects: * Processes may be put onto the dead list after they have been waited on. * *---------------------------------------------------------------------- */ ReturnStatus Proc_Wait(numPids, pidArray, flags, procIDPtr, reasonPtr, statusPtr, subStatusPtr, usagePtr) int numPids; /* Number of entries in pidArray. * 0 means wait for any child. */ Proc_PID pidArray[]; /* Array of IDs of children to wait * for. (user address, possibly nil) */ int flags; /* PROC_WAIT_BLOCK => wait if no * children have exited, detached or * suspended. * PROC_WAIT_FOR_SUSPEND => return * status of suspended children. */ Proc_PID *procIDPtr; /* ID of the process that terminated. */ int *reasonPtr; /* Reason why the process exited. */ int *statusPtr; /* Exit status or termination signal * number. */ int *subStatusPtr; /* Additional signal status if the * process died because of a signal. */ Proc_ResUsage *usagePtr; /* Resource usage summary for the * process and its descendents. * (user address, possibly nil) */ { register Proc_ControlBlock *curProcPtr; ReturnStatus status; Proc_PID *newPidArray = (Proc_PID *) NIL; int newPidSize; ProcChildInfo childInfo; Proc_ResUsage resUsage; Boolean foreign = FALSE; curProcPtr = Proc_GetCurrentProc(); if (curProcPtr == (Proc_ControlBlock *) NIL) { panic("Proc_Wait: curProcPtr == NIL.\n"); } if (curProcPtr->genFlags & PROC_FOREIGN) { foreign = TRUE; } /* * If a list of pids to check was given, use it, otherwise * look for any child that has changed state. */ if (numPids < 0) { return(SYS_INVALID_ARG); } else if (numPids > 0) { if (pidArray == USER_NIL) { return(SYS_INVALID_ARG); } else { /* * If pidArray is used, make it accessible. Also make sure that * the pids are in the proper range. */ newPidSize = numPids * sizeof(Proc_PID); newPidArray = (Proc_PID *) ckalloc((unsigned)newPidSize); status = Vm_CopyIn(newPidSize, (Address) pidArray, (Address) newPidArray); if (status != SUCCESS) { ckfree((Address) newPidArray); return(SYS_ARG_NOACCESS); } } } if (!foreign) { status = DoWait(curProcPtr, flags, numPids, newPidArray, &childInfo); } else { status = ProcRemoteWait(curProcPtr, flags, numPids, newPidArray, &childInfo); } if (numPids > 0) { ckfree((Address) newPidArray); } if (status == SUCCESS) { *procIDPtr = childInfo.processID; *reasonPtr = childInfo.termReason; *statusPtr = childInfo.termStatus; *subStatusPtr = childInfo.termCode; if (usagePtr != USER_NIL) { /* * Convert the usages from the internal Timer_Ticks format * into the external Time format. */ Timer_TicksToTime(childInfo.kernelCpuUsage, &resUsage.kernelCpuUsage); Timer_TicksToTime(childInfo.userCpuUsage, &resUsage.userCpuUsage); Timer_TicksToTime(childInfo.childKernelCpuUsage, &resUsage.childKernelCpuUsage); Timer_TicksToTime(childInfo.childUserCpuUsage, &resUsage.childUserCpuUsage); resUsage.numQuantumEnds = childInfo.numQuantumEnds; resUsage.numWaitEvents = childInfo.numWaitEvents; if (Vm_CopyOut(sizeof(Proc_ResUsage), (Address) &resUsage, (Address) usagePtr) != SUCCESS) { status = SYS_ARG_NOACCESS; } } } return(status); } /* *---------------------------------------------------------------------- * * DoWait -- * * Execute monitor level code for a Proc_Wait. Return the information * about the child that was found if any. * * Results: * PROC_INVALID_PID - a process ID in the pidArray was invalid. * * Side effects: * None. * *---------------------------------------------------------------------- */ ENTRY ReturnStatus DoWait(curProcPtr, flags, numPids, newPidArray, childInfoPtr) register Proc_ControlBlock *curProcPtr; /* Parent process. */ /* PROC_WAIT_BLOCK => wait if no children have changed * state. * PROC_WAIT_FOR_SUSPEND => return status of suspended * children. */ int flags; int numPids; /* Number of pids in * newPidArray. */ Proc_PID *newPidArray; /* Array of pids. */ ProcChildInfo *childInfoPtr; /* Place to store child * information. */ { ReturnStatus status; LOCK_MONITOR; while (TRUE) { /* * If a pid array was given, check the array to see if someone on it * has changed state. Otherwise, see if any child has done so. */ status = FindExitingChild(curProcPtr, flags & PROC_WAIT_FOR_SUSPEND, numPids, newPidArray, childInfoPtr); /* * If someone was found or there was an error, break out of the loop * because we are done. FAILURE means no one was found. */ if (status != FAILURE) { break; } /* * If the search doesn't yields a child, we go to sleep waiting * for a process to wake us up if it exits or detaches itself. */ if (!(flags & PROC_WAIT_BLOCK)) { /* * Didn't find anyone to report on. */ status = PROC_NO_EXITS; break; } else { /* * Since the current process is local, it will go to sleep * on its waitCondition. A child will wakeup the process by * doing a wakeup on its parent's waitCondition. * * This technique reduces the number of woken processes * compared to having every process wait on the same * event (e.g. exiting list address) when it goes to * sleep. When we wake up, the search will start again. * * Check for the signal being SIG_CHILD, in which case * don't abort the Proc_Wait. This can happen if the parent and * the child are on different hosts so the Sync_Wait is aborted * by the signal rather than a wakeup. (The parent should handle * SIGCHLD better, but it might not, thereby missing the child's * change in state.) */ if (Sync_Wait(&curProcPtr->waitCondition, TRUE)) { if (Sig_Pending(curProcPtr) != (1 << (SIG_CHILD - 1))) { status = GEN_ABORTED_BY_SIGNAL; break; } } } } UNLOCK_MONITOR; return(status); } /* * ---------------------------------------------------------------------------- * * ProcRemoteWait -- * * Perform an RPC to do a Proc_Wait on the home node of the given * process. Transfer the information for a child that has changed state, * if one exists, and set up the information for a remote * wait if the process wishes to block waiting for a child. Note * that this routine is unsynchronized, since monitor locking is * performed on the home machine of the process. * * Results: * The status from the remote Proc_Wait (or RPC status) is returned. * * Side effects: * None. * * ---------------------------------------------------------------------------- */ ReturnStatus ProcRemoteWait(procPtr, flags, numPids, pidArray, childInfoPtr) Proc_ControlBlock *procPtr; int flags; int numPids; Proc_PID pidArray[]; ProcChildInfo *childInfoPtr; { #ifdef lint procPtr = procPtr; flags = flags; numPids = numPids; pidArray[0] = 42; childInfoPtr = childInfoPtr; #endif panic("ProcRemoteWait called.\n"); return FAILURE; /* lint */ } /* *---------------------------------------------------------------------- * * FindExitingChild -- * * Find a child of the specified process who has changed state, * subject to possible constraints (a list of process * IDs to check). If a process is found, send that process to the * reaper if appropriate. * * If numPids is 0, look for any child, else look for specific * processes. * * Results: * PROC_NO_CHILDREN - There are no children of this process left * to be waited on. * FAILURE - didn't find any child of interest. * SUCCESS - got one. * * Side effects: * If a process is found, *childInfoPtr is set to contain the relevant * information from the child. * *---------------------------------------------------------------------- */ INTERNAL static ReturnStatus FindExitingChild(parentProcPtr, returnSuspend, numPids, pidArray, infoPtr) Proc_ControlBlock *parentProcPtr; /* Parent's PCB */ Boolean returnSuspend; /* Return information about * suspended or resumed * children. */ int numPids; /* Number of Pids in pidArray */ Proc_PID *pidArray; /* Array of Pids to check */ register ProcChildInfo *infoPtr; /* Place to return info */ { ReturnStatus status; Proc_LockedPCB *paramProcPtr; register Proc_ControlBlock *procPtr; if (numPids > 0) { status = CheckPidArray(parentProcPtr, returnSuspend, numPids, pidArray, &paramProcPtr); } else { status = LookForAnyChild(parentProcPtr, returnSuspend, &paramProcPtr); } if (status == SUCCESS) { procPtr = (Proc_ControlBlock *)paramProcPtr; if (procPtr->state == PROC_EXITING || (procPtr->exitFlags & PROC_DETACHED)) { List_Remove((List_Links *) &(procPtr->siblingElement)); infoPtr->termReason = procPtr->termReason; if (procPtr->state == PROC_EXITING) { /* * Once an exiting process has been waited on it is moved * from the exiting state to the dead state. */ ProcPutOnDeadList(procPtr); } else { /* * The child is detached and running. Set a flag to make sure * we don't find this process again in a future call to * Proc_Wait. */ procPtr->exitFlags |= PROC_WAITED_ON; } } else { /* * The child was suspended or resumed. */ if (procPtr->exitFlags & PROC_SUSPEND_STATUS) { procPtr->exitFlags &= ~PROC_SUSPEND_STATUS; infoPtr->termReason = PROC_TERM_SUSPENDED; } else if (procPtr->exitFlags & PROC_RESUME_STATUS) { procPtr->exitFlags &= ~PROC_RESUME_STATUS; infoPtr->termReason = PROC_TERM_RESUMED; } } infoPtr->processID = procPtr->processID; infoPtr->termStatus = procPtr->termStatus; infoPtr->termCode = procPtr->termCode; #ifdef SPRITED_ACCOUNTING infoPtr->kernelCpuUsage = procPtr->kernelCpuUsage.ticks; infoPtr->userCpuUsage = procPtr->userCpuUsage.ticks; infoPtr->childKernelCpuUsage = procPtr->childKernelCpuUsage.ticks; infoPtr->childUserCpuUsage = procPtr->childUserCpuUsage.ticks; infoPtr->numQuantumEnds = procPtr->numQuantumEnds; infoPtr->numWaitEvents = procPtr->numWaitEvents; #else infoPtr->kernelCpuUsage = time_ZeroSeconds; infoPtr->userCpuUsage = time_ZeroSeconds; infoPtr->childKernelCpuUsage = time_ZeroSeconds; infoPtr->childUserCpuUsage = time_ZeroSeconds; infoPtr->numQuantumEnds = 0; infoPtr->numWaitEvents = 0; #endif /* SPRITED_ACCOUNTING */ Proc_Unlock(Proc_AssertLocked(procPtr)); } return(status); } /* *---------------------------------------------------------------------- * * LookForAnyChild -- * * Search the process's list of children to see if any of * them have exited, become detached or been suspended or resumed. * If no child is found, make sure there is a child who can wake us up. * * Results: * PROC_NO_CHILDREN - There are no children of this process left * to be waited on. * FAILURE - didn't find any child of interest. * SUCCESS - got one. * * Side effects: * None. * *---------------------------------------------------------------------- */ INTERNAL static ReturnStatus LookForAnyChild(curProcPtr, returnSuspend, procPtrPtr) register Proc_ControlBlock *curProcPtr; /* Parent proc.*/ Boolean returnSuspend; /* Return info about * suspended children.*/ Proc_LockedPCB **procPtrPtr; /* Child proc. */ { register Proc_ControlBlock *procPtr; register Proc_PCBLink *procLinkPtr; Boolean foundValidChild = FALSE; /* * Loop through the list of children, looking for the first child * to have changed state. Ignore children that are detached * and waited-on. */ LIST_FORALL((List_Links *) curProcPtr->childList, (List_Links *) procLinkPtr) { procPtr = procLinkPtr->procPtr; /* * It may be that one of our children is in the process of exiting. * If it is marked as 'dying' but not 'exiting', then it has * left the monitor (obvious because we're in the monitor now) * but hasn't completed the context switch to the 'exiting' state. * We'll wait for the child to become exiting since it will * take at most the length of a context switch to finish. If * we don't wait for this child we will miss the transition * and potentially wait forever. */ if (procPtr->genFlags & PROC_DYING) { while (procPtr->state != PROC_EXITING) { /* * Wait for the other processor to set the state to exiting. */ } } if ((procPtr->state == PROC_EXITING) || (procPtr->exitFlags & PROC_DETACHED) || (returnSuspend && (procPtr->exitFlags & PROC_STATUSES))) { if (!(procPtr->exitFlags & PROC_WAITED_ON)) { Proc_Lock(procPtr); *procPtrPtr = Proc_AssertLocked(procPtr); return(SUCCESS); } } else { foundValidChild = TRUE; } } if (foundValidChild) { return(FAILURE); } return(PROC_NO_CHILDREN); } /* *---------------------------------------------------------------------- * * CheckPidArray -- * * Search the process's array of children to see if any of them * have exited, become detached or been suspended or resumed. * * Results: * FAILURE - didn't find any child of interest. * PROC_INVALID_PID - a pid in the array was invalid. * SUCCESS - got one. * * Side effects: * None. * *---------------------------------------------------------------------- */ INTERNAL static ReturnStatus CheckPidArray(curProcPtr, returnSuspend, numPids, pidArray, procPtrPtr) register Proc_ControlBlock *curProcPtr; /* Parent proc. */ Boolean returnSuspend; /* Return information * about suspended or * resumed children. */ int numPids; /* Number of pids in * pidArray. */ Proc_PID *pidArray; /* Array of pids to * check. */ Proc_LockedPCB **procPtrPtr; /* Child proc. */ { register Proc_LockedPCB *procPtr; int i; /* * The user has specified a list of processes to wait for. * If a specified process is non-existent or is not a child of the * calling process return an error status. */ for (i=0; i < numPids; i++) { procPtr = Proc_LockPID(pidArray[i]); if (procPtr == NULL) { return(PROC_INVALID_PID); } if (!Proc_ComparePIDs(procPtr->pcb.parentID, curProcPtr->processID)) { Proc_Unlock(procPtr); return(PROC_INVALID_PID); } if ((procPtr->pcb.state == PROC_EXITING) || (procPtr->pcb.exitFlags & PROC_DETACHED) || (returnSuspend && (procPtr->pcb.exitFlags & PROC_STATUSES))) { if (!(procPtr->pcb.exitFlags & PROC_WAITED_ON)) { *procPtrPtr = procPtr; return(SUCCESS); } } Proc_Unlock(procPtr); } return(FAILURE); } /* *---------------------------------------------------------------------- * * WakeupMigratedParent -- * * Call the function Proc_NotifyMigratedWaiters by starting a process * on it. * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ static INTERNAL void WakeupMigratedParent(pid) Proc_PID pid; { #ifdef lint pid = pid; #endif panic("WakeupMigratedParent called.\n"); } /* *---------------------------------------------------------------------- * * ProcPutOnDeadList -- * * Put the given process on the dead list. * * Results: * None. * * Side effects: * The process state is set to "dead", and we arrange for the * process to get reaped. * *---------------------------------------------------------------------- */ static INTERNAL void ProcPutOnDeadList(procPtr) Proc_ControlBlock *procPtr; { Proc_SetState(procPtr, PROC_DEAD); List_Insert((List_Links *)&procPtr->deadElement, LIST_ATREAR(deadProcessList)); } /* *---------------------------------------------------------------------- * * UpdateChildCpuUsage -- * * Update the "child" CPU usage information for a waiting parent. * This is an internal proc, because the monitor lock protects updates * to the parent's accounting information. * * Results: * None. * * Side effects: * The CPU usage and child CPU usage for the exiting process are * added to the child CPU usage for the parent process. * *---------------------------------------------------------------------- */ static INTERNAL void UpdateChildCpuUsage(parentProcPtr, exitProcPtr) Proc_ControlBlock *parentProcPtr; Proc_ControlBlock *exitProcPtr; { /* XXX not implemented */ #ifdef lint parentProcPtr = parentProcPtr; exitProcPtr = exitProcPtr; #endif } /* *---------------------------------------------------------------------- * * Proc_Kill -- * * Routine to destroy a process, usually asynchronously. * * User processes are stopped, so that if they're in an infinite * loop they stop consuming cycles. The process is marked so that we * will not accept any more requests from it. System processes and * user processes that have pending requests are woken up and allowed * to continue running until they reach a convenient place to quit. * User processes that don't have a pending request die now. * * Note: it might be useful to call this routine directly in some * places, so that a specific termination reason (i.e., something more * meaningful than "the process got a SIG_KILL") is recorded in the * PCB. * * XXX Are there any other things that Proc_ExitInt does that we * should do here? * * Results: * None. * * Side effects: * None. * *---------------------------------------------------------------------- */ void Proc_Kill(procPtr, reason, status) Proc_LockedPCB *procPtr; /* the process to kill */ int reason; /* signaled or destroyed */ int status; /* signal number or destroy status */ { /* * If the process is already near death, leave it alone. */ if (procPtr->pcb.genFlags & PROC_DYING) { return; } /* * Clean up after migrated or profiled processes. * XXX Need to think some more about whether this will all do the right * thing. For example, is it okay to call ProcRemoteExit with a locked * PCB other than the current PCB? */ #ifdef SPRITED_MIGRATION if (procPtr->genFlags & PROC_FOREIGN) { ProcRemoteExit(procPtr, reason, status, 0); } #endif #ifdef SPRITED_PROFILING if (procPtr->Prof_Scale != 0) { Prof_Disable(procPtr); } #endif /* * In general, we can only nuke the thread. The task information * should be left around until the process exits, in case the process * has a request in the server. This is because various routines * (e.g., Vm_Copy{In,Out}, ProcMakeTaskThread) access the task * information without locking the pcb. */ if (procPtr->pcb.genFlags & PROC_USER) { ProcKillThread(procPtr); } /* * If the process is already on its way out, this is all we need to do. * ProcExitProcess isn't idempotent, so avoid calling it multiple times * for the same process. */ if (procPtr->pcb.genFlags & PROC_NO_MORE_REQUESTS) { return; } procPtr->pcb.genFlags |= PROC_NO_MORE_REQUESTS; procPtr->pcb.termReason = reason; procPtr->pcb.termStatus = status; procPtr->pcb.termCode = 0; /* * If it's a user process that has no pending request, force it to exit * now. Otherwise, we just marked it dead, so let the cleanup happen * later. */ if ((procPtr->pcb.genFlags & (PROC_KERNEL | PROC_BEING_SERVED)) == 0) { if ((Proc_ControlBlock *)procPtr == Proc_GetCurrentProc()) { panic("Proc_Kill: process in server but not marked.\n"); } ProcExitProcess((Proc_ControlBlock *)procPtr, reason, status, 0, FALSE); } else { Sync_WakeWaitingProcess(procPtr); } }
C
// // rotation.c // openGLProject // // Created by 김혜지 on 2016. 5. 17.. // Copyright © 2016년 김혜지. All rights reserved. // #include <stdio.h> #include <GLUT/GLUT.h> #define PI 3.1415926 float x, y, z; float radius; float theta; float phi; float zoom = 60.0; int beforeX, beforeY; GLfloat vertices[][3] = { { -1.0, -1.0, 1.0 }, { -1.0, 1.0, 1.0 }, { 1.0, 1.0, 1.0 }, { 1.0, -1.0, 1.0 }, { -1.0, -1.0, -1.0 }, { -1.0, 1.0, -1.0 }, { 1.0, 1.0, -1.0 }, { 1.0, -1.0, -1.0 }}; GLfloat colors[][3] = { { 1.0, 0.0, 0.0 }, // red { 1.0, 1.0, 0.0 }, // yellow { 0.0, 1.0, 0.0 }, // green { 0.0, 0.0, 1.0 }, // blue { 1.0, 1.0, 1.0 }, // white { 1.0, 0.0, 1.0 }}; // magenta void polygon(int a, int b, int c, int d) { glColor3fv(colors[a]); glBegin(GL_POLYGON); glVertex3fv(vertices[a]); glVertex3fv(vertices[b]); glVertex3fv(vertices[c]); glVertex3fv(vertices[d]); glEnd(); } // 6개의 면을 만든다. void createCube(void) { polygon(0, 3, 2, 1); // front polygon(2, 3, 7, 6); // right polygon(3, 0, 4, 7); // bottom polygon(4, 5, 6, 7); // back polygon(1, 2, 6, 5); // top polygon(5, 4, 0, 1); // right } void init (void) { glClearColor (0.0, 0.0, 0.0, 0.0) ; glColor3f(1.0, 1.0, 0.0); glEnable(GL_DEPTH_TEST);    // 깊이 활성화 } void reshape (int w, int h) { printf("reshape\n"); glViewport(0, 0, w, h); glMatrixMode (GL_PROJECTION); glLoadIdentity(); //glOrtho (-5.0, 5.0, -5.0, 5.0, -5.0, 5.0); gluPerspective(zoom, 1.0, 1.0, 100.0); // 멀고 가까움을 표현. radius = 10.0; theta = 10.0; phi = -10.0; } void display (void) { printf("display\n"); // for zoom glMatrixMode (GL_PROJECTION); glLoadIdentity(); gluPerspective(zoom, 1.0, 1.0, 100.0); // 멀고 가까움을 표현. x = radius * cos(phi) * cos(theta); y = radius * cos(phi) * sin(theta); z = radius * sin(phi); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glMatrixMode (GL_MODELVIEW); glLoadIdentity(); gluLookAt(x, y, z, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0); // (앞의 세 인자는 카메라의 위치, 중간의 세 인자는 카메라의 초점, //  뒤의 세 인자는 법선벡터 방향 (0, 1, 0))으로 해줘야 세워져 보인다. glBegin(GL_LINES); // X, Y, Z 선 표시 glColor3f(1.0, 0.0, 0.0); // X축 glVertex3f(0.0, 0.0, 0.0); glVertex3f(10.0, 0.0, 0.0); glColor3f(0.0, 1.0, 0.0); // Y축 glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 10.0, 0.0); glColor3f(0.0, 0.0, 1.0); // Z축 glVertex3f(0.0, 0.0, 0.0); glVertex3f(0.0, 0.0, 10.0); glEnd(); createCube();// 큐브 생성 glFlush (); glutSwapBuffers(); } void specialKey(int key, int xx, int yy) { switch(key) { case 'a': zoom--; break; case 'z': zoom++; break; } } void processMouse(int button, int state, int x, int y) { if(button == GLUT_LEFT_BUTTON){ if(state == GLUT_DOWN){ beforeX = x; beforeY = y; printf("down- x:%d , y:%d\n ",x,y); } else{ printf("up- x:%d , y:%d\n ",x,y); } } } void processMouseMotion(int x, int y) { printf("process- x:%d , y:%d\n ",x,y); if(abs(beforeX-x) > abs(beforeY-y)){ if(beforeX < x) { theta -= 0.1; }else if(beforeX > x){ theta += 0.1; } }else { if(beforeY > y){ phi -= 0.1; }else if(beforeY < y){ phi -= 0.1; } } beforeX = x; beforeY = y; glutPostRedisplay(); if ( theta > 2.0 * PI ) // 360도 넘어가면 theta -= (2.0 * PI); else if ( theta < 0.0 ) theta += (2.0 * PI); } void main (int argc, char** argv) { glutInit (&argc, argv); glutInitDisplayMode (GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH ); glutInitWindowPosition (100, 100); glutInitWindowSize (500, 500); glutCreateWindow ("Cube"); init(); glutDisplayFunc (display); glutReshapeFunc (reshape); glutMouseFunc(processMouse); glutMotionFunc(processMouseMotion); glutSpecialFunc(specialKey); glutIdleFunc(display); glutMainLoop(); }
C
#include "../common/common.h" #include "../common/trie.h" #include "../common/error.h" #include "server.h" #include <stdlib.h> /* BY gaochao Use the heap memory. ADD LOCK!!!!!!! */ struct trie_node *root; //indexed by name struct stored_data{ struct in_addr addr; in_port_t port; pid_t pid; }; void init() { root=create(); } void kill(pid_t pid) { } /** valid field: data_in->name,addr,port field to be filled: data_out->result valid result: see common/common.h TODO: 1.organize the struct stored_data. 2.insert into dataset(PS ERROR) **/ void register_node(struct register_data *data_in,struct register_data* data_out,pid_t pid) { int t; struct stored_data *tmp,* s=malloc(sizeof(struct stored_data)); s->addr=data_in->addr; s->port=data_in->port; s->pid=pid; switch(t=(struct stored_data*)insert(data_in->name,(void*)s,root)) { case ROOT_NULL: dumperror("ROOT INIT ERROR!\n"); break; case INSERT_SUCCESS: data_out->result = SUCCESS; break; default: { tmp=(struct stored_data*)(((struct trie_node*)t)->data); if(tmp->addr.s_addr==s->addr.s_addr&&tmp->port==s->port) { data_out->result=ALREADY_REGISTERED_ERROR; } else data_out->result = SAME_NAME_REGISTER_ERROR; kill(pid); } } } /** valid field: data_in->name field to be filled: data_out->addr,port,result valid result: see common/common.h **/ void request_node(struct register_data* data_in, struct register_data* data_out) { struct trie_node *t; struct stored_data *s; t=search(data_in->name,root); if(!t) { data_out->result=NOT_FOUND_REQUEST_ERROR; return ; } s=(struct stored_data*)(t->data); data_out->addr = s->addr; data_out->port = s->port; data_out->result = SUCCESS; } /** valid field: data_in->name,addr,port field to be filled: data_out->result valid result: see common/common.h TODO: 1.search the stored data with 'name' 2.check the stored data with 'addr port' 3.if valid ,remove the stored data 4.kill the pid **/ void deregister_node(struct register_data* data_in,struct register_data*data_out) { struct stored_data *s; struct trie_node *t; t=search(data_in->name,root); if(!t) { data_out->result=NAME_NOT_FOUND_ERROR; return ; } s=(struct stored_data*)(t->data); if(!(data_in->addr.s_addr==s->addr.s_addr&&data_in->port==s->port)) { data_out->result=SOURCE_NOT_MATCH_ERROR; } kill(s->pid); t->data=NULL; data_out->result=SUCCESS; }
C
#include <string.h> #include <math.h> #include <windows.h> void Emp() { int i,j,a; gotoxy(22,7); printf("%c",201); for(i=0;i<=120;i++) { printf("%c",205); } printf("%c",187); gotoxy(22,8); printf("%c",186); for(i=0;i<=28;i++) { gotoxy(22,8+i); printf("%c",186); } gotoxy(22,37); printf("%c",200); for(i=0;i<=120;i++) { printf("%c",205); } printf("%c",188); for(i=28;i>=0;i--) { gotoxy(144,36-i); printf("%c",186); } for(i=0;i<=29;i++){ for(j=0;j<=120;j+=18) { gotoxy(22+j,7+i); printf("%c",186); } } for(i=0;i<=120;i++){ for(j=0;j<=28;j+=6) { gotoxy(23+i,7+j); printf("%c",205); } } gotoxy(24,10); printf("HORAIRE/JOUR"); gotoxy(46,10); printf("LUNDI"); gotoxy(65,10); printf("MARDI"); gotoxy(81,10); printf("MERCREDI"); gotoxy(99,10); printf("JEUDI"); gotoxy(117,10); printf("VENDREDI"); gotoxy(133,10); printf("SAMEDI"); //Carr du coin suprieur gauche coloration(13); for(a=0;a<=7;a++){ gotoxy(1,1+a); printf("%c%c%c%c%c%c%c%c%c%c%c%c",35,35,35,35,35,35,35,35,35,35,35,35); } //Trait horizontal suprieur for(a=0;a<=150;a++){ gotoxy(1+a,4); printf("%c%c",35,35); gotoxy(1+a,5); printf("%c%c",35,35); } //Carr du coin suprieur droit for(a=0;a<=7;a++){ gotoxy(153,1+a); printf("%c%c%c%c%c%c%c%c%c%c%c%c",35,35,35,35,35,35,35,35,35,35,35,35); } for(a=0;a<=35;a++){ gotoxy(6,6+a); printf("%c%c",35,35); } for(a=0;a<=35;a++){ gotoxy(158,6+a); printf("%c%c",35,35); } //Symtrique for(a=0;a<=7;a++){ gotoxy(1,35+a); printf("%c%c%c%c%c%c%c%c%c%c%c%c",35,35,35,35,35,35,35,35,35,35,35,35); } for(a=0;a<=150;a++){ gotoxy(1+a,38); printf("%c%c",35,35); gotoxy(1+a,39); printf("%c%c",35,35); } for(a=0;a<=7;a++){ gotoxy(153,35+a); printf("%c%c%c%c%c%c%c%c%c%c%c%c",35,35,35,35,35,35,35,35,35,35,35,35); } }
C
#include<stdio.h> int main() { int i=20,j=30; swap(&i,&j) printf("%d %d",i,j); return 0; } void swap(int *x,int *y) { int temp; temp=*x; *x=*y; *y=temp; }
C
#include<stdio.h> extern int countv(char *); int main(){ int a; a = countv("2 3, 4 5, 6 7"); printf("%d\n",a); return 0; }
C
#include<stdio.h> int main(int argc, char *argv[]){ int flag,tmp,i,j,k,l,m,n; char c[1005]; scanf("%d",&n); scanf(" %s",c); flag=0; for(i=n-1;i>=0;i--) c[i+1] = c[i]; for(i=1;i<=n/4;i++){ for(j=1;j+i<=n;j++){ tmp = j; m = 0; while(c[tmp]=='*' && tmp<=n){ tmp = tmp+i; m++; } if(m>=5) flag=1; } } if(flag==1) printf("yes\n"); else printf("no\n"); return 0; }
C
#include<stdio.h> #include<conio.h> void main() { char ch[25]={" "}; char c[25]={'\0'}; int i,flag=0,cnt=0; clrscr(); printf("\n Enter string"); scanf("%s",ch); printf("%s",ch); for(i=0;ch[i]!='\0';i++) { cnt++; } /* cnt=strlen(ch); for(i=0;i<cnt;i++) { c[i]=ch[i]; } */ printf("\nString length is =%d",cnt); for(i=cnt-1;i>=0;i--) { c[cnt-i-1]=ch[i]; } for(flag=1,i=0;i<cnt;i++) { if(c[i]!=ch[i]) flag=0; } if(flag==1) { printf("\nString is palindrome %s",ch); } else { printf("\nString is not palindrome %s",ch); } getch(); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<string.h> #include<stdlib.h> #include<assert.h> typedef int QDataType; // ʽṹʾ typedef struct QListNode { struct QListNode* _pNext; QDataType _data; }QNode; // еĽṹ typedef struct Queue { QNode* _front; QNode* _rear; size_t size; }Queue; // ʼ void QueueInit (Queue* q){ q->_front = NULL; q->_rear = NULL; q->size = 0; } // β void QueuePush (Queue* q , QDataType data) { assert (q); QNode*new = (QNode*)malloc (sizeof (QNode)); new->_data = data; new->_pNext = NULL; if ( !q->_front ) { q->_front = new; q->_rear = new; } else { q->_rear->_pNext = new; q->_rear = new; } q->size++; } // ͷ void QueuePop (Queue* q) { assert (q); QNode* get = q->_front->_pNext; free (q->_front); q->_front = get; q->size--; } // ȡͷԪ QDataType QueueFront (Queue* q) { return q->_front->_data; } // ȡжβԪ QDataType QueueBack (Queue* q) { return q->_rear->_data; } // ȡЧԪظ int QueueSize (Queue* q) { return (int)q->size; } // ǷΪգΪշطǿշ0 int QueueEmpty (Queue* q) { return !q->size; } // ٶ void QueueDestroy (Queue* q) { QNode* go = q->_front; while ( go ) { QNode* next = go->_pNext; free (go); go = next; } q->_front = NULL; q->_rear = NULL; q->size = 0; } int main () { Queue a; QueueInit (&a); QueuePush (&a , 1); QueuePush (&a , 4); QueuePush (&a , 3); QueuePush (&a , 2); printf ("%d\n",QueueSize(&a)); QueuePop (&a); printf ("%d\n" , QueueSize (&a)); printf ("%d %d\n" , a._front->_data , a._rear->_data); system ("pause"); return 0; }