language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
//#include "cuda_runtime.h" //#include "device_launch_parameters.h" #include <stdlib.h> #include <stdio.h> //#include <iostream> #include <math.h> //#include <iomanip> #define X 1 #define Y 4 #define Z 4 #define N 1 static inline int MAX(int a, int b) { if (a > b) { return a; } return b; } void printMatrixMult(float a[], float b[], float c[], int x, int y, int z){ //print one line //std::cout<<std::setprecision(3); //std::cout<<std::fixed; int maxi = MAX(z,MAX(x,y)); for(int line=0;line<maxi;++line){ //matrix a if(line<y){ printf("["); for(int i=0;i<x;++i) printf(" %f,",a[line*x+i]); printf("]"); } if(line==0) printf("*"); else printf(" "); //matrix b if(line<z){ printf("["); for(int i=0;i<y;++i) printf(" %f,",b[line*y+i]); printf("]"); } if(line==0) printf("="); else printf(" "); //matrix c if( line<z){ printf("["); for(int i=0;i<x;++i) printf(" %f,",c[line*x+i]); printf("]"); } printf("\n"); } printf("\n"); } //single threaded matrix multiplication void matrixMult(float xy[], float yz[], float xz[], int q) { for (int i = 0; i < X; ++i) { for (int j = 0; j < Z; ++j) { for (int k = 0; k < Y; ++k) { xz[q*X*Z + i*Y + j] += xy[q*X*Y + i*Y + k] * yz[q*Y*Z + k*Z + j]; } } } } // multi threaded matrix multiplication of a single matrix void matrixMultSingle(float xy[], float yz[], float xz[], int q ) { int index = 0;//blockIdx.x * blockDim.x + threadIdx.x; int stride = 1;//blockDim.x * gridDim.x; for(int a = index; a < X*Y*Z; a+=stride){ xz[q*X*Z + a/Y/Z*Y + (a/Z) % Y] += xy[q*X*Y + a/Y/Z*Y + a%Z] * yz[q*Y*Z + a%Z*Z + (a/Z) % Y]; } } // multi threaded multiplication of many matrices //__global__ void multAll(float matrixListXY[], float matrixListYZ[], float matrixListXZ[]) { int index = 0;//blockIdx.x * blockDim.x + threadIdx.x; int stride = 1;//blockDim.x * gridDim.x; //matrix a size is n*x*y //matrix b size is n*y*z for (int i = index; i < N; i += stride) { matrixMult(matrixListXY, matrixListYZ, matrixListXZ, i ); } } int main(void) { //dim3 matrixDim(X, Y, Z); //initialization for cuda float* matrixListXY, * matrixListYZ; //cudaMallocManaged(&matrixListXY, N * X * Y * sizeof(float)); //cudaMallocManaged(&matrixListYZ, N * Y * Z * sizeof(float)); //set randomizer srand(2); //initialize matrices float *XY, *YZ, *XZ; XY = (float*)malloc(N * X * Y * sizeof(float)); YZ = (float*)malloc(N * Y * Z * sizeof(float)); XZ = (float*)malloc(N * X * Z * sizeof(float)); for (int i = 0; i < N * X * Y; ++i) { //XY[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); XY[i] = (float) (i+1); } for (int i = 0; i < N * Y * Z; ++i) { //YZ[i] = static_cast <float> (rand()) / static_cast <float> (RAND_MAX); YZ[i] = (float) (i+1); } for (int i = 0; i < N * X * Z; ++i) { XZ[i] = (float) 0; } //make events for profiling //cudaEvent_t start, stop; //cudaEventCreate(&start); //cudaEventCreate(&stop); //copy data to GPU mem //cudaMemcpy(matrixListXY, XY, N * X * Y * sizeof(float), cudaMemcpyHostToDevice); //cudaMemcpy(matrixListYZ, YZ, N * Y * Z * sizeof(float), cudaMemcpyHostToDevice); //cudaEventRecord(start); //do work multAll /*<<< (N+511)/512, 512 >> > */(XY, YZ, XZ); //copy data back to cpu mem before printintg //TO DO //print if we want printMatrixMult(XY,YZ,XZ,X,Y,Z); //reset memory for (int i = 0; i < N * X * Z; ++i) { XZ[i] = (float) 0; } //copy data to gpu again //TO DO //do work again matrixMultSingle(XY,YZ,XZ,0); //copy data back to cpu again //TO DO //print if we want printMatrixMult(XY,YZ,XZ,X,Y,Z); //final book keeping /*cudaEventRecord(stop); cudaEventSynchronize(stop); float milliseconds = 0.0f; cudaEventElapsedTime(&milliseconds, start, stop); printf("Effective Bandwidth (GB/s): %f", ((N * 4 * X * Y )+ (N*4*Y*Z)) / milliseconds / 1e6); cudaFree(matrixListXY); cudaFree(matrixListYZ);*/ //free(XY); //free(YZ); //free(XZ); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* type_csp.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: weilin <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/20 17:42:55 by weilin #+# #+# */ /* Updated: 2020/02/24 16:01:16 by weilin ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void type_chars(char type, t_data *t) { unsigned char ch; char *str; t->flag.minus == 1 ? t->flag.zero = 0 : 0; if (type == 'c') { ch = (unsigned char)va_arg(t->valist, int); print_char(t, ch); } else if (type == 's') { if ((str = (char*)va_arg(t->valist, char*)) != NULL) { if (!(t->bf = ft_strdup(str))) return ; } else if (!(t->bf = ft_strdup("(null)"))) return ; print_str(t); } } void type_percent(t_data *t) { int tmp; tmp = t->flag.width; if (t->flag.minus == 1) { t->nb_print += write(t->fd, "%", 1); while (tmp-- > 1) t->nb_print += write(t->fd, " ", 1); } else { while (tmp-- > 1) t->nb_print += (t->flag.zero ? write(t->fd, "0", 1) : write(t->fd, " ", 1)); t->nb_print += write(t->fd, "%", 1); } t->i++; } void type_addr(t_data *t) { unsigned long val; t->flag.minus == 1 ? t->flag.zero = 0 : 0; val = va_arg(t->valist, unsigned long); if (t->flag.prec == 0) t->bf = ft_strdup("\0"); else t->bf = ft_ultoa_base(val, 16); if (!t->bf) return ; ft_strtolower(t->bf); print_addr(t); }
C
/* Take a note of the main function parameter. There is an extra item of char * envp[]. This allows the program to retrieve the system environment variable. */ #include <stdio.h> int main(int argc, char *argv[], char *envp[]){ int i; for(i = 0; envp[i]; i++){ printf("[%d] = %s\n", i, envp[i]); } return 0; }
C
#include<stdio.h> #include<math.h> void main(){ int x1, y1, x2, y2, radius; float dis; printf("Enter the center points "); scanf("%d %d", &x1, &y1); printf("Enter the radius of the circle: "); scanf("%d", &radius); printf("Enter the points "); scanf("%d %d", &x2, &y2); dis = sqrt(pow(x2-x1, 2)+pow(y2-y1,2)); if(dis>radius){ printf("Point (%d,%d) lies outside the circle.", x2, y2); }else if(dis<radius){ printf("Point (%d,%d) lies inside the circle.", x2, y2); } else(dis==radius){ printf("Point (%d,%d) lies on the boundary of circle.", x2, y2); } }
C
/* ** EPITECH PROJECT, 2021 ** zappy ** File description: ** main */ bool add_id(int **ids, int const id) { int *tmp = *ids; unsigned int len = 0; int *new = NULL; if (tmp) for (unsigned int j = 0; tmp[j]; ++j) ++len; new = malloc(sizeof(char) * (len + 2)); if (!new) return (false); while(tmp && -1 != tmp[i]) { new[i] = tmp[i]; ++i; } new[i] = id; new[i + 1] = -1; free(*ids); *ids = new; return (true); } static bool realloc_ids(int **ids, unsigned int const len, int const id) { int *new = malloc(sizeof(int) * (len)); unsigned int y = 0; if (!new) return (false); for (unsigned int i = 0; -1 != *ids[i]; ++i) if (id != *ids[i]) { new[y] = *ids[i]; ++y; } new[len - 1] = -1; free(*ids); *ids = new; } bool rm_id(int **ids, int const id) { int *tmp = *ids; unsigned int len = 0; int *new = NULL; if (!tmp) return (true); for (unsigned int i = 0; -1 != tmp[i]; ++i) ++len; if (1 == len) free(*ids); else if (!realloc_ids(ids, len, id)) return (false); return (true); }
C
/* * Developed by Rafa Garcia <[email protected]> * * queue.c 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. * * queue.c 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 Foobar. If not, see <http://www.gnu.org/licenses/>. * */ #include "queue.h" #include "anyRTOS-conf.h" #if defined(ANYRTOS_USE_QUEUE) && ANYRTOS_USE_QUEUE /* Initializes a queue. */ void queue_init( queue_t* queue, uint8_t memory[], size_t size ) { event_init( &queue->input ); event_init( &queue->output ); mutex_init( &queue->putting ); mutex_init( &queue->getting ); queue->first = queue->last = queue->qty = (size_t)0; queue->size = size; queue->data = memory; } /** Checks if a queue is full. * @param queue: Queue handler. * @retval true: If queue is full; * @retval false: If queue is not full. */ static bool _isFull( queue_t const* queue ) { return (queue->qty >= queue->size); } /* Checks if a queue is full. */ bool queue_isFull( queue_t const* queue ) { task_enterCritical(); bool retVal = _isFull( queue ); task_exitCritical(); return retVal; } /** Tries to put a byte in a queue. * @param queue: Queue handler. * @param data: Byte to be put. * @retval true If success; * @retval false If queue was full. */ static bool _put( queue_t* queue, uint8_t data ) { if ( _isFull( queue ) ) return false; queue->data[ queue->last ] = data; if( ++queue->last >= queue->size ) queue->last = (size_t)0; ++queue->qty; return true; } /* Waits until put a block of memory. */ void queue_put( queue_t* queue, void const* src, size_t size ) { if ( !size ) return; mutex_enterCritical( &queue->putting ); for(;; ++src ) { while ( !_put( queue, *(uint8_t*)src ) ) event_wait( &queue->output ); if ( !--size ) break; if ( _isFull( queue ) ) event_notify( &queue->input ); } event_notify( &queue->input ); mutex_exitCritical( &queue->putting ); } /** Checks if a queue is empty. * @param queue: Queue handler. * @retval true: If queue is empty; * @retval false: If queue is not empty. */ static bool _isEmpty( queue_t const* queue ) { return !queue->qty; } /* Checks if a queue is empty. */ bool queue_isEmpty( queue_t const* queue ) { task_enterCritical(); bool retVal = _isEmpty( queue ); task_exitCritical(); return retVal; } /** Tries to get a byte from a queue. * @param queue: Queue handler. * @param data: Destination byte. * @retval true If success; * @retval false If queue was empty. */ static bool _get( queue_t* queue, uint8_t* data ) { if ( _isEmpty( queue ) ) return false; *data = queue->data[ queue->first ]; if( ++queue->first >= queue->size ) queue->first = (size_t)0; --queue->qty; return true; } /* Waits until get a block of memory. */ void queue_get( queue_t* queue, void* dst, size_t size ) { if ( !size ) return; mutex_enterCritical( &queue->getting ); for(;; ++dst ) { while( !_get( queue, dst) ) event_wait( &queue->input ); if ( !--size ) break; if ( _isEmpty( queue ) ) event_notify( &queue->output ); } event_notify( &queue->output ); mutex_exitCritical( &queue->getting ); } /* Waits until put a byte. */ void queue_put8( queue_t* queue, uint8_t data ) { mutex_enterCritical( &queue->putting ); while ( !_put( queue, data ) ) event_wait( &queue->output ); event_notify( &queue->input ); mutex_exitCritical( &queue->putting ); } /* Waits until get a byte. */ uint8_t queue_get8( queue_t* queue ) { mutex_enterCritical( &queue->getting ); uint8_t retVal; while ( !_get( queue, &retVal ) ) event_wait( &queue->input ); event_notify( &queue->output ); mutex_exitCritical( &queue->getting ); return retVal; } /* Waits until put a null-terminated string. */ void queue_putStr( queue_t* queue, char const* src ) { mutex_enterCritical( &queue->putting ); for(;; ++src ) { while ( !_put( queue, *src ) ) event_wait( &queue->output ); if( !*src ) break; if ( _isFull( queue ) ) event_notify( &queue->input ); } event_notify( &queue->input ); mutex_exitCritical( &queue->putting ); } /* Waits until get a null-terminated string. */ void queue_getStr( queue_t* queue, char* dst ) { mutex_enterCritical( &queue->getting ); for(;; ++dst ) { while( !_get( queue, (uint8_t *)dst) ) event_wait( &queue->input ); if ( !*dst ) break; if ( _isEmpty( queue ) ) event_notify( &queue->output ); } event_notify( &queue->output ); mutex_exitCritical( &queue->getting ); } /* Tries to get a block of memory from a queue before a timeout. */ bool queueTimer_get( queue_t* queue, timer_t* timer, void* dst, size_t size ) { if ( !size ) return true; if ( !mutexTimer_enterCritical( &queue->getting, timer ) ) return false; bool timeout = false; while ( !timeout && !_get( queue, dst) ) timeout = !eventTimer_wait( &queue->input, timer ); if ( !timeout ) { if ( --size ) for( ++dst;; ++dst ) { while ( !_get( queue, dst) ) event_wait( &queue->input ); if ( !--size ) break; if ( _isEmpty( queue ) ) event_notify( &queue->output ); } event_notify( &queue->output ); } mutex_exitCritical( &queue->getting ); return !timeout; } /* Tries to put a block of memory in a queue before a timeout. */ bool queueTimer_put( queue_t* queue, timer_t* timer, void const* src, size_t size ) { if ( !size ) return true; if ( !mutexTimer_enterCritical( &queue->putting, timer ) ) return false; bool timeout = false; while ( !timeout && !_put( queue, *(uint8_t*)src ) ) timeout = !eventTimer_wait( &queue->output, timer ); if ( !timeout ) { if ( --size ) for( ++src;; ++src ) { while ( !_put( queue, *(uint8_t*)src ) ) event_wait( &queue->output ); if ( !--size ) break; if ( _isFull( queue ) ) event_notify( &queue->input ); } event_notify( &queue->input ); } mutex_exitCritical( &queue->putting ); return !timeout; } /* Waits until put a byte in a queue or until * the tick counter of a timer gets the task tick. */ bool queueTimer_put8( queue_t* queue, timer_t* timer, uint8_t data ) { if ( !mutexTimer_enterCritical( &queue->putting, timer ) ) return false; bool timeout = false; while ( !timeout && !_put( queue, data ) ) timeout = !eventTimer_wait( &queue->output, timer ); if ( !timeout ) event_notify( &queue->input ); mutex_exitCritical( &queue->getting ); return !timeout; } /* Waits until get a byte from a queue or until * the tick counter of a timer gets the task tick. */ bool queueTimer_get8( queue_t* queue, timer_t* timer, uint8_t *data ) { if ( !mutexTimer_enterCritical( &queue->getting, timer ) ) return false; bool timeout = false; while ( !timeout && !_get( queue, data ) ) timeout = !eventTimer_wait( &queue->input, timer ); if ( !timeout ) event_notify( &queue->output ); mutex_exitCritical( &queue->getting ); return !timeout; } /* Tries to put a null-terminated string before a timeout. */ bool queueTimer_putStr( queue_t* queue, timer_t* timer, char const* src ) { if ( !*src ) return true; if ( !mutexTimer_enterCritical( &queue->putting, timer ) ) return false; bool timeout = false; while ( !timeout && !_put( queue, *src ) ) timeout = !eventTimer_wait( &queue->output, timer ); if ( !timeout ) { if ( *src ) for( ++src;; ++src ) { while ( !_put( queue, *src ) ) event_wait( &queue->output ); if( !*src ) break; if ( _isFull( queue ) ) event_notify( &queue->input ); } event_notify( &queue->input ); } mutex_exitCritical( &queue->putting ); return !timeout; } /* Tries to get a null-terminated string before a timeout. */ bool queueTimer_getStr( queue_t* queue, timer_t* timer, char* dst ) { if ( !mutexTimer_enterCritical( &queue->getting, timer ) ) return false; bool timeout = false; while ( !timeout && !_get( queue, (uint8_t*)dst ) ) timeout = !eventTimer_wait( &queue->input, timer ); if ( !timeout ) { if ( *dst ) for( ++dst;; ++dst ) { while( !_get( queue, (uint8_t*)dst) ) event_wait( &queue->input ); if ( !*dst ) break; if ( _isEmpty( queue ) ) event_notify( &queue->output ); } event_notify( &queue->output ); } mutex_exitCritical( &queue->getting ); return !timeout; } /* Puts a byte in an interrupt service routine. */ queueCode_t queue_put8ISR( queue_t* queue, uint8_t data ) { if ( !_put( queue, data ) ) return QUEUE_ERROR; if ( event_notifyISR( &queue->input ) ) return QUEUE_DOYIELD; return QUEUE_DONOTYIELD; } /* Gets a byte in an interrupt service routine. */ queueCode_t queue_get8ISR( queue_t* queue, uint8_t *data ) { if ( !_get( queue, data ) ) return QUEUE_ERROR; if ( event_notifyISR( &queue->output ) ) return QUEUE_DOYIELD; return QUEUE_DONOTYIELD; } /* Gets a byte in an interrupt service routine. * Only an input event is generated when the data quantity in queue * is less or equal than a threshold. */ queueCode_t queue_get8ThdISR( queue_t* queue, uint8_t* data, unsigned thd ) { if ( !_get( queue, data ) ) return QUEUE_ERROR; if ( (queue->qty <= thd) && event_notifyISR( &queue->output ) ) return QUEUE_DOYIELD; return QUEUE_DONOTYIELD; } #endif /* ANYRTOS_USE_QUEUE */ /* ------------------------------------------------------------------------ */
C
/** * @file sudoku.c * @author Juan Gonzalez * @brief main sudoku code */ #include <stdio.h> #include <string.h> #include <stdint.h> #include <inttypes.h> #include <stdlib.h> #include <stdbool.h> #include <getopt.h> #include "sudoku.h" #include "version.h" enum moves_t { ZERO = 0x0, ONE = 0x1, TWO = 0x2, THREE = 0x4, FOUR = 0x8, FIVE = 0x10, SIX = 0x20, SEVEN = 0x40, EIGHT = 0x80, NINE = 0x100, }; static bool _show_intermediate = false; static const uint16_t masks[] = {ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE}; static struct option _long_options[] = { {"intermediate", no_argument, 0, 'i'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {0, 0, 0, 0} }; /** * prints a sudoku puzzle * * @param sp a sudoku_puzzle struct pointer */ void sudoku_puzzle_print(struct sudoku_puzzle *sp) { if(sp == NULL) { printf("no solution\n"); return; } int row, column; for(row = 0; row < 9; row++) { printf("["); for(column = 0; column < 9; column++) { if(sp->element[row][column] == 0) { printf("_"); } else { printf("%"PRIu16"", sp->element[row][column]); } if(column < 8) printf(" "); } printf("]\n"); } } /** * advances the current element to the next zero element * * @param sp a sudoku_puzzle struct pointer */ static void _go_to_next(struct sudoku_puzzle *sp) { int idx, jdx; for(idx = sp->x; idx < 9; idx++) { for(jdx = sp->y; jdx < 9; jdx++) { if(sp->element[idx][jdx] == 0) { sp->x = idx; sp->y = jdx; return; } } if(jdx == 9 && idx < 9) { jdx = 0; sp->x = idx; sp->y = jdx; } } } /** * given an integer 'val' between 0-9, return the mask for the 'val' bit * * @param val unsigned 16-bit integer * @return unsigned 16-bit integer */ static uint16_t _get_val(uint16_t val) { switch(val) { case 1: return ONE; case 2: return TWO; case 3: return THREE; case 4: return FOUR; case 5: return FIVE; case 6: return SIX; case 7: return SEVEN; case 8: return EIGHT; case 9: return NINE; default: return ZERO; } } /** * get the numbers that are valid for a puzzle's current position in * the form of a bitmask * * @param sp a sudoku_puzzle struct pointer * @return unsigned 16-bit integer */ static uint16_t _get_possible_moves(struct sudoku_puzzle *sp) { uint16_t ret = 0; int idx, jdx, ide, jde; uint64_t index[10] = {0}; for(idx = 0; idx < 9; idx++) { index[sp->element[idx][sp->y]]++; index[sp->element[sp->x][idx]]++; } idx = sp->x / 3 * 3; jdx = sp->y / 3 * 3; ide = idx + 3; jde = jdx + 3; for(; idx < ide; idx++) { for(; jdx < jde; jdx++) { index[sp->element[idx][jdx]]++; } jdx = sp->y / 3 * 3; } for(idx = 1; idx <= 9; idx++) { if(index[idx] == 0) { ret |= _get_val((uint16_t)idx); } } return ret; } /** * solve the sudoku puzzle (recursive backtracking algorithm) * * @param sp a sudoku_puzzle struct * @return a sudoku_puzzle struct pointer */ static struct sudoku_puzzle *_sudoku_puzzle_solve_bt(struct sudoku_puzzle sp) { _go_to_next(&sp); uint16_t moves = _get_possible_moves(&sp); uint8_t tmp = 0; struct sudoku_puzzle *solution = NULL; int idx, jdx; if(_show_intermediate) { printf("intermediate:\n"); sudoku_puzzle_print(&sp); printf("====================\n"); } // base case if(moves == 0) { bool no_zeroes = true; for(idx = 0; idx < 9; idx++) { for(jdx = 0; jdx < 9; jdx++) { if(sp.element[idx][jdx] == 0) { no_zeroes = false; } } } if(no_zeroes) { solution = malloc(sizeof(sp)); memcpy(solution, &sp, sizeof(sp)); return solution; } } for(idx = 0; idx < 9; idx++) { if(moves & masks[idx]) { tmp = sp.element[sp.x][sp.y]; sp.element[sp.x][sp.y] = idx + 1; solution = _sudoku_puzzle_solve_bt(sp); if(solution) { return solution; } else { sp.element[sp.x][sp.y] = tmp; } } } return NULL; } /** * solve the sudoku puzzle * * @param sp a sudoku_puzzle struct pointer * @return a sudoku_puzzle struct pointer */ struct sudoku_puzzle *sudoku_puzzle_solve(struct sudoku_puzzle *sp) { return _sudoku_puzzle_solve_bt(*sp); } /** * load a sudoku puzzle from stdin * * @param sp a sudoku_puzzle struct pointer */ static void _sudoku_puzzle_load(struct sudoku_puzzle *sp) { char buf[1024] = {0}; fread(&buf, 1, sizeof(buf), stdin); int idx, jdx, count; idx = jdx = count = 0; while(buf[count]) { if(idx > 8) break; if(jdx > 8) { idx++; jdx = 0; continue; } if(buf[count] < '0' && buf[count] > '9' && buf[count] != '_') { count++; continue; } if((buf[count] >= '0' && buf[count] <= '9') || buf[count] == '_') { if(buf[count] == '_') { sp->element[idx][jdx] = 0; } else { sp->element[idx][jdx] = buf[count] - '0'; } jdx++; count++; continue; } count++; } } /** * print help */ static void _print_help(void) { printf("Usage: sudoku [OPTION]...\n" "Print solved sudoku puzzle for a given sudoku puzzle from stdin\n\n" " -i, --intermediate\tshow intermediate results\n" " -h, --help\tdisplay this help and exit\n"); } /** * print version */ static void _print_version(void) { if(commit_id == NULL) { printf("sudoku solver: version %s\n", version); } else { printf("sudoku solver: version %s-%s\n", version, commit_id); } } /** * main. * * @param argc an integer for number of args * @param argv a char** for the args */ int main(int argc, char **argv) { struct sudoku_puzzle sp = {0}; struct sudoku_puzzle *solution; int c; while(true) { int option_index = 0; c = getopt_long(argc, argv, "hi", _long_options, &option_index); if(c == -1) break; switch(c) { case 'h': _print_help(); return 0; case 'v': _print_version(); return 0; case 'i': _show_intermediate = true; break; } } _sudoku_puzzle_load(&sp); printf("original:\n"); sudoku_puzzle_print(&sp); solution = sudoku_puzzle_solve(&sp); printf("solution:\n"); sudoku_puzzle_print(solution); free(solution); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <assert.h> typedef struct node { struct node *next; int64_t val; } listnode_t; /* floyd's cycle detection algorithm */ int cycle_detect(listnode_t *head) { listnode_t *fast, *slow; slow = head; fast = head; while(!(slow == NULL || fast == NULL)) { /* bump fast pointer second time */ printf("fast node data = %ld\n", fast->val); fast = fast->next; if(!fast) return 0; if(fast == slow) return 1; printf("fast node data = %ld\n", fast->val); printf("slow node data = %ld\n", slow->val); fast = fast->next; slow = slow->next; } return 0; } int main() { int64_t i,n = (1L<<3); int rc=0; unsigned iter = 10; listnode_t *nodes = NULL; nodes = (listnode_t*)malloc(n*sizeof(listnode_t)); memset(nodes, 0, n*sizeof(listnode_t)); for(i=0;i<n;i++) { nodes[i].val = (int64_t)i; if((i+1) < n) nodes[i].next = &nodes[i+1]; } for (size_t c = 0; c < iter; ++c) { i = rand() % (2*n); printf("i = %ld n = %ld\n", i, n); if(i <n ) nodes[n-1].next = nodes+i; else nodes[n-1].next = NULL; rc = cycle_detect(nodes); if(rc) assert(i < n); printf("cycle %s\n", rc ? "found" : "not found"); } printf("Test Passed\n"); free(nodes); return 0; }
C
#include <stdio.h> #include <stdlib.h> int main() { long num; long suma=0L; int stan; printf("wpisz liczbe calkowita"); printf("wpisz litere aby zakonczyc\n"); stan=scanf("%d",&num); while(stan==1) { suma+=num; printf("podaj kolejna liczbe calkowita"); printf("wpisz litere aby zakonczyc\n"); stan=scanf("%d",&num); } printf("dzieki suma podanych liczb wynosi %d\n",suma); return 0; }
C
#ifndef NEWLINE_H #define NEWLINE_H string add_newline(string str) { string lchar; if(!str) return "\n"; lchar = extract(str,strlen(str)-1); return (lchar == "!" || lchar == "." || lchar == "?") ? str + "\n" : (lchar == "\n") ? str : str + ".\n"; } #endif
C
#include <stdio.h> int main () { long int l=0,r,k; scanf("%d",&k); while(k) { r=k%10; k=k/10; l++; } printf("%d",l); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "nmea.h" /* takes a line from a NMEA file and extracts the message and the checksum */ status_t get_NMEA_message(string NMEA_message, uint *checksum) { char *tmp; if(NMEA_message == NULL || checksum == NULL){ return ERROR_NULL_POINTER; } /* Go over the NMEA datagram looking for a checksum or its end */ for(; *NMEA_message; NMEA_message++){ /* If the checksum delimiter is found */ if(*NMEA_message == NMEA_CHECKSUM_DELIMITER){ /* Separate the NMEA message from the checksum */ *NMEA_message = '\0'; /* Move to the beginning of the checksum */ NMEA_message++; break; } } /* Get the checksum value. Note that if there isn't one, it's just tries to * convert "", which strtoul interprets as 0 */ *checksum = strtoul(NMEA_message, &tmp, 16); if(*tmp && *tmp != '\r' && *tmp != '\n'){ return ERROR_INVALID_LINE; } return OK; } /* Makes a checksum of a NMEA message */ status_t check_NMEA_message(const char *NMEA_message, uint checksum) { uint crc = 0; /* Calculate the CRC, skips the beginning of the datagram character $ */ for(NMEA_message++; *NMEA_message; NMEA_message++){ crc ^= *NMEA_message; } /* Check if it differs */ if(crc != checksum){ return ERROR_INVALID_LINE; } return OK; }
C
/* | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith */ #include <stdio.h> #include <math.h> #include "lisp.h" /************************************************************************* ** buascii : given a realatom parameter it will return an alpha atom of** ** one character corresponding to the ascii value of the number. It ** ** will not check the range except that it must be 0..255. ** *************************************************************************/ struct conscell *buascii(form) struct conscell *form; { char work[2]; long int v; work[1] = '\0'; if ((form != NULL)&&(form->cdrp == NULL)) { if (GetFix(form->carp,&v)) { if ((v >= 0L) && (v < 256L)) { *work = (char) v; return(LIST(CreateInternedAtom(work))); }; }; }; ierror("ascii"); /* doesn't return */ return NULL; /* keep compiler happy */ }
C
//damorenor + joacarrilloco #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #define REGISTER_SIZE ( (int) 1e7 ) #define NOMBRE_SIZE 32 #define TIPO_SIZE 32 #define RAZA_SIZE 16 #define TOTAL_NAMES 1716 #define TOTAL_BREEDS 13 #define HASH_SIZE 10007 #define MOD 256 struct dogType { unsigned char nombre [NOMBRE_SIZE]; unsigned char tipo [TIPO_SIZE]; int edad; unsigned char raza [RAZA_SIZE]; int estatura; float peso; unsigned char sexo; int idPrev; }; FILE *f; unsigned char ** mainNames; unsigned char ** mainBreeds; int * lastID; void initPointers(); void nameArrayGenerator(); void breedArrayGenerator(); int getHash( unsigned char * nombre ); void saveDog( void *ap ); void saveHeads(); int main() { srand( time( NULL ) ); initPointers(); nameArrayGenerator(); breedArrayGenerator(); struct dogType * perro; perro = ( struct dogType *) malloc( sizeof ( struct dogType ) ); if( perro == NULL ) { perror("error en el malloc"); exit( -1 ); } int i, hash; for( i = 0; i < REGISTER_SIZE; ++ i ) { memset( perro -> nombre, 0, sizeof ( perro -> nombre ) ); strcpy( perro -> nombre, mainNames[ rand()%TOTAL_NAMES] ); strcpy( perro -> tipo, "perro" ); perro -> edad = rand() % 18; strcpy( perro -> raza, mainBreeds[ rand()%TOTAL_BREEDS ] ); perro -> estatura = 50 + rand() % 51; perro -> peso = 10.0 + 20.0 * ( (float) rand() / RAND_MAX ); perro -> sexo = ( rand() % 2 ) ? 'H' : 'M' ; hash = getHash( perro -> nombre ); perro -> idPrev = lastID[hash]; lastID[hash] = i; saveDog( perro ); } saveHeads(); fclose( f ); return 0; } void saveHeads(){ FILE *points; int check; points = fopen("dataPointers.dat","w+"); if(points == NULL){ perror("error generando apuntadores"); exit(-1); } fwrite( lastID, HASH_SIZE * sizeof(int), 1, points ); fclose(points); } void initPointers() { f = fopen("dataDogs.dat", "w+"); if( f == NULL ) { perror("error abriendo archivo principal"); exit( -1 ); } mainNames = ( unsigned char ** ) malloc( TOTAL_NAMES * sizeof ( unsigned char * ) ); if( mainNames == NULL ) { perror("error en el malloc de mainNames"); exit(-1); } int i; for( i = 0; i < TOTAL_NAMES; ++ i ) { mainNames[i] = (unsigned char * ) malloc ( NOMBRE_SIZE * sizeof ( unsigned char ) ); if( mainNames[i] == NULL ) { perror("error en el malloc de mainNames"); exit(-1); } memset( mainNames[i], 0, NOMBRE_SIZE * sizeof ( unsigned char ) ); } mainBreeds = ( unsigned char ** ) malloc( TOTAL_BREEDS * sizeof ( unsigned char * ) ); if( mainBreeds == NULL ) { perror("error en el malloc de mainBreeds"); exit(-1); } for( i = 0; i < TOTAL_BREEDS; ++ i ) { mainBreeds[i] = (unsigned char * ) malloc ( RAZA_SIZE * sizeof ( unsigned char ) ); if( mainBreeds[i] == NULL ) { perror("error en el malloc de mainBreeds"); exit(-1); } memset( mainBreeds[i], 0, RAZA_SIZE * sizeof ( unsigned char ) ); } lastID = ( int * ) malloc ( HASH_SIZE * sizeof ( int ) ); if( lastID == NULL ) { perror("error en el malloc lastID" ); exit( -1 ); } memset( lastID, -1, HASH_SIZE * sizeof ( int ) ); } void nameArrayGenerator(){ FILE *names; names = fopen("dataNames.dat","r"); if(names == NULL){ perror("error open de dataNames"); exit(-1); } int check; unsigned char buffer[NOMBRE_SIZE]; for(int i=0;i<TOTAL_NAMES;i++){ check = fseek(names,sizeof(buffer)*i,SEEK_SET); if(check == -1){ perror("error seek dataNames"); exit(-1); } check = fread(&buffer,sizeof(buffer),1,names); if(check == 0){ perror("error lectura de dataNames"); exit(-1); } strcpy(mainNames[i], buffer); } fclose(names); } void breedArrayGenerator(){ FILE *breeds; breeds = fopen("dataBreeds.dat","r"); if(breeds == NULL){ perror("error open de dataBreeds"); exit(-1); } int check; unsigned char buffer[RAZA_SIZE]; for(int i=0;i<TOTAL_BREEDS;i++){ check = fseek(breeds,sizeof(buffer)*i,SEEK_SET); if(check == -1){ perror("error seek dataBreeds"); exit(-1); } check = fread(&buffer,sizeof(buffer),1,breeds); if(check == 0){ perror("error lectura de dataBreeds"); exit(-1); } strcpy(mainBreeds[i], buffer); } fclose(breeds); } int getHash( unsigned char * nombre ) { int hash, base, i, auxC; for( i = 0, hash = 0, base = 1; i < NOMBRE_SIZE; ++ i ) { auxC = (int) nombre[i]; if( auxC >= 'A' && auxC <= 'Z' ) auxC = 'a' + ( auxC - 'A' ); hash += auxC * base; base *= MOD; base %= HASH_SIZE; hash %= HASH_SIZE; } return hash; } void saveDog ( void *ap ) { struct dogType * dato; dato = (struct dogType *) ap; int r; r = fwrite( dato, sizeof( struct dogType ), 1, f ); if( r == 0 ) { perror("error en la escritura en el archivo principal"); exit( -1 ); } }
C
/* a. write(STDOUT_FILENO, &buff, count) This will write the contents on char buffer named 'buff' (from its index 0 to the index 'count-1') to the standard output (default; to the terminal) b. Theoretically it is possible to read and write from both ends. But if both parent and child write to the pipes at same time, the data can be corrupted. (No concurrency control in pipes) So it is recommended to use two pipes for bi-directional communication. c. unnamed pipes are implemented only to communicate between parent and child processes. The implement is not supported to pass the read or write descriptors to outside process except child of the current process. d. [Find the below code] */ #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <unistd.h> #define READ_END 0 #define WRITE_END 1 const char banner [] = "hello there\n"; int main() { int pipe_parent2child[2]; int pipe_child2parent[2]; pid_t pid; // Create a pipe to send data from the parent to child if(pipe(pipe_parent2child)){ perror("Pipe creation"); return -1; } // Create a pipe to send data from child to parent if(pipe(pipe_child2parent)){ perror("Pipe creation"); return -1; } pid = fork(); if(pid < 0){ perror("Fork"); return -1; } if(pid > 0){ /* parent : send chars read fron the stdin to child */ close(pipe_parent2child[READ_END]); close(pipe_child2parent[WRITE_END]); char buff[255]; char buff2[255]; while(1){ fgets(buff, 255, stdin); // read a line buff[strlen(buff)-1] = '\0'; // Replace new line char with line end printf("Parent writes '%s' to the pipe.\n", buff); write(pipe_parent2child[WRITE_END], buff, strlen(buff)); sleep(2); read(pipe_child2parent[READ_END], buff2, 255); printf("Child say, '%s'\n\n", buff2); } close(pipe_parent2child[WRITE_END]); close(pipe_child2parent[READ_END]); } if(pid == 0){ /* child : reads input pipe and write the capitalized chars to output pipe*/ char buffC[128]; int count; close(pipe_parent2child[WRITE_END]); close(pipe_child2parent[READ_END]); while((count = read(pipe_parent2child[READ_END], buffC, 128)) > 0) { for(int i=0;i<strlen(buffC);i++){ // Capitalize the simple alphabet letters if(buffC[i]>=97 && buffC[i]<=122)buffC[i] = toupper(buffC[i]); } write(pipe_child2parent[WRITE_END], buffC, strlen(buffC)); sleep(1); } close(pipe_parent2child[READ_END]); close(pipe_child2parent[WRITE_END]); } return 0; }
C
#include <GL/glut.h> /* 再描写時に実行される関数*/ void display(void) { /* 画面全体を指定した色で塗りつぶす */ glClear(GL_COLOR_BUFFER_BIT); /* まだ実行されていない命令をすべて実行 */ glFlush(); } int main(int argc, char **argv){ glutInit(&argc, argv); /* ウィンドウの位置とサイズを指定 */ glutInitWindowPosition(100, 100); glutInitWindowSize(400, 400); /* ウィンドウを生成 */ glutCreateWindow("test"); /* 背景色を指定: 白 */ glutInitDisplayMode(GLUT_RGBA); glClearColor(1.0, 1.0, 1.0, 1.0); /* 画面を再描写するときに実行される関数を指定 (初期化、ウィンドウサイズ変更時など) */ glutDisplayFunc(display); /* ウィンドウが閉じられるまでループ */ glutMainLoop(); return 0; }
C
#include "buttons.h" // Button states // 0 : Idle // 1 : Press :: first press // 2 : Release :: still pressed char btn_sw1_state=0, btn_sw2_state=0; void btn_onSW1ButtonDown(void); void btn_onSW2ButtonDown(void); void btn_onSW1ButtonUp(void); void btn_onSW2ButtonUp(void); /************************************************************************************ * ALL Button UP/DOWN Handlers * * ************************************************************************************/ // Interrupt handler for all button down void btn_onButtonDown(void) {/* if (GPIOIntStatus(GPIO_PORTF_BASE, false) & GPIO_PIN_4) { btn_onSW1ButtonDown(); } else if (GPIOIntStatus(GPIO_PORTF_BASE, false) & GPIO_PIN_0) { btn_onSW2ButtonDown(); }*/ if ( (GPIOIntStatus(GPIO_PORTF_BASE, false) & GPIO_PIN_4) && btn_sw1_state == 0) { btn_sw1_state = 1; TimerEnable(TIMER0_BASE, TIMER_A); } if ((GPIOIntStatus(GPIO_PORTF_BASE, false) & GPIO_PIN_0) && btn_sw2_state == 0) { btn_sw2_state = 1; TimerEnable(TIMER0_BASE, TIMER_A); } GPIOIntClear(GPIO_PORTF_BASE, GPIO_PIN_0 | GPIO_PIN_4); } // Interrupt handler for all button up void btn_onButtonUp(void) { // Disabling up interrupt /*if (GPIOIntStatus(GPIO_PORTF_BASE, false) & GPIO_PIN_4) { btn_onSW1ButtonUp(); } else if (GPIOIntStatus(GPIO_PORTF_BASE, false) & GPIO_PIN_0) { btn_onSW2ButtonUp(); }*/ } /************************************************************************************ * SW1 Button UP/DOWN Handlers * * ************************************************************************************/ /*void btn_onSW1ButtonDown(void) { GPIOIntRegister(GPIO_PORTF_BASE, btn_onButtonUp); // Register our handler function for port F GPIOIntTypeSet(GPIO_PORTF_BASE, GPIO_PIN_4, GPIO_RISING_EDGE); // Configure SW1 for rising edge trigger GPIOIntClear(GPIO_PORTF_BASE, GPIO_PIN_4); // Clear interrupt flag if (btn_sw1_state == 0) { btn_sw1_state = 1; TimerEnable(TIMER0_BASE, TIMER_A); } } void btn_onSW1ButtonUp(void) { GPIOIntRegister(GPIO_PORTF_BASE, btn_onButtonDown); // Register our handler function for port F GPIOIntTypeSet(GPIO_PORTF_BASE, GPIO_PIN_4, GPIO_FALLING_EDGE); // Configure PF4 for falling edge trigger GPIOIntClear(GPIO_PORTF_BASE, GPIO_PIN_4); // Clear interrupt flag TimerDisable(TIMER0_BASE, TIMER_A); btn_sw1_state = 0; // Reset to idle state }*/ /************************************************************************************ * SW2 Button UP/DOWN Handlers * * ************************************************************************************/ /*void btn_onSW2ButtonDown(void) { GPIOIntRegister(GPIO_PORTF_BASE, btn_onButtonUp); // Register our handler function for port F GPIOIntTypeSet(GPIO_PORTF_BASE, GPIO_PIN_0, GPIO_RISING_EDGE); // Configure PF4 for rising edge trigger GPIOIntClear(GPIO_PORTF_BASE, GPIO_PIN_0); // Clear interrupt flag if (btn_sw2_state == 0) { btn_sw2_state = 1; TimerEnable(TIMER0_BASE, TIMER_A); } } void btn_onSW2ButtonUp(void) { GPIOIntRegister(GPIO_PORTF_BASE, btn_onButtonDown); // Register our handler function for port F GPIOIntTypeSet(GPIO_PORTF_BASE, GPIO_PIN_0, GPIO_FALLING_EDGE); // Configure SW2 for falling edge trigger GPIOIntClear(GPIO_PORTF_BASE, GPIO_PIN_0); // Clear interrupt flag TimerDisable(TIMER0_BASE, TIMER_A); btn_sw2_state = 0; // Reset to idle state }*/ /************************************************************************************ * Timer Interrupt Handlers * * ************************************************************************************/ void Timer0IntHandler(void) { // Get button pressed status int32_t sw1_pin4 = !GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_4); int32_t sw2_pin0 = !GPIOPinRead(GPIO_PORTF_BASE, GPIO_PIN_0); // Clear the timer interrupt TimerIntClear(TIMER0_BASE, TIMER_TIMA_TIMEOUT); // Read the current state of the GPIO pin and // write back the opposite state if (btn_sw1_state == 1) { // If sw1 button is in state 1, i.e. if sw1 was pressed 10ms earlier if (sw1_pin4) { // If pin4 is low, i.e. if sw1 is pressed btn_sw1_state = 2; // Go in sw1 button state 2 (*btn_onSW1ButtonDownHdr)(); // Execute the registered sw1 down handler by user } else { //btn_onSW1ButtonUp(); // Reset the button state if (btn_sw2_state==0) TimerDisable(TIMER0_BASE, TIMER_A); btn_sw1_state = 0; // Reset to idle state } } else if (btn_sw1_state == 2 && !sw1_pin4) { // If button was already in state 2 and pin4 is high now i.e. button is not pressed now (*btn_onSW1ButtonUpHdr)(); // Execute button up handler //btn_onSW1ButtonUp(); if (btn_sw2_state==0) TimerDisable(TIMER0_BASE, TIMER_A); btn_sw1_state = 0; // Reset to idle state // Reset button state } if (btn_sw2_state == 1) { // If sw2 button is in state 1, i.e. if sw2 was pressed 10ms earlier if (sw2_pin0) { // If pin0 is low, i.e. if sw2 is pressed btn_sw2_state = 2; // Go in sw2 button state 2 (*btn_onSW2ButtonDownHdr)(); // Execute the registered sw2 down handler by user } else { //btn_onSW2ButtonUp(); // Reset the button state if (btn_sw1_state==0) TimerDisable(TIMER0_BASE, TIMER_A); btn_sw2_state = 0; // Reset to idle state } } else if (btn_sw2_state == 2 && !sw2_pin0) { // If button was already in state 2 and pin0 is high now i.e. button is not pressed now (*btn_onSW2ButtonUpHdr)(); // Execute button up handler //btn_onSW2ButtonUp(); // Reset button state if (btn_sw1_state==0) TimerDisable(TIMER0_BASE, TIMER_A); btn_sw2_state = 0; // Reset to idle state // Reset button state } } /************************************************************************************ * Button Initialization * * ************************************************************************************/ void btn_initialize() { SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOF); // Enable port F // // Unlock PF0 so we can change it to a GPIO input // Once we have enabled (unlocked) the commit register then re-lock it // to prevent further changes. PF0 is muxed with NMI thus a special case. // HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = GPIO_LOCK_KEY; HWREG(GPIO_PORTF_BASE + GPIO_O_CR) |= 0x01; HWREG(GPIO_PORTF_BASE + GPIO_O_LOCK) = 0; // Init PF4 and PF0 as input GPIOPinTypeGPIOInput(GPIO_PORTF_BASE, GPIO_PIN_4 | GPIO_PIN_0); // Enable weak pullup resistor for PF4 GPIOPadConfigSet(GPIO_PORTF_BASE, GPIO_PIN_4 | GPIO_PIN_0, GPIO_STRENGTH_2MA, GPIO_PIN_TYPE_STD_WPU); // Interrupt setup sw1 PF4 & sw2 PF0 GPIOIntDisable(GPIO_PORTF_BASE, GPIO_PIN_4 | GPIO_PIN_0); // Disable interrupt for PF4 & PF0 (in case it was enabled) GPIOIntClear(GPIO_PORTF_BASE, GPIO_PIN_4 | GPIO_PIN_0); // Clear pending interrupts for PF4 & PF0 GPIOIntRegister(GPIO_PORTF_BASE, btn_onButtonDown); // Register handler function for port F // Configure PF4 & PF0 for falling edge trigger GPIOIntTypeSet(GPIO_PORTF_BASE, GPIO_PIN_4 | GPIO_PIN_0, GPIO_FALLING_EDGE); GPIOIntEnable(GPIO_PORTF_BASE, GPIO_PIN_4 | GPIO_PIN_0); // Enable interrupt for PF4 & PF0 // Timer initialization SysCtlPeripheralEnable(SYSCTL_PERIPH_TIMER0); // Enable the clock on the timer0 peripheral TimerConfigure(TIMER0_BASE, TIMER_CFG_PERIODIC); // Configure Timer0A to be periodic TimerLoadSet(TIMER0_BASE, TIMER_A, (SysCtlClockGet() / 100) -1); // Set timer to 10ms, subtracting 1 to make sure the interrupt is generated on 10th ms IntEnable(INT_TIMER0A); // Enable Timer0A interrupt TimerIntEnable(TIMER0_BASE, TIMER_TIMA_TIMEOUT); // Enable Timer0A interrupt on timeout event IntMasterEnable(); // Enable master interrupts }
C
#include <stdio.h> #include <stdlib.h> int main () { int i = 5, *p; p = &i; printf(“%u %d %d %d %d \n”, p, *p+2, **&p, 3**p, **&p+4); return 0; }
C
#include <avr/io.h> #include <avr/interrupt.h> #include <avr/signal.h> unsigned int A=0; // unsigned int B=0; unsigned int C=0; unsigned int i=0; void INIT() // { PORTB=0; DDRB=0xff; PORTG=0; DDRG=0b11;// 0 1 2 3 4 5 6 7 8 9 const unsigned int buffer[9]={63,6,91,79,102,109,125,7,127,111}; PORTA=0; DDRA=0; // } void raschet() { B=A/10; Numeral(B); C=A-B; Numeral(C); } void Numeral(int temp) // 0...9 { switch (temp) { case 0: PORTB = buffer[0]; case 1: PORTB = buffer[1]; case 2: PORTB = buffer[2]; case 3: PORTB = buffer[3]; case 4: PORTB = buffer[4]; case 5: PORTB = buffer[5]; case 6: PORTB = buffer[6]; case 7: PORTB = buffer[7]; case 8: PORTB = buffer[8]; case 9: PORTB = buffer[9]; default: PORTB = buffer[0]; } } int main(void) { =i++ i=PINA; // if ((1<<PA1)&i) { A=A++ // raschet(); } return 0; }
C
#include "graph.h" //This file contains graph utility functions // create a new adjacency list node Node* newListNode(int v, int w) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->v = v; newNode->w = w; newNode->next = NULL; return newNode; } // A utility function that creates a graph of size vertices Graph* createGraph(int size) { Graph* g = (Graph*) malloc(sizeof(Graph)); g->size = size; // Create an array of adjacency lists. Size of array will be size g->array = (List*)malloc(size * sizeof(List)); // Initialize each list as empty int i=0; for (i = 0; i <= size; i++) { g->array[i].head = NULL; } return g; } // Adds edge to undirected graph void addEdge(Graph* graph, int src, int dest, int weight) { // Add an edge from src to dest. A new node is added to the adjacency Node* newNode = newListNode(dest, weight); newNode->next = graph->array[src].head; graph->array[src].head = newNode; return; } void Dijkstra(Graph* g) { int i=0, front=1, u=-1; int size = g->size; int* d = malloc(sizeof(int)* size);//current shortest distance int* Q = malloc(sizeof(int)* size);//List of unknown shortest paths (Sorry I didn't use a heap) :( Node* temp = NULL; for(i=0; i< g->size; i++)//Initialize all { d[i] = -1; Q[i] = i;//Insert all vertices into Q } d[1] = 0;//Distance from 1 to itself is 0 Q[1] = 1; while(front < (g->size)) { u = Q[front];//Extract smallest value front++; if(d[u] == -1)//Go to next loop if parent node hasn't been found yet { continue; } temp = g->array[u].head; while(temp != NULL)//For each element in the adjacency list { if(d[temp->v] == -1 || d[temp->v] > (d[u] + temp->w)) { d[temp->v] = d[u] + temp->w; } temp = temp->next; } } for(i=1; i<g->size; i++)//Print result { printf("%d %d\n", i, d[i]); } return; } void freeGraph(Graph* g) { int i=0; for(i=0; i<g->size; i++) { while(g->array[i].head != NULL) { Node* temp = g->array[i].head; g->array[i].head = g->array[i].head->next; free(temp); } } free(g->array[i].head); //free(g->array); return; }
C
#include "FIF.h" PRAGMA_FIF_OBJ PRAGMA_FIF_Initialize(PRAGMA_FIF_CONFIG config) { PRAGMA_FIF_OBJ F; F.FIF.SELF = config.FIF_MAP; F.FIF.RTR = 1; F.FIF.RTS = 0; F.FIF.DESTINATION = 0x00; F.FIF.TIP = 0; F.PRAGMA_FIF_cntMAP = config.PRAGMA_FIF_cntMAP; F.state = READY; return F; } void PRAGMA_FIF_ADD_TO_MAP(PRAGMA_FIF_OBJ F, PRAGMA_FIF_INTERFACE* module) { F.PRAGMA_FIF_MAP[F.PRAGMA_FIF_cntMAP] = module; F.PRAGMA_FIF_cntMAP++; } PRAGMA_FIF_INTERFACE* PRAGMA_FIF_Find_RTR(PRAGMA_FIF_OBJ F, PRAGMA_FIF_INTERFACE* sender) { int i; for (i = 0; i < F.PRAGMA_FIF_cntMAP; i++) { if (F.PRAGMA_FIF_MAP[i]->SELF == sender->DESTINATION) { return F.PRAGMA_FIF_MAP[i]; } } return sender; } void PRAGMA_FIF_Task(PRAGMA_FIF_OBJ F) { F.state = RUN; PRAGMA_FIF_INTERFACE* rts; PRAGMA_FIF_INTERFACE* rtr; int i; for (i = 0; i < F.PRAGMA_FIF_cntMAP; i++) { rts = F.PRAGMA_FIF_MAP[i]; //Check every module for ready to sent flag if (rts->RTS == 1) { rtr = PRAGMA_FIF_Find_RTR(F, rts); //check if the destination module is able to receive the data if (rtr != rts && rtr->RTR == 1 && rtr->TIP) { /* Clear destination.rtr transfer data and clear source.rts*/ rtr->RTR = 0; rtr->SOURCE = rts->SELF; rtr->MODULE_REGISTER = rts->MODULE_REGISTER; rts->RTS = 0; /* If trasfer is done and the sender module is in trasfer in progress. The TIP flag is cleared*/ if (rts->TIP == 1) rts->TIP = 0; } } } }
C
/* ** PERSONAL PROJECT, 2019 ** 2_pow_computer ** File description: ** 2 powers computer settings setup */ #include <stdlib.h> #include <getopt.h> #include "../include/2pow.h" #include "../include/my.h" static uint limit_slow(int slow) { if (slow > 100000000) return (0); return (slow); } static char *do_switch(char c, char *optarg, set_t **settings) { switch (c) { case ODIGITS : (*settings)->digits = adjust(optarg, my_atou(optarg)); break; case OEND : (*settings)->end = my_strdup(optarg); break; case OFIND : (*settings)->find = my_atou(optarg); break; case OSILENT : (*settings)->silent = 1; break; case OSLOW : (*settings)->slow = limit_slow(my_atou(optarg) * 1000); break; case OSTART : (*settings)->start = my_strdup(optarg); break; case OSTORE : (*settings)->store = 1; break; case OUNTIL : (*settings)->until = adjust(optarg, my_atou(optarg)); break; case '?' : my_putstr("Try './2_pow_computer --help' for more information.\n"); return (NULL); break; } return ("-"); } static void set_longopts(struct option **longopts) { (*longopts)[0].name = "digits"; (*longopts)[0].has_arg = 1; (*longopts)[0].flag = NULL; (*longopts)[0].val = ODIGITS; (*longopts)[1].name = "end"; (*longopts)[1].has_arg = 1; (*longopts)[1].flag = NULL; (*longopts)[1].val = OEND; (*longopts)[2].name = "find"; (*longopts)[2].has_arg = 1; (*longopts)[2].flag = NULL; (*longopts)[2].val = OFIND; (*longopts)[3].name = "start"; (*longopts)[3].has_arg = 1; (*longopts)[3].flag = NULL; (*longopts)[3].val = OSTART; (*longopts)[4].name = "slow"; (*longopts)[4].has_arg = 1; (*longopts)[4].flag = NULL; (*longopts)[4].val = OSLOW; (*longopts)[5].name = "until"; (*longopts)[5].has_arg = 1; (*longopts)[5].flag = NULL; (*longopts)[5].val = OUNTIL; (*longopts)[6].name = "silent"; (*longopts)[6].has_arg = 0; (*longopts)[6].flag = NULL; (*longopts)[6].val = OSILENT; (*longopts)[7].name = "store"; (*longopts)[7].has_arg = 0; (*longopts)[7].flag = NULL; (*longopts)[7].val = OSTORE; } int get_settings(int ac, char **av, set_t *settings) { struct option *longopts = malloc(sizeof(struct option) * 8); set_longopts(&longopts); for (char c = 0; c != END_OF_ARGS;) { c = getopt_long(ac, av, "d:u:E:F:S:", longopts, NULL); if (do_switch(c, optarg, &settings) == NULL) { free(longopts); freer(settings); return (FAILURE); } } free(longopts); return (SUCCESS); } set_t *setup(void) { set_t *settings = malloc(sizeof(set_t)); settings->start = NULL; settings->end = NULL; settings->find = 0; settings->digits = MAX; settings->slow = 0; settings->until = MAX; settings->silent = 0; settings->store = 0; return (settings); }
C
#include <stdio.h> int main(){ double N[12][12], sum=0; char O[2]; int i, j, n=1, m=10; scanf("%s", &O); for(i = 0; i < 12; i++) for(j=0; j < 12; j++) scanf("%lf", &N[i][j]); for(i = n; i < m; i++){ for(j = 0; j <= 5; j++){ sum += N[i][j]; } n++; m--; } if(O[0] =='S') printf("%.1lf\n", sum); else printf("%.1lf\n", sum/30.0); return 0; }
C
#include <stdio.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> /* receive udp packets * * usage: recv-udp [port] */ #define BUFSZ 200 int main(int argc, char *argv[]) { char buf[BUFSZ]; int rc, port; /********************************************************** * defaults apply unless arguments given *********************************************************/ port = (argc > 1) ? atoi(argv[1]) : 6180; /********************************************************** * create an IPv4/UDP socket, not yet bound to any address *********************************************************/ int fd = socket(AF_INET, SOCK_DGRAM, 0); if (fd == -1) { fprintf(stderr,"socket: %s\n", strerror(errno)); exit(-1); } /********************************************************** * internet socket address structure: our address and port *********************************************************/ struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = htonl(INADDR_ANY); sin.sin_port = htons(port); /********************************************************** * bind socket to address and port we'd like to receive on *********************************************************/ if (bind(fd, (struct sockaddr*)&sin, sizeof(sin)) == -1) { fprintf(stderr,"bind: %s\n", strerror(errno)); exit(-1); } /********************************************************** * uses recvfrom to get data along with client address/port *********************************************************/ do { struct sockaddr_in cin; socklen_t cin_sz = sizeof(cin); rc = recvfrom(fd, buf, BUFSZ, 0, (struct sockaddr*)&cin, &cin_sz); if (rc < 0) fprintf(stderr,"recvfrom: %s\n", strerror(errno)); else fprintf(stderr,"received %d bytes from %s:%d: %.*s\n", rc, inet_ntoa(cin.sin_addr), (int)ntohs(cin.sin_port), rc, buf); } while (rc >= 0); }
C
//#define _XOPEN_SOURCE 500 #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <sys/wait.h> #include "sh.h" #include <pthread.h> void sig_handler(int sig){ printf("\ncaught signal\n"); signal(sig, SIG_IGN); } int main(int argc, char **argv, char **envp) { signal(SIGINT, sig_handler); signal(SIGTSTP, sig_handler); signal(SIGTERM, sig_handler); char buf[MAXLINE]; char *arg[MAXARGS]; // an array of tokens char *ptr; char *pch; pid_t pid; int status, i, arg_no; char *prompt_message = ">> "; char *stat; int noclobber = 0; printf(">> "); /* print prompt (printf requires %% to print %) */ while ((stat = fgets(buf, MAXLINE, stdin)) != NULL) { if (strlen(buf) == 1 && buf[strlen(buf) - 1] == '\n') goto nextprompt; // "empty" command line if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = 0; /* replace newline with null */ // parse command line into tokens (stored in buf) arg_no = 0; pch = strtok(buf, " "); while (pch != NULL && arg_no < MAXARGS) { arg[arg_no] = pch; arg_no++; pch = strtok (NULL, " "); } arg[arg_no] = (char *) NULL; if (arg[0] == NULL) // "blank" command line goto nextprompt; /* print tokens for (i = 0; i < arg_no; i++) printf("arg[%d] = %s\n", i, arg[i]); */ else if(strcmp(arg[0], "noclobber") == 0) {// built-in command noclobbe printf("Executing built-in [noclobber]\n"); noclobber = 1 - noclobber; printf("%d\n", noclobber); } else if (strcmp(arg[0], "pwd") == 0) { // built-in command pwd printf("Executing built-in [pwd]\n"); ptr = getcwd(NULL, 0); printf("%s\n", ptr); free(ptr); } else if (strcmp(arg[0], "list") == 0) { //built-in command list printf("Executing built-in [list].\n"); if(arg[1] == NULL){ list(getcwd(NULL, 0)); } else list(arg[1]); } else if (strcmp(arg[0], "prompt") == 0) { //built-in command prompt printf("Executing built-in [prompt].\n"); if(arg[1] == NULL){ printf("Enter a prompt: "); char str[100]; fgets(str, 100, stdin); prompt_message = prompt(str); goto nextprompt; } else{ prompt_message = prompt(arg[1]); goto nextprompt; } } else if (strcmp(arg[0], "kill") == 0) { //built-in command kill printf("Executing built-in [kill]\n"); if(arg[1] == NULL){ printf("[kill] not enough arguments"); goto nextprompt; } if(arg[2] == NULL){ int p = *arg[1] - '0'; kill_s(p, SIGTERM); goto nextprompt; } else{ int p = *arg[2] - '0'; int s = *arg[1] - '0'; kill_s(p, s); goto nextprompt; } } else if (strcmp(arg[0], "pid") == 0) { //built-in command pid printf("Executing built-in [pid]\n"); printf("%ld\n",(long)getpid()); } else if (strcmp(arg[0], "exit") ==0) {//built-in command exit printf("Executing built-in [exit].\n"); exit(0); } else if (strcmp(arg[0], "printenv") == 0) { printf("Executing built-in [printenv].\n"); if(arg[1] == NULL){ printenv(); goto nextprompt; } if(arg[2] != NULL){ printf("printenv: too many arguments.\n"); goto nextprompt; } else{ printf("%s\n", getenv(arg[1])); goto nextprompt; } } else if (strcmp(arg[0], "setenv") == 0) { //built-in command setenv printf("Executing built-in [setenv].\n"); if(arg[3] != NULL){ printf("setenv: too many arguments.\n"); goto nextprompt; } else{ if(arg[1] == "PATH"){ char *p = getenv("PATH"); p = strcat(p, arg[1]); setenv_s(p, arg[2]); goto nextprompt; } if(arg[2] == NULL){ setenv_s(arg[1], ""); goto nextprompt; } else{ setenv_s(arg[1], arg[2]); goto nextprompt; } } } else if (strcmp(arg[0], "cd") == 0) { //built-in command cd printf("Executing built-in [cd].\n"); if(arg[1] == NULL){ cd(getenv("HOME")); goto nextprompt; } if(strcmp(arg[1], "-") == 0){ cd("./.."); } else{ cd(arg[1]); } } else if (strcmp(arg[0], "where") == 0) { //built-in command where if(arg[1] == NULL) { //"empty" where printf("where: Too few arguments.\n"); goto nextprompt; } if(strcmp(arg[1],"where") == 0 || strcmp(arg[1], "cd") == 0 || strcmp(arg[1], "printtenv") == 0 || strcmp(arg[1], "setenv") == 0 || strcmp(arg[1], "pid") == 0 || strcmp(arg[1], "pwd") ==0 || strcmp(arg[1], "prompt") == 0 || strcmp(arg[1], "kill") == 0 || strcmp(arg[1], "exit") == 0 || strcmp(arg[1], "list") == 0){ printf("[%s] is a built-in command.\n", arg[1]); goto nextprompt; } struct pathelement *p, *tmp; char *cmd; printf("Executing built-in [where]\n"); p = get_path(); tmp = p; cmd = where(arg[1], p); if(cmd) { printf("%s\n", cmd); free(cmd); } else{ printf("%s: Command not found\n", arg[1]); } } else if (strcmp(arg[0], "which") == 0) { // built-in command which if(strcmp(arg[1],"where") == 0 || strcmp(arg[1], "cd") == 0 || strcmp(arg[1], "printtenv") == 0 || strcmp(arg[1], "setenv") == 0 || strcmp(arg[1], "pid") == 0 || strcmp(arg[1], "pwd") ==0 || strcmp(arg[1], "prompt") == 0 || strcmp(arg[1], "kill") == 0 || strcmp(arg[1], "exit") == 0 || strcmp(arg[1], "list") == 0){ printf("[%s] is a built-in command.\n", arg[1]); goto nextprompt; } struct pathelement *p, *tmp; char *cmd; printf("Executing built-in [which]\n"); if (arg[1] == NULL) { // "empty" which printf("which: Too few arguments.\n"); goto nextprompt; } p = get_path(); cmd = which(arg[1], p); if (cmd) { printf("%s\n", cmd); free(cmd); } else // argument not found printf("%s: Command not found\n", arg[1]); while (p) { // free list of path values tmp = p; p = p->next; free(tmp->element); free(tmp); } } else if(arg[0][0] == '/' || arg[0][0] == '.') { // Checking for absolute path pid_t child; if(access(arg[0], X_OK) == 0) { if((child = fork()) > 0) { waitpid(child, NULL, 0); goto nextprompt; } else if(!child){ execve(arg[0],&arg[1], envp); } } } else { struct pathelement *p; p = get_path(); char *path; path = which(arg[0], p); if ((pid = fork()) < 0) { printf("fork error"); } else if (pid == 0) { /* child */ execve(path, &arg[0], envp); printf("couldn't execute: %s", buf); goto nextprompt; } /* parent */ if (pid){ waitpid(-1,&status,WNOHANG); goto nextprompt;} goto nextprompt; /** if (WIFEXITED(status)) S&R p. 239 printf("child terminates with (%d)\n", WEXITSTATUS(status)); **/ } nextprompt: printf("%s", prompt_message); } if(stat == NULL){ printf("^D\n"); printf("Use \"exit\" to leave shell.\n"); goto nextprompt; } exit(0); }
C
#include <stdio.h> #include <stdlib.h> /* Zad. 8. Napisz funkcj, ktra znajduje sum elementw oraz sum wartoci bezwzgldnych elementw tablicy. */ void suma(int tab[], int *sum){ int i; for (i=0; i<5; i++){ if(tab[i] <0) tab[i]*=(-1); *sum += tab[i]; } printf("suma %d", *sum); } int tab1[5] ={8, -32, 3 ,5,6}; int sum; int main() { suma(tab1, &sum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include "common.h" void create_report(int size, struct report *r) { FILE *report_file; int i = 0; report_file = fopen("report.mpi-matrix.txt", "a"); printf("\nReport of MPI performance for %d as the specified size:\n\n", r[0].size); for (i = 0; i < size; i++) { struct report lr = r[i]; printf("Algorithm: %s\n", lr.process_name); printf("\tBig O : %s\n", lr.big_o); printf("\tExecution Time : %f\n", lr.runtime); printf("\tDataset Size : %d\n", lr.size); printf("\tProcess Count : %d\n\n\n", lr.number_of_processess); // Write to the log for later analysis fprintf(report_file, "Algorithm: %s\n", lr.process_name); fprintf(report_file, "\tBig O : %s\n", lr.big_o); fprintf(report_file, "\tExecution Time : %f\n", lr.runtime); fprintf(report_file, "\tDataset Size : %d\n", lr.size); fprintf(report_file, "\tProcess Count : %d\n\n", lr.number_of_processess); } fprintf(report_file, "\n----------------------------------------------------\n"); printf("\n\nAlso see report generated in report.mpi-matrix.txt, append strategy.\n\n"); fclose(report_file); }
C
// htab_clear.c // Brief: IJC-DU2, part 2) // Date: 19.4.2020 // Author: Peter Urgoš - xurgos00, FIT VUT Brno #include "htab_internal.h" void htab_clear(htab_t * t) { for (size_t i = 0; i < htab_bucket_count(t); i++) { if (t->items[i] == NULL) { continue; } struct htab_item *item = t->items[i]; struct htab_item *temp = NULL; while (item->next != NULL) { temp = item->next; free((void *)item->key); free((void *)item); item = temp; } free((void *)item->key); free((void *)item); } }
C
#include <stdio.h> #include <math.h> int main(int argc, char** argv) { float x, y; scanf("%f %f", &x, &y); x = x * M_PI / 180; y = y * M_PI / 180; //(1-tg x)^(ctg x)+ cos(x-y). printf("%f\n", pow(1 - tan(x), (cos(x) / sin(x))) + cos(x - y)); return 0; }
C
/* El Servidor */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netinet/in.h> #include <netdb.h> #include <sys/un.h> #include <time.h> #include <sys/time.h> #include <sys/un.h> #include<unistd.h> #include <stdbool.h> //librerias para usar booleanos #include<pthread.h> #include "daemon.h" #define MAXBUF 512 // constantes a usar en el programa #define MAXNAME 10 #define MAXSZ 200 #define NUMREGIONES 16 typedef struct reg { int numhogares; int numresidentes; int numhombres; int nummujeres; }Region; typedef struct { char Rut[12]; char Nombre[40]; char tipo[40]; }ficha; //estructura ficha que almacena los datos persona ficha vector[50]; //hasta 50 personas FILE *f; //para la lectura del texto int persona_registrada = 0; char validacion[]="si"; char supervisor[1] = "s"; char censista[1] = "c"; Region regiones[NUMREGIONES]; void *connection_handler(); int sin_size, lenght; void RegistraPersona(){ //funcion que almacena los censistas o supervisores if ((f=fopen("censista.txt","r"))==NULL) { //valida la apertura del archivo printf("El fichero no se pudo abrir \n "); } else{ int i=0; while(!feof(f)) { fscanf(f,"%s %s %s",vector[i].Rut,vector[i].Nombre,vector[i].tipo); printf("%s %s %s\n",vector[i].Rut,vector[i].Nombre,vector[i].tipo); i++; persona_registrada = i; } fclose(f); } } bool Persona(char msg[MAXSZ]){ //valida que el votante esté dentro del archivo indicado printf("%s\n",msg); int j=0; for(j=0; j<persona_registrada; j++) { if(strcmp(vector[j].Rut,msg)==0) { return true; } } return false; } int main () { RegistraPersona(); void ctrlc(); //ejecuta la funcion para cerrar con control+C int sock, s, lenght, n, i, nbytes, *new_sock;; //inicializacion de socket y otros struct sockaddr_in name; //direccion del socket char msg[MAXBUF]; //buffer daemonize(); int k; for (k=0; k<NUMREGIONES; k++) { regiones[k].numhogares = 0; regiones[k].numresidentes = 0; regiones[k].numhombres = 0; regiones[k].nummujeres = 0; } signal (SIGINT,ctrlc); sock = socket(AF_INET,SOCK_STREAM,0); //conexion con el socket name.sin_family = AF_INET; name.sin_addr.s_addr = INADDR_ANY; name.sin_port = 0; bind(sock,(struct sockaddr *)&name, sizeof name); lenght = sizeof name; printf ("%d\n", getsockname(sock,(struct sockaddr *)&name, &lenght)); printf ("El puerto asociada al socket es %d\n", ntohs(name.sin_port)); char puerto[10]; sprintf(puerto, "%d", ntohs(name.sin_port)); log_message("El puerto asociada al socket es \n"); log_message(puerto); log_message("El servidor esta OK"); printf ("El servidor esta OK, Para bajarlo Presione Control C\n\n"); listen (sock, 10); //espera al cliente while(1){ s=accept(sock,0,0); //espera y acepta la conexion printf("Nuevo cliente conectado\n"); log_message("Nuevo cliente conectado\n"); pthread_t sniffer_thread; new_sock = malloc(1); *new_sock = s; if( pthread_create( &sniffer_thread , NULL , connection_handler , (void*) new_sock) < 0){ perror(" no se pudo crear el thread"); log_message("no se puedo crear el thread"); return 1; } pthread_join(sniffer_thread, NULL); }//cierre while return 0; }//cierre main void *connection_handler(void *socket_desc) { int sock = *(int*)socket_desc; int s,salida=0,numero=0,n; char msg[MAXSZ]; char respuesta[MAXSZ]; char mRut[MAXSZ]; n=recv(sock,mRut,MAXSZ,0); if(n==0){ close(sock); //// break; } log_message("Rut recibido: "); log_message(mRut); if(Persona(mRut)) { sprintf(msg,"Persona registrada\n"); n=strlen(msg)+1; send(sock,msg,MAXSZ,0); log_message(msg); } else{ sprintf(msg,"Persona NO habilitada para censar\n"); n=strlen(msg)+1; send(sock,msg,MAXSZ,0); log_message(msg); close(sock); pthread_exit(0); } n=recv(sock,msg,MAXSZ,0); // Recibe la región if(n==0){ close(s); //break; } printf("Recibido: %s\n",msg); sprintf(respuesta,"Region recibida: %s\n",msg); log_message("Region recibida: "); log_message(msg); send(sock,respuesta,MAXSZ,0); int region = atoi( msg ); //write(regionpipe[1],&region,sizeof(region)); // Escribe la región recibida en el pipe correspondiente n=recv(sock,msg,MAXSZ,0); // Recibe la cantidad de casas if(n==0){ close(s); //break; } printf("Recibido: %s\n",msg); sprintf(respuesta,"Cantidad de casas recibida: %s\n",msg); log_message("Casas recibidas: "); log_message(msg); send(sock,respuesta,MAXSZ,0); int casas = atoi(msg); //write(mypipefd[1],&casas,sizeof(casas)); // Escribe en el pipe n=recv(sock,msg,MAXSZ,0); // Recibe el numero de habitantes total de las casas a censar en esta sesión. if(n==0){ close(s); //break; } printf("Recibido: %s\n",msg); sprintf(respuesta,"Numero de habitantes recibido: %s\n",msg); log_message("Habitantes recibida: "); log_message(msg); send(sock,respuesta,MAXSZ,0); int residentes = atoi( msg ); //write(habitantesPipe[1],&residentes,sizeof(residentes)); n=recv(sock,msg,MAXSZ,0); // Recibe el numero total de hombres en los hogares a censar en esta sesión if(n==0){ close(s); //break; } printf("Recibido: %s\n",msg); sprintf(respuesta,"Numero de hombres recibido: %s\n",msg); log_message("Hombres recibida: "); log_message(msg); send(sock,respuesta,MAXSZ,0); int hombres = atoi( msg ); //write(hombresPipe[1],&hombres,sizeof(hombres)); n=recv(sock,msg,MAXSZ,0); // Recibe el numero total de mujeres en los hogares a censar en esta sesión if(n==0){ close(s); //break; } printf("Recibido: %s\n",msg); sprintf(respuesta,"Numero de mujeres recibido: %s\n",msg); log_message("Mujeres recibida: "); log_message(msg); send(sock,respuesta,MAXSZ,0); int mujeres = atoi( msg ); //write(mujeresPipe[1],&mujeres,sizeof(mujeres)); regiones[region].numhogares = regiones[region].numhogares + casas; regiones[region].numresidentes = regiones[region].numresidentes + residentes; regiones[region].numhombres = regiones[region].numhombres + hombres; regiones[region].nummujeres = regiones[region].nummujeres + mujeres; log_message("....................RESULTADOS DEL CENSO..................\n" ); int x; for(x=0;x< NUMREGIONES;x++){ if( x == 13){ x++; } log_message("Region: "); sprintf(respuesta,"%d", x); log_message(respuesta); log_message("Casas: "); sprintf(respuesta,"%d", regiones[x].numhogares); log_message(respuesta); log_message("Habitantes: "); sprintf(respuesta,"%d", regiones[x].numresidentes); log_message(respuesta); log_message("Hombres: "); sprintf(respuesta,"%d", regiones[x].numhombres); log_message(respuesta); log_message("Mujeres: "); sprintf(respuesta,"%d", regiones[x].nummujeres); log_message(respuesta); log_message("\n"); } close(sock); pthread_exit(0); return 0; } void ctrlc() { printf("\nServidor is OUT\n"); exit(0); }
C
/*C program used to keep track of the number of people entering an Art Exhibition. This program has 4 functions, One which is called when a person enters the exhibition. One which is called when a person leaves the exhibition. The ticket costs 8. Another Function should keep a track of total amount of money that has been taken and print that to the screen. The final function should report the current number of people at the exhibition.*/ #include <stdio.h> //function prototypes int Enter(); int Leave(); int Money(); void PeopleLeft(); //global variables - used throughout the program int in; int out; int main(void) { //calling functions in main in = Enter(); Money(in); out = Leave(); PeopleLeft(in, out); return 0; } int Enter(int in) { //user input printf("\nHow many people entered the exhibition? "); scanf("%d", &in); //returning the variable return in; } int Money(int in) { //variable to keep track of the total money int TotalMoney; //total is equal to 8 by the number of people (8 per person) TotalMoney = in * 8; printf("\nThe total amount of money that has been taken: %d Euro", TotalMoney); } int Leave(int out) { //user input printf("\n\nEnter the number of people that left the exhibition: "); scanf("%d", &out); return out; } void PeopleLeft(int in, int out, int totalPeople) { //total number of people = the number of people entered minus the ones that left totalPeople = in - out; printf("\nCurrent number of people at the exhibition: %d", totalPeople); }
C
#include "cp2task1headers.h" void bcvelocity(int nx, int ny, float* u, float* v){ /*Sets zero-gradient collocated BCs*/ int i,j,ij,ijw,ije,ijn,ijs; for(i=0;i<nx+2;i++){ //Bottom surface j=0; ij = i +j*(nx+2); ijn = i + (j+1)*(nx+2); u[ij] = u[ijn]; v[ij] = v[ijn]; //Top surface j = ny+1; ij = i +j*(nx+2); ijs = i + (j-1)*(nx+2); u[ij] = u[ijs]; v[ij] = v[ijs]; } for(j=0;j<ny+2;j++){ //Left surface i=0; ij = i +j*(nx+2); ije = (i+1)+ j*(nx+2); u[ij] = u[ije]; v[ij] = v[ije]; //Right surface i=nx+1; ij = i +j*(nx+2); ijw = (i-1)+ j*(nx+2); u[ij] = u[ijw]; v[ij] = v[ijw]; } } void bcphi(int nx, int ny, float* phi){ /*Sets zero-gradient collocated BCs*/ int i,j,ij,ijw,ije,ijn,ijs; for(i=0;i<nx+2;i++){ //Bottom surface j=0; ij = i +j*(nx+2); ijn = i + (j+1)*(nx+2); phi[ij] = phi[ijn]; //Top surface j = ny+1; ij = i +j*(nx+2); ijs = i + (j-1)*(nx+2); phi[ij] = phi[ijs]; } for(j=0;j<ny+2;j++){ //Left surface i=0; ij = i +j*(nx+2); ije = (i+1)+ j*(nx+2); phi[ij] = phi[ije]; //Right surface i=nx+1; ij = i +j*(nx+2); ijw = (i-1)+ j*(nx+2); phi[ij] = phi[ijw]; } }
C
int main(int argc, char* argv[]) { char s[101],pre; int i; gets(s); pre='-'; for(i=0;s[i]!='\0';i++) { if(s[i]!=' ') printf("%c",s[i]); else if(pre!=' ') printf(" "); pre=s[i]; } return 0; }
C
#ifndef __AC_KSW_H #define __AC_KSW_H struct _ksw_query_t; typedef struct _ksw_query_t ksw_query_t; typedef struct { // input unsigned gapo, gape; // the first gap costs gapo+gape unsigned T; // threshold // output int score, te, qe, score2, te2; int tb, qb; // tb and qb are only generated when calling ksw_align_16() } ksw_aux_t; #ifdef __cplusplus extern "C" { #endif /** * Initialize the query data structure * * @param size Number of bytes used to store a score; valid valures are 1 or 2 * @param qlen Length of the query sequence * @param query Query sequence * @param m Size of the alphabet * @param mat Scoring matrix in a one-dimension array * * @return Query data structure */ ksw_query_t *ksw_qinit(int size, int qlen, const uint8_t *query, int m, const int8_t *mat); // to free, simply call free() /** * Compute the maximum local score for queries initialized with ksw_qinit(1, ...) * * @param q Query data structure returned by ksw_qinit(1, ...) * @param tlen Length of the target sequence * @param target Target sequence * @param a Auxiliary data structure (see ksw.h) * * @return The maximum local score; if the returned value equals 255, the SW may not be finished */ int ksw_sse2_8(ksw_query_t *q, int tlen, const uint8_t *target, ksw_aux_t *a, int cutsc); /** Compute the maximum local score for queries initialized with ksw_qinit(2, ...) */ int ksw_sse2_16(ksw_query_t *q, int tlen, const uint8_t *target, ksw_aux_t *a); /** Unified interface for ksw_sse2_8() and ksw_sse2_16() */ int ksw_sse2(ksw_query_t *q, int tlen, const uint8_t *target, ksw_aux_t *a); int ksw_align_short(int qlen, uint8_t *query, int tlen, uint8_t *target, int m, const int8_t *mat, ksw_aux_t *a); #ifdef __cplusplus } #endif #endif
C
#include <p24F16KA102.h> #include "uart.h" void UART1Init(int BAUD){ U1BRG = BAUD; U1MODE = 0x8000; U1STA = 0x8400; IFS0bits.U1RXIF = 0; } void UART1DMXInit(int BAUD){ U1BRG = BAUD; U1MODEbits.RXINV = 0;//idle is one? U1MODEbits.BRGH = 1; //high speed mode U1MODEbits.PDSEL = 0b11;//9 bits, no parity U1MODEbits.RTSMD = 1; U1MODEbits.STSEL = 0;//one stop bit U1MODEbits.UARTEN = 1; U1MODEbits.UEN = 0; //only rx and tx pins are used U1STAbits.URXISEL = 0x00;//interrupt every char U1STA = 0x8400; IEC4bits.U1ERIE = 1; //enable error interrupt IEC0bits.U1RXIE = 1; //enable receive interrupt IFS0bits.U1RXIF = 0; } UART1GuteInit(int BAUD){ U1BRG = BAUD; U1MODEbits.RXINV = 0;//idle is one,definitely U1MODEbits.BRGH = 0; //high speed mode U1MODEbits.PDSEL = 0b00;//8 bits, no parity U1MODEbits.RTSMD = 1; U1MODEbits.STSEL = 0;//one stop bit U1MODEbits.UARTEN = 1; U1MODEbits.UEN = 0; //only rx and tx pins are used U1STAbits.URXISEL = 0x00;//interrupt every char U1STA = 0x8400; // IEC4bits.U1ERIE = 1; //enable error interrupt IPC2bits.U1RXIP = 0x02; //priority of 2.. IEC0bits.U1RXIE = 1; //enable receive interrupt IFS0bits.U1RXIF = 0; } void UART2Init(int BAUD){ U2BRG = BAUD; U2MODE = 0x8000; U2STA = 0x8400; IFS1bits.U2RXIF = 0; } void UART1PutChar(char c){ while(U1STAbits.UTXBF == 1); U1TXREG = c; } void UART2PutChar(char c){ while(U2STAbits.UTXBF == 1); U2TXREG = c; } char UART1GetChar(){ char Temp; while(IFS0bits.U1RXIF == 0); Temp = U1RXREG; IFS0bits.U1RXIF = 0; return Temp; } char UART2GetChar(){ char Temp; while(IFS1bits.U2RXIF == 0); Temp = U2RXREG; IFS1bits.U2RXIF = 0; return Temp; } void printStringConstant(const char * data){ while(*data != '\0'){ UART1PutChar(*data); data++; } }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct cmd { //char *command[8]; char command[8][256]; char in[256]; char out[256]; }x, *p = &x; void analysis_cmd(char *a) { int i = 0, j = 0, k = 0; int flag = 1; int in_i = 0, out_i = 0; int len; //p = (struct cmd *)malloc(300); while (*(a + i) != '\0') { if ((*(a + i) != ' ') && (*(a + i) != '>') && (*(a + i) != '<')) { x.command[j][k] = *(a + i); k++; if (flag == 1) { flag = 0; } } if ((*(a + i) == ' ') && (flag == 0)) { flag = 1; x.command[j][k] = '\0'; j++; k = 0; } if ((*(a + i) == '>') && (flag == 1)) { len = j; out_i = j; } if ((*(a + i) == '<') && (flag == 1)) { len = j; in_i = j; } i++; } //if (flag == 1) //{ //i = 0; //while (x.command[j][i] != ' ') //{ //i++; //} //x.command[j][k] = '\0'; //} if (in_i > 0) { strcpy(x.in, x.command[in_i]); } if (out_i > 0) { strcpy(x.out, x.command[out_i]); } printf("\ncommand: %s\n",x.command[0]); for (i = 1; i < len; i++) { printf("argument: %s\n",x.command[i]); } printf("in_file: %s\n",x.in); printf("out_file: %s\n\n",x.out); } int main(int argc, const char *argv[]) { char a[] = " ls -a "; char b[256]; strcpy(x.in, "NULL"); strcpy(x.out, "NULL"); gets(b); analysis_cmd(b); return 0; }
C
#include<stdio.h> #include<string.h> int main() { char str[60]; int l,n,flag,count=0; scanf("%d", &n); while(n--) { l=0; flag=1; fflush(stdin); gets(str); l=strlen(str); if(l%2!=0) flag=0; else { } if(flag==1) count++; } printf("%d", count); return 0; }
C
#include <WiFi.h> #include "PubSubClient.h" #include "arduino_json.h" const char* mqtt_server = "192.168.0.100"; unsigned int red = 0, green = 0, blue = 0; // the Red Green and Blue color components bool color_change = false; bool power_off = false; WiFiClient espClient; PubSubClient client(espClient); long lastMsg = 0; char msg[50]; int value = 0; void callback(char* topic, byte* message, unsigned int length) { Serial.print("Message arrived on topic: "); Serial.print(topic); Serial.println(); // Changes the LED color according to the message if (String(topic) == "lights/1") { DynamicJsonDocument doc(1024); deserializeJson(doc, message); if(doc["state"] == "on"){ power_off = false; Serial.println("Power on"); } else if(doc["state"] == "off"){ power_off = true; Serial.println("Power off"); } else{ unsigned int r = doc["color"]["r"]; unsigned int g = doc["color"]["g"]; unsigned int b = doc["color"]["b"]; Serial.print("Color change: "); Serial.print("rgb("); Serial.print(r); Serial.print(", "); Serial.print(g); Serial.print(", "); Serial.print(b); Serial.print(")"); Serial.println(); red = r; green = g; blue = b; } color_change = true; } } void watch(){ client.setServer(mqtt_server, 1883); client.setCallback(callback); client.subscribe("lights/1"); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("lights/1")) { Serial.println("connected"); // Subscribe client.subscribe("lights/1"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); // Wait 5 seconds before retrying delay(5000); } } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_itoa.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: piguerry <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/06 15:49:27 by piguerry #+# #+# */ /* Updated: 2019/11/11 18:24:43 by piguerry ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static int powerten(int nb, int pow) { if (pow == 0) return (1); if (pow == 1) return (nb); return (powerten(nb * 10, pow - 1)); } static char *niszero(void) { char *str; str = (char*)malloc(sizeof(char) * 2); str[0] = '0'; str[1] = '\0'; return (str); } static void fillstr(char *str, int len, long int n, int isneg) { int count; count = 0; if (isneg == 1) { count = 1; n = -n; } while (len >= 0) { str[count] = ((n / (powerten(10, len))) % 10) + '0'; len--; count++; } str[count] = '\0'; if (isneg == 1) str[0] = '-'; } char *ft_itoa(int n) { int isneg; char *str; int len; long int buff; if (n == 0) return (niszero()); isneg = 0; len = 0; buff = n; if (n < 0) isneg = 1; while (buff != 0) { len++; buff /= 10; } buff = n; if (!(str = (char*)malloc(sizeof(char) * (isneg + len + 1)))) return (0); len--; fillstr(str, len, buff, isneg); return (str); }
C
#include "holberton.h" /** * rot13 - function that encodes * @s: string to be encoded * * Description: function that encodes a string using rot13 * Return: an encoded string */ char *rot13(char *s) { int i, j; char ab[] = {"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"}; char ro[] = {"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"}; i = 0; while (s[i]) { j = 0; while (j < 52) { if (s[i] == ab[j]) { s[i] = ro[j]; break; } j++; } i++; } return (s); }
C
/*! Command.c Authors: Gabriela Marques and Leonardo Mizoguti Updated: 2015-10-28 */ #include "Command.h" /*! @const CMND_NEXT_STATE @abstract Table indicating to which state the automaton must go given a current state and the value of the input token. @discussion The lines in this table represent the current state, and the columns represent the value of the input token. An error transition goes to a state represented by -1. */ const SubAutomatonState CMND_NEXT_STATE[CMND_COUNT_OF_STATES][CMND_COUNT_OF_SYMBOLS] = { // "if" "while" "for" "scan" "print" "return" "endwhile" "endfor" "[" "]" "(" ")" "," ";" ":" "." int id other { 2, 3, 4, 5, 6, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , 1, 1, 1 }, // State 0 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 8, -1, -1 , -1, -1, -1 }, // State 1 { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 , 8, 8, 8 }, // State 2 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, -1, -1, -1, -1, -1 , -1, -1, -1 }, // State 3 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 18, -1, -1, -1, -1, -1 , -1, -1, -1 }, // State 4 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 15, -1, -1, -1, -1, -1 , -1, -1, -1 }, // State 5 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 9, -1, -1, -1, -1, -1 , -1, -1, -1 }, // State 6 { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 8, 1, 1 , 1, 1, 1 }, // State 7 { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 , 8, 8, 8 }, // State 8 { 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11 , 11, 11, 11 }, // State 9 { 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12 , 12, 12, 12 }, // State 10 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1 , -1, -1, -1 }, // State 11 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 13, -1, -1, -1, -1 , -1, -1, -1 }, // State 12 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 14, -1 , -1, -1, -1 }, // State 13 { 14, 14, 14, 14, 14, 14, 8, 14, 14, 14, 14, 14, 14, 14, 14, 14 , 14, 14, 14 }, // State 14 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , -1, 16, -1 }, // State 15 { -1, -1, -1, -1, -1, -1, -1, -1, 17, -1, -1, 1, 15, -1, -1, 15 , -1, 17, -1 }, // State 16 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 , 23, -1, -1 }, // State 17 { 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19, 19 , 19, 19, 19 }, // State 18 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 20, -1, -1 , -1, -1, -1 }, // State 19 { 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21 , 21, 21, 21 }, // State 20 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 22, -1, -1 , -1, -1, -1 }, // State 21 { 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24 , 24, 24, 24 }, // State 22 { -1, -1, -1, -1, -1, -1, -1, -1, -1, 16, -1, -1, -1, -1, -1, -1 , -1, -1, -1 }, // State 23 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 25, -1, -1, -1, -1 , -1, -1, -1 }, // State 24 { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, -1 , -1, -1, -1 }, // State 25 { 26, 26, 26, 26, 26, 26, 26, 8, 26, 26, 26, 26, 26, 26, 26, 26 , 26, 26, 26 } // State 26 }; /*! @const CMND_SUB_AUTOMATON_CALL @abstract Table indicating if a sub automaton should be called given the current state and the input token. @discussion The lines in this table represent the current state, and the columns represent the value of the input token. If no sub automaton is to be token, this is expressed by the value "saiNONE". If the sub automaton reaches its end, this is represented by the value "saiFSTE". */ const SubAutomatonIdentifier CMND_SUB_AUTOMATON_CALL[CMND_COUNT_OF_STATES][CMND_COUNT_OF_SYMBOLS] = { // "if" "while" "for" "scan" "print" "return" "endwhile" "endfor" "[" "]" "(" ")" "," ";" ":" "." int id other { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR }, // State 0 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 1 { saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY, saiIFBY }, // State 2 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 3 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 4 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 5 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 6 { saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiNONE, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR }, // State 7 { saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE, saiFSTE }, // State 8 { saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS, saiEXPS }, // State 9 { saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR }, // State 10 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 11 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 12 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 13 { saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiNONE, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND }, // State 14 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 15 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 16 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 17 { saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR }, // State 18 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 19 { saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR, saiEXPR }, // State 20 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 21 { saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR, saiATTR }, // State 22 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 23 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 24 { saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE, saiNONE }, // State 25 { saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiNONE, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND, saiCMND } // State 26 }; int GET_CMND_TRANSITION(SubAutomatonState currentState, Token* token, SubAutomatonState* nextState, SubAutomatonIdentifier* subAutomatonCall) { int terminalIndex = cmndOther; switch (token->type) { case tokenTypeReservedWord: switch (token->value.intValue) { case rwIf: terminalIndex = cmndIf; break; case rwWhile: terminalIndex = cmndWhile; break; case rwFor: terminalIndex = cmndFor; break; case rwScan: terminalIndex = cmndScan; break; case rwPrint: terminalIndex = cmndPrint; break; case rwReturn: terminalIndex = cmndReturn; break; case rwEndwhile: terminalIndex = cmndEndwhile; break; case rwEndfor: terminalIndex = cmndEndfor; break; default: break; } case tokenTypeSpecialSymbol: switch (token->value.charValue) { case '[': terminalIndex = cmndOpenBrackets; break; case ']': terminalIndex = cmndCloseBrackets; break; case '(': terminalIndex = cmndOpenParenthesis; break; case ')': terminalIndex = cmndCloseParenthesis; break; case ',': terminalIndex = cmndComma; break; case ';': terminalIndex = cmndSemiColon; break; case ':': terminalIndex = cmndColon; break; case '.': terminalIndex = cmndDot; break; default: break; } break; case tokenTypeNumberInteger: terminalIndex = cmndInteger; break; case tokenTypeIdentifier: terminalIndex = cmndIdentifier; break; default:break; } *nextState = CMND_NEXT_STATE[currentState][terminalIndex]; *subAutomatonCall = CMND_SUB_AUTOMATON_CALL[currentState][terminalIndex]; return terminalIndex; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> char aStack[20]; int aTop = -1; //Please implement all the functions int isEmpty (char stack[], int* pTop) { // This assignment was extremely vague and poorly defined // imma do obfusicated C challenge :D return !*stack; // pls add `inline` to fxn def } int isFull (char stack[], int* pTop) { while (stack < pTop) if (!*stack++) return 0; return 1; } //You need to throw exceptions when user try to push more char but the stack is full char push (char stack[], int* pTop, char c) { // check for error if (isFull(stack, pTop)) return 0; // full while (*stack++); // find null terminator *stack = c; // replace it w/ c return 'k'; } //You need to throw exceptions when user try to pop out more char but the stack is empty char pop (char stack[], int* pTop) { if (isEmpty(stack, pTop)) return 0; while (*stack++); // find null terminator const char r = *--stack; // copy top *stack = 0; // delete top return r; // return old top } //You need to throw exceptions when the stack is empty char top (char stack [], int* pTop) { if (isEmpty(stack, pTop)) return 0; while (*stack++); // find top+1 return *--stack; // ret top } //you need to reverse the order of the input string(size <= 20) //the implementation requires using the stack //e.g. input "Hello World", your program need to print "dlr" void reverse(char* string, int size){ // but I thought all functions use the stack? char s[size]; char c; while (c = pop(string, string + size)) if (!push(s, s + size, c)) { printf("reverse: Error: stack too small\n"); return; } for (c = 0; c < size; c++) string[c] = s[c]; } //you need to check whether the input expression's brackets is balanced //return 1:true 0:false //the implementation requires using the stack //e.g. input "(a+b)*c)" is not balanced and "((a+b)/c)" is balanced int balancedbrackets(char* string, int size){ // only checking parens char s[size]; int* e = s + size; for (unsigned i = 0; i < size; i++) if (string[i] == '(' && !push(s, e, string[i])) return 0; // string only has open parens else if (string[i] == ')' && pop(s, e) != '(') return 1; return !isEmpty(s, e); } int main () { char* string = "Hello World"; printf("The reverse of %s is ", string); reverse(string, strlen(string)); char* expression = "((a+b)/c)"; int result = balancedbrackets(expression, sizeof(expression)); printf("The expression %s is ", expression); if(result){ printf("balanced\n"); } else { printf("not balanced\n"); } return 0; }
C
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <sys/wait.h> #include <stdio.h> #include <limits.h> int main(int argc, char *argv[]) { int fd1 = open(argv[2], O_RDONLY); int fd2 = open(argv[3], O_CREAT | O_WRONLY | O_APPEND, 0660); int fd3 = open(argv[4], O_CREAT | O_WRONLY | O_TRUNC, 0660); pid_t pid = fork(); if(pid == -1) { return 0; }else if(pid > 0){ int status; wait(&status); printf("%d\n", status); }else{ if(dup2(fd1, STDIN_FILENO) == -1 || dup2(fd2, STDOUT_FILENO) == -1 || dup2(fd3, STDERR_FILENO) == -1) { _exit(42); } execlp(argv[1], argv[1], NULL); _exit(42); } close(fd1); close(fd2); close(fd3); return 0; }
C
#include<stdio.h> #include<conio.h> void main() { int i,j; clrscr(); for (i = 1,j = 10;i<10 && j>=1;i+=2, j -=2) printf(" %d %d",i,j); getch(); }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> void main(int argc,char **argv) { int i,c; char ch,s[50]; FILE *fp; if(argc!=3) { printf("Missing operand.\nUsage.: ./a.out file word\n"); return; } fp=fopen(argv[1],"r"); if(fp==0) { printf("File is not present.\n"); return; } c=0; while(fscanf(fp,"%s",s)!=-1) { if(strcmp(argv[2],s)==0) c++; } printf("\e[34m%s\e[m is \e[34m%d\e[m times present.\n",argv[2],c); }
C
/*****************************************************************/ /* Class: Computer Programming, Fall 2019 */ /* Author: 胡紹宇 */ /* ID: 108820008 */ /* Date: 2019.11.14 */ /* Purpose: Calculating numbers */ /* Change History: log the change history of the program */ /*****************************************************************/ #include<stdio.h> #define N 100 int stack[N], top=0; int trigger=0; void push(int x) { stack[top++]=x; if(top>=N) trigger=1; } void pop() { if(!top) trigger=-1; else top--; } void calc(char op) { int y=stack[top-1]; pop(); int x=stack[top-1]; pop(); int result; if(trigger==-1) return; switch(op) { case '+': result=x+y; break; case '-': result=x-y; break; case '*': result=x*y; break; case '/': result=x/y; break; } push(result); // printf("%d %c %d = %d\n",x,op,y,result); // printf("top = %d, stack[%d] = %d\n",top,top-1,stack[top-1]); } int main() { char ch; printf("Enter an RPN expression: "); while(1) { scanf("%c",&ch); if(ch==' ' || ch=='\n') continue; if(ch>='0' && ch<='9') push(ch-'0'); else if(ch=='+' || ch=='-' || ch=='*' || ch=='/') calc(ch); else if(ch=='=') { printf("Value of expression : %d\n",stack[--top]); trigger=0, top=0; printf("Enter an RPN expression: "); } else break; if(trigger==1) { printf("Expression is too complex\n"); break; } if(trigger==-1) { printf("Not enough operands in expression\n"); break; } } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_printf.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aes-salm <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/18 17:08:54 by aes-salm #+# #+# */ /* Updated: 2019/12/16 15:41:26 by aes-salm ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" static void bzero_struct(t_struct *list) { list->i = 0; list->nprint = 0; list->minus = 0; list->zero = 0; list->width = 0; list->precision = -1; } static void conversions(const char *format, t_struct *list, va_list ap) { if (format[list->i] == 'd' || format[list->i] == 'i') is_int(list, ap); else if (format[list->i] == 's') is_string(list, ap); else if (format[list->i] == 'c') is_char(list, ap); else if (format[list->i] == 'x' || format[list->i] == 'X') is_hexa(format[list->i], list, ap); else if (format[list->i] == 'p') is_pointer(list, ap); else if (format[list->i] == 'u') is_unsigned(list, ap); else is_percent(list); } static void flags_handle(const char *format, t_struct *list, va_list ap) { if (ft_strchr(FLAGS, format[list->i])) { flags_fill_in(format, list, ap); } if (ft_strchr(CONVERSIONS, format[list->i])) { conversions(format, list, ap); list->i++; } } static void format_handle(const char *format, t_struct *list, va_list ap) { while (format[list->i] != '\0') { list->minus = 0; list->zero = 0; list->precision = -1; list->width = 0; if (format[list->i] != '%') list->nprint += write(1, &format[list->i], 1); else if (format[list->i] == '%') { list->i++; if (!ft_strchr(ALLSYMBOLS, format[list->i])) break ; else { flags_handle(format, list, ap); list->i--; } } list->i++; } } int ft_printf(char *format, ...) { int format_len; t_struct *list; va_list ap; format_len = ft_strlen(format); if (!(list = (t_struct*)malloc(sizeof(t_struct)))) return (0); bzero_struct(list); va_start(ap, format); if (!format[0] || (format_len == 1 && format[0] == '%')) return (0); else format_handle(format, list, ap); va_end(ap); free(list); return (list->nprint); }
C
/* ** EPITECH PROJECT, 2018 ** PSU_2017_nmobjdump ** File description: ** stor_function */ #include <zconf.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include "server.h" #include "lib/get_next_line.h" static bool err_create_file(server_t *serv) { write_to_client(serv, "550 Failed to create file.\n"); return false; } static bool check_protocol(server_t *serv, const char *filename) { if (serv->data_mode == NONE) { write_to_client(serv, "425 Use PORT or PASV first.\n"); return false; } if (!filename) { return err_create_file(serv); } return true; } /** * Check if stor do not exceed * @param serv * @param path * @return */ static bool check_root(server_t *serv, const char *path) { char *tmp; if (!strcmp(serv->path->home, serv->path->curr)) { tmp = strdup(serv->path->home + strlen(serv->path->home) - 1); } else { tmp = strdup(serv->path->curr + strlen(serv->path->home) - 1); } strcat(tmp, path); if (!strncmp(tmp, "/..", 3)) { return false; } return true; } /** * Creation of file and fill it * @param serv * @param filename * @return */ static bool creating_file(server_t *serv, const char *filename) { FILE *fptr; char *buffer; if (directory_exists(filename) || check_root(serv, filename) == false) { return err_create_file(serv); } write_to_client(serv, "150 Opening ASCII mode data connection\n"); fptr = fopen(filename, "w"); if (!fptr) { return err_create_file(serv); } while ((buffer = get_next_line(serv->passv_fd))) { fprintf(fptr, "%s\n", buffer); free(buffer); } fclose(fptr); return true; } /** * Upload file from client to server * @param serv * @param cmd * @return */ bool stor_function(server_t *serv, char **cmd) { if (!check_protocol(serv, cmd[1])) return false; printf("Current file creating: [%s]\n", cmd[1]); if (!creating_file(serv, cmd[1])) { return false; } close(serv->passv_fd); serv->data_mode = NONE; printf("[%s] : created and filled.\n", cmd[1]); write_to_client(serv, "226 Transfer complete.\n"); return true; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strcdup_loop.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: luperez <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2015/01/31 02:01:55 by luperez #+# #+# */ /* Updated: 2015/03/14 12:57:50 by luperez ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static unsigned int count(char *str, char c) { unsigned int i; i = 0; while (str[i] && str[i] != c) i++; return (i); } void *ft_strcdup_loop(void **dst, const void *src, int c) { unsigned int i; if (!src || !(i = count((char *)src, c)) || !(*dst = ft_strnew(sizeof(char) * i))) return (NULL); i = -1; while (((unsigned char *)src)[++i]) { if (((unsigned char *)src)[i] == (unsigned char)c) return ((void *)&((char *)src)[i + 1]); ((unsigned char *)*dst)[i] = ((unsigned char *)src)[i]; } return (NULL); }
C
#include <stdarg.h> #include <stdio.h> int sum(int n, ...) { int sum = 0; va_list vl; va_start(vl, n); for (int i = 0; i < n; i++) { sum += va_arg(vl, int); } va_end(vl); return sum; } int main() { printf("%d\n", sum(3, 2, 3, 4)); return 0; }
C
#include "Z-OS.h" #include <stdlib.h> #include <string.h> Int16 TotalMemAllocs = 0; Int64 TotalMemUsage = 0; #define Word UInt16 #define WordSize sizeof(Word) #define HeapSize 5000 __attribute__ ((__far__)) Word MainHeap[HeapSize] = {0}; size_t FreeWords = HeapSize; void HeapInit(void* heap, size_t size) { memset(heap,0,size); } void* HeapAlloc(Word* heap, UInt16 heapSize, size_t allocSize) { Word *block = heap; size_t wallocSize; Word backref = -1; Word forwardref = 0; // block represents a list node // block[0] is an offset to the previous node // block[1] is an offset to the next node // Check for zero allocSize if(!allocSize) return NULL; // Align allocSize to a word boundary if(allocSize & (WordSize - 1)) allocSize = (allocSize | (WordSize - 1)) + 1; wallocSize = allocSize / WordSize + 2; EnterCriticalSection(); // Quick free space check if(wallocSize > FreeWords) { ExitCriticalSection(); return NULL; } // Iterate through the list do { // Move to the next block block += forwardref; // Back references are only needed to recombine blocks during freeing. So, free regions don't need // a back reference. Therefore, a block will be marked as free if its back reference is null. if(!block[0]) { // If this is the last block, the forward reference will be null, and the block's allocSize is just the remaining heap // length. Otherwise, the allocSize of this block is the value of the forward reference. size_t ballocSize = block[1] ? block[1] : heapSize - (block - heap); // Is free region large enough? if(ballocSize >= wallocSize) { // Allocate the block by setting the back and forward references to their new values block[0] = backref; // Since a valid block must be at least 3 words long, if the allocSize of the free fragment left after this allocation // would be less than 3, just allocate the remainder of the block to avoid unallocatable free fragments. if(ballocSize - wallocSize >= 3) { Word *freefragment = block + wallocSize; // Insert node for the remainder of the free space freefragment[0] = 0; if(block[1]) // Not the last block, inserted free fragment must have a forward reference and the proceeding block must // be updated to point back to the new free fragment as well. freefragment[1] = *(block + ballocSize) = ballocSize - wallocSize; else freefragment[1] = 0; block[1] = wallocSize; // Update free word count FreeWords -= wallocSize; } // Else, the forward reference stays the same else FreeWords -= ballocSize; // Zero the actual memory (depending on this in an allocator is bad practice, however) memset(&block[2], 0, (wallocSize - 2) * WordSize); TotalMemAllocs++; TotalMemUsage += wallocSize * WordSize; ExitCriticalSection(); return &block[2]; } } // Prepare to move to the next block in the next loop iteration backref = forwardref = block[1]; } while(forwardref); // No contiguous regions of free space were large enough to contain the allocation ExitCriticalSection(); return NULL; } void HeapFree(Word* heap, UInt16 heapSize, void* pointer) { Word *block = (Word*) pointer; // This cast is not required in C, but C++ is retarded. block -= 2; EnterCriticalSection(); // Update free word count FreeWords += block[1] ? block[1] : heapSize - (block - heap); TotalMemUsage = (heapSize - FreeWords) * WordSize; // Recombine a proceeding free region if(block[1] && !((block + block[1])[0])) { Word *nextblock = block + block[1]; // Test if the proceeding free region is the last block if(nextblock[1]) { // Since we're recombining with the proceeding free block, the block after next, which was pointing to the block // to be recombined, needs to have its back reference updated (we're removing the recombined node) *(nextblock + nextblock[1]) += block[1]; block[1] += nextblock[1]; } else block[1] = 0; } // Recombine a preceeding free region (a value of -1 for the back reference indicates that the block is allocated and that it // is the first block) if(block[0] != -1 && !((block - block[0])[0])) { Word *prevblock = block - block[0]; if(block[1]) { // This time, the proceeding block needs to have its back reference updated (we're removing the node being freed) *(block + block[1]) += prevblock[1]; prevblock[1] += block[1]; } else prevblock[1] = 0; } // Free the block else block[0] = 0; TotalMemAllocs--; ExitCriticalSection(); } // Returns the size of an allocated buffer UInt16 HeapAllocSize(Word* heap, UInt16 heapSize, void* alloc) { Word* pointer = alloc; Word index = pointer - heap; Word next = heap[index - 1]; if (next) { return next * sizeof(Word); } else { return heapSize - index * sizeof(Word); } } // Reimplementation of standard C malloc and free void* malloc(size_t size) { return HeapAlloc(MainHeap, HeapSize * sizeof(UInt16), size); } void free(void* pointer) { HeapFree(MainHeap, HeapSize * sizeof(UInt16), pointer); } // Some safe-buffer routines for the IO manager and other debug purposes void* mallocSafe(size_t size) { UInt16* ptr; if (size & 1) size++; ptr = malloc(size + 4); ptr[0] = (UInt16)ptr; ptr[(size >> 1) + 1] = ~(UInt16)ptr; return ptr + 1; } // Frees a buffer allocated using mallocSafe void freeSafe(void* ptr) { free((UInt16*)ptr - 1); } // Checks a buffer for possible corruption // true - check succeeded // false - check failed, corruption likely Bool safeCheck(void* ptr, size_t size) { UInt16* p = ptr; if ((*(p - 1) != (UInt16)(p - 1)) || (*(p + size) != ~(UInt16)(p - 1))) { return false; } return true; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define NIL -1 int test_biggest = 0; int biggest_scc = 0; int number_connections_scc = 0; int number_of_scc = 0; int visited = 0; typedef struct edge Edge; typedef struct stack Stack; typedef struct vertex Vertex; typedef struct list List; typedef struct stack_head StackHead; struct vertex { int id; int d; int low; struct edge *connect; }; struct edge { int id; struct edge *next; }; struct stack { int stack; struct vertex *vertex; }; struct stack_head { struct list* first; }; struct list { int id; struct list* next; }; void create_edge(Stack* stack, int p1, int target_id); void print_list(Stack* stack, int n); Stack* create_stack(int n); void create_vertex(Stack* stack, int id); StackHead* create_list(); void push (StackHead* stack, Stack* list, int n); int pop (StackHead* stack, Stack* list); void print_stack(StackHead* stack); void scc_tarjan(Stack *stack, StackHead *head, int number_vertices); void tarjan_visit(Stack *stack, Vertex *vertex, StackHead *head); int main() { Stack* stack; StackHead* stackhead; int n_people, n_connections, i, p1, p2; scanf("%d %d", &n_people, &n_connections); stack = create_stack(n_people); stackhead = create_list(); for( i = 0; i<n_connections; i++) { scanf("%d %d", &p1, &p2); create_edge(stack, p1, p2); } scc_tarjan(stack, stackhead, n_people); printf("%d\n%d\n%d\n", number_of_scc, biggest_scc, number_connections_scc); return 0; } void create_vertex(Stack* stack, int id) { Vertex *ptr = (Vertex*)malloc(sizeof(Vertex)); if(ptr == NULL) { exit(-1); } ptr->id = id + 1; ptr->connect = NULL; ptr->d = NIL; ptr->low = NIL; stack[id].vertex = ptr; stack[id].stack = 0; } StackHead* create_list() { StackHead *list; list = (StackHead*)malloc(sizeof(StackHead)); list->first = NULL; return list; } void push (StackHead* stack, Stack* list, int n) { List* ptr; List* curr; curr = stack->first; ptr = (List*)malloc(sizeof(List)); ptr->id = n; ptr->next = NULL; if (curr == NULL) { stack->first = ptr; } else { stack->first = ptr; ptr->next = curr; } list[n-1].stack = 1; } int pop (StackHead* stack, Stack* list) { int i; List* curr = stack->first; if (curr != NULL) { i = curr->id; stack->first = curr->next; free(curr); list[i-1].stack = 0; } else if (curr == NULL) { stack->first = NULL; i = -1; } return i; } void create_edge(Stack* stack, int p1, int target_id) { Vertex* v = stack[p1-1].vertex; Edge *curr; Edge *ptr = (Edge*)malloc(sizeof(Edge)); if(ptr == NULL) { exit(-1); } ptr->id = target_id; ptr->next = NULL; curr = v->connect; if (curr == NULL) { v->connect = ptr; } else { v->connect = ptr; ptr->next = curr; } } Stack* create_stack(int n) { Stack *stack; int i; stack = (Stack*)malloc(sizeof(Stack)*n); for (i = 0; i < n; i++) { create_vertex(stack, i); } return stack; } void print_list(Stack* stack, int n) { Vertex *ptr; Edge* ptr2; int i; for (i = 0; i < n; i++) { ptr = stack[i].vertex; if (ptr->connect != NULL) { ptr2 = ptr->connect; for( ; ptr2 != NULL; ptr2 = ptr2->next) { printf("v:[%d] liga a [%d]\n", ptr->id, ptr2->id); } } } } void print_stack(StackHead* stack) { List* ptr = stack->first; printf("stack: -"); while(ptr != NULL) { printf("-[%d]-", ptr->id); ptr = ptr->next; } printf("-\n"); } void scc_tarjan(Stack *stack, StackHead *head, int number_vertices) { int index; Vertex *curr; for(index = 0; index < number_vertices; index++) { curr = stack[index].vertex; if(curr->d == NIL) { tarjan_visit(stack, curr, head); } } } void tarjan_visit(Stack *stack, Vertex *vertex, StackHead *head) { int i; Edge* aux; Vertex* curr; vertex->d = visited; vertex->low = visited; visited++; push(head, stack, vertex->id); aux = vertex->connect; while(1) { if (aux == NULL) { break; } curr = stack[((aux->id)-1)].vertex; if (curr->d == NIL) { tarjan_visit(stack, curr, head); if (vertex->low > curr->low) { vertex->low = curr->low; } } else if (stack[((curr->id)-1)].stack == 1) { if (vertex->low > curr->d) { vertex->low = curr->d; } } aux = aux->next; } if (vertex->low == vertex->d) { i = pop (head, stack); if (i != -1) { if (i != vertex->id) { while(1) { test_biggest++; i = pop (head, stack); if (i == vertex->id) { test_biggest++; if ((head->first != NULL && stack[i-1].vertex->connect == NULL) || head->first == NULL) { number_connections_scc++; } break; } if (i == -1) { test_biggest++; number_connections_scc++; break; } } } else { if ((head->first != NULL && ((stack[i-1].vertex->connect == NULL) || (stack[i-1].vertex->connect->id == i))) || (head->first == NULL && stack[i-1].vertex->connect == NULL)) { number_connections_scc++; } test_biggest++; } } else { number_connections_scc++; test_biggest++; } number_of_scc++; if (test_biggest > biggest_scc) { biggest_scc = test_biggest; } test_biggest = 0; } }
C
/* ** nbr.c for nbr in /root/rendu/CPE_2014_corewar/asm ** ** Made by ** Login <[email protected]> ** ** Started on Sun Aug 10 12:08:01 2014 ** Last update Sun Aug 24 21:29:05 2014 chenev_d chenev_d */ #include "utils.h" static void _check_nbr(const char *str) { int i; i = (str[0] == '-') ? 0 : -1; if (str[0] == '-' && str[i] == '\0') { my_write(2, "error: '", my_strlen("error: '")); my_write(2, str, my_strlen(str)); my_puterror("' is not valid number !\n"); } while (str[++i]) { if (str[i] < '0' || str[i] > '9') { my_write(2, "error: '", my_strlen("error: '")); my_write(2, str, my_strlen(str)); my_puterror("' is not valid number !\n"); } } } /* ** brief: Like ATOI ** @str: we will convert this string to an integer ** return: it will return the new integer */ int my_getnbr(const char *str) { int i; int nbr; _check_nbr(str); i = (str[0] == '-') ? 0 : -1; nbr = 0; if (str[0] == '-') { while (str[++i] && nbr <= 0) nbr = nbr * 10 + (str[i] - '0'); } else { while (str[++i] && nbr >= 0) nbr = nbr * 10 + (str[i] - '0'); } return (nbr); } /* ** brief: print a number (positif) into a fd ** @nbr: our number ** @fd: our file descriptor */ void my_putnbr(int nbr, const int fd) { if (nbr < 10) my_putchar(fd, nbr + '0'); else { my_putnbr(nbr / 10, fd); my_putchar(fd, (nbr % 10) + '0'); } }
C
/* Write a C program that reads the hours an employee worked in a week, computes the gross pay and income tax, and prints the gross pay, income tax and net pay on the screen. Assume that the pay structure and tax rate are given as follows: (1) the basic pay rate is $6.00 per hour; (2) the over-time pay rate (in excess of 40 hours) is one and a half time of the basic pay rate; and (3) the tax rate is 10\% of the first $1000 of the gross pay, 20\% of the next $500 and 30% of the rest. Sample input and output sessions are given below: (1) Test Case 1: Enter hours of work: 37 Gross pay = 222.00 Tax = 22.20 Net pay = 199.80 (2) Test Case 2: Enter hours of work: 50 Gross pay = 330.00 Tax = 33.00 Net pay = 297.00 */ #include <stdio.h> int main() { int hours; float tax, grossPay, netPay; printf("Enter hours of work: \n"); scanf("%d", &hours); if(hours < 0) return 0; //gross pay if(hours<=40) grossPay = 6.00 * hours; else { grossPay = 6.00*40 + (hours-40)*6.00*1.5; } //tax if(grossPay <= 1000) tax = grossPay * 0.1; else if(grossPay > 1000 && grossPay <= 1500) tax = (grossPay-1000)*0.2 + 1000*0.1; else tax = (grossPay-1500)*0.3 + 1000*0.1 + 500*0.2; //net pay netPay = grossPay - tax; printf("Gross pay = %.2f\n", grossPay); printf("Tax = %.2f\n", tax); printf("Net pay = %.2f\n", netPay); return 0; }
C
int minlen(char** strs, int strsSize){ int i,j,len=0,min=99999999; for(i=0;i<strsSize;i++){ if(strs[i]==NULL) return 0; len=0; for(j=0;strs[i][j]!='\0';j++){ len++; } if(len<min) min=len; } return len; } char* longestCommonPrefix(char** strs, int strsSize) { int i,len=0,mark,j=0,min; char *s,c; min=minlen(strs,strsSize); while(j<min){ c=strs[0][j]; mark=1; for(i=1;i<strsSize;i++){ if(strs[i][j]!=c){ mark=0; break; } } if(mark==1) {len++;j++;} else break; } s=(char *)malloc((len+1)*sizeof(char)); for(j=0;j<len;j++) s[j]=strs[0][j]; s[j]='\0'; return s; }
C
#include<stdio.h> #include<stdlib.h> main () { float f,c,pol,mm; printf("Escreva a temperatura: \n"); scanf("%f",&f); c=(5*f-160)/9; printf("%f\n",c); printf("Escreva a quantidade de chuva: \n"); scanf("%f",&pol); mm=pol*25.4; printf("%f\n",mm); system("PAUSE"); }
C
#ifndef CHAPTER03_LINKED_QUEUE_H #define CHAPTER03_LINKED_QUEUE_H typedef char ElemType; // 链队数据结点类型 typedef struct QNode { ElemType data; // 下一结点指针 struct QNode *next; } DataNode; // 链队结点类型 typedef struct { // 指向队首结点 DataNode *front; DataNode *rear; } LinkQuNode; /** * 初始化链队 * @param queue */ void InitQueue(LinkQuNode *&queue); /** * 销毁链队 */ void DestroyQueue(LinkQuNode *&queue); /** * 判断队列是否为空 */ bool QueueEmpty(LinkQuNode *queue); /** * 元素e进队 * @param queue * @param e */ void enQueue(LinkQuNode *&queue, ElemType e); /** * 出队 * @param queue * @param e * @return */ bool deQueue(LinkQuNode *&queue, ElemType &e); #endif //CHAPTER03_LINKED_QUEUE_H
C
#include<stdio.h> int main() { long long int a; scanf("%I64d",&a); if(a%2==0 && a!=2) printf("YES"); else printf("NO"); return 0; }
C
/** * Samuel Sweet * CS 5600-1 Assignment 5 * * Represents useful information about * an object that a ray has hit. */ #ifndef HITDATA_H #define HITDATA_H #include "vector.h" #include "material.h" typedef struct _HitData { Vector3D surfaceNormal; Vector3D intersectPoint; Material material; float intersectT; } HitData; inline void initHitData(HitData* data, Vector3D surfaceNormal, Vector3D intersectPoint, Material material, float t) { copyVector3D(&surfaceNormal, &data->surfaceNormal); copyVector3D(&intersectPoint, &data->intersectPoint); copyMaterial(&material, &data->material); data->intersectT = t; } #endif
C
#include "aluno.h" #define SUCCESS 0 #define INVALID_NULL_POINTER -1 #define OUT_OF_MEMORY -2 #define OUT_OF_RANGE -3 #define ELEM_NOT_FOUND -4 #define INVALID_POS -5 typedef struct list List; List *list_create(); //Cria a Lista int list_free(List *li); //Libera a lista int list_push_front(List *li, Aluno al); //Insere no inicio da lista int list_push_back(List *li, Aluno al); //Insere no final da lista int list_insert(List *li, Aluno al, int pos); //Insere na lista dada uma posição int list_pop_front(List *li); //Remove o primeiro elemento da lista int list_pop_back(List *li); //Remove o ultimo elemento da lista int list_erase_pos(List *li, int pos); //Remove um elemento dado a sua posição int list_erase_data(List *li, int nmat); //Remove um aluno dado a sua matricula int list_front(List *li, Aluno *al); //Retorna o primeiro elemento da lista int list_back(List *li, Aluno *al); //Retorna o ultimo elemento da lista int list_find_pos(List *li, int pos, Aluno *al); //Retorna um aluno dada a sua posição int list_find_mat(List *li, int nmat, Aluno *al); //Retorna um aluno dado o seu numero de matricula int list_get_pos(List *li, int nmat, int *pos); //Dado um número de matrícula, retornar a posição a lista int list_size(List *li); int list_empty(List *li); //Retorna 1 se a lista está vazia, e 0 caso o contrário! //Fazendo o cálculo do tamanho da lista sem utilizar a variável li->size, da estrutura da lista int list_size_alternative(List *li); void list_print(List *li); //Printa a lista, apenas para testes /* Função exigida no exercicio 2 da prática, função que retornará sempre o próximo elemento. Por exemplo, se a lista não foi percorrida ainda, o próximo elemento é a cabeça. */ int list_next_elem(List *li, Aluno *al);
C
#include <stdio.h> #include <string.h> struct student { char name[30]; char id[10]; int age; char course[30]; } student1; void main() { // struct student student1; // struct student student1 = {"Vic", "123456", 25, "CS"}; struct student s[10]; // Declaring the variables manually // strcpy(student1.name, "Vic"); // strcpy(student1.id, "123456"); // student1.age=26; // strcpy(student1.course, "Computer Science"); // Declaring the variables using scanf for one student. // printf("\nEnter the name of the student\n"); // scanf("%s", student1.name); // printf("\nEnter the id of the student\n"); // scanf("%s", student1.id); // printf("\nEnter the age of the student\n"); // scanf("%d", &student1.age); // printf("\nEnter the course of the student\n"); // scanf("%s", student1.course); // printf("\n\nThe student %s of ID %s and age %d is persuing %s\n\n", student1.name, student1.id, student1.age, student1.course); for (int i = 0; i < 10; i++ ) { printf("\nEnter the name of the student %d\n", i+1); scanf("%[^\n]s", s[i].name); printf("\nEnter the id of the student %d\n", i+1); scanf("%s", s[i].id); printf("\nEnter the age of the student %d\n", i+1); scanf("%d", &s[i].age); printf("\nEnter the course of the student %d\n", i+1); scanf("%[^\n]s", s[i].course); printf("\n\nThe student %s of ID %s and age %d is persuing %s\n\n", s[i].name, s[i].id, s[i].age, s[i].course); } }
C
#include<stdio.h> int n; char s[6000]; int min(int a,int b) { return a>b?b:a; } int isPallin(int i,int j) { int k,l; for(k=i,l=j;k<j;k++,l--) if(s[i]!=s[j]) return 0; return 1; } int calc(int i,int j) { if(i>j||i==n||j==n) return 0; if(isPallin(i,j)){ printf("%d %d\n",i,j); return 1; } return min(calc(i,j+1),calc(i+1,j)+1); } int main() { int t,i; scanf("%d",&t); while(t--) { scanf("%d",&n); scanf("%s",s); printf("%d\n",calc(0,1)); } return 0; }
C
/* ** Warning: for big pattern length, libgmp will be required to handle >64bits integers */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define REHASH(a,b,h) ((((h) - (a)*d) << 1) + b) int rabin_karp(char *text, char *pattern) { unsigned int tsize, psize; int ht, hp; int i, d; tsize = strlen(text); psize = strlen(pattern); for (d = i = 1; i < psize; i++) d <<= 1; for (ht = hp = i = 0; i < psize; i++) { hp = (hp << 1) + pattern[i]; ht = (ht << 1) + text[i]; } for (i = 0; i <= tsize - psize; i++) { if (ht == hp) if (!memcmp(pattern, text + i, psize)) return i; ht = REHASH(text[i], text[i + psize], ht); } return -1; } int main(int argc, char *argv[]) { int res; res = rabin_karp("stupid_spring_string", "string"); printf("Res=%d\n", res); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_lserror.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msoudan <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/01/21 15:36:01 by msoudan #+# #+# */ /* Updated: 2016/06/08 17:26:04 by msoudan ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ls.h" void delete_elem(t_list **dir, t_list **tmp, t_list **prev) { t_list *del; if ((del = *tmp) == *dir) *dir = (*dir)->next; *tmp = (*tmp)->next; if (*prev != NULL) (*prev)->next = *tmp; if (del->content != NULL) { free(del->content); del->content = NULL; } free(del); del = NULL; } int ft_printerror_option(char error) { char *str; str = "usage: ls [-ABCFGHLOPRSTUWabcdefghiklmnopqrstuwx1] [file ...]"; ft_putstr_fd("ft_ls: illegal option -- ", STDERR_FILENO); ft_putchar_fd(error, STDERR_FILENO); ft_putchar_fd('\n', STDERR_FILENO); ft_putendl_fd(str, STDERR_FILENO); return (-1); } int ft_lserrorlist(t_list **dir) { t_list *tmp; t_list *prev; struct stat buf; if ((tmp = *dir) != NULL) { prev = NULL; while (tmp != NULL) { if (lstat((char *)tmp->content, &buf) == -1) { ft_lserror((char *)tmp->content); delete_elem(dir, &tmp, &prev); } else { prev = tmp; tmp = tmp->next; } } return (0); } return (-1); } void *ft_lserrornull(char *name) { ft_putstr_fd("ls: ", STDERR_FILENO); perror(name); return (NULL); } int ft_lserror(char *name) { ft_putstr_fd("ls: ", STDERR_FILENO); perror(name); return (-1); }
C
#include <stdio.h> void main() { int array[10] = {785, 428, 612, 812, 307, 19, 723, 1024, 305, 492}; int i; for(i = 9;i>= 0;i--) printf("%d ", array[i]); }
C
#include<stdio.h> #define NAME_LEN 64 struct student { char name[NAME_LEN]; int height; float weight; long schools; }; int main(void) { struct student takao = {}; printf("请输入姓名为:"); scanf("%s", &takao.name); printf("请输入身高为:"); scanf("%d", &takao.height); printf("请输入体重为:"); scanf("%f", &takao.weight); printf("请输入奖学金为:"); scanf("%ld", &takao.schools); printf("姓名 = %s\n", takao.name); printf("身高 = %d\n", takao.height); printf("体重 = %.1f\n", takao.weight); printf("奖学金 = %ld\n", takao.schools); return 0; }
C
/* * items.c * * Created on: Sep 26, 2020 * Author: eddie */ #include "items.h" #include <stdlib.h> #include <stdio.h> #include <string.h> /** * Takes in name and description strings and a pointer to item to link to * Creates items with given data and returns pointer to item */ struct Item * items(char* name, char* desc, struct Item *next){ // Allocating memory for Item being created struct Item *temp = (struct Item *) malloc(sizeof(struct Item)); // Case where malloc fails if (temp == NULL){ // Print message for exact location/item being created when malloc failed printf("MALLOC FAILED\n"); printf("Location: items()\nName: %s\nDesc: %s\n", name, desc); exit(-1); } // Malloc succeeded; defining data for new Item temp->name = name; temp->desc = desc; temp->next = next; return temp; } /** * Creates dummy item designed to be the first item of an item linked list * Returns pointer to dummy item * Params are: * name: "dummy" * desc: "dummy" * next: "NULL" */ struct Item *dummyItem(void){ // Allocating memory for Item being created struct Item *temp = (struct Item *)malloc(sizeof(struct Item)); // Case where malloc fails if (temp == NULL){ // Print message for exact location/item being created when malloc failed printf("MALLOC FAILED\n"); printf("Location: Dummy Item Creation\n"); exit(0); } // Malloc success; defining data for new item temp->name = "dummy"; temp->desc = "dummy"; temp->next = NULL; return temp; } /** * Function that takes in an item and returns the name of the item * Returns NULL if item is null */ char* item_name(struct Item *item){ if (item == NULL){ return NULL; } return item->name; } /** * Function that takes in an item and returns the description of the item * Returns NULL if item is null */ char* item_desc(struct Item *item){ if (item == NULL){ return NULL; } return item->desc; } /** * Function that takes in an item and returns the next item * Returns NULL if item is null */ struct Item* item_next(struct Item *item){ if (item == NULL){ return NULL; } return item->next; } /** * Function to set the name data of an item */ void item_setName(struct Item *item, char* name){ // Does not function if item is null if (item != NULL){ item->name = name; } } /** * Function to set the desc data of an item */ void item_setDesc(struct Item *item, char* desc){ // Does not function if item is null if (item != NULL){ item->desc = desc; } } /** * Function to set the next data of an item */ void item_setNext(struct Item *item, struct Item *next){ // Does not function if item is null if (item != NULL){ item->next = next; } } /** * Function that takes in an item and name of item to search for * Returns pointer to item with given name if found * If not found, returns NULL * Needs to be used with item linked list where the first item is a dummy item */ struct Item* item_take(struct Item *item, char* name){ if (item == NULL){ return NULL; } // Variable used for current item in loop struct Item *currItem = item; // Variable used for next item in loop struct Item *nextItem = item_next(currItem); // Goes through item linked list until there is no next item while (nextItem != NULL){ // Checking for if next item is the item function is looking for if (strcmp(item_name(nextItem), name) == 0){ // Removing nextItem from linked list and linking curr item with nextItem's next item item_setNext(currItem, item_next(nextItem)); // Removing nextItem's link to the list item_setNext(nextItem, NULL); return nextItem; } // Iterating through linked list of item currItem = nextItem; nextItem = item_next(currItem); } // Item name not found return NULL; } /** * Function that adds given item to a given item list * Takes in pointers to item list, and item to add to that item list * * HOW TO USE * * When adding items to BACKPACK from ROOM: * item_take(item from room), and then item_add(backpack, pointer from item_take) * * When adding items to ROOM from BACKPACK: * item_take(item from backpack), and then item_add(room, pointer from item_take) */ void item_add(struct Item *list, struct Item *toAdd){ // Only adds when list is not null if (list != NULL){ // Variable used for current item in loop struct Item *currItem = list; // Variable used for next item in loop struct Item *nextItem = item_next(list); // Iterates until nextItem is NULL, aka reaching end of linkedlist while (nextItem != NULL){ currItem = nextItem; nextItem = item_next(currItem); } // Adding item toAdd to the end of the list item_setNext(currItem, toAdd); } } /** * Iterates through linkedList of this item to see if item find is in there * Returns 0 if false, 1 if true */ int item_has(struct Item *list, char* name){ if (list != NULL && name != NULL){ // Variable used for current item in loop struct Item *currItem = list; // Variable used for next item in loop struct Item *nextItem = item_next(list); while (nextItem != NULL){ if (strcmp(item_name(nextItem), name) == 0){ return 1; } currItem = nextItem; nextItem = item_next(currItem); } } return 0; } /** * Function that takes in a pointer to an Item struct * Prints out all the items linked to the Item given */ void item_print(struct Item *list){ struct Item *currItem = list; struct Item *nextItem = item_next(currItem); if (nextItem == NULL){ printf("No items\n"); } else { while (nextItem != NULL){ printf("%s\n", item_name(nextItem)); currItem = nextItem; nextItem = item_next(currItem); } } }
C
/*PMSat -- Copyright (c) 2006-2007, Lus Gil Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ #include "Statistics.h" /*to measure the used time since the begining of the program fills the parameters with user time and system time. */ void Statistics::getTime(double & dest){ struct rusage resources; // used resources getrusage(RUSAGE_SELF, &resources); dest = (double) resources.ru_utime.tv_sec + 1.e-6 * (double) resources.ru_utime.tv_usec + (double) resources.ru_stime.tv_sec + 1.e-6 * (double) resources.ru_stime.tv_usec; } /*sets the number of cpus and initializes the stats data structure*/ void Statistics::setCPUS(int n){ int i; nWorkers = n-1 ; stats.growTo(n); for(i = 0; i < stats.size(); i++) { stats[i].masterTime = 0; stats[i].workerTime = 0; stats[i].nSolveCalls = 0; stats[i].sentDB = 0; stats[i].receivedDB = 0; } } /* increases the number of erased assmptions */ void Statistics::increaseErased(int n){ erasedAssumps += n; } /*To start measure the time. To be called just before a send, receive or solve().*/ void Statistics::startMeasure(){ getTime(init); } /*to finish one measure*/ double Statistics::finishMeasure(){ getTime(end); return end - init; } /*----- functions that call the finishMeasure method, to be used with the startMeasure -----*/ void Statistics::finishMeasureInit(){ initializationTime = finishMeasure(); } void Statistics::finishMeasureFinal(){ finalizationTime = finishMeasure(); } /* ------------------------------------------------------ */ /*to measure the idle time of workers*/ void Statistics::startMeasureMasterTime(){ getTime(initMaster); } /*increases the idle time of a given worker*/ void Statistics::finishMeasureMasterTime(int worker){ getTime(endMaster); stats[worker].masterTime += endMaster - initMaster; } /*sets the cpu time of a given worker */ void Statistics::incCpuTime(int worker, double newTime){ stats[worker].workerTime += newTime; stats[worker].nSolveCalls++; } /* increases the number of databases (with learnt clauses) received from the master*/ void Statistics::increaseReceived(int worker){ stats[worker].receivedDB++; } /* increases the number of databases (with learnt clauses) sent by the worker*/ void Statistics::increaseSent(int worker){ stats[worker].sentDB++; } /*to measure the wall time*/ void Statistics::startMeasureWallTime(){ struct timeval tp; gettimeofday(&tp, NULL); wall0 = (double)tp.tv_sec+(1.e-6)*tp.tv_usec; } void Statistics::finishMeasureWallTime(){ struct timeval tp; gettimeofday(&tp, NULL); wall1 = (double)tp.tv_sec+(1.e-6)*tp.tv_usec; } /*calculates the total time spent by the computation*/ double Statistics::calcTotalTime(bool parallel){ int i; double total = initializationTime + finalizationTime, max = 0; if(!parallel) { total += stats[0].workerTime; } else{ //lets calculate the maximum of the execution times of the workers. for(i = 1; i < stats.size(); i++){ if( max < (stats[i].workerTime + stats[i].masterTime) ) max = stats[i].workerTime + stats[i].masterTime; } total += max; } return total; } /*writes all the times to a file, or just one if it runs on local mode */ int Statistics::write2file(bool parallel, char * fileName, Options & opts){ FILE * res; int i; res = fopen(fileName, "wb"); if(res == NULL) return -1; fprintf(res,"Master initialization time: %f secs\n\n",initializationTime); if(parallel){ fprintf(res,"Workers: %d\nVariables to be assumed: %d\n",nWorkers,opts.nVars); fprintf(res,"Search mode: %c\nVariable's selection mode: %c\n",opts.searchMode,opts.varChoiceMode); if(opts.conflicts) fprintf(res,"Erased assumptions: %d\n",erasedAssumps); if(opts.shareLearnts) { fprintf(res, "Learnt max amount: %d\nLearnts max size: %d\n", opts.maxLearnts, opts.learntsMaxSize); } if(opts.removeLearnts) fprintf(res, "All learnts were removed after each solve() call.\n"); for(i = 1; i < stats.size(); i++){ fprintf(res,"\nWorker %d:\nsolve() was executed %d times\nTotal time spent by worker: %lf secs\n",i,stats[i].nSolveCalls,stats[i].workerTime); fprintf(res,"Total time spent by master with this worker: %lf secs\n",stats[i].masterTime); if(opts.shareLearnts) fprintf(res,"Databases received: %d\nDatabases sent: %d\n",stats[i].receivedDB, stats[i].sentDB); } } else{ fprintf(res,"Solve time: %lf secs\n",stats[0].workerTime); } fprintf(res,"\nMaster finalization time: %lf secs\n",finalizationTime); fprintf(res,"\nTotal CPU time: %lf secs\n",calcTotalTime(parallel)); fprintf(res,"\nTotal wall time: %lf secs\n",wall1-wall0); fclose(res); return 0; } /*writes a xml file with the statistics*/ int Statistics::write2xml(bool parallel, char * fileName, Options & opts){ FILE * res; int i; res = fopen(fileName, "wb"); if(res == NULL) return -1; fprintf(res, "<Statistics>\n"); fprintf(res, "<InitializationTime>\n %f \n</InitializationTime>\n", initializationTime); if(parallel){ fprintf(res, "<NumberOfWorkers>\n %d \n</NumberOfWorkers>\n",nWorkers); fprintf(res, "<NumberOfVariables>\n %d\n </NumberOfVariables>\n",opts.nVars); fprintf(res, "<SearchMode>\n %c \n</SearchMode>\n",opts.searchMode); if(opts.conflicts) fprintf(res, "<ErasedAssumptions>\n %d \n</ErasedAssumptions>\n",erasedAssumps); fprintf(res,"<RemoveLearnts>\n %s\n</RemoveLearnts>\n",opts.removeLearnts ? "true": "false" ); for(i = 1; i < stats.size(); i++){ fprintf(res,"<Runtime worker=\"%d\">\n",i); fprintf(res,"<NumberOfExecutions>\n %d \n</NumberOfExecutions>\n",stats[i].nSolveCalls); fprintf(res,"<MasterTime>\n %f \n</MasterTime>\n",stats[i].masterTime); fprintf(res,"<WorkerTime>\n %f \n</WorkerTime>\n",stats[i].workerTime); if(opts.shareLearnts){ fprintf(res,"<DBSent>\n %d\n</DBSent>\n",stats[i].sentDB); fprintf(res,"<DBReceived>\n %d\n</DBReceived>\n",stats[i].receivedDB); } fprintf(res,"</Runtime>\n"); } } else{ fprintf(res,"<RunTime>\n %lf \n</RunTime>\n",stats[0].workerTime); } fprintf(res,"<FinalizationTime>\n %f \n</FinalizationTime>\n",finalizationTime); fprintf(res, "<MaxTime>\n %f \n</MaxTime>\n",calcTotalTime(parallel)); fprintf(res, "<WallTime>\n %f \n</WallTime>\n",wall1-wall0); fprintf(res, "</Statistics>\n"); fclose(res); return 0; }
C
#include<stdio.h> #include<conio.h> int a[15],i,ptr,t,j,n; void main() { clrscr(); printf("\nEnter no. of array elements"); scanf("%d",&n); printf("\nEnter array elements"); for(i=1;i<=n;i++) { printf("\nEnter %d element",i); scanf("%d",&a[i]); } for(i=1;i<=n-1;i++) { ptr=1; while(ptr<=n-i) { if(a[ptr]>a[ptr+1]) { t=a[ptr]; a[ptr]=a[ptr+1]; a[ptr+1]=t; } ptr++; } for(j=1;j<=n;j++) { printf("%d\t",a[j]); } printf("\n"); } printf("\nThe sorted array elements are"); for(i=1;i<=n;i++) { printf("%d\t",a[i]); } getch(); }
C
//Whatever you are trying to return from dequeue function to show it as an error should not be a member of queue. //We are going to use circular representation of an array in order to use the free spaces available in queue. //Even though the size of array is max we will use it as if it is max-1 queue and leave a blank space because of the fact that it is circular array and to distinguish between one side is begining and other side ending. #include<stdio.h> #define max 10 int front=-1,rear=-1; int queue[max]; void enqueue(int item){ rear=(rear+1)%max; if(front==rear){ printf("Queue is full\n"); if(rear==0) rear=max-1; else rear=rear-1; return; } else{ queue[rear]=item; return; } } int dequeue(){ if(front==rear){ printf("Queue is empty\n"); return -1; } else{ front=(front+1)%max; int item=queue[front]; return item; } } int main(){ int i,ele; printf("Enter the slno for the corresponding operation\n"); while(1){ printf("1:Enqueue\n2:Dequeue\n3:Exit\nEnter the operation value::"); scanf("%d",&i); if(i==1){ printf("Enter the element to be enqueued into the queue::"); scanf("%d",&ele); enqueue(ele); } else if(i==2) printf("The dequeud element is::%d\n",dequeue()); else if(i==3) break; else printf("Invalid Input\n"); } return 0; }
C
#include "ush.h" static t_list *get_process_by_cmd(char *arg, t_list *processes) { t_list *ret_process = NULL; unsigned int count_processes = 0; t_process *tmp = NULL; while (processes) { tmp = (t_process*)processes->data; if (!mx_get_substr_index(tmp->cmd, arg)) { count_processes++; ret_process = processes; } processes = processes->next; } if (count_processes == 1) return ret_process; else if (count_processes > 1) fprintf(stderr, "fg: %s: ambiguous job spec\n", arg); else if (!count_processes) fprintf(stderr, "fg: %s: no such job\n", arg); return NULL; } static t_list *get_process_by_id(char *arg, t_list *processes) { int cur_pos = atoi(arg); t_process *tmp = NULL; while (processes) { tmp = (t_process*)processes->data; if (tmp->pos == cur_pos) { return processes; } processes = processes->next; } fprintf(stderr, "fg: %s: no such job\n", arg); return NULL; } static t_list *get_process(char *arg) { bool is_num = true; unsigned int len = 0; t_list **processes = mx_get_list_procs(); if (!arg) return mx_get_last_process(*processes); arg++; len = strlen(arg); for (unsigned int i = 0; i < len; i++) { if (!isnumber(arg[i])) { is_num = false; break; } } if (is_num) return get_process_by_id(arg, *processes); else return get_process_by_cmd(arg, *processes); } static bool check_args(char **args) { if (!mx_arr_size(args)) return true; if (mx_arr_size(args) > 1) { fprintf(stderr, "fg: too many arguments\n"); return false; } if (args[0][0] != '%' || !args[0][1]) { fprintf(stderr, "fg: invalid argument: %s\n", args[0]); return false; } return true; } int mx_fg(char **args, int fd) { t_list *process = NULL; t_process *f_process = NULL; t_list **all_processes = mx_get_list_procs(); if (!check_args(args)) return 1; process = get_process(args[0]); if (process) { f_process = (t_process*)process->data; mx_disable_canon(); tcsetpgrp(STDIN_FILENO, f_process->gpid); mx_continue_process(f_process, all_processes, fd); tcsetpgrp(STDIN_FILENO, getpgrp()); mx_enable_canon(); } else { fprintf(stderr, "%s", *args ? "" : "fg: no current jobs\n"); return 1; } return f_process->status; }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdbool.h> #include <limits.h> #define N 10 #define M 10 #define LOWER 0 #define UPPER 100 void matrixFillRand(int matrix[N][M], int height, int width, int lowerBound, int upperBound) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { matrix[i][j] = (rand() % (upperBound - lowerBound)) + lowerBound; } } return; } void matrixPrint(int matrix[N][M], int height, int width) { for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { printf("%.2d ", matrix[i][j]); } putchar('\n'); } return; } int main(int argc, char const *argv[]) { int matrix[N][M]; srand(time(NULL)); matrixFillRand(matrix, N, M, LOWER, UPPER); matrixPrint(matrix, N, M); int max = INT_MIN; int maxW, maxH; int min = INT_MAX; int minW, minH; for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if(matrix[i][j] > max) { max = matrix[i][j]; maxW = i; maxH = j; } if(matrix[i][j] < min) { min = matrix[i][j]; minW = i; minH = j; } } } int temp = min; matrix[minH][minW] = max; matrix[maxH][maxW] = temp; matrixPrint(matrix, N, M); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* light.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tjinichi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/10/16 20:05:51 by tjinichi #+# #+# */ /* Updated: 2020/10/26 05:52:05 by tjinichi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../includes/environment.h" void clear_llst(t_light **llst) { if (*llst == NULL) return ; clear_llst(&((*llst)->next)); free(*llst); } static void llstadd_back(t_light **llst, t_light *new) { if (!llst) return ; if (!*llst) *llst = new; else llstadd_back(&((*llst)->next), new); } char *parse_light(char **p, t_light **llst) { t_light *new; char *tmp; if (count_2d(p) != 3) return (ERR_RT_FORMAT3); if (!MALLOC(new, 1)) return (ERR_MALLOC); new->next = NULL; llstadd_back(llst, new); if (!ft_stov(p[0], &(new->pos)) || !ft_stod(p[1], &(new->ratio)) || !ft_stov(p[2], &(new->rgb))) return (ERR_RT_FORMAT2); if ((tmp = check_out_of_range(new->ratio, 0.0, 1.0, "[Light brightness_ratio"))) return (tmp); if ((tmp = check_vec_range(new->rgb, 0, 255, "[Light color"))) return (tmp); return (tmp); }
C
#ifndef __VINT2_H__ #define __VINT2_H__ #include "StdMath.h" #include "VFactor.h" struct VInt2 { int32_t x; int32_t y; static const VInt2 zero; static const int32_t Rotations[]; int32_t sqrMagnitude() const { return (int32_t)sqrMagnitudeLong(); } int64_t sqrMagnitudeLong() const { int64_t num = (int64_t)x; int64_t num2 = (int64_t)y; return num * num + num2 * num2; } int32_t magnitude() const; VInt2 normalized() const { VInt2 result = VInt2(x, y); result.Normalize(); return result; } VInt2(int32_t _x, int32_t _y) : x(_x), y(_y) { } VInt2() : x(0), y(0) { } static int32_t Dot(const VInt2& a, const VInt2& b) { return (int32_t)((int64_t)a.x * (int64_t)b.x + (int64_t)a.y * (int64_t)b.y); } static int64_t DotLong(const VInt2& a, const VInt2& b) { return (int64_t)a.x * (int64_t)b.x + (int64_t)a.y * (int64_t)b.y; } static int64_t DetLong(const VInt2& a, const VInt2& b) { return (int64_t)a.x * (int64_t)b.y - (int64_t)a.y * (int64_t)b.x; } int32_t GetHashCode() const { return x * 49157 + y * 98317; } static VInt2 Rotate(const VInt2& v, int32_t r) { r %= 4; return VInt2(v.x * Rotations[r * 4] + v.y * Rotations[r * 4 + 1], v.x * Rotations[r * 4 + 2] + v.y * Rotations[r * 4 + 3]); } static VInt2 Min(const VInt2& a, const VInt2& b) { return VInt2(StdMath::Min(a.x, b.x), StdMath::Min(a.y, b.y)); } static VInt2 Max(const VInt2& a, const VInt2& b) { return VInt2(StdMath::Max(a.x, b.x), StdMath::Max(a.y, b.y)); } // string ToString() // { // return string.Concat(object[] // { // "(", // x, // ", ", // y, // ")" // }); // } void Min(const VInt2& r) { x = StdMath::Min(x, r.x); y = StdMath::Min(y, r.y); } void Max(const VInt2& r) { x = StdMath::Max(x, r.x); y = StdMath::Max(y, r.y); } void Normalize(); void NormalizeTo(int32_t newMagn); static VInt2 ClampMagnitude(const VInt2& v, int32_t maxLength); VInt2 operator +(const VInt2& b) const { return VInt2(x + b.x, y + b.y); } VInt2 operator -(const VInt2& b) const { return VInt2(x - b.x, y - b.y); } bool operator ==(const VInt2& b) const { return x == b.x && y == b.y; } bool operator !=(const VInt2& b) const { return x != b.x || y != b.y; } VInt2 operator -() const { return VInt2(-x, -y); } VInt2 operator *(int32_t rhs) const { return VInt2(x * rhs, y * rhs); } VInt2 operator *(const VFactor& f) const; VInt2 operator /(const VFactor& f) const; }; #endif // __VINT2_H__
C
#include "driverlib.h" #include "device.h" #include "events.h" #include "everythings.h" #include "leds.h" bool systickFlag=false; __interrupt void cpuTimer2ISR ( void ); void initCPUTimers ( void ); void configCPUTimer ( uint32_t cpuTimer, uint32_t freq, uint32_t period ); void initTimer2(void) { // ISRs for each CPU Timer interrupt Interrupt_register(INT_TIMER2, &cpuTimer2ISR); // Initializes the Device Peripheral. For this example, only initialize the Cpu Timers. initCPUTimers(); // Configure CPU-Timer 0, 1, and 2 to interrupt every second: // 1 second Period (in uSeconds) configCPUTimer(CPUTIMER2_BASE, DEVICE_SYSCLK_FREQ, 10000); // To ensure precise timing, use write-only instructions to write to the // entire register. Therefore, if any of the configuration bits are changed // in configCPUTimer and initCPUTimers, the below settings must also // be updated. CPUTimer_enableInterrupt(CPUTIMER2_BASE); // // Enables CPU int1, int13, and int14 which are connected to CPU-Timer 0, // CPU-Timer 1, and CPU-Timer 2 respectively. // Enable TINT0 in the PIE: Group 1 interrupt 7 Interrupt_enable(INT_TIMER2); // Starts CPU-Timer 0, CPU-Timer 1, and CPU-Timer 2. CPUTimer_startTimer(CPUTIMER2_BASE); } // initCPUTimers - This function initializes all three CPU timers // to a known state. void initCPUTimers(void) { // Initialize timer period to maximum CPUTimer_setPeriod(CPUTIMER2_BASE, 0xFFFFFFFF); // Initialize pre-scale counter to divide by 1 (SYSCLKOUT) CPUTimer_setPreScaler(CPUTIMER2_BASE, 0); // Make sure timer is stopped CPUTimer_stopTimer(CPUTIMER2_BASE); // Reload all counter register with period value CPUTimer_reloadTimerCounter(CPUTIMER2_BASE); } // // configCPUTimer - This function initializes the selected timer to the // period specified by the "freq" and "period" parameters. The "freq" is // entered as Hz and the period in uSeconds. The timer is held in the stopped // state after configuration. //void configCPUTimer(uint32_t cpuTimer, float freq, float period) void configCPUTimer(uint32_t cpuTimer, uint32_t freq, uint32_t period) { // Initialize timer period: CPUTimer_setPeriod(cpuTimer ,(freq / 1000000) * period ); // Set pre-scale counter to divide by 1 (SYSCLKOUT): CPUTimer_setPreScaler(cpuTimer, 0); // Initializes timer control register. The timer is stopped, reloaded, // free run disabled, and interrupt enabled. // Additionally, the free and soft bits are set CPUTimer_stopTimer ( cpuTimer ); CPUTimer_reloadTimerCounter ( cpuTimer ); CPUTimer_setEmulationMode ( cpuTimer, CPUTIMER_EMULATIONMODE_STOPAFTERNEXTDECREMENT ); CPUTimer_enableInterrupt ( cpuTimer ); } void disableTimer2Interrupt(void) { CPUTimer_disableInterrupt ( CPUTIMER2_BASE ); } void enableTimer2Interrupt(void) { CPUTimer_enableInterrupt ( CPUTIMER2_BASE ); } __interrupt void cpuTimer2ISR(void) { // The CPU acknowledges the interrupt. systickFlag=true; } void systickFunc(void) { if(systickFlag==true) { systickFlag=false; Send_Event(ANY_Event,everythings()); } }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include "statistics/datafile.h" #include "statistics/ttest.h" #include "util.h" typedef struct parse_test_type_result_t{ TTestType type; bool isValid; } ParseTestTypeResult; ParseTestTypeResult parseTestType(const char * type) { if (0 == strcasecmp(type, "paired")) { return (ParseTestTypeResult) {PairedT, true}; } if (0 == strcasecmp(type, "unpaired")) { return (ParseTestTypeResult) {UnpairedT, true}; } return (ParseTestTypeResult) {0, false}; } void outputDataFile(FILE * outFile, const DataFile * data) { int rowCount = dataFileRowCount(data); int colCount = dataFileColumnCount(data); for (int row = 0; row < rowCount; ++row) { for (int col = 0; col < colCount; ++col) { fprintf(outFile, "%0.3f ", dataFileItem(data, row, col)); } fputc('\n', outFile); } } static const int ExitOk = 0; static const int ExitErrMissingTestType = 1; static const int ExitErrInvalidTestType = 2; static const int ExitErrNoDatafile = 3; int main (int argc, char ** argv) { TTestType type = PairedT; char * dataFileName = (char *) 0; for (int argIndex = 1; argIndex < argc; ++argIndex) { if (0 == strcmp("-t", argv[argIndex])) { ++argIndex; if (argIndex >= argc) { fprintf(stderr, "ERR -t requires a test type - paired or unpaired\n"); return ExitErrMissingTestType; } ParseTestTypeResult parsedType = parseTestType(argv[argIndex]); if (!parsedType.isValid) { fprintf(stderr, "ERR test type '%s' is not recognised\n", argv[argIndex]); return ExitErrInvalidTestType; } type = parsedType.type; } else { dataFileName = argv[argIndex]; break; } } if (!dataFileName) { fprintf(stderr, "ERR No data file provided.\n"); return ExitErrNoDatafile; } DataFile * data = newDataFile(dataFileName); outputDataFile(stdout, data); TTest tTest = { type, data }; fprintf(stdout, "t = %0.6f\n", tTestT(&tTest)); freeDataFile(&data); return ExitOk; }
C
#ifndef TREE_H #define TREE_H // Tree structure based on double-linked lists and array. struct Tree; typedef struct Tree Tree; // Main functions. extern void initializeTree(Tree**); extern void destroyTree(Tree*); // Auxiliary functions. extern void addTreeNode(Tree*, int); void splitTreeNodeByIndex(Tree*, int, int); extern void deleteTreeNodeByIndex(Tree*, int); extern void deleteSubtreeByIndex(Tree*, int); // Getters. extern int getTreeNodesAmount(Tree*); extern int getTreeNodeRightmostChildIndexByIndex(Tree*, int); #endif /* TREE_H */
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <sys/mman.h> #include <sys/stat.h> #include <fcntl.h> #define NAME_POSIX_SHM "/mmapfile" #define SZ_SHM_SEGMENT 4096 int main() { int shm_fd; char *shm_ptr; int n_read = 0; size_t n_input = 128; char *p_input = (char *)malloc(n_input); printf("* SHM Name : %s \n", NAME_POSIX_SHM); if ((shm_fd = shm_open(NAME_POSIX_SHM, O_RDWR | O_CREAT | O_EXCL, 0660)) > 0) { printf("* Create SHM : /dev/shm/%s\n", NAME_POSIX_SHM); if (ftruncate(shm_fd, SZ_SHM_SEGMENT) == -1) exit(EXIT_FAILURE); } else { if (errno != EEXIST) { exit(EXIT_FAILURE); } if ((shm_fd = shm_open(NAME_POSIX_SHM, O_RDWR, 0)) == -1) { exit(EXIT_FAILURE); } } shm_ptr = (char *)mmap(NULL, SZ_SHM_SEGMENT, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); if (shm_ptr == MAP_FAILED) { exit(EXIT_FAILURE); } printf("'*' Print current shm.\n'.' Exit.\n"); printf("otherwise change shm to your input.\n"); while (1) { printf("\n>> "); if ( (n_read = (int) getline(&p_input, &n_input, stdin)) == -1) { perror("getline error"); return -1; } if (p_input[0] == '.') { break; } else if (p_input[0] == '*') { printf("shm -> '%.*s'\n", SZ_SHM_SEGMENT, shm_ptr); } else { p_input[n_read - 1] = 0; memcpy(shm_ptr, p_input, n_read - 1); } } munmap(shm_ptr, SZ_SHM_SEGMENT); printf("* Would you remove shm (name : %s) (y/n) ", NAME_POSIX_SHM); if ( (n_read = (int)getline(&p_input, &n_input, stdin)) == -1) { perror("getline error"); return -1; } if (p_input[0] == 'y') { shm_unlink(NAME_POSIX_SHM); } return 0; }
C
#include <stdio.h> int main() { int row,column,s1,s2,x,y,score=0; scanf("%d%d",&row,&column); char array[row][column]; char flag,a; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { if(i==0||i==row-1||j==0||j==column-1) { array[i][j]='#'; } else { array[i][j]=' '; } } } scanf(" %c %d%d ",&a,&s1,&s2); array[s1][s2]='X'; x=1; y=1; while(1) { scanf("%c",&flag); if(flag=='\n') { break; } else if(flag=='B'||flag=='G'||flag=='R') { array[x][y]=flag; y++; if(array[x][y]=='#') { x++; y=1; } } } for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); int r=2023; while(r--) { scanf("%c",&flag); if(flag=='q'|| flag==EOF) { printf("Game Over, Total Score : %d \n",score); return 0; } if(flag=='p') { scanf(" %c",&flag); if(flag=='q') { printf("Game Over, Total Score : %d \n",score); return 0; } } while(flag==' ' || flag=='\n') { if(r==0) { break; } scanf("%c",&flag);; if(flag=='q') { printf("Game Over, Total Score : %d \n",score); return 0; } r--; } if(flag=='A') { if(array[s1][s2-1]!='#') { array[s1][s2]=' '; s2--; array[s1][s2]='X'; } } else if(flag=='D') { if(array[s1][s2+1]!='#') { array[s1][s2]=' '; s2++; array[s1][s2]='X'; } } else if(flag=='B') { for(int i=s1;i>0;i--) { if(array[s1-1][s2]!=' ' && array[s1-1][s2]!='B') { for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; printf("Game Over, Total Score : %d \n",score); return 0; } if(array[i][s2]=='B') { array[i][s2]=' '; score+=1; printf("Score: %d\n",score); for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); if(array[i-1][s2]!='B') { break; } } else if(array[i-1][s2]=='#') { array[i][s2]='B'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } else if(array[i-1][s2]=='R') { array[i][s2]='B'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } else if(array[i-1][s2]=='G') { array[i][s2]='B'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } } } else if(flag=='R') { for(int i=s1;i>0;i--) { if(array[s1-1][s2]!=' ' && array[s1-1][s2]!='R') { for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); printf("Game Over, Total Score : %d \n",score); return 0; } if(array[i][s2]=='R') { array[i][s2]=' '; score+=3; printf("Score: %d\n",score); for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); if(array[i-1][s2]!='R') { break; } } else if(array[i-1][s2]=='#') { array[i][s2]='R'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } else if(array[i-1][s2]=='B') { array[i][s2]='R'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } else if(array[i-1][s2]=='G') { array[i][s2]='R'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } } } else if(flag=='G') { for(int i=s1;i>0;i--) { if(array[s1-1][s2]!=' ' && array[s1-1][s2]!='G') { for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); printf("Game Over, Total Score : %d \n",score); return 0; } if(array[i][s2]=='G') { array[i][s2]=' '; score+=2; printf("Score: %d\n",score); for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); if(array[i-1][s2]!='G') { break; } } else if(array[i-1][s2]=='#') { array[i][s2]='G'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } else if(array[i-1][s2]=='B') { array[i][s2]='G'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } else if(array[i-1][s2]=='R') { array[i][s2]='G'; for(int i=0;i<row;i++) { for(int j=0;j<column;j++) { printf("%c",array[i][j]); } printf("\n"); } printf("\n"); break; } } } } printf("Game Over, Total Score : %d \n",score); }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> #define N 4 #define M 33 int main(int argc, char *argv[]) { int array[N][N]; int final_array[N][N]; int i, j; clock_t start, end; start = clock(); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { array[i][j] = rand()%100; printf("%d ", array[i][j]); } putchar('\n'); } for (i = 0; i < N; i++) for (j = 0; j < N; j++) final_array[j][i] = array[i][j]; printf("\n*********** The final array is **********\n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", final_array[i][j]); putchar('\n'); } end = clock(); printf("end is %lu\n", (long int)end ); printf("** TOTAL TIME: %ld secs\n", (end - start) / CLOCKS_PER_SEC ); return 0; } /* int main(int argc, char *argv[]) { int array[N][N]; int final_array[N][N]; int buffer[M][M]; int i, j, k, l, x, y; for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { array[i][j] = rand()%100; printf("%d ", array[i][j]); } printf("\n\n"); } for (i = 0; i < N; i++) { for (j = 0; j < N; j++) { k = 0; while ((k < M) && (k + i < N) ) { l = 0; while ( (l < M) && (l + j < N) ) { buffer[k][l] = array[i+k][j+l]; //printf("%d ", buffer[k][l]); l++; } k++; //printf("\n"); } // edw ypologizw ton anastrofo for (x = 0; x < l; x++) for (y = 0; y < k; y++) final_array[j+x][i+y] = buffer[y][x]; } } printf("*********** THE FINAL ARRAY IS ***************\n"); for (i = 0; i < N; i++) { for (j = 0; j < N; j++) printf("%d ", final_array[i][j]); putchar('\n'); } return 0; } */
C
/* ** Packed Move ** ** Moves string `s' to storage area `b' of length `l' bytes. If ** `s' is too long, it is truncated, otherwise it is padded to ** length `l' with character `c'. `B' after the transfer is ** returned. */ char *AApmove(s, b, l, c) register char *s; register char *b; register int l; register int c; { /* move up to `l' bytes */ while (*s && l > 0) { *b++ = *s++; --l; } /* if we still have some `l', pad */ while (l-- > 0) *b++ = c; return (b); }
C
#include "./ft_strcpy.c" #include <stdio.h> int main(void) { char *src = "A vida e loka"; char dest[13]; printf("%s\n", dest); ft_strcpy(dest, src); printf("%s\n", dest); }
C
#ifndef _H_MISC #define _H_MISC /** A compile time assertion check. * * Validate at compile time that the predicate is true without * generating code. This can be used at any point in a source file * where typedef is legal. * * On success, compilation proceeds normally. * * On failure, attempts to typedef an array type of negative size. The * offending line will look like * typedef assertion_failed_file_h_42[-1] * where file is the content of the second parameter which should * typically be related in some obvious way to the containing file * name, 42 is the line number in the file on which the assertion * appears, and -1 is the result of a calculation based on the * predicate failing. * * \param predicate The predicate to test. It must evaluate to * something that can be coerced to a normal C boolean. * * \param file A sequence of legal identifier characters that should * uniquely identify the source file in which this condition appears. */ #define CASSERT(predicate, file) _impl_CASSERT_LINE(predicate,__LINE__,file) #define _impl_PASTE(a,b) a##b #define _impl_CASSERT_LINE(predicate, line, file) \ typedef char _impl_PASTE(assertion_failed_##file##_,line)[2*!!(predicate)-1]; #define BTN_A 7 #define BTN_B 6 #define BTN_SELECT 5 #define BTN_START 4 #define BTN_UP 3 #define BTN_DOWN 2 #define BTN_LEFT 1 #define BTN_RIGHT 0 #define PORT_LED D #define PIN_LED 0 /* Button pins */ #define PORT_B_ACTION D #define PIN_B_ACTION 6 #define PORT_B_NEXT D #define PIN_B_NEXT 7 /* Shift output pins * LATCH - INT0 */ #define PORT_LATCH D #define PIN_LATCH 2 #define PORT_DATA B #define PIN_DATA 4 /* #define PORT_CLK B #define PIN_CLK 5 */ #define PORT_FORCE_SS B #define PIN_FORCE_SS 1 /* NRF24L01 pins * IRQ - INT1 */ #define PORT_IRQ D #define PIN_IRQ 3 #define PORT_CE C #define PIN_CE 5 #define PORT_CSN C #define PIN_CSN 4 #define PORT_MOSI C #define PIN_MOSI 1 #define PORT_MISO C #define PIN_MISO 0 #define PORT_SCK C #define PIN_SCK 2 #endif
C
#include <stdio.h> int main() { /* Para as declarações do tipo char e int os valores mostrados pelo programa estão bem parecidos com o que eu idealizei. Agora para os valores mostrados para as variáveis quando elas são declaradas como dos tipos float e double, minhas suposições não estavam corretas, pois os valores mostrados foram todos zeros. */ }
C
#include <stdio.h> int main(void) { int i, j, r, c, row, col, addrow, addcol; char init[50][50], mid[250][250], end[250][250]; scanf("%d %d %d %d", &row, &col, &addrow, &addcol); for(r = 0; r < row; r++) for(c = 0; c < col; c++) scanf(" %c", &init[r][c]); for(r = 0; r < row; r++) { i = 0; for(c = 0; c < col; c++) for(j = 0; j < addcol; j++, i++) mid[r][i] = init[r][c]; } j = 0; for(r = 0; r < row; r++) for(i = 0; i < addrow; i++, j++) for(c = 0; c < col * addcol; c++) end[j][c] = mid[r][c]; for(r = 0; r < row * addrow; r++, printf("\n")) for(c = 0; c < col * addcol; c++) printf("%c", end[r][c]); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* client.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: msousa <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/11/11 18:50:03 by msousa #+# #+# */ /* Updated: 2021/11/18 15:53:12 by msousa ### ########.fr */ /* */ /* ************************************************************************** */ #include "minitalk.h" /* #include <sys/time.h> #include <stdio.h> struct timeval start, end; gettimeofday(&start, NULL); printf("Starting of the program, seconds: %ld, micro seconds: %d\n", start.tv_sec, start.tv_usec); gettimeofday(&end, NULL); printf("Ending of the program, seconds: %ld, micro seconds: %d\n", end.tv_sec, end.tv_usec); printf("Total of the program, seconds: %ld, micro seconds: %d\n", end.tv_sec - start.tv_sec, end.tv_usec - start.tv_usec); */ static void kill_error(void) { ft_putendl_fd("Error while trying to send signal!", STDERR); exit(EXIT_FAILURE); } static void usage(void) { ft_putendl(NULL); ft_putendl("Usage: ./client <pid> <message>"); ft_putendl(NULL); ft_putendl(" - pid Server PID"); ft_putendl(" int"); ft_putendl(NULL); ft_putendl(" - message Message to be sent to Server."); ft_putendl(" string"); ft_putendl(NULL); exit(EXIT_FAILURE); } static void send_char_bits(int pid, char c) { int bit; bit = 0; while (bit < 8) { if (kill(pid, ft_ternary(c & (128 >> bit++), SIGUSR2, SIGUSR1)) < 0) kill_error(); else usleep(INTERVAL); } } int main(int argc, char *argv[]) { int pid; char *str; if (!(argc == 3 && ft_isnumber(argv[1]))) usage(); str = argv[2]; pid = ft_atoi(argv[1]); send_char_bits(pid, 0); while (*str) send_char_bits(pid, *str++); send_char_bits(pid, 0); return (0); }
C
#include "mt.h" int main(int argc, char *argv[]) { if(argc != 2) { printf("Uso: %s <dirección IP>\n", argv[0]); return -1; } struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_port = htons(PORT); if(inet_aton(argv[1], &sin.sin_addr) == 0) { printf("IP inválido.\n"); return -1; } int s = socket(AF_INET, SOCK_DGRAM, 0); for(;;) { char buf[1024]; printf("> "); fgets(buf, sizeof(buf), stdin); sendto(s, buf, strlen(buf) + 1, 0, (const struct sockaddr *) &sin, sizeof(sin)); } close(s); }
C
#include "state_machine.h" typedef enum { STATES_A = 0x0100, STATES_B, STATES_C } ; static void _action_a (state_machine_t* this, char* reason) { } static void _action_b (state_machine_t* this, char* reason) { } static void _action_c (state_machine_t* this, char* reason) { } void SM_second_state_2_action (state_machine_t* this) { switch (this->current_state_) { case BEGIN: _action_a (this, "action_a"); break; case STATES_A: _action_c (this, "action_c"); break; case STATES_B: break; case STATES_C: _action_b (this, "action_b"); break; default: // TODO: ALARM - sth may wrong break; }; } Bool SM_second_check_conditions (state_machine_t* this) { if (BEGIN == this->current_state_) { return SM_set_new_state (this, (unsigned int)STATES_A); } switch (this->current_state_) { case STATES_A: return SM_set_new_state (this, STATES_B); case STATES_B: return SM_set_new_state (this, STATES_C); case STATES_C: return SM_set_new_state (this, STATES_A); default: // TODO: Oops break; }; return False; }
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <math.h> #define N 100 int powplus(int n, int k) { int s = 1; while (k--) { s *= n; } return s; } int sum1(int n) { return powplus((n + 1) * n / 2, 2); } int sum2(int n) { return (n * (n + 1) * (2 * n + 1)) / 6; } void solve() { printf("%d\n", sum1(N)); printf("%d\n", sum2(N)); printf("%d\n", sum1(N) - sum2(N)); } int main() { solve(); return 0; } //Answer:25164150
C
#include <Python.h> int fac_function(int n){ if (n > 1) { return n*fac_function(n - 1); } return 1; } static PyObject* _fac_function(PyObject *self, PyObject *args) { int _n; int res; if (!PyArg_ParseTuple(args, "i", &_n)) return NULL; res = fac_function(_n); return PyLong_FromLong(res); } static PyMethodDef facModuleMethods[] = { { "fac_function", _fac_function, METH_VARARGS, "the factorial of a non-negative integer n" }, { NULL, NULL, 0, NULL } }; static struct PyModuleDef fac_module = { PyModuleDef_HEAD_INIT, "fac_module", "", -1, facModuleMethods }; PyMODINIT_FUNC PyInit_fac_module(void) { PyObject *m; m = PyModule_Create(&fac_module); if (m == NULL) return NULL; printf("init fac_module module\n"); return m; }
C
#include <stdio.h> #include <stdlib.h> struct Node{ int data; struct Node *next; struct Node *prev; }; struct Node *head = NULL; void display_beg(){ if(head == NULL){ printf("\nList is empty....\n"); } else{ struct Node *temp; temp = head; printf("\nThe elements in the list are(forward): "); if(head->next == head){ printf("%d",temp->data); } else{ while(temp->next!=head){ printf("%d ",temp->data); temp= temp->next; } printf("%d ",temp->data); } } } void display_end(){ if(head == NULL){ printf("\nList is empty...\n"); } else{ printf("\nThe elements in the list are(backward): "); struct Node *temp; temp = head->prev; if(head->prev == head){ printf("%d",temp->data); } else{ while(temp!= head){ printf("%d ",temp->data); temp = temp->prev; } printf("%d",temp->data); } } } void insert_end(struct Node *new_node){ int x; printf("Enter the element to add: "); scanf("%d",&x); new_node->data = x; new_node->next = NULL; new_node->prev = NULL; if(head == NULL){ head = new_node; new_node->next = head; new_node->prev = head; } else{ new_node->next = head; new_node->prev = head->prev; head->prev->next = new_node; head->prev = new_node; } } void insert_after(struct Node *new_node){ int ele; printf("\nEnter element after which you want to insert: "); scanf("%d",&ele); if(head == NULL){ printf("\nInsertion not possible.....\n"); } else if(head->data == ele && head ->next == head){ new_node->next = head; new_node->prev = head->prev; head->prev->next = new_node; head->prev = new_node; } else{ struct Node *temp; temp = head; if(head->data == ele){ new_node->next = temp->next; new_node->prev = temp; temp->next = new_node; new_node->next->prev = new_node; } else{ temp = head->next; while(temp->data!=ele && temp!=head){ temp = temp->next; } if(temp == head){ printf("\nElement not found...\n"); } else{ new_node->next = temp->next; new_node->prev = temp; temp->next = new_node; new_node->next->prev = new_node; } } } } int main(){ int n, i; printf("Enter the number of element: "); scanf("%d",&n); struct Node *a[n]; for(i=0; i<n; i++){ a[i] = (struct Node*)malloc(sizeof(struct Node*)); insert_end(a[i]); } display_beg(); display_end(); struct Node *w; printf("\nEnter the element you want to insert: "); scanf("%d",&n); w = (struct Node*)malloc(sizeof(struct Node*)); w->data = n; w->next = w->prev = NULL; insert_after(w); display_beg(); display_end(); return 0; }
C
#include <stdio.h> void printArr(int *arr, int size) { int i; for (i = 0; i < size; ++i) { printf("arr[%d]=%d\n", i, arr[i]); } } void printArrString(char *arr, int size) { int i; for (i = 0; i < size; ++i) { printf("arr[%d]=%c\n", i, arr[i]); } } void passAsPointer(int *arr, int size) { printf("\npassAsPointer\n"); printArr(arr, size); } void passAsSize(int arr[4], int size) { printf("\npassAsSize\n"); printArr(arr, size); } void passAsSquareBracket(int arr[], int size) { printf("\npassAsSquareBracket\n"); printArr(arr, size); } int main(int argc, char** argv) { int size = 4; int arr[] = {1, 2, 3, 4}; char text[] = "Word"; passAsPointer(arr, size); passAsSize(arr, size); passAsSquareBracket(arr, size); printf("\nprintArrString\n"); printArrString(text, size); }
C
#include "AI.h" #include "Game.h" #include "PlayList.h" // Handle a Human v. AI game void Inky(int board[3][3], PLAY *p1, PLAY *p2, PLIST *l) // Human is always player1 and AI is player2 { printf("Human v. AI game started\n"); PLAY *d = CreatePlay(0, '0', 'd', "ZZ", board); AppendPlaySnapshot(l, d); print_fun(board,p1,p2); int tie=1; int count = 0; while((is_there_empty_cell(board))) { printf("Player 1, please choose your move:"); entered_one_char(board,p1); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p1->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p1); PrintPlayList(l); print_fun(board,p1,p2); int win_flag = IsWin(board); if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; printf("AI is choosing its move:\n"); int foundMove = 0; int i,j; for (i=0; i<3; i++) { for (j=0; j<3; j++) { if (board[i][j] == 0) { board[i][j] = 2; foundMove = 1; break; } } if(foundMove) { break; } } p2 -> move[0] = row_char(i); p2 -> move[1] = col_char(j); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p2->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p2); PrintPlayList(l); print_fun(board,p1,p2); win_flag = IsWin(board); if(win_flag == 0) { printf("Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: if(count == 0) { RemoveFirstPlay(l); } count++; break; } } if(win_flag == 2) { printf("AI won. Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); if (count == 0) { ResetBoard(board); } print_fun(board,p1,p2); continue; default: break; } } if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; } else if (is_there_empty_cell(board)==0) break; } if (tie==1) { printf("The game is a tie!\n"); } DeletePlay(d); } void Blinky(int board[3][3],PLAY *p1,PLAY *p2, PLIST *l) { srand(time(NULL)); printf("Human v. AI game started\n"); PLAY *d = CreatePlay(0, '0', 'd', "ZZ", board); AppendPlaySnapshot(l, d); print_fun(board,p1,p2); int tie=1; int count = 0; while((is_there_empty_cell(board))) { printf("Player 1, please choose your move:"); entered_one_char(board,p1); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p1->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p1); PrintPlayList(l); print_fun(board,p1,p2); int win_flag = IsWin(board); if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; printf("AI is choosing its move:\n"); int foundMove = 0; int i,j; while(1) { i = rand()%3; j = rand()%3; if (board[i][j] == 0) { board[i][j] = 2; foundMove = 1; break; } if(foundMove) { break; } } p2 -> move[0] = row_char(i); p2 -> move[1] = col_char(j); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p2->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p2); PrintPlayList(l); print_fun(board,p1,p2); win_flag = IsWin(board); if(win_flag == 0) { printf("Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: if(count == 0) { RemoveFirstPlay(l); } count++; break; } } if(win_flag == 2) { printf("AI won. Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: break; } } if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; } if (tie==1) { printf("The game is a tie!\n"); } DeletePlay(d); } void Pinky(int board[3][3],PLAY *p1, PLAY *p2, PLIST *l) { printf("Human v. AI game started\n"); PLAY *d = CreatePlay(0, '0', 'd', "ZZ", board); AppendPlaySnapshot(l, d); print_fun(board,p1,p2); int tie=1; int count = 0; while((is_there_empty_cell(board))) { printf("Player 1, please choose your move:"); entered_one_char(board,p1); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p1->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p1); PrintPlayList(l); print_fun(board,p1,p2); int win_flag = IsWin(board); if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; printf("AI is choosing its move:\n"); int foundMove = 0; int i, j; for (i=0; i<3; i++) { for (j=0; j<3; j++) { if (board[i][j] == 0) { board[i][j] = 1; if(IsWin(board)) { board[i][j] = 2; foundMove = 1; } else { board[i][j] = 0; } } } if(foundMove) { break; } } while(foundMove == 0) { i = rand()%3; j = rand()%3; if (board[i][j] == 0) { board[i][j] = 2; foundMove = 1; break; } if(foundMove) { break; } } p2 -> move[0] = row_char(i); p2 -> move[1] = col_char(j); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p2->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p2); PrintPlayList(l); print_fun(board,p1,p2); win_flag = IsWin(board); if(win_flag == 0) { printf("Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: if(count == 0) { RemoveFirstPlay(l); } count++; break; } } if(win_flag == 2) { printf("AI won. Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: break; } } if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; } if (tie==1) { printf("The game is a tie!\n"); } DeletePlay(d); } void Clyde(int board[3][3], PLAY *p1, PLAY *p2, PLIST *l) { printf("Human v. AI game started\n"); PLAY *d = CreatePlay(0, '0', 'd', "ZZ", board); AppendPlaySnapshot(l, d); print_fun(board,p1,p2); int tie=1; int count = 0; while((is_there_empty_cell(board))) { printf("Player 1, please choose your move:"); entered_one_char(board,p1); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p1->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p1); PrintPlayList(l); print_fun(board,p1,p2); int win_flag = IsWin(board); if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; printf("AI is choosing its move:\n"); int moverow = -1; int movecol = -1; int score = -2; int i,j; for (j=0; j<3; j++) { for (i=0; i<3; i++) { if (board[i][j] == 0) { board[i][j] = 2; int tempScore = -minimax(board, 1); board[i][j] = 0; if(tempScore > score) { score = tempScore; moverow = i; movecol = j; } } } } board[moverow][movecol] = 2; p2 -> move[0] = row_char(moverow); p2 -> move[1] = col_char(movecol); for(int i = 0; i < 3; i++) { for(int j = 0; j < 3; j++) { p2->board[i][j] = board[i][j]; } } AppendPlaySnapshot(l, p2); PrintPlayList(l); print_fun(board,p1,p2); win_flag = IsWin(board); if(win_flag == 0) { printf("Take back move? y/n: "); char takeback; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: if(count == 0) { RemoveFirstPlay(l); } count++; break; } } if(win_flag == 2) { printf("AI won. Take back move? y/n: "); char takeback = 'y'; scanf(" %c", &takeback); switch(takeback) { case 'y': TakeBack(board,l); print_fun(board,p1,p2); continue; default: break; } } if(win_flag != 0) { if (win_flag == 1) { printf("Player 1 wins! Game Over!\n\n"); } else if (win_flag == 2) { printf("AI wins! Game Over!\n\n"); } tie=0; break; } else if (is_there_empty_cell(board)==0) break; } if (tie==1) { printf("The game is a tie!\n"); } DeletePlay(d); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: seruiz <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/02 13:18:34 by seruiz #+# #+# */ /* Updated: 2021/03/09 16:13:49 by seruiz ### ########lyon.fr */ /* */ /* ************************************************************************** */ # include "minishell.h" /* int ft_add_spaces(char *s, int x, char c, char v) { s[x] = ' '; s[x + 1] = c; if (v != '\0') { s[x + 2] = v; s[x + 3] = ' '; return (x + 3); } else s[x + 2] = ' '; return (x + 2); } char *ft_get_blocks(char *line, int i, int compt, int n) { int j; char *s; int x; x = 0; j = i + compt * 2; s = malloc(sizeof(char) * (j + 1)); if (s == NULL) return (0); while (n <= i) { if (line[n] == '|') { if (n < i - 1 && line[n + 1] == '|') { x = ft_add_spaces(s, x, '|', '|'); n++; } else x = ft_add_spaces(s, x, '|', '\0'); } else if (line[n] == '&') { if (n < i - 1 && line[n + 1] == '&') { x = ft_add_spaces(s, x, '&', '&'); n++; } } else if (line[n] == ';') x = ft_add_spaces(s, x, line[n], '\0'); else s[x] = line[n]; x++; n++; } //s[x] = '\0'; return (s); } char *ft_test(char *line, int i) { int j; int compt; int n; n = 0; compt = 0; j = 0; while (j < i) { if (line[j] == '|') { if (j < i - 1 && line[j + 1] == '|') j += 2; else j++; compt += 1; } else if (line[j] == '&') { if (j < i - 1 && line[j + 1] == '&') j += 2; else j++; compt += 1; } else if (line[j] == ';') compt += 1; j++; } printf("found %d separators\n", compt); return (ft_get_blocks(line, i, compt, n)); } int ft_treat_line(char **line) { int i; int j; char **test; char *s; j = 0; i = ft_strlen(*line); s =ft_test(*line, i); //printf("line len = %d\n", i); test = ft_split(s, ' '); while (test[j]) { printf("%s\n", test[j]); j++; } return (1); } */ int ft_treat_quotes(char *line, int i, int j, int ret) { } int ft_treat_sep(char *line, int i, int j, t_node *node) { int ret; t_sep *separator; ret = j; separator = malloc(sizeof(t_sep)); while (ret < i) { if (line[ret] == '\'' || line[ret] == '\"') return (ret + ft_treat_quotes(line, i, j, ret)); else if (line[ret] == '|' || line[ret] == ';' || line[ret] == '&') { if (ret + 1 < i && line[ret + 1] == '|') { } } } } int ft_treat_line(char *line, t_node *node) { int i; int j; int ret; i = ft_strlen(line); j = 0; while (j < i) { ret = ft_treat_sep(line, i, j, node); if (ret > 0) j += ret; else { ret = ft_treat_command(line, i, j, node); if (ret > 0) j += ret; } //printf("%c", line[j]); //j++; } printf("\n"); } int main(void) { char **line; char *prompt; int ret; t_node *node; ret = 0; node = malloc(sizeof(t_node *)); line = malloc(sizeof(char **)); prompt = malloc(sizeof(char) * 12); if (line == NULL || prompt == NULL || node == NULL) return (0); prompt = "\e[1;1H\e[2J"; write(1, prompt, 11); prompt = "Minishell ~ "; while (ret >= 0) { write(1, prompt, 12); ret = get_next_line(0, line); ft_treat_line(*line, node); //ft_treat_line(line); free(*line); } return (1); }
C
/*模块头文件*/ #include <linux/init.h> #include <linux/module.h> /*驱动注册的头文件,包含驱动的结构体和注册和卸载的函数*/ #include <linux/platform_device.h> /*注册杂项设备头文件*/ #include <linux/miscdevice.h> /*注册设备节点的文件结构体*/ #include <linux/fs.h> /*其他需要头文件*/ #define DRIVER_NAME "hian_deviceName" #define DEVICE_NAME "hian_deviceName" MODULE_LICENSE("Dual BSD/GPL"); MODULE_AUTHOR("HIAN"); static int hian_deviceName_open(struct inode *inode, struct file *file) { printk(KERN_EMERG "hian_deviceName open in!\n"); ... printk(KERN_EMERG "hian_deviceName open success!\n"); return 0; } static int hian_deviceName_release(struct inode *inode, struct file *file) { printk(KERN_EMERG "hian_deviceName release\n"); ... return 0; } static struct file_operations hian_deviceName_ops = { .owner = THIS_MODULE, .open = hian_deviceName_open, .release = hian_deviceName_release, }; static struct miscdevice hian_deviceName_dev = { .minor = MISC_DYNAMIC_MINOR, .name = DEVICE_NAME, .fops = &hian_deviceName_ops, }; static int hian_deviceName_probe(struct platform_device *pdv) { printk(KERN_EMERG "\thian_deviceName initialized\n"); misc_register(&hian_deviceName_dev); return 0; } static int hian_deviceName_remove(struct platform_device *pdv) { printk(KERN_EMERG "\thian_deviceName remove\n"); misc_deregister(&hian_deviceName_dev); return 0; } struct platform_driver hian_deviceName_driver = { .probe = hian_deviceName_probe, .remove = hian_deviceName_remove, .driver = { .name = DRIVER_NAME, .owner = THIS_MODULE, } }; static int hian_deviceName_init(void) { int DriverState; printk(KERN_EMERG "hian_deviceName enter!\n"); DriverState = platform_driver_register(&hian_deviceName_driver); printk(KERN_EMERG "\thian_deviceName DriverState is %d\n",DriverState); return 0; } static void hian_deviceName_exit(void) { printk(KERN_EMERG "hian_deviceName exit!\n"); platform_driver_unregister(&hian_deviceName_driver); } module_init(hian_deviceName_init); module_exit(hian_deviceName_exit);
C
#include "soplib.h" #define BACKLOG 3 volatile sig_atomic_t do_work = 1; void sigint_handler(int sig) { do_work = 0; } void usage(char *name) { fprintf(stderr, "USAGE: %s socket port\n", name); } void calculate(int32_t data[5]) { int32_t op1, op2, result, status = 1; op1 = ntohl(data[0]); op2 = ntohl(data[1]); switch ((char)ntohl(data[3])) { case '+': result = op1 + op2; break; case '-': result = op1 - op2; break; case '*': result = op1 * op2; break; case '/': if (0 == op2) status = 0; else result = op1 / op2; break; default: status = 0; } data[4] = htonl(status); data[2] = htonl(result); } void doServer(int fdL) { int cfd; int32_t data[5]; ssize_t size; fd_set base_rfds, rfds; sigset_t mask, oldMask; FD_ZERO(&base_rfds); FD_SET(fdL, &base_rfds); sigemptyset(&mask); sigaddset(&mask, SIGINT); sigprocmask(SIG_BLOCK, &mask, &oldMask); while (do_work) { rfds = base_rfds; if (pselect(fdL + 1, &rfds, NULL, NULL, NULL, &oldMask) > 0) { if ((cfd = add_new_client(fdL)) >= 0) { if ((size = bulk_read(cfd, (char *)data, sizeof(int32_t[5]))) < 0) ERR("read:"); if (size == (int)sizeof(int32_t[5])) { calculate(data); if (bulk_write(cfd, (char *)data, sizeof(int32_t[5])) < 0 && EPIPE != errno) ERR("write:"); } if (TEMP_FAILURE_RETRY(close(cfd)) < 0) ERR("close: "); } } else { if (EINTR == errno) continue; ERR("pselect"); } } sigprocmask(SIG_UNBLOCK, &mask, NULL); } int main(int argc, char **argv) { int fdL; int new_flags; if (argc != 3) { usage(argv[0]); return EXIT_FAILURE; } if (sethandler(SIG_IGN, SIGPIPE)) ERR("Setting SIGPIPE:"); if (sethandler(sigint_handler, SIGINT)) ERR("Setting SIGINT:"); fdL = bind_socket(argv[1], BACKLOG); new_flags = fcntl(fdL, F_GETFL) | O_NONBLOCK; fcntl(fdL, F_SETFL, new_flags); doServer(fdL); if (TEMP_FAILURE_RETRY(close(fdL)) < 0) ERR("close:"); if (unlink(argv[1]) < 0) ERR("close"); fprintf(stderr, "Server has terminated.\n"); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> int main() { char *strss; int num = 66; sprintf(strss, "%d", num); printf("str = %s\n", strss); return(0); }
C
//非递归的先序遍历 //先序遍历的顺序是根左右。对于任意一个结点都可以看成是一个根结点,直接对其访问,如果访问完成后,左孩子不为空,将左孩子看成是一个新的根结点,重复以上步骤。对于一般程序而言,递归程序转换为非递归程序需要引入栈这个数据结构。注意到栈的先进先出的特性,根节点入栈,判断右孩子是否为空,若为空,则右孩子入栈。若为左孩子或右孩子为空则出栈访问,最后知道栈为空,则出栈访问 void PreOrderBiTree(BiTNode *T){ SqStack(&S); InitSqStack(S); BiTNode *p=T; Push(S,p); while(p||isEmpty(&S)!=0){ p=Pop(&S); p=printf("%c",p->data); if(p->lchild!=NULL){ Push(&S,p->lchild); if(p->rchild!=NULL){ push(&S,p->rchild); } } } //非递归的二叉树的中序遍历 //中序遍历的顺序是左根右,先扫描根结点的所有孩子(不访问)并将他们一一入栈,然后出栈一个*p结点并访问它,然后扫描*p的右孩子,并将其入栈,再扫描以该结点*P的孩子的根节点的所有左孩子,并将其一一入栈,如此继续,直至栈为空为止。首先判断节点T是否为空,若不为空则入栈,然后指针p指向T的左孩子,一一入栈,直至T为空,经过第一步可以保证栈顶元素必定为二叉树的最左孩子结点,出栈访问该结点,接着判断其右结点是否为空,若不为空,接着扫描右孩子的左孩子结点,重复以上步骤,直至栈为空为止 void InOrderBiTree(BiTNode *T){ SqStack(&S); InitStack(S); BiTNode *p=T; while(p||isEmptySqStack(&S)!=0){ if(p!=NULL){//若根节点不为空,则依次入栈,直至为空 Push(&S,p); p=p->lchild; }else{ p=Pop(&S);//弹出栈顶元素 printf("%c",p->data);//访问最左结点 p=p->rchild;//指向右孩子重复以上步骤 } } } //非递归的二叉树的后续遍历 //二叉树中的后续遍历的顺序为左右根,当用栈来存储结点时,需要分清返回根结点时是从左孩子返回的还是从右孩子返回的,需要设置一个指针r用来记录最近访问过的结点。首先判断节点是否为空,若不为空,则不断入栈,直至最左边的左孩子为空为止,接着取出栈顶结点,判断其右结点是否为空,右孩子入栈,若右孩子为空,则取出并做出栈访问 void PostOrderBiTree(BiTNode *T){ SqStack(&S); InitStack(S); BiTNode *p=T; BiTNode *r=T;//辅助指针r,记录结点是否被访问过,以区分是从右返回还是从左返回 while(p||isEmptySqStack(&S)!=0){ if(p!=NULL){//左孩子结点不为空 Push(&S,p); p=p->lchild; }else{ p=GetTop(&S);//取栈顶元素 if(r->lchild!=NULL&&p->rchild!=r){ p=p->rchild; Push(&S,p); p=p->lchild; }else{ p=Pop(&S); printf("%c",p->data); r=p; p=NULL; } } } //二叉树的层次遍历 void BSTBiTNode(BiTNode *T){ SqQueue(Q); InitQueue(&Q); BiTNode *p=T; while(p){ p=DeQueue(&Q,p->data); if(p->lchild!=NULL){ EnQueue(Q,p->lchild); } if(p->rchild!=NULL){ EnQueue(Q,p->rchild); } } } #include <stdio.h> #include <stdlib.h> #define MaxSize 100 typedef char ElemType; typedef struct BiTNode{ ElemType data; struct BiTNode *lchild,*rchild; }BiTNode,*BiTree; BiTNode* CreateBiTree(BiTNode*); void PreOrder(BiTNode*); void InOrder(BiTNode*); void PostOrder(BiTNode*); void LevelOrder(BiTNode*); typedef struct SqStack{ BiTNode* data[MaxSize]; int top; }SqStack; void InitStack(SqStack*); void Push(SqStack*,BiTNode*); BiTNode* Pop(SqStack*); BITNode* GetTop(SqStack*); int IsEmptyStack(SqStack*); typedef struct SqQueue{ BiTNode* data[MaxSize]; int front,rear; }SqQueue; void InitQueue(SqQueue*); void EnQueue(SqQueue*,BiTNode*); BiTNode* DeQueue(SqQueue*); int IsEmptyQueue(SqQueue*); int main(int argc,char *argv[]){ BiTNode *T=(BiTNode*)malloc(sizeof(BiTNode)); T=CreateBiTree(T); PreOrder(T);printf("\n"); InOrder(T);printf("\n"); PostOrder(T);printf("\n"); LevelOrder(T);printf("\n"); return 0; } //创建二叉树 BiTree CreateBiTree(BiTNode *T){ ElemType x; scanf("%c",&x); if(x=='#'){ return T; }else{ T=(BiTNode*)malloc(sizeof(BITNode)); T->data=x; T->lchild=CreateBiTree(T->lchild); T->rchild=CreateBiTree(T->rchild); } return T; } //先序遍历 void PreOrder(BiTNode *T){ SqStack S; InitStack(&S); BiTNode *p=T; Push(&S,p); while(IsEmptyStack(&S)!=0){ p=Pop(&S); printf("%c",p->data); if(p->rchild!=NULL){ Push(&S,p->rchild); } if(p->lchild!=NULL){ Push(&S,p->lchild); } } } //中序遍历 void InOrder(BiTNode *T){ SqStack S; InitStack(&S); BiTNode *p=T; while(p||IsEmpty(&S)!=0){ if(p!=NULL){ Push(&S,p); p=p->lchild; }else{ p=Pop(&S); printf("%c",p->data); p=p->rchild; } } } //后续遍历 void PostOrder(BiTNode *T){ SqStack S; InitStack(&S); BiTNode *p=T; BiTNode *r=NULL; while(p||IsEmptyStack(&S)!=0){ if(p!=NULL){ Push(&S,p); p=p->lchild; }else{ p=GetTop(&S); if(p->rchild!=NULL&&p->rchild!=r){ p=p->rchild; Push(&S,p); p=p->lchild; }else{ p=Pop(&S); printf("%c",p->data); r=p; p=NULL; } } } } //层次遍历 void LevelOrder(BiTNode *T){ SqQueue Q; InitQueue(&Q); BiTNode *p=T; EnQueue(&Q,p); while(IsEmptyQueue(&Q)!=0){ p=DeQueue(&Q); printf("%c",p->data); if(p->lchild!=NULL){ EnQueue(&Q,p->lchild); } if(p->rchild!=NULL){ EnQueue(&Q,p->rchild); } } } void InitStack(SqStack *S){ S->top=-1; } void Push(SqStack*S,BiTNode *T){ if(S->top==MaxSize-1){ return; } S->data[++S->top]=T; } BiTNode *Pop(SqStack *S){ if(S->top==-1){ return NULL; } return S->data[S->top--]; } BiTNode *GetTop(SqStack *S){ if(S->top==-1){ return NULL; } return S->data[S->top]; } int IsEmptyStack(SqStack *S){ if(S->top==-1){ return 0; } return -1; } void InitQueue(SqQueue *Q){ Q->front=0; Q->rear=0; } void EnQueue(SqQueue *Q,BiTNode *T){ if(Q->rear+1)%MaxSize==Q->front{ return; } q->data[Q->rear++]=T; } BiTNode *DeQueue(SqQueue *Q){ if(Q->front==Q->rear){ return NULL; } return Q->data[Q->front++]; } int IsEmptyQueue(SqQueue *Q){ if(Q->front==Q->rear){ return 0; } return -1; }
C
#include <stdio.h> #include <stdlib.h> #include"plante.h" #include <string.h> #include<gtk/gtk.h> enum { ID, NOM, EMPLACEMENT, PERIODE, DATE, NOMBRE, TEMPS, COLUMNS }; //////////////////ajouter une plante void ajouter_plante(plante p) { FILE *f; f=fopen("plantes.txt","a+"); if (f!=NULL) {fprintf(f,"%s %s %s %s %s %s %s \n",p.id,p.nom,p.emplacement,p.periode,p.date,p.nombre,p.temps); } fclose(f); } ////////////////fonction supprimer void supprimer_plante (plante p) { char id[30]; char nom[30]; char emplacement[30]; char periode[30]; char date[30]; char nombre[20]; char temps[30]; FILE *f,*g; f=fopen("plantes.txt","r"); g=fopen("plantes2.txt","w"); if (f==NULL || g==NULL ) return; else {while(fscanf(f,"%s %s %s %s %s %s %s \n",p.id,p.nom,p.emplacement,p.periode,p.date,p.nombre,p.temps)!=EOF) {if(strcmp(p.id,id)!=0 || strcmp(p.nom,nom)!=0 || strcmp(p.emplacement,emplacement)!=0 || strcmp(p.periode,periode)!=0 || strcmp(p.date,date)!=0 || strcmp(p.nombre,nombre)!=0|| strcmp(p.temps,temps)!=0) fprintf(g,"%s %s %s %s %s %s %s \n",id,nom,emplacement,periode,date,nombre,temps); } fclose(f); fclose(g); remove("plantes.txt"); rename("plantes2.txt","plantes.txt"); }} /////////////fonction afficher void afficher_plante(GtkWidget *liste) { GtkCellRenderer *renderer; GtkTreeViewColumn *column; GtkTreeIter iter; GtkListStore *store; char nombre[20]; char id[20]; char periode[20]; char nom[20]; char emplacement[20]; char date[30]; char temps[30]; store=NULL; FILE *f; store=gtk_tree_view_get_model(liste); if(store==NULL) { renderer=gtk_cell_renderer_text_new (); column=gtk_tree_view_column_new_with_attributes("id",renderer,"text",ID,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW (liste),column); renderer=gtk_cell_renderer_text_new(); column=gtk_tree_view_column_new_with_attributes("nom",renderer,"text",NOM,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(liste),column); renderer=gtk_cell_renderer_text_new(); column=gtk_tree_view_column_new_with_attributes("periode",renderer,"text", PERIODE,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(liste),column); renderer=gtk_cell_renderer_text_new(); column=gtk_tree_view_column_new_with_attributes("emplacement",renderer,"text",EMPLACEMENT,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(liste),column); renderer=gtk_cell_renderer_text_new(); column=gtk_tree_view_column_new_with_attributes("date",renderer,"text",DATE,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(liste),column); renderer=gtk_cell_renderer_text_new(); column=gtk_tree_view_column_new_with_attributes("temps",renderer,"text",TEMPS,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(liste),column); renderer=gtk_cell_renderer_text_new(); column=gtk_tree_view_column_new_with_attributes("nombre",renderer,"text",NOMBRE,NULL); gtk_tree_view_append_column(GTK_TREE_VIEW(liste),column); store=gtk_list_store_new(COLUMNS,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING,G_TYPE_STRING); f=fopen("plantes.txt","r"); if(f==NULL) { return; } else { f=fopen("plantes.txt","a+"); while(fscanf(f,"%s %s %s %s %s %s %s ",id,nom,emplacement,periode,date,nombre,temps)!=EOF) { gtk_list_store_append(store,&iter); gtk_list_store_set(store,&iter,ID,id,NOM,nom,EMPLACEMENT,emplacement,PERIODE,periode,DATE,date,NOMBRE,nombre,TEMPS,temps,-1); } fclose(f); gtk_tree_view_set_model(GTK_TREE_VIEW(liste),GTK_TREE_MODEL(store)); g_object_unref(store); } } } //////annee_seche int valeur_max(float tab[],int n) { int i,pos; float max; max=tab[0]; for(i=1;i<n;i++) { if(tab[i]>max) {max=tab[i]; pos=i;} } return pos; } int annee_seche(int tab_an[],float tab_temp[]) { FILE *f; int i; int id,j,m,a,n; float temp; f=fopen("temperature.txt","r"); if(f!=NULL) {fscanf(f,"%d %d %d %d %f",&id,&j,&m,&a,&temp); tab_an[0]=a; i=1; while(fscanf(f,"%d %d %d %d %f",&id,&j,&m,&a,&temp)!=EOF) { if(a!=tab_an[i-1]) {tab_an[i]=a; i++;} } n=i; rewind(f); while(fscanf(f,"%d %d %d %d %f",&id,&j,&m,&a,&temp)!=EOF) {for(i=0;i<n;i++) { if(tab_an[i]==a) tab_temp[i]+=temp/365;} } } return n; }
C
#ifndef CACHEDQUEUE_H_ #define CACHEDQUEUE_H_ #include "queue.h" typedef struct CachedQueue CachedQueue; struct CachedQueue { Queue* queue; /* base class */ /* new attributes */ char filename[80]; int numberElementsOnDisk; /* aggregation in subclass */ Queue* outputQueue; /* inherited virtual functions */ int (*is_full) (CachedQueue* const me); int (*is_empty)(CachedQueue* const me); int (*get_size)(CachedQueue* const me); void (*insert) (CachedQueue* const me, int k); int (*remove) (CachedQueue* const me); /* new virtual functions */ void (*flush)(CachedQueue* const me); void (*load)(CachedQueue* const me); }; /* Constructors and destructors:*/ void CachedQueue_Init(CachedQueue* const me, char* fName, int (*isFullfunction)(CachedQueue* const me), int (*isEmptyfunction)(CachedQueue* const me), int (*getSizefunction)(CachedQueue* const me), void (*insertfunction)(CachedQueue* const me, int k), int (*removefunction)(CachedQueue* const me), void (*flushfunction)(CachedQueue* const me), void (*loadfunction)(CachedQueue* const me)); void CachedQueue_Cleanup(CachedQueue* const me); /* Operations */ int CachedQueue_is_full(CachedQueue* const me); int CachedQueue_is_empty(CachedQueue* const me); int CachedQueue_get_size(CachedQueue* const me); void CachedQueue_insert(CachedQueue* const me, int k); int CachedQueue_remove(CachedQueue* const me); void CachedQueue_flush(CachedQueue* const me); void CachedQueue_load(CachedQueue* const me); CachedQueue * CachedQueue_Create(void); void CachedQueue_Destroy(CachedQueue* const me); #endif /*CACHEDQUEUE_H_*/