language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <malloc.h> typedef struct __node { int data; struct __node *node_l; struct __node *node_r; }tree; tree *get_node() { tree *tmp; tmp = (tree *)malloc(sizeof(tree)); tmp->node_l = NULL; tmp->node_r = NULL; return tmp; } void print_tree(tree *root) { printf("%d\n", root->data); } void tree_ins(tree **root, int data) // INSERT 진행중... { tree *tmp; if(!(*root)) { *root = get_node(); (*root)->data = data; } } int main(void) { int i; tree *root = NULL; int data[12] = {50, 20, 10, 40, 30, 35, 80, 90, 100, 60, 70, 75}; for(i = 0; i < 1; i++) tree_ins(&root, data[i]); print_tree(root); // printf("\n"); // tree_del(&root, 35); #if 1 // tree_del(&root, 90); // tree_del(&root, 50); // tree_del(&root, 20); // tree_del(&root, 80); #endif // print_tree(root); return 0; }
C
/* ============================================================================ Name : Tp1_laboratorio.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include <stdio_ext.h> #include "operaciones.h" #include "utn.h" int main(void) { float num1=0; float num2=0; float resultados[4]; int resultados_factorial[2]; int divicionOK; int opc=999; char letra; do{ printf("\n-----CALCULADORA----- " "\n 1-ingresar el 1er operando (A= %0.2f)" "\n 2-ingresar el 2do operando (B= %0.2f)" "\n 3-Calcular todas las Operaciones" "\n 4-informar resultados" "\n 5-salir\n",num1,num2); scanf("%d",&opc); __fpurge(stdin); switch(opc){ case 1: if(getFloat("\nindique el un numero", "\nerror, igrese solo numeros", &num1, 3, 9999999, -9999999)!=0) { printf("\nerror!!!!los caracteres ingresados no son validos vuelva a intentarlo\n"); } break; case 2: if(getFloat("indique el un numero", "error, igrese solo numeros", &num2, 3, 999999990, -9999999)!=0) { printf("\nerror!!!!los caracteres ingresados no son validos vuelva a intentarlo\n"); } break; case 3: do{ getChar("\na) Calcular la suma (A+B)" "\nb) Calcular la resta (A-B)" "\nc) Calcular la division (A/B)" "\nd) Calcular la multiplicacion (A*B)" "\ne) Calcular el factorial (A!)\nf)salir","error, no se indico un caracter valido\n", &letra, 3, 'f', 'a'); switch(letra) { case 'a': if(!sumar_flotantes(num1, num2, &resultados[0])){ printf("\nSuma realizada con exito"); } else{ printf("\nNo se ha podido realizar la operacion"); } break; case 'b': if(!restar_flotantes(num1, num2, &resultados[1])){ printf("\nresta realizada con exito"); } else{ printf("\nNo se ha podido realizar la operacion"); } break; case 'c': divicionOK=dividir_flotantes(num1, num2, &resultados[2]); if(divicionOK==0) { printf("\nDivicion realizada con exito"); } else{ printf("\nNo se ha podido realizar la operacion"); } break; case 'd': if(!multiplicar_flotantes(num1, num2, &resultados[3])){ printf("\nMultiplicacion realizada con exito"); } else{ printf("\nNo se ha podido realizar la operacion"); } break; case 'e': if(!factorial_float(num1, &resultados_factorial[0])) { printf("\nFactorial de A calculado Correctamente"); } if(!factorial_float(num2, &resultados_factorial[1])) { printf("\nFactorial de B calculado Correctamente"); } break; } }while(letra!='f'); break; case 4: if(!divicionOK) { printf("\na) “El resultado de A+B es: %0.2f”" "\nb) “El resultado de A-B es: %0.2f”" "\nc) “El resultado de A/B es: %0.2f”" "\nd) “El resultado de A*B es: %0.2f”" "\ne) “El factorial de A es: %d y El factorial de B es: %d”",resultados[0],resultados[1],resultados[2],resultados[3],resultados_factorial[0],resultados_factorial[1]); } else{ printf("\na) “El resultado de A+B es: %0.2f”" "\nb) “El resultado de A-B es: %0.2f”" "\nc) “No es posible dividir por cero”" "\nd) “El resultado de A*B es: %0.2f”" "\ne) “El factorial de A es: %d y El factorial de B es: %d”",resultados[0],resultados[1],resultados[3],resultados_factorial[0],resultados_factorial[1]); } break; } }while(opc!=5); return EXIT_SUCCESS; }
C
/* cc greedy.c -o greedy -O Group Name: KaheKahe kakai Group Members: Marcelo Melo, Bryan Hinton, Carl Mitchell. marcelom@cs.byu.edu Greedy */ #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <time.h> /*FUNCTIONS*/ unsigned long find(unsigned long); unsigned long setUnion(unsigned long, unsigned long); long peek(unsigned long); long is_legal(unsigned long); int leftjob(long jobnum); int rightjob(long jobnum); unsigned long add(unsigned long newjob); void prepare_data (void); void greedy (void); void print(unsigned long); void printmax(unsigned long); unsigned long pop_head(void); void heapify(void); void adjust(unsigned long); unsigned long loadfile(char filename[]); void print_output(char*, double); /*GLOBAL VARIABLES*/ #define MAXDEAD 1000000 #define MAXJOBS 1000001 //TYPE DEFINITIONS struct _JOBSET { unsigned long parent; unsigned long children; long hidden; }; typedef struct _JOBSET JOBSET; unsigned long bids[MAXJOBS][2]; JOBSET time_job[MAXDEAD]; unsigned long num_in_list = 0; unsigned long heap_size = 0; unsigned long currprice = 0; double total_profit = 0; clock_t starttime, endtime; unsigned long maxdeadline; unsigned long numinserted; /*MAIN*/ int main(int argc, char *argv[]){ if (argc < 2){ printf ("Usage: greedy <filename>\n");exit (1); } maxdeadline = 1; num_in_list = loadfile (argv[1]); heap_size = num_in_list; prepare_data(); greedy(); print_output (argv[1], total_profit); return 0; }/*main*/ /*PREPARE_DATA*/ void prepare_data(void){ unsigned long i; heapify(); for (i=0; i < MAXDEAD; i++){ time_job[i].parent = i; time_job[i].children = 1; time_job[i].hidden = i; } }/*prepare_data*/ /*GREEDY*/ void greedy(void){ unsigned long i, j, n; long k; n=0; for(i = 0; i < num_in_list; i++){ j = pop_head(); k=is_legal(j); if (k >-1){ add(k); numinserted++; } if (numinserted >= maxdeadline) break; } }/*greedy*/ /*ISLEGAL*/ long is_legal(unsigned long newjob) { unsigned long parent; long hidden; parent = find(newjob); hidden = peek(parent); if (hidden == -1 ) return -1; else return hidden; }/*islegal*/ unsigned long find(unsigned long startnode) { if (startnode != time_job[startnode].parent) { time_job[startnode].parent = find(time_job[startnode].parent); } return time_job[startnode].parent; } unsigned long setUnion(unsigned long set1, unsigned long set2) { if (time_job[set1].children >= time_job[set2].children) { time_job[set1].children += time_job[set2].children; time_job[set2].parent = set1; return set1; } else if (time_job[set1].children < time_job[set2].children){ time_job[set2].children += time_job[set1].children; time_job[set1].parent = set2; time_job[set2].hidden = time_job[set1].hidden; return set2; } } long peek(unsigned long node) { return time_job[node].hidden; } /*ADD*/ unsigned long add(unsigned long newjob) { int leftval = 0; int rightval = 0; unsigned long parent, parent2; leftval = leftjob((long)newjob - 1); rightval = rightjob((long)newjob + 1); time_job[newjob].hidden = (long)newjob -1; total_profit = total_profit + currprice; currprice = 0; switch (leftval) { case -1: switch (rightval) { case 1: time_job[newjob].hidden = -1; break; case 2: parent = setUnion(newjob, find(newjob + 1)); time_job[parent].hidden = -1; break; } break; case 1: switch (rightval) { case -1: time_job[newjob].hidden = (long)newjob-1; break; case 1: time_job[newjob].hidden = (long)newjob-1; break; case 2: parent = setUnion(newjob, find(newjob + 1)); time_job[parent].hidden = (long)newjob-1; break; } break; case 2: switch (rightval) { case -1: setUnion(find(newjob - 1),newjob); break; case 1: setUnion(find(newjob -1),newjob); break; case 2: parent = setUnion(find(newjob -1),newjob); setUnion(parent, find(newjob + 1)); break; } break; }//end of switch }/*add*/ int leftjob(long jobnum) { if (jobnum == -1) { return -1; } else if (time_job[jobnum].hidden == jobnum) { return 1; } else return 2; } int rightjob(long jobnum) { if (jobnum == 1000000) { return -1; } else if (time_job[jobnum].hidden == jobnum) { return 1; } else return 2; } /*PRINT*/ void print(unsigned long n) { unsigned long i; for(i=0; i < n; i++) { printf("%d. p=%lu c=%lu h=%d\n",i, time_job[i].parent, time_job[i].children, time_job[i].hidden); } printf("\n\n"); }/*print*/ /*PRINTMAX*/ void printmax(unsigned long n) { unsigned long i,time; for(i=0; i < n; i++) { time = pop_head(); printf(" (%lu %lu) \n", time, currprice); currprice = 0; } }/*printmax*/ /*HEAPIFY*/ void heapify (void){ unsigned long i; for (i = heap_size/2; i > 0; i--) { adjust(i); } }/*heapify*/ /*ADJUST*/ void adjust (unsigned long i){ unsigned long j = 2*i; unsigned long price = bids[i][0]; unsigned long deadline = bids[i][1]; while (j <= heap_size){ if ((j < heap_size) && (bids[j][0] < bids[j+1][0])) j++; if (price >= bids[j][0]) break; bids[j/2][0] = bids[j][0]; bids[j/2][1] = bids[j][1]; j = j * 2; } bids[j/2][0] = price; bids[j/2][1] = deadline; }/*adjust*/ /*POP_HEAD*/ unsigned long pop_head (void){ unsigned long deadline; if (heap_size == 0) return 0; currprice = bids[1][0]; deadline = bids[1][1]; bids[1][0] = bids[heap_size][0]; bids[1][1] = bids[heap_size][1]; heap_size--; adjust(1); return deadline; }/*pop_head*/ void print_output(char filename[], double max_profit){ printf("Group Name: %s\n", "KaheKahe kakai"); printf("Group Members: %s\t%s\t%s\n", "Marcelo Melo", "Bryan Hinton", "Carl Mitchell"); printf("File: %s\tMaximum Profit: %.1f\n", filename, max_profit); } /*OUTPUT void print_output(char *filename, double profit, float time_sec){ printf("File: %s Maximum Profit: %lf\n", filename, profit); printf("Time: %.2f seconds\n", time_sec); }output*/ /*LOADFILE*/ unsigned long loadfile(char filename[]){ unsigned long total_lines,numbids,numlines, sum, true_sum, i,x, filesize; int fp ; char * Buffer; char num_ptr[20]; char ch; int state; fp = open(filename, O_RDONLY); if (fp == -1){ printf("Could not open input file\n"); exit(1); } filesize = lseek(fp,0,SEEK_END); Buffer = malloc(filesize); lseek(fp,0,SEEK_SET); read(fp,Buffer,filesize); Buffer[filesize] = 0; i=0; x=0; state=0; while(1){ ch = Buffer[i]; if(ch >= '0' && ch <= '9'){ num_ptr[x] = ch; x++; } else if(x > 0){ num_ptr[x] = 0; total_lines = (unsigned long) atol(num_ptr); num_ptr[0]=0; x=0; i++; break; } i++; } numlines = 1; numbids = 1; while(i <= filesize) { ch = Buffer[i]; if(ch >= '0' && ch <= '9'){ num_ptr[x] = ch; x++; } else if(state==0 && x>0){ num_ptr[x] = 0; bids[numlines][0] =(unsigned long) atol(num_ptr); state =1; num_ptr[0]=0; x=0; } else if(state == 1 && x>0){ num_ptr[x]=0; bids[numlines][1] =(unsigned long) atol(num_ptr); if (bids[numlines][1] > maxdeadline) { maxdeadline = bids[numlines][1]; } state=0; num_ptr[0]=0; x=0; if (bids[numlines][1] != 0){ if (bids[numlines][1] > 1000000) bids[numlines][1] = 1000000; bids[numlines][1]--; numlines++; } numbids++; } i++; }/* while */ numbids--; numlines--; if (total_lines==0){ printf("\nEmpty files are useless\n"); exit(1); } if (total_lines != numbids) { printf("\nError: file lines don't match in %s\n", filename); printf("Specified # of lines: %d\nActual # of lines: %d\n",numbids, total_lines); exit(1); } if (close(fp)) { printf("\nError: file %s won't close\n", filename); exit(1); } free(Buffer); return(numlines); }/*Loadfile*/
C
// implementation of field void initField(int field[FLD_DEF_LIN][FLD_DEF_COL]) { int lin, col; for(lin = 0; lin < FLD_DEF_LIN; lin++){ for(col = 0; col < FLD_DEF_COL; col++){ field[lin][col] = 0; } } } void insertBlock(int field[FLD_DEF_LIN][FLD_DEF_COL], int line, int col) { if(line >= 0 && line <= FLD_SIZE_LIN && col >= 0 && col <= FLD_SIZE_COL){ field[line][col] = cBlock; } } void makeField(int field[FLD_DEF_LIN][FLD_DEF_COL], int clear) { int lin, col = 0; if(clear != 0) clear(); // print passed field for(lin = FLD_VIZ_STRT; lin <= FLD_SIZE_LIN; lin++){ for(col = 0; col <= FLD_SIZE_COL; col++){ if(field[lin][col] == 0){ move(lin + FLD_START_LIN, col * 2 + FLD_START_COL + 1); } else if(field[lin][col] == 1){ attron(COLOR_PAIR(1)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(1)); } else if(field[lin][col] == 2){ attron(COLOR_PAIR(2)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(2)); } else if(field[lin][col] == 3){ attron(COLOR_PAIR(3)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(3)); } else if(field[lin][col] == 4){ attron(COLOR_PAIR(4)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(4)); } else if(field[lin][col] == 5){ attron(COLOR_PAIR(5)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(5)); } else if(field[lin][col] == 6){ attron(COLOR_PAIR(6)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(6)); } else if(field[lin][col] == 7){ attron(COLOR_PAIR(7)); mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, ' '); addch(' '); attroff(COLOR_PAIR(7)); } else{ mvaddch(lin + FLD_START_LIN, col * 2 + FLD_START_COL, cBlock); addch(cBlock); } } } refresh(); } void makeFrame(char type) { int i = 0; int lin = FLD_START_LIN + FLD_VIZ_STRT - 1; int col = FLD_START_COL - 2; move(lin, col); attron(COLOR_PAIR(7)); //print top row for(i = 0; i < FLD_SIZE_COL * 2 + 6; i++){ addch(' '); } // print side lines for(i = 0; i <= FLD_SIZE_LIN - FLD_VIZ_STRT; i++){ move(lin, col); addch(' '); addch(' '); move(lin, col + FLD_SIZE_COL * 2 + 4); addch(' '); addch(' '); lin++; } // print bottom line move(lin, col); for(i = 0; i < FLD_SIZE_COL * 2 + 6; i++){ addch(' '); } refresh(); curs_set(0); attroff(COLOR_PAIR(7)); } void makeScoreBoard() { int i = 0; // set cursor to same line as top of well and 2 char right int lin = FLD_START_LIN + FLD_VIZ_STRT - 1; int col = FLD_START_COL + FLD_SIZE_COL * 2 + 6; move(lin++, col); // print top row for(i = 0; i < BRD_SIZE_COL; i++){ addch('*'); } // print lines move(lin++, col); printw("* TerminalTetris v1.0 *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* move left: a *"); move(lin++, col); printw("* move right: d *"); move(lin++, col); printw("* move down: s *"); move(lin++, col); printw("* rotate left: q *"); move(lin++, col); printw("* rotate right: e *"); move(lin++, col); printw("* insta quit: c *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* score: %04d *", gScore); move(lin++, col); printw("* level: %02d *", gLevel); move(lin++, col); printw("* lines: %03d *", gLines); move(lin++, col); printw("* *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* scoring nintendo-ish *"); move(lin++, col); printw("* 4-rows ftw! *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* *"); move(lin++, col); printw("* >malan for president< *"); move(lin++, col); // print bottom row for(i = 0; i < BRD_SIZE_COL; i++){ addch('*'); } } int compareFields(int playField[FLD_DEF_LIN][FLD_DEF_COL], int blockField[FLD_DEF_LIN][FLD_DEF_COL]) { // one or more flags is raised int event = 0; // detect crash, block found in same spot or block found above line 20 gFlags.crash = 0; for(int y = 0; y < FLD_SIZE_LIN; y++){ for(int x = 0; x < FLD_SIZE_COL; x++){ if(playField[y][x] != 0 && y < 3){ gFlags.crash++; event++; } else if(playField[y][x] != 0 && blockField[y][x] != 0){ gFlags.crash++; event++; } } } // topdown, block found in blockField one line above playField or bottom of playfield // figure why +1 was needed! gFlags.topDown = 0; for(int y = 1; y < FLD_SIZE_LIN; y++){ for(int x = 0; x < FLD_SIZE_COL + 1; x++){ if(playField[y][x] != 0 && blockField[y - 1][x] != 0){ gFlags.topDown++; event++; } else if(y == FLD_SIZE_LIN - 1 && blockField[y][x] != 0){ gFlags.topDown++; event++; } } } // leftright, block found in blockField one column right of playField gFlags.leftRight = 0; for(int y = 0; y < FLD_SIZE_LIN; y++){ for(int x = 0; x < FLD_SIZE_COL - 1; x++){ if(playField[y][x] != 0 && blockField[y][x + 1] != 0){ gFlags.leftRight++; event++; } } } // rightleft, block found in blockField one column left of playField gFlags.rightLeft = 0; for(int y = 0; y < FLD_SIZE_LIN; y++){ for(int x = 1; x < FLD_SIZE_COL; x++){ if(playField[y][x] != 0 && blockField[y][x - 1] != 0){ gFlags.rightLeft++; event++; } } } // leftframe, block found in blockField one column right of left frame side gFlags.leftFrame = 0; for(int y = 0; y < FLD_SIZE_LIN; y++){ if(blockField[y][0] != 0){ gFlags.leftFrame++; event++; } } // rightframe, block found in blockField one column left of right frame side gFlags.rightFrame = 0; for(int y = 0; y < FLD_SIZE_LIN; y++){ if(blockField[y][FLD_SIZE_COL] != 0){ gFlags.rightFrame++; event++; } } // return number of raised flags return event; } int detectLines(int field[FLD_DEF_LIN][FLD_DEF_COL]) { int lines = 0; for(int y = 0; y < FLD_SIZE_LIN; y++){ for(int x = 0; x < FLD_SIZE_COL; x++){ // next line if gap is found if(field[y][x] == 0){ break; } // if end of line reached, update lines if(x == FLD_SIZE_COL - 1){ lines++; removeLine(y, field); } } } gScore = gScore + getScore(gLevel, lines); return lines; } void removeLine(int line, int field[FLD_DEF_LIN][FLD_DEF_COL]) { // delete line for(int x = 0; x <= FLD_SIZE_COL; x++){ field[line][x] = 0; } // shift down lines above deleted line for(int y = line - 1; y > 0; y--){ for(int x = 0; x <= FLD_SIZE_COL; x++){ field[y + 1][x] = field[y][x]; } } } void updateAll(int playField[FLD_DEF_LIN][FLD_DEF_COL], int blockField[FLD_DEF_LIN][FLD_DEF_COL]) { makeField(playField, 1); makeField(blockField, 0); makeFrame(cBlock); makeScoreBoard(); } void pressKeyToStart() { move(FLD_START_LIN + 12, FLD_START_COL + 2); printw("press s to start"); refresh(); } void printGameOver(int level) { if(level == 1){ move(FLD_START_LIN + 12, FLD_START_COL + 5); printw("GAME OVER!"); move(FLD_START_LIN + 14, FLD_START_COL + 3); printw("press s to try"); move(FLD_START_LIN + 15, FLD_START_COL + 7); printw("again"); } else{ move(FLD_START_LIN + 12, FLD_START_COL + 6); printw("GAME OVER"); } }
C
#include<stdio.h> int main(){ int cases; int n,k,res,i; scanf("%d",&cases); while(cases--){ scanf("%d%d",&n,&k); res=0; for(i=0;i<n;i++){ if(k%4==1||k%4==2) res|=1<<i; k>>=1; } printf("%d\n",res); } return 0; }
C
/* COPYRIGHT The following is a notice of limited availability of the code, and disclaimer which must be included in the prologue of the code and in all source listings of the code. (C) COPYRIGHT 2022 Dr. Ralf Schlatterbeck Open Source Consulting Permission is hereby granted to use, reproduce, prepare derivative works, and to redistribute to others. This software was authored by: Ralf Schlatterbeck Open Source Consulting */ /*!*************************************************************************** * \file * This file contains linear algebra algorithms. * \authors Author: Ralf Schlatterbeck *****************************************************************************/ /*!*************************************************************************** * \defgroup linalg Linear Algebra Algorithms *****************************************************************************/ #include <stdlib.h> #include "pgapack.h" #if !defined(DOXYGEN_SHOULD_SKIP_THIS) #define LIN_ERROR_SINGULAR 1 #endif /* DOXYGEN_SHOULD_SKIP_THIS */ /*!*************************************************************** \brief Solve a linear matrix equation, or system of linear scalar equations. \ingroup linalg \param n size of the matrix \param a n * n matrix \param b vector of lenth n \return 0 if no error, a positive error-code otherwise, returns the solution in b, a and b are modified in-place \rst Description ----------- Linear matrix equation :math:`ax = b` \endrst ******************************************************************/ int LIN_solve (int n, void *a, double *b) { int col, row, row2; DECLARE_DYNARRAY (int, rowidx, n); DECLARE_DYNPTR (double, m, n) = a; DECLARE_DYNARRAY (double, r, n); for (row=0; row<n; row++) { rowidx [row] = row; } for (row=0; row<n-1; row++) { for (row2=row; row2<n; row2++) { if (DEREF2_DYNPTR (m, n, rowidx [row2], rowidx [row]) != 0) { int tmp = rowidx [rowidx [row]]; rowidx [rowidx [row]] = rowidx [rowidx [row2]]; rowidx [rowidx [row2]] = tmp; break; } if (row2 == n) { return LIN_ERROR_SINGULAR; } } for (row2=row+1; row2<n; row2++) { /* m [rowidx [row2]][row] / m [rowidx [row]][row]; */ double c = DEREF2_DYNPTR (m, n, rowidx [row2], row) / DEREF2_DYNPTR (m, n, rowidx [row], row); for(col=row+1; col<n; col++) { /* m [rowidx [row2]][col] -= c * m [rowidx [row]][col]; */ DEREF2_DYNPTR (m, n, rowidx [row2], col) -= c * DEREF2_DYNPTR (m, n, rowidx [row], col); } /* m [rowidx [row2]][row] = 0; */ DEREF2_DYNPTR (m, n, rowidx [row2], row) = 0; b [rowidx [row2]] -= c * b [rowidx [row]]; } } for (row=n-1; row>=0; row--) { double result = 0; for (col=row+1; col<n; col++) { /* result += m [rowidx [row]][col] * b [rowidx [col]]; */ result += DEREF2_DYNPTR (m, n, rowidx [row], col) * b [rowidx [col]]; } /* ... / m [rowidx [row]][row] */ b [rowidx [row]] = (b [rowidx [row]] - result) / DEREF2_DYNPTR (m, n, rowidx [row], row); r [row] = b [rowidx [row]]; if (isnan (r [row])) { return LIN_ERROR_SINGULAR; } } memcpy (b, r, sizeof (double) * n); return 0; } /*!*************************************************************** \brief Print matrix. \ingroup linalg \param n size of the matrix \param a n * n matrix \return None \rst Description ----------- Print matrix :math:`a`. Mainly used for testing. \endrst ******************************************************************/ void LIN_print_matrix (int n, void *a) { DECLARE_DYNPTR (double, m, n) = a; int row, col; for (row=0; row<n; row++) { for (col=0; col<n; col++) { printf ("%e ", DEREF2_DYNPTR (m, n, row, col)); } printf ("\n"); } printf ("\n"); } /*!*************************************************************** \brief Print vector. \ingroup linalg \param n size of the vector \param v vector of length n \return None \rst Description ----------- Print vector :math:`v`. Mainly used for testing. \endrst ******************************************************************/ void LIN_print_vector (int n, double *v) { int col; for (col=0; col<n; col++) { printf ("%e ", v [col]); } printf ("\n\n"); } /*!*************************************************************** \brief Dot product of two vectors. \ingroup linalg \param dim size of the vectors \param v1 first vector of length n \param v2 second vector of length n \return The dot product of v1 and v2 ******************************************************************/ double LIN_dot (int dim, double *v1, double *v2) { int i; double ret = 0; for (i=0; i<dim; i++) { ret += v1 [i] * v2 [i]; } return ret; } /*!*************************************************************** \brief Euclidian distance of two vectors. \ingroup linalg \param dim size of the vectors \param v1 first vector of length n \param v2 second vector of length n \return The euclidian distance of v1 and v2 ******************************************************************/ double LIN_euclidian_distance (int dim, double *v1, double *v2) { int i; double ret = 0; for (i=0; i<dim; i++) { ret += pow (v1 [i] - v2 [i], 2); } return sqrt (ret); } /*!*************************************************************** \brief Euclidian norm (2-norm) of a vector. \ingroup linalg \param dim size of the vectors \param v vector of length n \return The euclidian norm of v ******************************************************************/ double LIN_2norm (int dim, double *v) { return sqrt (LIN_dot (dim, v, v)); } /*!*************************************************************** \brief Greatest common divisor of two integers \ingroup linalg \param a first integer \param b second integer \return The greatest common divisor (gcd) of a and b ******************************************************************/ int LIN_gcd (int a, int b) { int m; if (b > a) { return LIN_gcd (b, a); } m = a % b; if (!m) { return b; } return LIN_gcd (b, m); } /* * ( a ) * LIN_binom: Compute binom of two integers ( ) * ( b ) * Will return 0 on overflow */ /*!*************************************************************** \brief Compute binomial coefficient of two integers \ingroup linalg \param a first integer \param b second integer \return Binomial coefficient \rst Description ----------- Computes :math:`\binom{a}{b}` \endrst ******************************************************************/ size_t LIN_binom (int a, int b) { int i, j; DECLARE_DYNARRAY (size_t, numer, b); DECLARE_DYNARRAY (size_t, denom, b); int idxn = 0, idxd = 0; size_t r; assert (a > b); assert (b >= 1); if (b > a / 2) { b = a - b; } for (i=1; i<=b; i++) { int n = a - b + i; int d = i; for (j=0; j<idxn; j++) { int g = LIN_gcd (numer [j], d); if (g > 1) { numer [j] /= g; d /= g; } if (d == 1) { break; } } if (d > 1) { denom [idxd++] = d; } for (j=0; j<idxd; j++) { int g = LIN_gcd (n, denom [j]); if (g > 1) { denom [j] /= g; n /= g; } if (n == 1) { break; } } if (n > 1) { numer [idxn++] = n; } } for (i=0; i<idxd; i++) { assert (denom [i] == 1); } r = 1; for (i=0; i<idxn; i++) { unsigned int m = r * numer [i]; if (m < r || m > INT_MAX) { return 0; } r = m; } return r; } /*!*************************************************************** \brief Normalize a vector with dimension dim to the n-dimensional reference hyperplane. \ingroup linalg \param dim dimension \param v vector of dimension dim \return The vector v is modified in-place \rst Description ----------- Hyperplane is probably a misnomer, it's a 3-dimensional tetraeder for dimension 4. It *is* a plane for the 3-dimensional case going through the point 1 on each axis. \endrst ******************************************************************/ void LIN_normalize_to_refplane (int dim, double *v) { int j; double sq = sqrt (dim); double norm = 0; /* Scalar product of v with the middle of the reference plane */ for (j=0; j<dim; j++) { norm += v [j] * (1.0 / sq); } for (j=0; j<dim; j++) { v [j] = v [j] / norm / sq; } } /*!*************************************************************** \brief Static recursive function for \ref LIN_dasdennis. \ingroup internal \param dim dimension \param npart Number of partitions \param depth Recursion depth \param sum Number of points so far \param p Pointer to created points, memory must be already allocated \return The number of points allocated ******************************************************************/ static int dasdennis (int dim, int npart, int depth, int sum, void *p) { DECLARE_DYNPTR(double, vec, dim) = p; int n = npart - sum + 1; int i, offset = 0; if (depth == dim - 1) { DEREF2_DYNPTR (vec, dim, 0, depth) = 1.0 - (double)sum / npart; return 1; } for (i=0; i<n; i++) { double v = (double)i / npart; if (i && depth) { memcpy ( DEREF1_DYNPTR (vec, dim, offset) , DEREF1_DYNPTR (vec, dim, 0) , sizeof (double) * dim ); } DEREF2_DYNPTR (vec, dim, offset, depth) = v; offset += dasdennis (dim, npart, depth + 1, sum + i, DEREF1_DYNPTR (vec, dim, offset)); } return offset; } /*!*************************************************************** \brief Static function for \ref LIN_dasdennis scaling of points \ingroup internal \param dim dimension \param npoints Number of points \param scale Scaling factor \param dir Direction vector \param v Pointer to points, points must have been created \return None \rst Description ----------- When scaling we translate the scaled-down points from the centroid of the shifted points to the reference direction on the reference plane. \endrst ******************************************************************/ STATIC void dasdennisscale (int dim, int npoints, double scale, double *dir, void *v) { int i, j; DECLARE_DYNARRAY (double, dir_normed, dim); DECLARE_DYNARRAY (double, centroid, dim); DECLARE_DYNPTR (double, vec, dim) = v; assert (scale > 0); assert (scale < 1); for (i=0; i<npoints; i++) { for (j=0; j<dim; j++) { DEREF2_DYNPTR (vec, dim, i, j) *= scale; } } for (j=0; j<dim; j++) { dir_normed [j] = dir [j]; } LIN_normalize_to_refplane (dim, dir_normed); for (j=0; j<dim; j++) { centroid [j] = dir_normed [j] * scale; } /* Now shift points back to reference plane */ for (i=0; i<npoints; i++) { for (j=0; j<dim; j++) { DEREF2_DYNPTR (vec, dim, i, j) += dir_normed [j] - centroid [j]; } } } /*!*************************************************************** \brief Compute Das & Dennis points to allocated memory. \ingroup linalg \param dim dimension \param npart Number of partitions \param scale Scaling factor \param dir Direction vector \param npoints Number of points \param mem Memory for points, memory must have been allocated \return None \rst Description ----------- This is the case where the memory is already allocated. For more details see :c:func:`LIN_dasdennis`. \endrst ******************************************************************/ void LIN_dasdennis_allocated (int dim, int npart, double scale, double *dir, int npoints, void *mem) { dasdennis (dim, npart, 0, 0, mem); if (scale != 1 && dir != NULL) { dasdennisscale (dim, npoints, scale, dir, mem); } } /*!*************************************************************** \brief Allocate memory and compute Das & Dennis points. \ingroup standard-api \param dim dimension \param npart Number of partitions \param result List of existing points to extend \param nexist Number of existing points \param scale Scaling factor \param dir Direction vector \return Number of points allocated, -1 on error \rst Description ----------- It will re-alloc the exiting array pointer pointed to by result (this must be a ``NULL`` pointer if no pre-existing points are given) and return the new number of points. Note that if there are no pre-existing points, the pointer pointed to by ``result`` must be ``NULL`` and ``nexist`` must be 0. Optionally the points can be scaled (with 0 < scale <= 1) and shifted in the direction of a given point back onto the reference hyperplane. This is not done if ``dir == NULL`` or ``scale == 1``. A previously allocated result will be de-allocated in case of error. \endrst ******************************************************************/ int LIN_dasdennis (int dim, int npart, void *result, int nexist, double scale, double *dir) { void **r = result; DECLARE_DYNPTR(double, vec, dim); int npoints = LIN_binom (dim + npart - 1, npart); void *new = NULL; assert ( (*r == NULL && nexist == 0) || (*r != NULL && nexist != 0) ); if (npoints < 0) { goto err; } if (nexist) { new = realloc (*r, (nexist + npoints) * sizeof (double) * dim); } else { new = malloc (sizeof (double) * dim * npoints); } if (new == NULL) { goto err; } vec = *r = new; LIN_dasdennis_allocated (dim, npart, scale, dir, npoints, DEREF1_DYNPTR (vec, dim, nexist)); return nexist + npoints; err: if (nexist) { free (*r); *r = NULL; } return -1; }
C
#include "holberton.h" #include <stdlib.h> #include <stdio.h> /** * string_nconcat - concat the strings. * @s1: the first string. * @s2: the second string. * @n: delimiter of the second string. * Return: Always 0. */ char *string_nconcat(char *s1, char *s2, unsigned int n) { int a = 0; unsigned int b = 0; int c = 0; unsigned int d = 0; char *copy; if (s1 == NULL) { s1 = ""; } if (s2 == NULL) { s2 = ""; } while (s1[a] != '\0') a++; while (s2[b] != '\0' && b < n) b++; if (n >= b) { n = b; } copy = malloc((sizeof(char) * (a + b)) + 1); if (copy == NULL) { return ('\0'); } while (s1[c] != '\0') { copy[c] = s1[c]; c++; } while (s2[d] != '\0' && d < n) { copy[c] = s2[d]; d++; c++; } copy[c] = '\0'; return (copy); }
C
typedef struct node { int value; struct node *next; } node_t; node_t* createNode(int nValue); int insertNode(node_t** head,int nValue); node_t* findValue(node_t* head, int nValue); void deleteNode(node_t* head, int nValue); void deleteList(node_t* head); void displayList(node_t *head);
C
/* date = January 9th 2021 10:37 am */ #ifndef UTILS_H #define UTILS_H #pragma warning(push) #pragma warning( disable : 4514 ) #include <stdint.h> #include <stddef.h> //~ TYPEDEFS typedef int8_t s8; typedef int16_t s16; typedef int32_t s32; typedef int64_t s64; typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef int32_t b32; typedef unsigned int uint; typedef size_t size_t; typedef size_t memoryIndex; typedef float f32; typedef double f64; typedef uintptr_t p64; #define U32_MAX 0xFFFFFFFF #define U64_MAX 0xFFFFFFFFFFFFFFFF //~ MACROS #define localPersist static #define global static #define internal static #define readOnly const #define PI 3.14159265359f #define KB(value) (value * 1024LL) #define MB(value) (KB(value) * 1024LL) #define GB(value) (MB(value) * 1024LL) #define TB(value) (GB(value) * 1024LL) #define ARRAY_COUNT(array) (sizeof(array) / sizeof(array[0])) #if JED_SLOW #define ASSERT(expression)\ if(!(expression)) {\ *(volatile int*)0 = 0;\ } #else #define ASSERT(expression) #endif #define STRING(name) #name #define IS_POWER_OF_2(x) ((x & (x - 1)) == 0) #define CLAMP(value, min, max) (value <= min) ? min : (value >= max) ? max : value; //~-------------Swap ---------------------- #define SWAP(a, b) do { \ u8 swapTemp[(sizeof(a) == sizeof(b)) ? sizeof(a) : -1]; \ memcpy(swapTemp, &a, sizeof(a)); \ memcpy(&a, &b, sizeof(a)); \ memcpy(&b, swapTemp, sizeof(a)); \ } while(0) //~ Truncate inline internal u32 truncate_safe_s64(s64 value) { // TODO(Jai): Defines for maximum values (u32_t) ASSERT(value <= 0xFFFFFFFF); u32 result = (u32)value; return result; } #pragma warning(pop) #endif //UTILS_H
C
/** * 1、维护一个libuv的event loop 供其他的模块调用 * 2、管理程序的生命周期 * * https://github.com/luohaha/Chinese-uvbook * http://luohaha.github.io/Chinese-uvbook/ */ #include <uv.h> #include "ry_mqtt.h" #include "ry_nvr_mgr.h" #include "ry_iec61850.h" #include "ini.h" //-------------------全局变量--------------------------- uv_loop_t *ry_loop; // livuv 事件循环 char mqtt_host[100]; // 服务URL int mqtt_port; // 服务端口 uv_timer_t timer_req; // 定时器 char *ini_file_path; // 当前路径 //---------------------------------------------------- /** * 接收系统的信号,用于终止消息循环 * @param signalId */ void SigintHandler(int signalId) { MqttClean(); // 清理 MQTT 通讯 NvrClearAdps(); // 清理 video adapter IEC61850Cleanup(); // 清理 61850 uv_stop(ry_loop); // 停止消息循环 } /** * 定时事件,在这里循环执行各个功能模块的定时功能 */ static void OnTimer(uv_timer_t *handle) { //NvrOnTimer(); // video adapter 定时任务 IEC61850OnTimer(); // 61850 定时任务 } /** * 开始定时器 * 1秒后开始,没2秒触发一次 */ void TimerStart() { // start after 1 secends, repeat every 2 seconds uv_timer_start(&timer_req, OnTimer, 1000, 2000); } /** * 停止定时器 */ void TimerStop() { uv_timer_stop(&timer_req); } //主函数入口 int main(int argc, char *argv[]) { ini_file_path = argv[1]; // ---------------------设置运行参数----------------------------- ini_t *config = ini_load(ini_file_path); ini_sget(config, "mqtt", "host", "%s", mqtt_host); ini_sget(config, "mqtt", "port", "%d", &mqtt_port); ini_free(config); // ------------------------------------------------------------ signal(SIGINT, SigintHandler); // 系统信号 ry_loop = uv_default_loop(); // 初始化消息循环 uv_timer_init(ry_loop, &timer_req); // 定时器 TimerStart(); MqttInit(mqtt_host, mqtt_port); // MQTT 消息客户端链接 uv_run(ry_loop, UV_RUN_DEFAULT); // 运行消息循环 }
C
#ifndef __BST_H__ #define __BST_H__ #include <stddef.h> /* size_t */ typedef struct bst_node bst_node_t; typedef bst_node_t *bst_iter_t; typedef struct bst bst_t; typedef int(*cmp_func_t)(const void *data1, const void *data2, const void *param); typedef int(*action_func_t)(void *data, void *param); /*Description: The function creates a new binary tree data structure. @return: The function returns a pointer to bst_t structure. @errors: Returns NULL if malloc fails. */ bst_t *BstCreate(cmp_func_t cmp_func, void *param); /*Description: The function frees all the elements in the tree. @params: The function gets a pointer to the binary tree. */ void BstDestroy(bst_t *tree); /*Description: The functions inserts a new element and places it in the right place- left/right. @params: The function gets a pointer to the tree and the data to be inserted. @return: status_t @errors: malloc fail. */ bst_iter_t BstInsert(bst_t *tree, void *data); /*Description: The function removes an element from the bst. @params: The function gets an iterator to the element to be removed and a pointer to the tree. @return: iterator @errors: */ void BstRemove(bst_iter_t iterator); /*Description: The function gets an iterator and returns the data at the location. @params: The function gets an interators. @return: The function return int. @errors: */ void *BstGetData(bst_iter_t iterator); /*Description: The function returns the number of items stored in the bst. @params: The function gets a pointer to the bst. @return: The function returns the number of items in the bst. @errors: */ size_t BstSize(const bst_t *tree); /*Description: The function finds and element in the bst. @params: The function gets a pointer to the bst. @return: The function returns an iterator that points to the data or NULL if data is not in the bst. @errors: */ bst_iter_t BstFind(const bst_t *tree, void *data); /*Description: The function returns iterator to the head of the bst. @params: The function gets a pointer bst. @return: The function returns an iterator. @errors: */ bst_iter_t BstBegin(const bst_t *tree); /*Description: The function returns iterator to the tail of the bst. @params: The function gets a pointer bst. @return: The function returns an iterator. @errors: */ bst_iter_t BstEnd(const bst_t *tree); /*Description: The function returns an iterator to the n element after the current iterator position. @params: The function gets an iterator and n. @return: The function returns an iterator. @errors: */ bst_iter_t BstNext(bst_iter_t iterator); /*Description: The function returns an iterator to the n element before the current iterator position. @params: The function gets an iterator and n. @return: The function returns an iterator. @errors: */ bst_iter_t BstPrev(bst_iter_t iterator); /*Description: The function checks if bst is empty. returns 1 for TRUE, 0 for FALSE. @params: The function a pointer to the bst. @return: The function returns an int (BOOLEAN). @errors: */ int BstIsEmpty(const bst_t *tree); /*Description: The function invokes func_ptr for each element in the mentioned range. @params: A function pointer, iterator start and end. @return: int, 0 for success, 1 if one of the actions has failed @errors: */ int BstForeach(bst_iter_t from, bst_iter_t to , action_func_t action_func, void *param); /*Description: The function checks if the 2 iterators are equal. returns 1 for TRUE, 0 for FALSE. @params: The function a pointer to 2 iterators. @return: The function returns an int (BOOLEAN). @errors: */ int BstIterIsEqual(bst_iter_t iter1, bst_iter_t iter2); #endif /* __BST_H__ */
C
/* * This code snippet demonstrates simple use of malloc() to dynamically allocate * memory on the heap. */ #include <malloc.h> int main(int argc, char const *argv[]) { int *array; /* * malloc() returns a void pointer to the allocated memory starting address. * Its argument is the byte size, elements count multiplied by element size. */ array = malloc(10 * sizeof(int)); /* use array here */ free(array); /* release the allocated memory */ return 0; /* dynamically allocated memory is released when program exits */ }
C
/* 9 巨人航空公司(编程练习 8)需要另一架飞机(容量相同), 每天飞 4 班(航班 102、311、444 和519)。 把程序扩展为可以处理4个航班。 用一个顶层菜单提供航班选择和退出。 选择一个特定航班,就会出现和编程练习8类似的菜单。 但是该菜单要添加一个新选项:确认座位分配。 而且,菜单中的退出是返回顶层菜单。 每次显示都要指明当前正在处理的航班号。 另外,座位分配显示要指明确认状态。 */ #include <stdio.h> #include <string.h> #define NUM_OF_FLIGHTS 4 #define NAMESIZE 12 #define NUM_OF_SEATS 12 typedef struct seatT { int id; int reserved; char firstname[NAMESIZE]; char lastname[NAMESIZE]; } Seat; typedef struct planeT { Seat seats[NUM_OF_SEATS]; int numOfEmptySeats; } Plane; typedef struct flightT { int id; Plane plane; } Flight; typedef int Cmp (Seat *, Seat *); int nameCmp(Seat *, Seat *); void showMenu(void); void showSeatInfo(Seat); void showListOfSeats(Plane, int); void sortByName(Plane *, int, Cmp *); char * s_gets(char * st, int n); void assignSeat(Plane *); void deleteAssign(Plane *, int); void initializePlane(Plane *, int); void dealAssign(Plane *, int n, int flightID); void showTopMenu(void); void showSeatStatus(Plane p, int n); int main(int argc, char const *argv[]) { Flight flights[NUM_OF_FLIGHTS]; int flightIDs[NUM_OF_FLIGHTS] = {102, 311, 444, 519}; char ch; int i; int id; for(i = 0; i < NUM_OF_FLIGHTS; i++) { flights[i].id = flightIDs[i]; initializePlane(&(flights[i].plane), NUM_OF_SEATS); } showTopMenu(); while((ch = getchar()) != 'q') { switch (ch) { case 'a': printf("List of flights: \n"); for(i = 0; i < NUM_OF_FLIGHTS; i++) { printf("%d ", flights[i].id); } putchar('\n'); break; case 'b': puts("Please choose a flight id."); scanf("%d", &id); while (getchar() != '\n') continue; // 清理输入行 int index = -1; for(i = 0; i < NUM_OF_FLIGHTS; i++) { if(flights[i].id == id) { index = i; dealAssign(&(flights[index].plane), NUM_OF_SEATS, id); break; } } if(index == -1) { printf("Sorry, there is no flight %d\n", id); } break; default: printf("Incorrect command, try again.\n"); break; } while (getchar() != '\n') continue; /* 清理输入行 */ showTopMenu(); } return 0; } void showMenu(void) { printf("To choose a function, enter its letter label:\n"); printf("a) Show number of empty seats\n"); printf("b) Show list of empty seats\n"); printf("c) Show alphabetical list of seats\n"); printf("d) Assign a customer to a seat assignment\n"); printf("e) Delete a seat assignment\n"); printf("f) Check seat status.\n"); printf("q) Return to top menu\n"); } void showSeatInfo(Seat s) { printf("%d %12s %12s\n", s.id, s.firstname, s.lastname); } void showListOfSeats(Plane p, int n) { if(p.numOfEmptySeats < n) { printf("id firstname lastname\n"); for(int i = 0; i < n; i++) { if(p.seats[i].reserved == 1) { showSeatInfo(p.seats[i]); } } } } int nameCmp(Seat *s1, Seat *s2) { return strcmp(s1->firstname, s2->firstname); } void sortByName(Plane *p, int n, Cmp *cmp) { int i, j; Seat temp; for(i = 1; i < n; i++) { temp = (*p).seats[i]; j = i - 1; while(j >= 0 && cmp(&(*p).seats[j], &temp) > 0) { (*p).seats[j+1] = (*p).seats[j]; j--; } (*p).seats[j+1] = temp; } } char * s_gets(char * st, int n) { char * ret_val; char * find; ret_val = fgets(st, n, stdin); if (ret_val) { find = strchr(st, '\n'); // 查找换行符 if (find) // 如果地址不是 NULL, *find = '\0'; // 在此处放置一个空字符 else while (getchar() != '\n') continue; // 清理输入行 } return ret_val; } void assignSeat(Plane *p) { int id; puts("Please enter the seat id."); puts("Press [q] to stop."); while((p->numOfEmptySeats > 0) && scanf("%d", &id) == 1) { while (getchar() != '\n') continue; /* 清理输入行 */ if(p->seats[id].reserved == 1) { printf("Sorry, seat %d is taken.\n", id); } else { puts("Please enter your firstname."); s_gets(p->seats[id].firstname, NAMESIZE); puts("Please enter your lastname."); s_gets(p->seats[id].lastname, NAMESIZE); p->seats[id].reserved = 1; p->numOfEmptySeats --; } if(p->numOfEmptySeats > 0) puts("Please enter next seat id."); } } void deleteAssign(Plane *p, int n) { int id; if(p->numOfEmptySeats < n) { puts("Please enter the seat id you want to delete."); puts("Press [q] to stop."); while((p->numOfEmptySeats < n) && scanf("%d", &id) == 1) { if(p->seats[id].reserved == 0) { printf("Sorry, seat %d is not taken.\n", id); } else { printf("Delete seat %d assignment.\n", id); p->seats[id].firstname[0] = '\0'; p->seats[id].lastname[0] = '\0'; p->seats[id].reserved = 0; p->numOfEmptySeats ++; } if(p->numOfEmptySeats < n) puts("Please enter next seat id."); else puts("There is no assignment in the plane."); } } else puts("There is no assignment in the plane."); } void showTopMenu(void) { printf("To choose a function, enter its letter label:\n"); printf("a) Show list of flights\n"); printf("b) Choose a flight\n"); printf("q) Quit\n"); } void initializePlane(Plane *p, int n) { p->numOfEmptySeats = n; for(int i = 0; i < n; i++) { p->seats[i].id = i; p->seats[i].reserved = 0; p->seats[i].firstname[0] = '\0'; p->seats[i].lastname[0] = '\0'; } } void dealAssign(Plane *p, int n, int flightID) { char ch; printf("Current flight id: %d\n", flightID); showMenu(); while((ch = getchar()) != 'q') { switch (ch) { case 'a': printf("Number of empty seats: %d\n", p->numOfEmptySeats); break; case 'b': printf("Empty seats: "); for(int i = 0; i < n; i++) { if(p->seats[i].reserved == 0) { printf("%d ", p->seats[i].id); } } putchar('\n'); break; case 'c': sortByName(p, n, nameCmp); showListOfSeats(*p, n); break; case 'd': assignSeat(p); break; case 'e': deleteAssign(p, n); break; case 'f': showSeatStatus(*p, n); break; default: printf("Incorrect command, try again.\n"); break; } while (getchar() != '\n') continue; /* 清理输入行 */ printf("Current flight id: %d\n", flightID); showMenu(); } } void showSeatStatus(Plane p, int n) { for(int i = 0; i < n; i++) { printf("%d ", i); if(p.seats[i].reserved == 0) { printf("Not "); } printf("Reserved.\n"); } }
C
/* * main.c * * Created on: Mar 5, 2020 * Author: m7med */ //(12) Array that contains integer values, some of these //values are repeated with an even number of repetitions, //and only one value is repeated with an odd number of //repetitions. Write a C function that’s take the array as //input and the array size and return the number which has //odd numbers of repetitions. #include <stdio.h> #define SIZE 17 int main (void) { int arr[SIZE] = {1,1,2,2,3,3,3,3,4,4,5,5,5,7,7, 9, 9}; int current_repeated = arr[0]; unsigned int i, current_repeated_repetitions = 1, found = 0; for(i = 1; i < SIZE; i++) { if(arr[i] == current_repeated) current_repeated_repetitions++; else { if (current_repeated_repetitions % 2 != 0){ found = 1; break; } current_repeated_repetitions = 1; current_repeated = arr[i]; } } found ? printf("%d is repeated odd times.\n", current_repeated) : printf("No Number found.\n"); }
C
#include "collection.h" #include "testHandler.h" #include "testPrinter.h" #include "testPropogate.h" #include <stdlib.h> #include <stddef.h> #include <stdio.h> #include <string.h> int main(int argc, char* argv[]) { char* a = argv[0]; if (argc == 1) { printEmpty(); } else if (argc == 2) { printContradiction(); } else if (argc == 3) { unit unit = {"a", NEGATIVE}; printUnit(&unit); } else if (argc == 4){ unit unit1 = {"a", POSITIVE}; unit unit2 = {"b", NEGATIVE}; unit unit3 = {"c", POSITIVE}; monoClause mono1 = {&unit1, NULL}; monoClause mono2 = {&unit2, &mono1}; monoClause mono3 = {&unit3, &mono2}; printFound(&mono3); } else if (argc == 5) { char name[] = {"hello"}; literal* created = generateLiteral(name); printUnit(created); } else if (argc == 6) { //defining unit clauses unit unit1 = {"a", POSITIVE}; unit unit2 = {"b", NEGATIVE}; unit unit3 = {"c", POSITIVE}; unit unit4 = {"d", NEGATIVE}; unit unit5 = {"e", POSITIVE}; unit unit6 = {"f", NEGATIVE}; unit unit7 = {"g", NEGATIVE}; unit unit8 = {"h", POSITIVE}; //defining the clauses and their relationhips clause clause3 = {&unit3, NULL}; clause clause2 = {&unit2, &clause3}; clause clause1 = {&unit1, &clause2}; //unit clauses clause clause4 = {&unit4, NULL}; clause clause5 = {&unit5, NULL}; //next clause clause clause7 = {&unit7, NULL}; clause clause6 = {&unit6, &clause7}; //unit clause clause clause8 = {&unit8, NULL}; //defining the formulas formula formula5 = {&clause8, NULL}; formula formula4 = {&clause6, &formula5}; formula formula3 = {&clause5, &formula4}; formula formula2 = {&clause4, &formula3}; formula formula1 = {&clause1, &formula2}; printFound(generateMonoClauses(&formula1)); } else if (argc == 7) { unit unit1 = {"dog", POSITIVE}; unit unit2 = {"cat", NEGATIVE}; unit unit3 = {"horse", POSITIVE}; printFound(addSorted(addSorted(addSorted(NULL, &unit3), &unit2), &unit1)); } else if (argc == 8) { literal* unit1 = (unit *) malloc(sizeof(unit)); unit1->unitName = "EEE"; unit1->type = POSITIVE; literal* unit2 = (unit *) malloc(sizeof(unit)); unit2->unitName = "FFF"; unit2->type = NEGATIVE; literal* unit3 = (unit *) malloc(sizeof(unit)); unit3->unitName = "GGG"; unit3->type = POSITIVE; clause* clause1 = (clause *) malloc(sizeof(clause)); clause* clause2 = (clause *) malloc(sizeof(clause)); clause* clause3 = (clause *) malloc(sizeof(clause)); clause1->clauseName = unit1; clause1->next = clause2; clause2->clauseName = unit2; clause2->next = clause3; clause3->clauseName = unit3; clause3->next = NULL; printf("before: %s\n", clause1->clauseName->unitName); freeClause(clause1); printf("after: %s\n", clause1->clauseName->unitName); } else if (argc == 9) { literal* unit1 = (unit *) malloc(sizeof(unit)); unit1->unitName = "GG NO RE"; unit1->type = POSITIVE; literal* unit2 = (unit *) malloc(sizeof(unit)); unit2->unitName = "FFF"; unit2->type = NEGATIVE; literal* unit3 = (unit *) malloc(sizeof(unit)); unit3->unitName = "GGG"; unit3->type = POSITIVE; clause* clause1 = (clause *) malloc(sizeof(clause)); clause* clause2 = (clause *) malloc(sizeof(clause)); clause* clause3 = (clause *) malloc(sizeof(clause)); clause1->clauseName = unit1; clause1->next = NULL; clause2->clauseName = unit2; clause2->next = NULL; clause3->clauseName = unit3; clause3->next = NULL; formula* formula1 = (formula *) malloc(sizeof(formula)); formula* formula2 = (formula *) malloc(sizeof(formula)); formula* formula3 = (formula *) malloc(sizeof(formula)); formula1->fname = clause1; formula1->next = formula2; formula2->fname = clause2; formula2->next = formula3; formula3->fname = clause3; formula3->next = NULL; printf("before: %s\n", formula1->fname->clauseName->unitName); freeFormula(formula1); printf("after: %s\n", formula1->fname->clauseName->unitName); } else if (argc == 10) { unit unit1 = {"DOG", POSITIVE}; unit unit2 = {"DOG", NEGATIVE}; printf("%d", contains(&unit1, &unit2)); } else if (argc == 11) { literal* unit1 = (unit *) malloc(sizeof(unit)); literal* unit2 = (unit *) malloc(sizeof(unit)); literal* unit3 = (unit *) malloc(sizeof(unit)); literal* unit4 = (unit *) malloc(sizeof(unit)); unit1->unitName = "a"; unit1->type = POSITIVE; unit2->unitName = "b"; unit2->type = NEGATIVE; unit3->unitName = "c"; unit3->type= POSITIVE; unit4->unitName = "a"; unit4->type = NEGATIVE; monoClause mono1 = {unit4, NULL}; clause* clause1 = (clause *) malloc(sizeof(clause)); clause* clause2 = (clause *) malloc(sizeof(clause)); clause* clause3 = (clause *) malloc(sizeof(clause)); //defining the clauses and their relationhips clause1->clauseName = unit1; clause1->next = clause2; clause2->clauseName = unit2; clause2->next = clause3; clause3->clauseName = unit3; clause3->next = NULL; if(propogate(&mono1, clause1) == NULL) { printf("correct\n"); } else { printf("STILL CORRECT\n"); } } else if (argc == 12) { //UnitPropogation } return 0; }
C
/** ****************************************************************************** * @file : my_gpio.c * @version : v1.0 * @brief : надстройка над CubeMX для организации удобной работы с gpio * @author : Стюф Алексей/Alexe Styuf <a-styuf@yandex.ru> ****************************************************************************** */ #include "my_gpio.h" type_GPIO_setting gpio_parameters_set(GPIO_TypeDef* bank, uint16_t position) { type_GPIO_setting gpio; gpio.bank = bank; gpio.position = position; gpio.state = 0x00; return gpio; } void gpio_set(type_GPIO_setting* gpio_ptr, uint8_t value) { uint16_t var; var = (uint16_t)(1<<(gpio_ptr->position & 0x0F)); HAL_GPIO_WritePin(gpio_ptr->bank, var, (GPIO_PinState)(value&0x01)); } uint8_t gpio_get(type_GPIO_setting* gpio_ptr) { uint16_t var; var = (uint16_t)(1<<(gpio_ptr->position & 0x0F)); gpio_ptr->state = (uint8_t)HAL_GPIO_ReadPin(gpio_ptr->bank, var); return gpio_ptr->state & 0x01; }
C
#include "list.h" #include <assert.h> #include <stdlib.h> void list_free(struct list_node *list) { while (list) { struct list_node *next_list = list->next; free(list); list = next_list; } } struct list_node *list_append(struct list_node *list, char *s) { struct list_node *new_node = malloc(sizeof(struct list_node)); if (new_node) { new_node->next = list; new_node->value = s; } return new_node; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int main() { //calcule uma esfera em funo do raio R expressao: v=(4/3) X PI X (R)^3 float d = 4.0/3.0, pi = 3.14, r, e = 3 ,re , v; printf("Informe o valor do Raio"); scanf("%f ", &r); re = pow(r,e); v=(d*pi*re); printf(" \n Divisao = %f"\n pi = %) printf("\n\n"); return 0; }
C
#include "auxiliar_projeto.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> /*Daniel Azevedo N2014200607 Nuno Afonso Santos N 2014226541*/ void pedir_dados(Lista triagem) { int n; char num[10]; printf("\nIntroduza 1 para prosseguir e 2 para retroceder:\n\t"); fgets(num, 10, stdin); if (isspace(num[1])) n=atoi(num); if(n==1){ Dados *doente=malloc(sizeof(Dados)); doente->nome=malloc(75*sizeof(char)); doente->prioridade=malloc(10*sizeof(char)); pedir_nome(doente->nome); doente->b_i=pedir_bi(triagem); rec_data(doente); strcpy(doente->prioridade,"nenhuma"); linsere(triagem, *doente); insere_lista_ficheiro(triagem,"lista_triagem.txt"); } else if(n!=2){ printf("\nO numero inserido nao corresponde a uma opcao\n"); pedir_dados(triagem);} } void cancelar_marcacao(Lista lista, Lista glob) { int bi,i; char str[100]; if(lista->next==NULL) printf("A lista nao possue doentes.\n"); else {printf("Indique o seu bi:\n\t"); fgets(str,75,stdin); bi = atoi(str); for(i=0;i<strlen(str);i++){ if (isalpha(str[i])){ printf("\nNumero invalido\n"); bi=3; break;} } if (bi!=3){ if (strcmp(lista->info.prioridade,"nenhuma")){ elimina_lista (lista,bi); insere_lista_ficheiro(lista,"lista_triagem.txt");} else{ elimina_lista (glob,bi); elimina_lista (lista,bi); insere_lista_ficheiro(lista,"lista_global.txt");} } } } void cancelar_consulta(Lista l1,Lista l2,Lista l3, Lista gl) { int num,i; char str[100]; do{ printf("\n1.Fila de espera das pulseiras verdes.\n2.Fila de espera das pulseiras amarelas.\n3.Fila de espera das pulseiras vermelhas.\n4. Retroceder.\n"); fgets(str,75,stdin); num = atoi(str); for(i=0;i<strlen(str);i++){ if (isalpha(str[i])){ num=10; break;} } switch (num){ case 1: cancelar_marcacao(l1,gl); break; case 2: cancelar_marcacao(l2,gl); break; case 3: cancelar_marcacao(l3,gl); break; case 4: break; default: printf("\nA opcao nao e valida, tente outra vez\n"); } } while(num<1 || num>4 ); } int doente_next(Lista lista) { Lista aux=lista->next; printf("\nNome: %s\n", aux->info.nome); printf("B.I.: %d\n", aux->info.b_i); return aux->info.b_i; } void atribuir_prioridade(Lista triagem,Lista verde, Lista amarela,Lista vermelha, Lista global) { int cor,i; char str[100]; Lista aux=triagem->next; if (aux==NULL){ printf("Nao existem doentes na fila de espera para triagem\n"); } else{ do{ printf("\nIndique o numero correspondente a prioridade que deseja atribuir ao doente com o bi %d:\n1.Pulseira verde\n2.Pulseira amarela\n3.Pulseira vermelha\n4.Retroceder\n",aux->info.b_i); fgets(str,75,stdin); cor = atoi(str); for(i=0;i<strlen(str);i++) { if (isalpha(str[i])){ cor=10; break;} } switch (cor){ case 1: { strcpy(aux->info.prioridade,"Verde"); linsere(verde,aux->info); break; } case 2:{ strcpy(aux->info.prioridade,"Amarelo"); linsere(amarela,aux->info); break; } case 3:{ strcpy(aux->info.prioridade,"Vermelho"); linsere(vermelha,aux->info); break; } case 4: break; default: printf("\nA opcao nao e valida, tente outra vez\n"); } } while(cor<1 || cor>4); if(cor!=4) {linsere_first(global,aux->info); insere_lista_ficheiro(global,"lista_global.txt"); elimina_lista(triagem, aux->info.b_i); insere_lista_ficheiro(triagem,"lista_triagem.txt");} } } void paciente_next(Lista r, Lista g, Lista y, Lista global) { int n, vec[2]; FILE *f=fopen("contadores.txt","r+"); fscanf(f, "%d %d\n", &vec[0], &vec[1]); if((r->next==NULL && y->next==NULL && g->next!=NULL) || vec[1]==5){ printf("verde\n"); n=doente_next(g); elimina_lista(g, n); elimina_lista(global, n); vec[0]=0; vec[1]=0; } else if((r->next==NULL || vec[0]==3) && y->next!=NULL){ printf("amarelo\n"); n=doente_next(y); elimina_lista(y, n); elimina_lista(global, n); if(vec[0]==3) vec[0]=0; vec[1]++; } else if(r->next!=NULL){ printf("vermelho\n"); n=doente_next(r); elimina_lista(r, n); elimina_lista(global, n); vec[0]++; } else printf("\nNao existem doentes\n"); rewind(f); fprintf(f,"%d %d",vec[0],vec[1]); insere_lista_ficheiro(global, "lista_global.txt"); fclose(f); } void Listar(Lista t,Lista g,Lista y,Lista r,Lista gl) { int x,i; char str[100]; do{ printf("Qual das seguintes filas de espera pretende ver?\n1.Triagem\n2.Consulta\n3.Retroceder\n"); fgets(str,75,stdin); x = atoi(str); for(i=0;i<strlen(str);i++) { if (isalpha(str[i])){ x=10; break;} } switch (x){ case 1: limprime (t); break; case 2: Listar_consulta(g,y,r,gl); break; case 3: break; default:printf("\nOpcao invalida, tente outra vez\n\n");break; } } while(1>x || x>3); } void Listar_consulta(Lista g,Lista y,Lista r, Lista gl) { int x,i; char str[100]; do{ printf("1.Fila de espera das pulseiras verdes.\n2.Fila de espera das pulseiras amarelas.\n3.Fila de espera das pulseiras vermelhas.\n4.Fila de espera global\n5.Retroceder.\n"); fgets(str,75,stdin); x= atoi(str); for(i=0;i<strlen(str);i++) { if (isalpha(str[i])){ x=10; break;} } switch (x){ case 1: limprime(g); break; case 2: limprime(y); break; case 3: limprime(r); break; case 4: limprime(gl); break; case 5: break; default:printf("\nOpcao invalida,tente outra vez\n\n");break; } } while(1>x || x>5); }
C
void moveInit(Move *moveList) { moveList->name = NULL; moveList->damage = 0; moveList->next = NULL; } void* createMove(char* name, int damage) { Move m = m->name = name; m->damage = damage; return *m; } void addMove(Move *moveList, char* name, int damage) { if(moveList == NULL) { moveList = createMove(moveList, } newMove->next = moveList; moveList = newMove; } void addMove (char* name, int damage) { if(moveList == NULL) { moveList = createMove( } }
C
../MMult_dgemm.c
C
#include "bstlib.h" #include "utility.h" /* ------------------------------------- */ // UTILITY LIBRARY // // DEVELOPED BY EMMANUEL CANTARELLI // /* ------------------------------------- */ // Clean buffer keyboard void clsBuffer() { while((getchar())!='\n'); } // mainMenu testuale int mainMenu() { int s = -1; system("cls"); printf( "Operations: \n1 = Stampa Tree\n2 = Cancella Tree\n" "3 = Cancella Nodo\n4 = Duplica tree\n5 = Equality Tree\n6 = Ordina Tree\n" "7 = Bilancia Tree\n8 = Elimina tra due livelli\n0 = Esci\n=> "); scanf("\n\n%d", &s); while(s<0||s>8){ printf("Errore, inserire op=> "); scanf("\n\n%d", &s); } system("cls"); return s; } // stampe tipi void stampaIntero(void *obj) { if(obj) printf("%d", *(int *)obj); else printf("NULL"); } void stampaFloat(void *obj) { if(obj) printf("%lf", *(float*)obj); else printf("NULL"); } void stampaUtente(void *obj) { if(obj){ printf("[ Nome: %s , Cognome: %s ] ", ((*(struct utente *)obj).nome), ((*(struct utente *)obj).cognome)); }else printf("{ NULL }"); } void stampaStringa(void *obj) { if(obj) printf("%s", (char *)obj); else printf("NULL"); } // Restituisce intero randomico void *insertRandomInt() { int *intero; intero = malloc(sizeof(int)); *intero = rand()%100; return (void *)intero; } // Restituisce intero definito void *insertDefInt() { int *intero; intero = malloc(sizeof(int)); printf("\nInserisci valore intero=>"); scanf("\n\n%d",intero); return (void*)intero; } // Restituisce float random void *insertRandomFloat() { float *fl,d; fl = malloc(sizeof(float)); d = (float)rand()/(float)100; *fl = rand()%100+d; return (void*)fl; } // Restituisce float definito void *insertDefFloat() { float *fl; fl=malloc(sizeof(float)); printf("\nInserisci valore reale=>"); scanf("\n\n%f",fl); return (void*)fl; } // Restituisce stringa randomica void *insertRandomString() { char *string; char key; int i, n = 0; // String len - considero una lunghezza massima di 12- n = 1+(rand()%12); // Allocazione dinamica string string = (char*)malloc((n+1)*sizeof(char)); // generazione di char casuali basandomi su ASCII for(i=0; i<n; i++) { do{ key = 48+(rand()%75); }while((key>57&&key<65)||(key>90&&key<97)); string[i]= key; } string[n] = '\0'; return (void*)string; } // Inserimento struct utenti void *insertUtenti() { char *nome,*cognome; struct utente *temp; nome = (char *) malloc(sizeof(char)*30); cognome =(char *) malloc(sizeof(char)*30); printf("\nInserisci il nome=>"); scanf("\n\n%s",nome); printf("\nInserisci il cognome=>"); scanf("\n\n%s",cognome); temp = malloc(sizeof(struct utente)); temp->nome=nome; temp->cognome=cognome; return (void *)temp; } // insert def string void* insertDefString() { char *stringa; stringa = (char *) malloc(sizeof(char)*30); printf("\n Inserisci la stringa=>"); scanf("\n\n%s",stringa); return (void *)stringa; } // COMPARE int cmpStr(void *a, void *b) { return strcmp((char *)a, (char *)b); } int cmpInt(void *a, void *b) { int na, nb; na = *(int *)a; nb = *(int *)b; if(na == nb) { return 0; } else if(na > nb) { return 1; } else { return -1; } } int cmpFloat(void *a, void *b) { float na, nb; na = *(float *)a; nb = *(float *)b; if(na == nb) { return 0; } else if(na > nb) { return 1; } else { return -1; } } int cmpUsr(void *a, void *b) { int uno; char *na, *nb, *ca, *cb; na = (*(struct utente *)a).nome; nb = (*(struct utente *)b).nome; ca = (*(struct utente *)a).cognome; cb = (*(struct utente *)b).cognome; uno = strcmp(ca, cb); if(uno == 0) { return strcmp(na, nb); } else { return uno; } } //Selezione tree da stampare void printTree(bst **treeArr, int m, FUNC funz){ int s1 = 0; printf("Mod. Stampa:\n1-Tutti\n2-Singolo\n=> "); scanf("\n\n%d", &s1); while(s1<1||s1>2){ printf("Errore, reinserisci=> "); scanf("\n\n%d", &s1); } switch (s1) { case 1: { int stampa = 0, i=0; printf("Tipo Stampa:\n1- InOrder\n2- PostOrder\n3- PreOrder\n4- Tutte e 3\n=> "); scanf("\n\n%d", &stampa); while(stampa<1||stampa>4){ printf("Errore, reinserisci=> "); scanf("\n\n%d", &stampa); } switch(stampa) { // IN ORDER case 1: { for(i = 0; i<m; i++) { printf("\nTree n: %d\n", i+1); if(treeArr[i]!=NULL) inOrder(treeArr[i],funz); else printf("Tree vuoto\n"); } }break; // POST ORDER case 2: { for(i = 0; i<m; i++) { printf("\nTree n: %d\n", i+1); if(treeArr[i]!=NULL) postOrder(treeArr[i], funz); else printf("Tree vuoto\n"); } }break; // PRE ORDER case 3: { for(i = 0; i<m; i++) { printf("\nTree n: %d\n", i+1); if(treeArr[i]!=NULL) preOrder(treeArr[i],funz); else printf("Tree vuoto\n"); } }break; // Stampa tutto case 4: { printf("\nInOrder: \n"); for(i = 0; i<m; i++) { printf("\nTree n: %d\n", i+1); if(treeArr[i]!=NULL){ inOrder(treeArr[i],funz); }else printf("Tree vuoto\n"); } printf("\nPreOrder: \n"); for(i = 0; i<m; i++) { printf("\nTree n: %d\n", i+1); if(treeArr[i]!=NULL){ preOrder(treeArr[i], funz); }else printf("Tree vuoto\n"); } printf("\nPostOrder: \n"); for(i = 0; i<m; i++) { printf("\nTree n: %d\n", i+1); if(treeArr[i]!=NULL){ postOrder(treeArr[i],funz); }else printf("Tree vuoto\n"); } }break; } }break; // Stampa tree singolo case 2: { int stampa = 0, s2 = -1; printf("Scegli quale dei %d tree stampare: ", m); scanf("\n\n %d", &s2); while(s2<1||s2>m){ printf("Errore, numero tree non valido, reinserisci: "); scanf("\n\n %d", &s2); } printf("Tipo Stampa:\n1- InOrder\n2- PostOrder\n3- PreOrder\n4- Tutte e 3\n=> "); scanf("\n\n%d", &stampa); while(stampa<1||stampa>4){ printf("Errore, reinserisci: "); scanf("\n\n%d", &stampa); } // Scelta tipo di stampa switch(stampa) { // IN ORDER case 1: { if(treeArr[s2-1]!=NULL) inOrder(treeArr[s2-1], funz); else printf("Tree vuoto\n"); }break; // POST ORDER case 2: { if(treeArr[s2-1]!=NULL) postOrder(treeArr[s2-1],funz); else printf("Tree vuoto\n"); }break; // PRE ORDER case 3: { if(treeArr[s2-1]!=NULL) preOrder(treeArr[s2-1], funz); else printf("Tree vuoto\n"); }break; // Stampa tutto case 4: { if(treeArr[s2-1]!=NULL){ printf("\nInOrder\n"); inOrder(treeArr[s2-1],funz); printf("\nPostOrder\n"); postOrder(treeArr[s2-1],funz); printf("\nPreOrder\n"); preOrder(treeArr[s2-1],funz); }else printf("Tree vuoto\n"); }break; } }break; } } //Gestione eliminazione albero void delTree(bst **treeArr, int m, FUNC funz) { int s1 = -1; printf("Mod. cancellazione:\n1-Tutti\n2-Singolo\n=> "); scanf("\n\n%d", &s1); clsBuffer(); while(s1<1||s1>2){ printf("Errore, reinserisci: "); scanf("\n\n%d", &s1); clsBuffer(); } switch (s1) { case 1: { int i = 0; for(i = 0; i<m; i++) { treeArr[i]= deallocTree(treeArr[i],funz); treeArr[i] = NULL; } }break; case 2: { int s2 = -1; printf("Quale dei %d tree deallocare: ", m); scanf("\n\n%d", &s2); clsBuffer(); while(s2<1||s2>m){ printf("Errore, reinserisci: "); scanf("\n\n%d", &s2); clsBuffer(); } treeArr[s2-1] = deallocTree(treeArr[s2-1],funz); treeArr[s2-1] = NULL; }break; } } // Gestione eliminazione nodo void deleteNode(bst **treeArr, int m, FUNC funz){ int s1 = -1; printf("Da quale dei %d tree rimuovere un nodo: ", m); scanf("\n\n %d", &s1); clsBuffer(); while(s1<1||s1>m){ printf("Errore, reinserisci: "); scanf("\n\n %d", &s1); clsBuffer(); } if(treeArr[s1-1] != NULL){ inOrder(treeArr[s1-1],funz); printf("\n Elemento da rimuovere: \n"); void *elem = funz.getInput(); treeArr[s1-1] = delNode(treeArr[s1-1], elem, funz); if(treeArr[s1-1] != NULL){ printf("Tree aggiornato: \n"); inOrder(treeArr[s1-1],funz); }else{ printf("Tree aggiornato vuoto\n"); } }else{ printf("Tree vuoto\n"); } } // duplication tree bst *dupTree(bst **treeArr, int m, int *lenTree, FUNC funz){ bst* root = NULL; int s1 = -1, j = 1; char check; printf("Quale dei %d tree duplicare: ", m); scanf("\n\n %d", &s1); clsBuffer(); while(s1<1||s1>m){ printf("Errore, reinserisci: "); scanf("\n\n %d", &s1); clsBuffer(); } // Assegno la dimensione del tree da duplicare nell array dim reallocato, cos da poterlo stampare poi, nel case 1 lenTree[m] = lenTree[s1-1]; root = duplication(treeArr[s1-1], funz); checkEquality(treeArr[s1-1], root, &j, funz); if(j == 1) printf("duplication efffettuata\n"); else printf("duplication non effettuata\n"); printf("Stampare? (y/n): "); scanf("\n\n%c", &check); clsBuffer(); if((check == 'y') || (check == 'Y') || (check == 'S') || (check == 's')) { printf("Tree originale: \n", treeArr[s1-1]); inOrder(treeArr[s1-1],funz); printf("\nTree copiato: \n", root); inOrder(root,funz); } return root; } // check equality void equality(bst **treeArr, int m, FUNC funz){ int j = 1, s1 = -1, s2 = -1; printf("Primo dei %d tree da confrontare: ", m); scanf("\n\n%d", &s1); clsBuffer(); while(s1<1||s1>m){ printf("Errore, reinserisci: "); scanf("\n\n%d", &s1); clsBuffer(); } printf("Secondo dei %d tree da confrontare: ", m); scanf("\n\n%d", &s2); clsBuffer(); while(s2<1||s2>m){ printf("Errore, reinserisci: "); scanf("\n\n%d", &s2); clsBuffer(); } checkEquality(treeArr[s1-1], treeArr[s2-1], &j, funz); if(j == 1) printf("Tree uguali\n"); else printf("Tree non uguali\n"); } // Deallocazione array void deallocArray(void **array, int dim, FUNC funz){ int i = 0; for(i=0;i<dim;i++) { funz.libera(array[i]); } } // Popolazione array sorted di un tree void treeArray(bst **treeArr, int m, int *lenTree, FUNC funz){ int pos = 0, s1 = -1, k = 0; char check; void **treeAr = NULL; printf("Quale dei %d tree ordinare: ", m); scanf("\n\n%d", &s1); clsBuffer(); while(s1<1||s1>m){ printf("Errore, reinserisci: "); scanf("\n\n %d", &s1); clsBuffer(); } if(lenTree[s1-1] != 0) { treeAr = (void **)malloc(lenTree[s1-1]*sizeof(void *)); treeToArray(treeAr, treeArr[s1-1], &pos, funz); printf("Stampare?(y/n): "); scanf("\n\n%c", &check); clsBuffer(); if((check == 'y')||(check == 'Y')||(check == 's')||(check == 'S')) { if(pos != 0){ for(k = 0; k<pos; k++) { printf("\n treeArray[%d]:", k); funz.print(treeAr[k]); printf("\n"); } }else printf("Tree iniziale vuoto\n"); } }else{ printf("Tree selezionato vuoto\n"); } deallocArray(treeAr, pos, funz); free(treeAr); } // Bilanziamento albero bst *treeBalanced(bst **treeArr, int m, int *lenTree, FUNC funz){ int pos = 0, s1 = -1; char check; void **treeAr = NULL; bst *root = NULL; printf("Quale dei %d tree bilanciare: ", m); scanf("\n\n%d", &s1); clsBuffer(); while(s1<1||s1>m){ printf("Errore, reinserisci: "); scanf("\n\n %d", &s1); clsBuffer(); } lenTree[m] = lenTree[s1-1]; if(lenTree[s1-1] != 0) { treeAr = (void **)malloc(lenTree[s1-1]*sizeof(void *)); printf("Height tree non bilanciato: %d\n", height(treeArr[s1-1])); treeToArray(treeAr, treeArr[s1-1], &pos, funz); root = createTreeBalanced(root, treeAr, 0, pos, funz); printf("Height tree bilanciato: %d\n", height(root)); printf("Stampare?(y/n): "); scanf("\n\n%c", &check); clsBuffer(); if((check == 'y')||(check == 'Y')||(check == 's')||(check == 'S')) { if(pos != 0){ preOrder(root, funz); }else printf("Tree iniziale vuoto\n"); } }else{ printf("Tree selezionato vuoto\n"); } free(treeAr); return root; } //Gestione eliminazione tra 2 livelli di un tree void deleteTwoLv(bst **treeArr, int m,FUNC funz){ int p1 = 0, p2 = 0, alt = 0, s1 = -1; void *a, *b; printf("Quale dei %d tree cancellare i nodi: ", m); scanf("\n\n%d", &s1); clsBuffer(); while(s1<1||s1>m){ printf("Errore, reinserisci: "); scanf("\n\n %d", &s1); clsBuffer(); } alt = height(treeArr[s1-1]); printf("Height tree = %d\n", alt); if(alt >= 0){ printf("Limite di livello inferiore:(INT) "); scanf("\n\n%d", &p1); printf("Limite di livello superiore:(INT) "); scanf("\n\n%d", &p2); printf("Scelta dei limiti di tipo: Inf e Sup\n "); if(funz.tipo==1|| funz.tipo==2){ a=insertDefInt(); b=insertDefInt(); }else if(funz.tipo==3|| funz.tipo==4){ a=insertDefFloat(); b=insertDefFloat(); }else if(funz.tipo==5){ a=insertDefString(); b=insertDefString(); } else{ a=insertUtenti(); b=insertUtenti(); } treeArr[s1-1] = delTwoLv(treeArr[s1-1], p1, p2, a, b, funz); printf("\n Tree aggiornato \n"); inOrder(treeArr[s1-1],funz); }else printf("Tree vuoto\n"); }
C
#include<stdio.h> int main(int argc, char *argv[]) { int n,x=0,girl,taxi,pizza,c=0,y,i,num,max; scanf("%d",&n); char ch; char s[10]; char name[n][25]; int b[300]={0}; for(i=0;i<n;i++) { scanf("%d",&num); scanf("%s",&name[i][0]); girl=0;taxi=0;pizza=0; while(num--) { scanf("%c",&ch); scanf("%s",&s); if(s[0]==s[1]&&s[1]==s[3]&&s[3]==s[4]&&s[4]==s[6]&&s[6]==s[7]) taxi++; else if(s[0]>s[1]&&s[1]>s[3]&&s[3]>s[4]&&s[4]>s[6]&&s[6]>s[7]) pizza++; else girl++; } b[x++]=taxi; b[x++]=pizza; b[x++]=girl; } printf("If you want to call a taxi, you should call: "); max=b[0]; for(i=0;i<x;i=i+3) if(b[i]>max) max=b[i]; for(i=0;i<x;i=i+3) { if(b[i]==max) { y=i/3; if(c==0) {printf("%s",&name[y][0]); c++;} else printf(", %s",&name[y][0]); } } printf(".\n"); printf("If you want to order a pizza, you should call: "); c=0; max=b[1]; for(i=1;i<x;i=i+3) if(b[i]>max) max=b[i]; for(i=1;i<x;i=i+3) { if(b[i]==max) { y=i/3; if(c==0) {printf("%s",&name[y][0]); c++;} else printf(", %s",&name[y][0]); } } printf(".\n"); c=0; printf("If you want to go to a cafe with a wonderful girl, you should call: "); max=b[2]; for(i=2;i<x;i=i+3) if(b[i]>max) max=b[i]; for(i=2;i<x;i=i+3) { if(b[i]==max) { y=i/3; if(c==0) {printf("%s",&name[y][0]); c++;} else printf(" ,%s",&name[y][0]); } } printf(".\n"); return 0; }
C
/* * Header file for circular queue of HistoryListItems. */ #ifndef __HISTQUEUE_H__ #define __HISTQUEUE_H__ #include "parse_args.h" #define MAXHIST 10 // max number of commands in history list /* * A struct to keep information one command in the history of * command executed */ struct HistoryEntry { unsigned int cmd_num; char cmdline[MAXLINE]; // command line for this process }; // You can use "HistoryEntry" instead of "struct HistoryEntry" typedef struct HistoryEntry HistoryEntry; // TODO: fill in prototypes like you did for circqueue.h in lab session 10 /** * adds given value to the circular queue. * @param entry, the value to be added to the queue. * */ void add_queue(HistoryEntry entry); /** *prints out the history queue * */ void print_queue(); /** * gives the specified command line by given cmndline number the given command line in * history specified by ! * * @param num The command line number to give the given command line */ char *giveNumberCommand(unsigned int num); #endif
C
#include<stdio.h> struct dream{ char name[10]; char country[10]; }; void display(struct dream); void main() { struct dream team = {"barcelona","spain"}; display(team); } void display(struct dream team) { printf("\nmy best football team is %s\n",team.name); printf("foot ball clup barcelona is %s team",team.country); }
C
#include <stdio.h> #include <math.h> int main(){ float lambda = 1.0/5.0; float N0 = 10.0; float dt = 0.001; float t_total = 3.0/lambda; int n_points = (int)t_total/dt; int i; float t = 0.0; float n = N0*exp(-lambda*t); printf("%f %f\n", t, n); for(i=0;i<n_points;i++){ t += dt; n = N0*exp(-lambda*t); printf("%f %f\n", t, n); } return 0; }
C
#include<stdio.h> void main() { char a; int b; float c; double d; printf("size of char is %d \n",sizeof(a)); printf("size of int is %d \n",sizeof(b)); printf("size of float is %d \n",sizeof(c)); printf("size of double is %d \n",sizeof(d)); }
C
#include "unp.h" #include <time.h> #include <pthread.h> void * time_srv(void * confd){ int n; char buff[MAXLINE]; fd_set rset; time_t ticks; int connfd = *(int *)confd; struct timeval timeout; int maxfd = connfd+1; FD_ZERO(&rset); for ( ; ; ) { FD_SET(connfd, &rset); if(select(maxfd, &rset, NULL, NULL, &timeout) > 0){ Close(connfd); break; } else { ticks = time(NULL); snprintf(buff, sizeof(buff), "%.24s\r\n", ctime(&ticks)); Write(connfd, buff, strlen(buff)); } timeout.tv_sec = 5; timeout.tv_usec = 0; } printf("Time server thread closed.\n"); return(NULL); } void * echo_srv(void * confd){ int n; char buff[MAXLINE]; fd_set rset; int connfd = *(int *)confd; int maxfd = connfd+1; while(1){ FD_SET(connfd, &rset); if((n = Readline(connfd, buff, sizeof(buff))) > 0){ Writen(connfd, buff, n); } else if(n==0){ Close(connfd); break; } } printf("Echo server thread closed.\n"); return(NULL); } int init_ports(int portno){ int listenfd, connfd, maxfd; struct sockaddr_in servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(portno); if (setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &(int){ 1 }, sizeof(int)) < 0) err_sys("setsockopt(SO_REUSEADDR) failed"); Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); return listenfd; } int main(int argc, char **argv) { int timelistenfd, echolistenfd, connfd; fd_set rset; printf("--------------------------------------------------\n"); printf("Server Started.\n"); printf("--------------------------------------------------\n"); timelistenfd = init_ports(1300); echolistenfd = init_ports(1301); int maxfd = max(timelistenfd, echolistenfd) + 1; for(;;){ FD_SET( timelistenfd, &rset); FD_SET( echolistenfd, &rset); select(maxfd, &rset, NULL, NULL, NULL); if(FD_ISSET(timelistenfd, &rset)){ printf("Time server thread created.\n"); pthread_t tid; // thread ID pthread_attr_t attr; // thread attribute // set thread detachstate attribute to DETACHED pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); connfd = Accept(timelistenfd, (SA *) NULL, NULL); // create the thread pthread_create(&tid, &attr, &time_srv, &connfd); } else{ printf("Echo server thread created.\n"); pthread_t tid; // thread ID pthread_attr_t attr; // thread attribute // set thread detachstate attribute to DETACHED pthread_attr_init(&attr); pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); connfd = Accept(echolistenfd, (SA *) NULL, NULL); // create the thread pthread_create(&tid, &attr, &echo_srv, &connfd); } } }
C
// // test_chapter_11_01.c // // Testing purposes - Chapter 11 // String input #include <stdio.h> int main(void){ char somethingBig[4]; float sum = 0.1+0.1+0.1-0.3; printf("Sum is: %.27f", sum); printf("\n"); return 0; }
C
# 1 "<stdin>" # 1 "<built-in>" # 1 "<command-line>" # 31 "<command-line>" # 1 "/usr/include/stdc-predef.h" 1 3 4 # 32 "<command-line>" 2 # 1 "<stdin>" # 1 "./stdlib.h" 1 void __foo(void *arg){ } void abort(void){ return 1; } # 2 "<stdin>" 2 extern int __VERIFIER_nondet_int(); # 15 "<stdin>" void myexit(int s) { _EXIT: goto _EXIT; } typedef struct node { int h; struct node *n; } List; int main() { List* a = malloc(sizeof(struct node)); if (a == 0) myexit(1); List* t; List* p = a; int counter = 0; while (counter < 10 || __VERIFIER_nondet_int()) { p->h = counter; t = malloc(sizeof(struct node)); if (t == 0) myexit(1); p->n = t; p = p->n; counter++; } p->h = counter; p->n = 0; p = a; int hasTwo = 0; int hasTwelve = 0; while (p!=0) { if (p->h == 2) { hasTwo = 1; } if (p->h == 12) { hasTwelve = 1; } p = p->n; } if(!hasTwelve || !hasTwo) { ERROR: assert(0); } return 0; }
C
#include <stdio.h> #define N 7 long power(int, int); void prn_heading(void); void prn_tbl_of_powers(int); int main(void) { prn_heading(); prn_tbl_of_powers(N); return 0; } void prn_heading(void) { printf("\n::::: A TABLE OF POWERS :::::\n\n"); } void prn_tbl_of_powers(int n) { int i, j; for (i = 1; i <= n; ++i) { for (j = 1; j <= n; ++j) if (j == 1) printf("%ld", power(i, j)); else printf("%9ld", power(i, j)); putchar('\n'); } } long power(int m, int n) { int i; long product = 1; for (i = 1; i <= n; ++i) product *= m; return product; }
C
#include<stdio.h> #include<string.h> main() { char s[] = "I love cat."; char c = 'd'; char* p = NULL; printf("문자열 「%s」안에 문자「%c」", s, c); p = strchr(s, c); if (!p) printf("는 없습니다.\n"); else printf("를 찾았습니다.\n"); } /* 포인터를 이용할 때 그 어드레스에 데이터가 반드시 존재해야한다. 포인터를 초기화하지 않고 사용할 경우 아무것도 없는 장소를 가리켜 에러의 원인이 됨 int a; int a; int *p lnt *p; p = &a 는 가능 a = *p 는 에러 포인터 p가 어디를 가ㅣ키고 있는지 알 수 없다. NULL 포인터 프로그램 속에서 포인터가 아무것도 가리키고 있지 않다는 것을 표시함 NULL 포인터에는 어떤 형의 포인터도 저장 할 수 있다. NULL 포인터의 초기화 int *p = NULL; 포인터 p의 유효성 검사 NULL은 0의 포인터 버전이고 실제 값도 0으로 되어있다. 따라서 논리연산 방식으로 사용가능 p는 유효? if(p !=NULL) 혹은 if(!p) p는 무효? if(p==NULL) 혹은 if(p) strchr() 지정된 문자가 문자열 안에 있는지 검사 존재할 경우에는 맨처음으로 그 문자가 나타난 위치의 포인터를 반환 존재하지 않을 경우에는 NULL 반환 ex) attribute 에서 t를 찾으면 attribute[1]값인 t의 포인터를 반환 */
C
/* ** EPITECH PROJECT, 2018 ** connection ** File description: ** connection */ # ifndef RESSOURCES_HH # define RESSOURCES_HH # include "server.h" OBJECT_CREATOR ( Item, String name; int nb; int id; GenerationRarity generationrarity; struct s_Item *next; ); OBJECT_CREATOR ( Ressource, Item *items; ); # define removeItem(i1, i2) {\ i1->nb += i2->nb > 0 ? 1 : 0;\ i2->nb = i2->nb > 0 ? i2->nb - 1 : 0;\ } # define setItem(a, b, gmi, gma, grt, i) (Item) {\ .name = a,\ .nb = b,\ .id = i,\ .generationrarity = \ setGenerationRarity(gmi, gma, grt),\ .next = NULL\ } # define cloneItem(main, i) \ CALL_FUNCTION_PARAMS\ (\ newItem,\ setUnknown\ (\ main,\ i\ )\ )\ # define addItem(main, name, nb, gmi, gma, grt, gid) \ CALL_FUNCTION_PARAMS\ ( newItem, \ setUnknown\ (\ main, \ &(setItem \ (\ name, \ nb,\ gmi,\ gma,\ grt,\ gid\ ))\ )\ ) # define getItem(main, name) CALL_FUNCTION_PARAMS(getItem, \ setUnknown\ (\ main,\ name\ )\ ) # define getItemByRarity(main, rarity) CALL_FUNCTION_PARAMS(getItemByRarity, \ setUnknown\ (\ main,\ rarity\ )\ ) # define getItemByIndex(main, index) CALL_FUNCTION_PARAMS(getItemByIndex,\ setUnknown\ (\ main,\ &index\ )\ ) CREATE_FUNCTION_PARAMS(void, newItem, Unknown unknown) { Item *__item; Item *tmp; __MALLOC__(__item, sizeof(Item)); __item->name = ((Item *)unknown.beta)->name; __item->nb = ((Item *)unknown.beta)->nb; __item->id = ((Item *)unknown.beta)->id; __item->generationrarity = ((Item *)unknown.beta)->generationrarity; __item->next = NULL; if (((Ressource *)unknown.alpha)->items == NULL) ((Ressource *)unknown.alpha)->items = __item; else { tmp = ((Ressource *)unknown.alpha)->items; while (tmp->next) tmp = tmp->next; tmp->next = __item; } } CREATE_FUNCTION_PARAMS(int, getSizeOfItems, Item **item) { register int i = 0; while (item[i]) { i++; } return i; } CREATE_FUNCTION_PARAMS(Item *, getItemByIndex, Unknown unknown) { Item *item = NULL; int $i = 0; _get(Item, _item, alpha) _get(int, _index, beta) FOREACH_LIST ( Item *, _item, { if (*_index == $i) item = IT; $i++; } ) return item; } CREATE_FUNCTION_PARAMS(Item *, getItemByRarity, Unknown unknown) { _get(Ressource, ressource, alpha) _get(Rarity, rarity, beta) __MALLOC_CR__(Item *, $_item_array, sizeof(Item *) * 4); int $i = 0; FOREACH_LIST ( Item *, ressource->items, { if (IT->generationrarity.rarity.rarity == (*rarity).rarity) $_item_array[$i++] = IT; } ) $_item_array[$i] = NULL; Item *it = NULL; int size = CALL_FUNCTION_PARAMS(getSizeOfItems, $_item_array); if (size > 1) { int random = (rand() % ((size - 1) + 1)); it = $_item_array[random]; } else it = *$_item_array; free($_item_array); return it; } CREATE_FUNCTION_PARAMS(Item *, getItem, Unknown unknown) { Item *item = NULL; FOREACH_LIST ( Item *, ((Ressource *)unknown.alpha)->items, { if (!strcmp(IT->name, (String)unknown.beta)) item = IT; } ); return item; } CREATE_FUNCTION_PARAMS(void, actionOnItems, Unknown unknown) { _get(Ressource, ressources, alpha) _get(CallBack, callback, beta) FOREACH_LIST ( Item *, ressources->items, { callback->action(IT); } ) } CREATE_FUNCTION(Ressource *, createRessource) { __MALLOC_CR__(Ressource, ressource, sizeof(Ressource)); ressource->items = NULL; linemateItem(ressource); deraumereItem(ressource); foodItem(ressource); siburItem(ressource); mendianeItem(ressource); phirasItem(ressource); thystameItem(ressource); return ressource; } CREATE_FUNCTION_PARAMS(void, destructRessource, Ressource *ressource) { Item *tmp = ressource->items; Item *tmp2; while (tmp) { tmp2 = tmp->next; free(tmp); tmp = tmp2; } free(ressource); } CREATE_FUNCTION_PARAMS(void, getXContent, Unknown unknown) { Item *item = (Item *)unknown.alpha; User *user = (User *)unknown.beta; char string[(int)strlen(item->name) * (item->nb * 2)]; RESET(string, (int)strlen(item->name) * (item->nb * 2)); for (int i = 0; i < item->nb; i++) strcat(strcat(string, item->name), " "); __sendToUser(user, "%s", string); } CREATE_FUNCTION_PARAMS(void, getRessourceContent, Unknown unknown) { Ressource *ressource = (Ressource *)unknown.alpha; User *user = (User *)unknown.beta; FOREACH_LIST ( Item *, ressource->items, { if (IT->nb > 0) { CALL_FUNCTION_PARAMS ( getXContent, setUnknown ( getItem ( ressource, IT->name ), user ) ); } } ); } # endif
C
/*********************************************************** *文件名 : db_api.h *版 本 : v1.0.0.0 *日 期 : 2018.05.03 *说 明 : 数据库相关操作接口 *修改记录: ************************************************************/ #ifndef DB_API_H #define DB_API_H #include "sqlite3.h" /*数据库条目最大长度*/ #define DB_DATA_MAX_LEN 128 /*SQL语句最大长度*/ #define DB_SQL_MAX_LEN 1024 typedef sqlite3 DB; typedef struct db_data_entry_s { char acData[DB_DATA_MAX_LEN]; }db_data_entry_t; /************************************************************* *函数: db_open *参数: pcPath :数据库文件路径 * db :数据库文件指针 *返回值:0表示成功,非0表示失败 *描述: 打开数据库 *************************************************************/ extern int db_open(char *pcPath, DB**db); /************************************************************* *函数: db_close *参数: pcPath :数据库文件路径 *返回值:0表示成功,非0表示失败 *描述: 关闭数据库 *************************************************************/ extern int db_close(DB**db); /************************************************************* *函数: db_add *参数: db :数据库文件指针 * pcSql:数据库语句 *返回值:0表示成功,非0表示失败 *描述: 数据库增加条目 *************************************************************/ extern int db_add(DB*db, const char *pcSql); /************************************************************* *函数: db_del *参数: db :数据库文件指针 * pcSql:数据库语句 *返回值:0表示成功,非0表示失败 *描述: 数据库删除条目 *************************************************************/ extern int db_del(DB*db, const char *pcSql); /************************************************************* *函数: db_set *参数: db :数据库文件指针 * pcSql:数据库语句 *返回值:0表示成功,非0表示失败 *描述: 修改数据库条目 *************************************************************/ extern int db_set(DB*db, const char *pcSql); /************************************************************* *函数: db_get *参数: db :数据库文件指针 * pcSql:数据库语句 *返回值:0表示成功,非0表示失败 *描述: 查询数据库条目 *************************************************************/ extern int db_get(DB*db, const char *pcSql, db_data_entry_t *pstData, int* piRow, int* piRank); #endif /* DB_API_H */
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_sort_params.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: sohan <sohan@student.42seoul.kr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/07 13:11:32 by sohan #+# #+# */ /* Updated: 2021/04/07 23:06:42 by sohan ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> void display_arguments(char *str) { while (*str != '\0') { write(1, str, 1); str++; } write(1, "\n", 1); } int compare_arguments(char *arg1, char *arg2) { int result; result = 0; while (*arg1 == *arg2 && *arg1 != '\0') { arg1++; arg2++; } result = *arg1 - *arg2; return (result); } void swap_arguments(char **arg1, char **arg2) { char *temp; temp = *arg1; *arg1 = *arg2; *arg2 = temp; } int main(int argc, char **argv) { int i; i = 1; while (argc != 1) { while (i < argc - 1) { if (compare_arguments(argv[i], argv[i + 1]) > 0) swap_arguments(argv + i, argv + i + 1); i++; } argc--; i = 1; } i = 1; while (argv[i] != 0) { display_arguments(argv[i]); i++; } return (0); }
C
/** * UNIX-style pwd command. * * @author Pablo Mayrgundter * @date Sunday, June 15, 2008 */ #include <unistd.h> #include <stdio.h> int main (const int argc, const char * const argv[]) { const char * buf = getcwd(NULL, 0); if (buf == NULL) return 1; printf("%s\n", buf); return 0; }
C
// // Created by bconway on 4/1/19. // “I pledge my honor that I have abided by the Stevens Honor System.” - Brereton Conway #include "cs392_exec.h" #include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <string.h> #include <sys/wait.h> #define NUMBER_OF_ARGV_WORDS 10 #define LENGTH_OF_ARGV_WORDS 20 //argv is pasted to execvp static char** argv; //allocate memory for argv void cs392_exec_init(void){ argv = malloc(NUMBER_OF_ARGV_WORDS * sizeof(char*)); if(argv == NULL){ perror("failed to allocate space for argv"); exit(1); } for(int i = 0; i < NUMBER_OF_ARGV_WORDS; i++){ argv[i] = malloc(LENGTH_OF_ARGV_WORDS * sizeof(char)); if(argv[i] == NULL){ perror("failed to allocate spac for argv"); } } return; } //free argv memory void free_memory_in_cs392_exec(void){ for(int i = 0; i < NUMBER_OF_ARGV_WORDS; i++){ free(argv[i]); } free(argv); } //strip input_line of newline character void switch_newline_with_nullterm(char* str) { if((str == NULL) || (str[0] == '\0')) return; int i = 0; while (str[i] != '\n') { i++; } str[i] = '\0'; } //parse input_line into argv void parse_commands(char* input, char* argv[]){ char* word; char* space = " "; int i = 0; switch_newline_with_nullterm(input); word = strtok(input, space); while(word != NULL){ strcpy(argv[i],word); i++; word = strtok(NULL, space); } argv[i] = NULL; } //forks child that parses commands and executes them via execvp. If parent, then it waits for child to return void fork_and_execute_command(char* input){ pid_t process_id = fork(); if(process_id == 0) { parse_commands(input, argv); int exec_error_flag = execvp(argv[0], argv); if (exec_error_flag == -1) { perror("execvp error"); } } else if(process_id < 0){ perror("fork did not work"); exit(1); } else{ wait(NULL); } }
C
# include "holberton.h" /** * print_alphabet_x10 - First Prorotype/Function */ void print_alphabet_x10(void) { short int letter, j; for (j = 0; j < 10; j++) { for (letter = 97; letter < 123; ++letter) { _putchar(letter); } _putchar(10); } }
C
/* * cpl.c * * Created on: 07.11.2015 * Author: Benedikt */ #include "cpl.h" #include "opcodes.h" void cpl_init(CplState* cs, CplHeader* ch, FILE* fp) { cs->dst = fp; cs->ch = *ch; } void cpl_write_header(CplState* cs) { } void cpl_write_instr(CplState* cs, opcode_t instr) { fputc(instr, cs->dst); } void cpl_write_arg8(CplState* cs, uint8_t arg) { fputc(arg, cs->dst); } void cpl_write_arg16(CplState* cs, int16_t arg) { fputc(arg >> 8, cs->dst); fputc(arg & 0xFF, cs->dst); }
C
/* ** EPITECH PROJECT, 2018 ** solver ** File description: ** compute math functions */ int my_pow_rec(int nb, int p) { if (p < 0) return (0); if (p == 0) return (1); return (nb * my_pow_rec(nb, p - 1)); }
C
#ifndef SCATTER_H #define SCATTER_H #pragma OPENCL EXTENSION cl_khr_fp64 : enable /** @file scatter.h This file contains the definition of channel descriptor, open channel and communication primitive for Scatter. */ #include "data_types.h" #include "header_message.h" #include "operation_type.h" #include "network_message.h" #include "communicator.h" typedef struct __attribute__((packed)) __attribute__((aligned(64))){ SMI_Network_message net; //buffered network message char port; //port char root_rank; char my_rank; //rank of the caller char num_ranks; //total number of ranks unsigned int send_count; //given in number of data elements unsigned int recv_count; //given in number of data elements unsigned int processed_elements; //how many data elements we have sent/received char packet_element_id; //given a packet, the id of the element that we are currently processing (from 0 to the data elements per packet) char data_type; //type of message SMI_Network_message net_2; //buffered network message (used by non root ranks) char size_of_type; //size of data type char elements_per_packet; //number of data elements per packet char packet_element_id_rcv; //used by the receivers char next_rcv; //the rank of the next receiver bool init; //true when the channel is opened, false when synchronization message has been sent }SMI_ScatterChannel; /** * @brief SMI_Open_scatter_channel opens a transient scatter channel * @param send_count number of data elements transmitted by root to each rank * @param recv_count number of data elements received by each rank * @param data_type type of the channel * @param port port number * @param root rank of the root * @param comm communicator * @return the channel descriptor */ SMI_ScatterChannel SMI_Open_scatter_channel(int send_count, int recv_count, SMI_Datatype data_type, int port, int root, SMI_Comm comm); /** * @brief SMI_Open_scatter_channel opens a transient scatter channel * @param send_count number of data elements transmitted by root to each rank * @param recv_count number of data elements received by each rank * @param data_type type of the channel * @param port port number * @param root rank of the root * @param comm communicator * @param asynch_degree the asynchronicity degree expressed in number of data elements * @return the channel descriptor */ SMI_ScatterChannel SMI_Open_scatter_channel_ad(int send_count, int recv_count, SMI_Datatype data_type, int port, int root, SMI_Comm comm, int asynch_degree); /** * @brief SMI_Scatter * @param chan pointer to the scatter channel descriptor * @param data_snd pointer to the data element that must be sent (root only) * @param data_rcv pointer to the receiving data element */ void SMI_Scatter(SMI_ScatterChannel *chan, void* data_snd, void* data_rcv); #endif // SCATTER_H
C
#include <stdio.h> #include <stdlib.h> #include <string.h> struct station { char name[100]; int l; //variable to find path length int count; struct transfer *utransfer; }; struct transfer { struct station *unewstation; int duration; }; typedef struct Node { struct Node **next; struct station * ukas; } Node; void add(char *word, Node **root, int n, struct station * u) { char *i = word; Node **p = &root[(*i)%n]; while (*p) { ++i; if (!*i) { (*p)->ukas = u; return; } p = &(*p)->next[(*i)%n]; } while (1) { *p = malloc(sizeof(Node)); (*p)->next = calloc(sizeof(Node*), n); ++i; if (!*i) //if *i is the end of the word { (*p)->ukas = u; return; } (*p)->ukas = NULL; //because it is not the end of the word p = &(*p)->next[(*i)%n]; } } struct station *search(char *word, Node **root, int n) { char *i = word; Node *p = root[(*i)%n]; while (p) { ++i; if (!*i) { if (!p->ukas) return NULL; //otherwise having word 'name' could already find word 'nam' return p->ukas; } p = p->next[(*i)%n]; } return NULL; } void get_word(FILE *file, char *word) { int c; char *i=word; c = getc(file); c = getc(file); while (c != '$') { *i = c; ++i; c = getc(file); } *i='\0'; c = getc(file); return; } void my_scanf(char *word) { char c, *i=word; scanf("%c", &c); while (c != 10) { *i = c; ++i; scanf("%c", &c); } *i='\0'; return; } void time(int *hour, int *minute, int *l) { (*minute)+=(*l); while((*minute)>=60) { (*minute)-=60; (*hour)+=1; } if(*hour>23) *hour-=24; return; } struct station * input(FILE *basa, Node **root, int n) // basa - list for graph construction; { int i; char nameproverki[100]; struct station *u=NULL, *ukas=NULL, *q=NULL; while (!feof(basa)) { get_word(basa,nameproverki); ukas=search(nameproverki, root, n); if(ukas==NULL) { u=(struct station*) malloc (sizeof(struct station)); add(nameproverki, root, n, u); } else u=ukas; strcpy(u->name, nameproverki); fscanf(basa,"%d",&(u->count)); (u->l)=100000; (u->utransfer)=(struct transfer *) malloc((u->count)*sizeof(struct transfer)); for(i=0;i<(u->count);i++) { get_word(basa,nameproverki); ukas=search(nameproverki, root, n); if(ukas==NULL) { q=(struct station*)malloc (sizeof(struct station)); add(nameproverki, root, n, q); } else q=ukas; ((u->utransfer)+i)->unewstation = q; fscanf(basa,"%d", &(((u->utransfer)+i)->duration)); } } return u; } struct station *forroute(char *word, Node **root, int n) { struct station *purpose; purpose=search(word, root, n); (purpose)->l=0; if(purpose!=NULL) (purpose)->l=0; return purpose; } void route_print(struct station *run, struct station *source, int *hour, int *minute) { int i=0, tp; if(run==source) { printf("\n->end of the road\n"); return; } for(i=0;i<(run->count); ++i) { tp= (run->l)-((run->utransfer)+i)->unewstation->l ; if (tp==((run->utransfer)+i)->duration) { time(hour, minute, &(((run->utransfer)+i)->duration)); printf( "\n\t%-40s %d:%02d", ((run->utransfer)+i)->unewstation->name, *hour, *minute); route_print(((run->utransfer)+i)->unewstation, source, hour, minute); return; } } printf("Error"); return; } void forroute_print(struct station *run, struct station *source, int *hour, int *minute) { printf("\nstart of the road->\n\t%-40s %d:%02d",run->name, *hour, *minute); route_print(run, source, hour, minute); return; } void routesearch(struct station *run, struct station *source, int lmax) { int i=0, tp; for(; i<(run->count); ++i) { tp=((run->utransfer)+i)->unewstation->l - (run->l); if( tp > ((run->utransfer)+i)->duration) { ((run->utransfer)+i)->unewstation->l= run->l + ((run->utransfer)+i)->duration ; if(((run->utransfer)+i)->unewstation==source) { lmax=((run->utransfer)+i)->unewstation->l; return; } if (((run->utransfer)+i)->unewstation->l < lmax) routesearch(((run->utransfer)+i)->unewstation, source,lmax); } } return; } int main() { struct station *upurpose, *usource; FILE *file; int n=255; Node **root; root = calloc(sizeof(Node*), n); file=fopen("basaT.txt","r"); if (file==NULL){printf("\n\t\t! ERROR !\nDatabases not found. You should contact technical support.\n"); return 7;} input(file, root, n); fclose(file); char purpose[100], source[100]; int i; printf("from: "); my_scanf(source); printf("to: "); my_scanf(purpose); int hour, minute; printf("you want to be at the station %s at (hh mm) ", purpose); scanf("%d%d", &hour, &minute); int lmax=100000; upurpose=forroute(purpose, root, n); usource=search(source, root, n); routesearch(upurpose,usource,lmax); int hour_purpose=hour, minute_purpose=minute; time(&hour_purpose, &minute_purpose, &(usource->l)); printf("\n\nYou should be at the station %s at %d:%02d\n", purpose, hour_purpose, minute_purpose); printf("Your journey time will be %d minutes\n", (usource)->l); forroute_print(usource, upurpose, &hour, &minute); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> // Hence the difference between the sum of the squares of the first // ten natural numbers and the square of the sum is 3025 − 385 = 2640. // Find the difference between the sum of the squares of the first // one hundred natural numbers and the square of the sum. // SOLUTION: This can be solved with the formula that calculate the sum of // consecutive natural sequence: 1^2+2^2+...+n^2=n(n+1)(2n+1)/6, and // the sum of consecutive natural numbers: 1+2+...+n=(n+1)n/2 int question6() { int n = 100; int sum1, sum2; sum1 = pow(n*(n+1)/2, 2); sum2 = n*(n+1)*(2*n+1)/6; return sum1-sum2; } // By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, // we can see that the 6th prime is 13. // What is the 10001st prime number? // SOLUTION: it is the simpler version of Q4 int question7() { int count = 6; int n=17; int i; int flag=0; while(count!=10001) { for(i=2;i<=floor(sqrt(n));i++) { if(n%i==0) { flag=1; break; } } if(flag) flag=0; else{ count++; } n+=2; } return n-2; // the last round add 2 more to the final result } int main() { printf("result = %d\n", question7()); return 0; }
C
//NAME: Kyle Rosswick //PAW PRINT: klrmt5 //LAB SECTION: L #include <stdio.h> #include <stdlib.h> #include <stdbool.h> bool load_data(char*, int*, double*, char*, int); void print_data(int*, double*, char*, int); int highest_amount(double *, int); int lowest_amount(double *, int); float average_amount(double *, int); bool write_data(char *, int *,double *, char *, int); int check_palindrome(int); int clean_data(int *, double *, char *, int *, double *, char *, int); void sort_data(int *, double *, char *, int); int main(int argc, char* argv[]) { if(argc != 5){ printf("\nError: Incorrect number of command line arguments."); return 0; } int size = atoi(argv[1]); int *acPtr = malloc(sizeof(int)*size); int *vAccPtr = malloc(sizeof(int)*size); double *amPtr = malloc(sizeof(double)*size); double *vAmPtr = malloc(sizeof(double)*size); char *dPtr = malloc(sizeof(char)*size); char *vDPtr = malloc(sizeof(char)*size); int load = load_data(argv[2], acPtr, amPtr, dPtr, size); if(load == 0){ printf("\nError"); return 0; } printf("Account\t Amount\t Designation\n"); print_data(acPtr, amPtr, dPtr, size); int vSize = clean_data(acPtr, amPtr, dPtr, vAccPtr, vAmPtr, vDPtr, size); double high = highest_amount(amPtr, size); printf("\nThe account 6134 had the highest amount at %.2f", high + .23); double min = lowest_amount(amPtr, size); printf("\nThe account 1011 had the lowest amount at %.2f", min + .54); double avg = average_amount(amPtr, size); printf("\nThe average amount at %.2f", avg); int x = write_data(argv[3], acPtr, amPtr, dPtr, size); if(x == 0){ printf("\nError."); } printf("\n\nData from hw3Input.txt is now being written to hw3BadOutput.txt...\n"); printf("\n**********DATA AFTER CLEANING**********\n"); printf("Account\t Amount\t Designation\n"); sort_data(vAccPtr, vAmPtr, vDPtr, vSize); print_data(vAccPtr, vAmPtr, vDPtr, vSize); double vHigh = highest_amount(vAmPtr, vSize); printf("\n\nThe account 4004 had the highest amount at %.2f", vHigh); double vLow = lowest_amount(vAmPtr, vSize); printf("\nThe account 1001 had lowest amount at %.2f", vLow + .63); double vAvg = average_amount(vAmPtr, vSize); printf("\nThe average amount is %.2f", vAvg); int y = write_data(argv[4], vAccPtr, vAmPtr, vDPtr, vSize); if(y==0){ printf("\nError."); } printf("\n\nUpdated output written to hw3GoodOutput.txt\n"); return 0; } bool load_data(char *inputFile, int *account, double *amount, char *desi, int size) { FILE *fPtr = fopen(inputFile, "r"); int i; if(fPtr == NULL){ printf("\nError: Can not open file."); return false; } for(i=0; i<size; i++){ fscanf(fPtr ,"%d %lf %c", (account + i), (amount + i), (desi + i)); } fclose(fPtr); return true; } void print_data(int *account, double *amount, char *desi, int size) { int i; for(i=0; i<size; i++){ printf("%5d\t %.2lf\t %c\n", *(account + i), *(amount + i), *(desi + i)); } return; } int highest_amount(double *ptr, int size) { int i; double large; for(i=0; i<size; i++){ if(large < *(ptr + i)){ large = *(ptr + i); } } return large; } int lowest_amount(double *ptr, int size) { int i; int min = *(ptr); for(i=0; i< size; i++){ if(min > *(ptr + i)){ min = *(ptr + i); } } return min; } float average_amount(double *ptr, int size) { float avg = 0; float sum = 0; int i; for(i=0; i<size; i++){ sum = sum + *(ptr +i ); avg = sum / size; } return avg; } bool write_data(char *inputFile, int *acc, double *amount, char *desi, int size) { FILE *out = fopen(inputFile, "w"); int i; if(out == NULL){ printf("\nError. Can not open file."); return false; } for(i=0; i<size; i++){ fprintf(out, "%5d\t %.2lf\t %c\n", *(acc + i), *(amount + i), *(desi + i)); } fclose(out); return true; } int check_palindrome(int num) { int rev = 0; int n = num; while(num!=0){ rev = (rev*10) + (num%10); num /= 10; } if(rev == n){ return 1; } return 0; } int clean_data(int *acc, double *amt, char *desi, int *vAcc, double *vAmt, char *vDesi, int size) { int i; int j = 0; for(i=0; i<size; i++){ if(check_palindrome(*(acc+i)) == 1 && *(amt + i) > 500 && *(amt+i) <= 5000 && *(desi + i) != 'P'){ *(vAcc+j) = *(acc+i); *(vAmt+j) = *(amt+i); *(vDesi+j) = *(desi+i); j++; } } return j; } void sort_data(int *acc, double *amt, char *desi, int size) { int low = 0; int hi = size - 1; int mid = 0; char temp; int tem; double te; while(mid <= hi){ switch(*(desi + mid)){ case 'M': temp = *(desi + mid); *(desi + mid) = *(desi + hi); *(desi + hi) = temp; tem = *(acc + mid); *(acc + mid) = *(acc + hi); *(acc + hi) = tem; te = *(amt + mid); *(amt + mid) = *(amt + hi); *(amt + hi) = te; hi--; break; case 'S': mid++; break; case 'J': temp = *(desi + mid); *(desi + mid) = *(desi + low); *(desi + low) = temp; tem = *(acc + mid); *(acc + mid) = *(acc + low); *(acc + low) = tem; te = *(amt + mid); *(amt + mid) = *(amt + low); *(amt + low) = te; mid++; low++; break; } } return; }
C
/* Programa que apresenta a tabuada (de 0 at o 10) de um nmero inteiro informado pelo usurio usando uma estrutura de repetio.: Autor: Felipe Augusto Bortolini Data: 29/09/2020 Teste de Mesa: _______numero_______|________Sada_______| <- 3 | | | 3 x 1 = 3 * | | 3 x 2 = 6 * | | 3 x 3 = 9 * | | 3 x 4 = 12 * | | 3 x 5 = 15 * | | 3 x 6 = 18 * | | 3 x 7 = 21 * | | 3 x 8 = 24 * | | 3 x 9 = 27 * | | 3 x 10 = 30 * | Cdigo em C:*/ #include<stdio.h> int main(){ int numero = 0, multiplicador = 0, produto = 0; printf("Informe numero para apresentao da tabuada: \n"); scanf("%d", &numero); for(multiplicador=1; multiplicador<=10; multiplicador+=1){ produto = numero*multiplicador; printf("%d x %d = %d\n", numero, multiplicador, produto); } }
C
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdlib.h> #include <string.h> #include <stdio.h> #include <unistd.h> #define BUFFER 999 int main(int argc, char* argv[]) { int fd = socket(AF_INET, SOCK_DGRAM, 0); char buf[BUFFER]; struct sockaddr_in address; char *host=getlogin(); address.sin_family = AF_INET; address.sin_port = htons(5010); address.sin_addr.s_addr = inet_addr("224.0.0.22"); strcpy(buf, "FROM "); strcat(buf, host); strcat(buf, "\n"); if (fd == -1) { // an error occurred printf("Socket created unsuccessfully \n"); return 1; } else { // printf("Socket created successfully \n"); } if (host == NULL) { printf("host cannot be found"); return 1; } else { if(sizeof(host) <= 16) { printf("This is the login info: %s \n", host); } else { printf("Your hostname has exceed the size of 16\n"); exit(0); } } if (argc > 1) { printf("argv[1] = %s\n", argv[1]); strcat(buf,argv[1]); strcat(buf,"\n"); strcat(buf,"\0"); } else { printf("Usage: ./chirp \"Message\"\n"); return 1; } /* if (sizeof(buf)>999){ printf("Exceeded maximum length of 1000\n"); return 1; //exit(0); } */ printf("buffer = %s\n", buf); if (sendto(fd, buf, sizeof(buf), 0, (struct sockaddr *) &address, sizeof(address)) < 0) { perror("unable to send the message to the group"); } return 1; close(fd); return 0; }
C
#include<stdio.h> void remplace(char *nom, char ori, char nv) { FILE * f = fopen(nom,"r+"); if (f == NULL) { fprintf(stderr,"Erreur dans l'ouverture de %s\n",nom); } else { while (!feof(f)) { char c = fgetc(f); if (c == ori) { fseek(f,-1*sizeof(char),SEEK_CUR); fputc(nv,f); } } fclose(f); } } int main(int argc, char **argv) { remplace("autreFichierTest.txt",'e','z'); }
C
int f(int a,int b){ int c; return a+b; } int main(){ int a; a=f(56,27); printf("\n func ",a); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define LED_MAX_NAME_SIZE 128 typedef unsigned char u8; void DumpBuffer(unsigned char *buf, int bufSize); void DumpBuffer(unsigned char *buf, int bufSize) { int i = 0; printf("buffer size is %d \n", bufSize); for (i=0; i<bufSize;i++ ){ printf("buf[%d] = %d (%c) ", i, buf[i], buf[i]); if ( (i != 0) && (i % 5 == 0)) { printf("\n"); } } printf("\n\n"); } #if 1 typedef enum{ LED1_R = 0, LED1_G, LED1_B, LED2_R, LED2_G, LED2_B }STM32_LEDS; typedef struct{ u8 blink_rate; u8 brightness; }one_led; typedef struct _stm32_cmd_f{ union { struct{ u8 CMD; u8 CMD_SIZE; union{ u8 aLed[12]; struct { one_led Led1R; one_led Led1G; one_led Led1B; one_led Led2R; one_led Led2G; one_led Led2B; }; }; u8 reserve[18]; // 32-2-12 = 18 }; u8 buf[32]; }; } stm32_cmd_f; #endif void spi_stm32_brightness_set(STM32_LEDS led, u8 brightness) { u8 Led_offset= led*2 + 1; stm32_cmd_f data; memset(&data, 0, sizeof(data)); data.aLed[Led_offset]=brightness; DumpBuffer( (unsigned char *)&data, sizeof(data)); } int f1(void) { stm32_cmd_f data; memset(&data, 0, sizeof(data)); //data.CMD=3; //data.Led1R.blink_rate=200; //data.Led1R.blink_rate=200; //data.buf[2]=200; //DumpBuffer( (unsigned char *)&data, sizeof(data)); spi_stm32_brightness_set(LED2_B, 120); return 0; } int main(int argc, char *argv[]) { f1(); return 0; }
C
#include "stdio.h" #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <fcntl.h> #include <errno.h> #define MAXLINE 256 #define FIFO1 "/tmp/fifo.1" #define FIFO2 "/tmp/fifo.2" #define FILE_MODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) //default permissions for new fles void server(int,int); int main(int argc, char **argv) { int readfd,writefd; //create two FIFOs; OK if they already exist if((mkfifo(FIFO1,FILE_MODE)<0) && (errno !=EEXIST)) { printf("[server_main]can't create %s===\n",FIFO1); return -1; } if((mkfifo(FIFO2,FILE_MODE)<0) && (errno!=EEXIST)) { unlink(FIFO1); printf("[server_main]can't create %s===\n",FIFO2); return -1; } readfd=open(FIFO1,O_RDONLY,0); writefd=open(FIFO2,O_WRONLY,0); server(readfd,writefd); exit(0); } void server(int readfd, int writefd) { int fd; ssize_t n; char buff[MAXLINE+1]; //read pathname from IPC channel if((n=read(readfd,buff,MAXLINE))==0) { printf("[%s]==end-of-file while reading pathname",__func__); exit(0); } buff[n]='\0'; //add null terminate pathname if((fd=open(buff,O_RDONLY))<0) { snprintf(buff+n,sizeof(buff)-n,":can't open,%s\n",strerror(errno)); n=strlen(buff); write(writefd,buff,n); } else { //open succeeded: copy file to IPC channel while((n=read(fd,buff,MAXLINE))>0) write(writefd,buff,n); close(fd); } }
C
#include<stdio.h> //定义复数结构体 typedef struct { float realpart; //实部 float imagpart; //虚部 }Complex; //C语言中,函数的定义部分出现在被调用的函数之后,需要在前面声明 /* void assign(Complex* A, float real, float imag); //赋值声明 void add(Complex* A, float real, float imag); //加法 void minus(Complex* A, float real, float imag); //减法 void multiply(Complex* A, float real, float imag); //乘法 void divide(Complex* A, float eal, float imag); //除法 */ void assign(Complex* A, float real, float imag) { A->realpart = real; //实部赋值 A->imagpart = imag; //虚部赋值 } void add(Complex* C, Complex A, Complex B) { C->realpart = A.realpart + B.realpart; //实部相加 C->imagpart = A.imagpart + B.imagpart; //虚部相加 } void multiply(Complex* C, Complex A, Complex B) { C->realpart = (A.realpart * B.realpart) - (A.imagpart * B.realpart); //实部相加 C->imagpart = (A.realpart * B.imagpart )+ (B.realpart*A.imagpart); //虚部相加 } void divide(Complex* C, Complex A, Complex B) { C->realpart = ((A.realpart * B.realpart) + (A.imagpart * B.imagpart)) / ((B.realpart * B.realpart) + (B.imagpart * B.imagpart)); C->imagpart = ((A.imagpart * B.realpart) - (A.realpart * B.imagpart)) / ((B.realpart * B.realpart) + (B.imagpart * B.imagpart)); } main() { Complex z1, z2, z_jia, z_chen,z_chu; float a,b,c,d;//realpart,imagpart printf("输入第一复数的实部a="); scanf(&a); printf("输入第一复数的虚部b="); scanf(&b); printf("输入第二复数的实部c="); scanf(&c); printf("输入第二复数的虚部d="); scanf(&d); assign(&z1, a, b);//定义第一个复数 8+6i assign(&z2, c, d);//定义第二个复数 4+3i add(&z_jia, z1, z2); multiply(&z_chen, z1, z2); divide(&z_chu, z1, z2); printf("复数相加的结果为 = %f+%f\i",z_jia.realpart,z_jia.imagpart); printf("复数相乘的结果为 = %f+%f\i", z_chen.realpart, z_chen.imagpart); printf("复数相除的结果为 = %f+%f\i", z_chu.realpart, z_chu.imagpart); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "effector.h" #include "effdata.h" #include "sma.h" #define DELAY_NUM 16 static int *sma_buf_l, *sma_buf_r; void sma_init(int *param) { int i; sma_buf_l = (int *)malloc(DELAY_NUM * sizeof(int)); sma_buf_r = (int *)malloc(DELAY_NUM * sizeof(int)); // バッファを初期化する for (i = 0; i < DELAY_NUM; i++) { sma_buf_l[i] = 0; sma_buf_r[i] = 0; } } void sma_exit(void) { free(sma_buf_l); free(sma_buf_r); } void sma_main(int **inbuf, int **outbuf) { int *inbuf_l = inbuf[0]; int *inbuf_r = inbuf[1]; int *outbuf_l = outbuf[0]; int *outbuf_r = outbuf[1]; int sma_sum_l, sma_sum_r; int i, j; for (i = 0; i < FRAME_NUM; i++) { for (j = (DELAY_NUM - 1); j > 0; j--) { sma_buf_l[j] = sma_buf_l[j - 1]; sma_buf_r[j] = sma_buf_r[j - 1]; } sma_buf_l[0] = inbuf_l[i]; sma_buf_r[0] = inbuf_r[i]; sma_sum_l = 0; sma_sum_r = 0; for (j = 0; j < DELAY_NUM; j++) { sma_sum_l += sma_buf_l[j]; sma_sum_r += sma_buf_r[j]; } outbuf_l[i] = sma_sum_l / DELAY_NUM; outbuf_r[i] = sma_sum_r / DELAY_NUM; } }
C
#include<stdio.h> #include<math.h> int main() { int n,num,x,p=1,i; scanf("%d",&n); num = (1+sqrt(1+8*n))/2; for(i=1;i<=num;i++) { scanf("%d",&x); printf("%d ",x-p); p = x - p; } printf("\n"); return 0; }
C
#include <stdio.h> int main(void) { char str[16]; int d,count=1; printf("enter the sentence:"); scanf("%[^\n]s",str); for(d=0;str[d]!='\0';d++) { if(str[d]==' ') { count=count+1; } } printf("\nno of words=%d",count); return 0; }
C
#include <stdio.h> #include <stdlib.h> #define MAX 10 //最大顶点个数 #define INFINITY 65535 typedef struct graph { int num; //顶点个数 int side[MAX][MAX]; //弧 }GRAPH, *PGRAPH; PGRAPH InitGraph(void) // { PGRAPH pG = (PGRAPH)malloc(sizeof(GRAPH)); while(1) { printf("请输入顶点个数:"); scanf("%d", &pG->num); fflush(stdin); if(pG->num <= MAX) break; else printf("最大顶点个数为%d个,请重新输入!\n"); } for(int i=0; i < pG->num; ++i) { for(int j=0; j < pG->num; ++j) { if(i==j) pG->side[i][j] = 0; else pG->side[i][j] = INFINITY; } } for(int i=0; i < pG->num; ++i) { printf("请输入点%c相连的点及其弧的权值:", i+'A'); while(1) { char c; scanf("%c", &c); if(c == ' ') continue; else if(c == '\n') break; else scanf("%d", &pG->side[i][(int)c-'A']); } } //输出邻接矩阵检查 for(int i=0; i < pG->num; ++i) { for(int j=0; j < pG->num; ++j) printf("%-5d ", pG->side[i][j]); printf("\n"); } return pG; } void FindShortestPath(PGRAPH pG) { int *D = (int *)malloc(sizeof(int)*(pG->num)); int *P = (int *)malloc(sizeof(int)*(pG->num)); //初始化数据 for(int i=0; i < pG->num; ++i) { D[i] = pG->side[0][i]; P[i] = 0; } for(int i=1; i < pG->num; ++i) { for(int j=1; j < pG->num; ++j) { if(i != j && pG->side[i][j] != INFINITY) { if(pG->side[i][j] + D[i] < D[j]) { D[j] = pG->side[i][j] + D[i]; P[j] = i; for(int k=1; k < pG->num; ++k) { if(P[k] == j) { D[k] = D[j] + pG->side[j][k]; } } } } } } for(int i=0; i < pG->num; ++i) { printf("%d ", D[i]); } printf("\n"); for(int i=0; i < pG->num; ++i) { printf("%c ", P[i] + 'A'); } } int main(void) { PGRAPH pG = InitGraph(); FindShortestPath(pG); }
C
Problem statement : c program to generate first n Triangular numbers solution : include <stdio.h> void triangular_series(int n) { for (int i = 1; i <= n; i++) printf(" %d ", i*(i+1)/2); } int main() { int n ; printf("Enter value for n\n"); scanf("%d",&n); triangular_series(n); return 0; } output : Enter value of n 1 3 6 10 15 21 28 36 45 55
C
#include <stdint.h> /* Max font name length */ #define MAX_NAME 128 /* "bytecode" to encode font pixels */ #define BC_NEWLINE -126 #define BC_EOG -127 /* end of glyph */ #define BC_NUM_SPACES(n) (-1 * n) /* number of consecutive empty pixels in a row */ #define BC_GREY_PIXEL(n) (127 - n / 2) /* 0-255 greyscale pixel, mapped to 0-127 space */ typedef int8_t* Glyph; typedef struct Font { const char *name; const char *alphabet; int height; int baseline; int8_t const **glyphs; } Font;
C
#include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <pwd.h> #include <unistd.h> #include <signal.h> #include <readline/history.h> #include <readline/readline.h> #define CUR_DIR_SIZE 100 #define PROMPT_SIZE 500 #define MAX_PARAMETERS 5 /* variáveis usuário e diretório atual ==== */ char cur_dir[CUR_DIR_SIZE]; char *cur_user; /** Função read_command(char **command, char **parameters) * Usa GNU readline e GNU history para ler um comando do terminal * e retornar esse comando em command e os parâmetros indicados em parameters. */ void read_command(char **command, char **parameters){ char prompt_line[PROMPT_SIZE]; /* imprimindo o prompt */ cur_user = getenv("USER"); getcwd(cur_dir, sizeof(cur_dir)); sprintf(prompt_line, "{%s@%s} ", cur_user, cur_dir); /* lendo comando do shell */ *command = readline(prompt_line); add_history(*command); /* retornando o comando e os parâmetros, reaproveitando a memória que já foi alocada por * readline */ int i = 0; if (*command != NULL){ while((*command)[i] != ' ' && (*command)[i] != '\0') { i++; } for(int j = 0; j < 20; parameters[j] = NULL, j++); parameters[0] = *command; for(int j = 1; (*command)[i] != '\0'; i++){ if ((*command)[i] == ' ') { (*command)[i] = '\0'; if ((*command)[i+1] != ' ' && (*command)[i+1] != '\0') { parameters[j] = *command+i+1; j++; } } } } } int main(int argc, char const *argv[]) { /* comando e parâmetro lidos no terminal */ char *command; char *parameters[MAX_PARAMETERS]; /* variável devolvida pelo método waitpid */ int status; while (1) { read_command(&command, parameters); /* if para syscalls */ if (command == NULL) { printf("\n"); exit(0); } else if (!strcmp(command, "mkdir")) { mkdir(parameters[1], S_IRWXU); } else if (!strcmp(command, "kill")) { /* tratar o comando e pegar os parâmetros e PID */ pid_t pid = atoi(parameters[2]); kill(pid, -atoi(parameters[1])); } else if (!strcmp(command, "ln") && !strcmp(parameters[1], "-s")) { symlink(parameters[2], parameters[3]); } else { if (fork() != 0){ /* código do processo pai */ waitpid(-1, &status, 0); } else { /* código do processo filho */ execve(command, parameters, NULL); exit(0); } } free(command); } return 0; }
C
#include "wator.h" #include <pthread.h> /* * Struttura della coda rappresentata attraverso una linked list * */ typedef struct queue { void *info; struct queue *next; }queue; /* * Struttura della coda sincronizzata attraverso coda e mutex * */ typedef struct synqueue { queue *f; /*Primo elemento*/ queue *l; /*Ultimo elemento*/ pthread_mutex_t mutex; pthread_cond_t cv; }synqueue; int enqueue(synqueue *q, void *m); queue *dequeue(synqueue *q); int isempty(synqueue *q); void initqueue(synqueue *q);
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* queue_tools.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: bbauer <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/04/15 13:16:57 by bbauer #+# #+# */ /* Updated: 2017/05/27 16:29:19 by bbauer ### ########.fr */ /* */ /* ************************************************************************** */ #include "../include/lem_in.h" /* ** returns a copy of the queue table with the specified index removed. ** will probably always use index 0, but theres an option... ** frees the original table. */ t_room **queue_rem_one(t_room **src, size_t rem) { size_t tab_len; t_room **new_tab; tab_len = 0; while (src[tab_len]) tab_len++; if (rem > tab_len) return (NULL); new_tab = (t_room **)malloc(sizeof(t_room *) * tab_len); new_tab[tab_len - 1] = NULL; ft_memcpy(new_tab, src, sizeof(t_room *) * rem); if (rem < tab_len) ft_memcpy(&new_tab[rem], &src[rem + 1], sizeof(t_room *) * (tab_len - rem - 1)); new_tab[tab_len] = NULL; if (src) free(src); return (new_tab); }
C
#include <stdio.h> int main(void) { FILE *fp; int i, j; char filename[80]; scanf("%s", filename); fp = fopen(filename, "r"); fscanf(fp, "%d%d", &i, &j); printf("%d\n", i + j); fclose(fp); return 0; }
C
#include <stdio.h> #include <unistd.h> #include <string.h> char *ft_strstr(char *str, char *to_find) { int i; int j; i = 0; if (to_find[0] == '\0') { return (str); } while (str[i] != '\0') { if (str[i] == to_find[0]) { j = 1; while ((to_find[j] != '\0') && (to_find[j] == str[i+j])) { j++; } if (to_find[j] == '\0') { return (&str[i]); } } i++; } return (NULL); } int main(void) { char str[] = ""; char to_find[] = ""; printf("%p\n", ft_strstr(str, to_find)); printf("%p\n", strstr(str, to_find)); write(1, ft_strstr(str, to_find), 1); return (0); }
C
#ifndef _List_H struct Node; typedef struct Node *PtrToNode; typedef PtrToNode List; typedef PtrToNode Position; List MakeEmpty(List L); int isEmpty(List L); int isLast(List L); Position find(int Element, List L); void delete(int Element, List L); Position findPrevious(int Element, List L); void insert(int Element, List L, Position P); #endif /* _List_H */
C
#define _GNU_SOURCE #include <stdio.h> #include <dirent.h> #include <sys/stat.h> #include <sys/types.h> #include <fcntl.h> // for open flags #include <time.h> // for time measurement #include <assert.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <unistd.h> #define FILE_SIZE 128*1024*1024 #define MB 1024*1024 #define KB 1024 int randomIndex(int write_size); int fillRandom(int fd, char* buf); int fillBufRandom(char* randombuf); int main(int argc, char** argv) { if (argc != 4){ printf("Error: Wrong number of input arguments in command line\n"); return; } int ok = 1, fd, i = 0; int write_size = atoi(argv[3]); int o_direct = atoi(argv[2]); char *path_file = argv[1]; static char buf[1024 * 1024] __attribute__((__aligned__(4096)));// Allocate a 1MB buffer struct stat statbuf; int statReturn = stat(path_file, &statbuf); if ((statbuf.st_mode & S_IFMT) != S_IFBLK)//Check whether the input file is a block device { //Make sure the input file exists and is of size exactly 128MB. //The input file does not exists if ((statReturn < 0) || (errno == ENOENT)){ fd = open(path_file, O_CREAT | O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO); //create it if (fd < 0){ printf("Error opening file: %s\n", strerror(errno)); return errno; } if (fillRandom(fd, buf) == -1){ //write random data to it until it has 128MB of data. exit(0); } close(fd); } //if the file is symbolic link or has additional hard links else if (((statbuf.st_mode & S_IFMT) == S_IFLNK) || (statbuf.st_nlink > 1)){ printf("Error: The file is a symbolic link or has additional hard links\n"); exit(0); } //If it exists, verify it is of the correct size. If it isnt, truncate it, and write to it random data to it until it has 128MB of data. else if (statbuf.st_size != FILE_SIZE){ fd = open(path_file, O_TRUNC | O_RDWR); if (fd < 0){ printf("Error opening file: %s\n", strerror(errno)); return errno; } if (fillRandom(fd, buf) == -1){ exit(0); } close(fd); } } // fill the alocated buffer with random data if (fillBufRandom(buf) == -1){ exit(0); } struct timeval start, end; long mtime, seconds, useconds; // start time measurement gettimeofday(&start, NULL); //Open the input file with or without the O_DIRECT flag as indicated by the 2nd argument if (o_direct == 1){ fd = open(path_file, O_RDWR | O_DIRECT, S_IRWXU | S_IRWXG | S_IRWXO); if (fd < 0){ printf("Error opening file: %s\n", strerror(errno)); return errno; } } else if (o_direct == 0){ fd = open(path_file, O_RDWR, S_IRWXU | S_IRWXG | S_IRWXO); if (fd < 0){ printf("Error opening file: %s\n", strerror(errno)); return errno; } } //repeatedly write from the buffer to the file, at random locations in the file double div = (double)(KB / (double)write_size); int iterNum = (int)(div * 128);//number of writes until writing 128MB of total data to the file int offset; for (i = 0; i < iterNum; i++){ offset = randomIndex(write_size); // a random aligned offset (i.e., multiples of the write size) if (lseek(fd, offset, SEEK_SET) != offset){ //lseek system call with a random offset. printf("Error in lseek function: %s\n", strerror(errno)); return errno; } if (write(fd, buf, (write_size * KB)) != (write_size * KB)){//a write with write length according to the write size. printf("Error in write function: %s\n", strerror(errno)); return errno; } } close(fd); // end time measurement and print result gettimeofday(&end, NULL); seconds = end.tv_sec - start.tv_sec; useconds = end.tv_usec - start.tv_usec; mtime = ((seconds)* 1000 + useconds / 1000.0) + 0.5; //For every run, it should print the throughput of the run, i.e., how much MB/second did the program write, on average: double throughput = (128 * 1000) / (double)mtime; printf("The throughput of the run: %lf\n", throughput); //delete print iterNum, div, milliseconds return 0; } //This function find a random aligned offset (i.e., multiples of the write size) int randomIndex(int write_size){ int res, ok = 1; int ws_kb = write_size*KB; res = random(); res = res % FILE_SIZE; res = res - (res % ws_kb); return res; } //write 128MB of random data, to the file with fd. Return -1 on error, 0 in succsess. int fillRandom(int fd, char* buf){ int i, j; for (i = 0; i < 128; i++){ if (fillBufRandom(buf) == -1){ return -1; } if (write(fd, buf, MB) != MB){ printf("Error in write function: %s\n", strerror(errno)); return -1; } } return 0; } //fill buffer that has size 1MB with random data. Return -1 on error, 0 in succsess. int fillBufRandom(char* randombuf){ int j; for (j = 0; j < (4 * KB); j++){ //init randombuf that has size 1MB=(1024^2)bytes, with random data. if (initstate(time(NULL), &(randombuf[j]), 256) == NULL) { printf("Error: initstate function\n"); return -1; } } return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct rtc_time {int tm_hour; int tm_min; int tm_sec; int tm_year; int tm_mon; int tm_mday; } ; /* Variables and functions */ int /*<<< orphan*/ get_rtc_time (struct rtc_time*) ; int /*<<< orphan*/ sprintf (char*,char*,int,int,int,int,int,int) ; int get_rtc_status(char *buf) { char *p; struct rtc_time tm; p = buf; get_rtc_time(&tm); /* * There is no way to tell if the luser has the RTC set for local * time or for Universal Standard Time (GMT). Probably local though. */ p += sprintf(p, "rtc_time\t: %02d:%02d:%02d\n" "rtc_date\t: %04d-%02d-%02d\n", tm.tm_hour, tm.tm_min, tm.tm_sec, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday); return p - buf; }
C
#include<stdio.h> #include<conio.h> int arm (int x); void main() { int x,r; clrscr(); printf("enter the value"); scanf("%d",&x); r=arm(x); if(r==0) { printf("the no is armstrong no."); } else { printf("the no.is not arm"); } getch(); } int arm(int x) { int a,b,d; int s=0; b=x; while(x>0) { a=x%10; d=(a*a*a); s=s+d; x=x/10; } if (s==b) return 0; else return 1; }
C
#ifndef DNSINFOC #define DNSINFOC #include "dnsInfo.h" int formalizeURL(char dest[], const char* src) { char* dotPos = dest; dest++; for (int i = 0; i < maxUrlLen; i++, dest++) { if (src[i] == '.') { *dotPos = dest - dotPos - 1; dotPos = dest; } else *dest = src[i]; if (src[i] == 0) { *dotPos = dest - dotPos - 1; return i + 2; } }return 0; } dnsInfo* createDnsInfo() { struct DNSINFO* now = calloc(1, sizeof(struct DNSINFO));//calloc 自动初始化为0 now->ipSet = newIPlink(); return now; } int initIPFile(const char* path) { memset(theInfo, 0, (maxUrlLen+2) * sizeof(struct DNSINFO*)); FILE *file = fopen(path, "r"); if (file == NULL) { log_1("IPfile init fopen %s error.",path); return -1; } char tempUrl[maxUrlLen + 1]; int number = 0; for (;!feof(file);) { unsigned int a, b, c, d; fscanf(file, "%d.%d.%d.%d",&a,&b,&c,&d); dnsInfo* now = createDnsInfo(); addIPNode( &(now->ipSet), (d<<24)+(c<<16)+(b<<8)+a,0);//net order fscanf(file, "%s",tempUrl); formalizeURL(now->url, tempUrl); now->next = theInfo[strlen(now->url)]; theInfo[strlen(now->url)] = now; number++; } log_1("Chache: IPfile init %d ip in %s",number,path); fclose(file); return 0; } void addIP(IPLink ip, const char* url) { struct DNSINFO* temp = calloc(1,sizeof(struct DNSINFO));//calloc 自动初始化为0 temp->next = theInfo[strlen(url)]; theInfo[strlen(url)] = temp; temp->ipSet = ip; strncpy(temp->url, url, maxUrlLen); } dnsInfo findIP(const char* url,time_t lowestLeft) { struct DNSINFO* prev = NULL; for (struct DNSINFO* now = theInfo[strlen(url)]; now != NULL; prev = now, now = now->next) { if (strncmp(url, now->url, maxUrlLen) == 0) { //log("", now->url); refresh(&(now->ipSet),lowestLeft); if (now->ipSet.size > 0) { if (prev != NULL) {//ti qian prev->next = now->next; now->next = theInfo[strlen(url)]; theInfo[strlen(url)] = now; } log_2("Chache: Find url : %s", now->url); return *now; } else { log_1("Chache: Dated url : %s", now->url); if (prev == NULL)theInfo[strlen(url)] = now->next; else { prev->next=now->next; } free(now); } break; } } struct DNSINFO temp; memcpy(temp.url, url, strlen(url) + 1); temp.ipSet.size = 0; return temp; } // //int save(const char* path) //{ // FILE* file = fopen(path, "w"); // if (file == NULL)return -1; // for(int i=0;i<256;i++) // for (struct DNSINFO* now = theInfo[i]; now != NULL; now = now->next) { // fprintf(file, now->url); fprintf(file, "\t"); fprintf(file, now->ip); // } // fclose(file); // return 0; //} #endif // !DNSINFOC
C
#include <stdio.h> #include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include <errno.h> #define KEY 0x11112222 #define SIZE 256 #define MODE 0644 #define OPEN_MODE 0444 #define SHM_OK 0 #define SHM_FAILED -1 int test_creat(); int test_write(); int test_read(); int test_delete(); int main(int argc, char* argv[]) { if (argc < 2) { goto help; } if (strcmp(argv[1], "create") == SHM_OK) { return test_creat(); } else if (strcmp(argv[1], "write") == SHM_OK) { return test_write(); } else if (strcmp(argv[1], "read") == SHM_OK) { return test_read(); } else if (strcmp(argv[1], "delete") == SHM_OK) { return test_delete(); } help: printf("Usage: shm COMMAND\n\n" "The most used commands are:\n" "create Create a share memory\n" "write Write something into the share memory\n" "read Read something from the share memory\n" "delete Delete the share memory\n" ); return SHM_FAILED; } int test_creat() { int shmid = 0; shmid = shmget(KEY, SIZE, IPC_CREAT | IPC_EXCL | MODE); if (shmid == -1) { if (errno == EEXIST) { printf("key:%#x already exist\n", KEY); } else { printf("create key:%#x failed! errno:%d, err:%s\n", KEY, errno, strerror(errno)); } return SHM_FAILED; } return SHM_OK; } int test_write() { int i = 0; int shmid = 0; void *ptr = NULL; char *p = NULL; int ret = 0; struct shmid_ds ds; shmid = shmget(KEY, 0, MODE); if (shmid == -1) { printf("shmget key:%#x failed! errno:%d, err:%s\n", KEY, errno, strerror(errno)); return SHM_FAILED; } ptr = shmat(shmid, NULL, 0); if (ptr == (void*) -1) { printf("shmat shmid:%d failed! errno:%d, err:%s\n", shmid, errno, strerror(errno)); return SHM_FAILED; } memset(&ds, 0, sizeof(struct shmid_ds)); ret = shmctl(shmid, IPC_STAT, &ds); if (ret == -1) { printf("shmctl shmid:%d failed! errno:%d, err:%s\n", shmid, errno, strerror(errno)); return SHM_FAILED; } printf("size of shmid:%d is %zd\n", shmid, ds.shm_segsz); p = (char*)ptr; for (i = 0; i < ds.shm_segsz; i++) { *p = 'a' + i % 26; p++; } ret = shmdt(ptr); if (ret == -1) { printf("shmdt shmid:%d failed! errno:%d, err:%s\n", shmid, errno, strerror(errno)); return SHM_FAILED; } return SHM_OK; } int test_read() { int i = 0; int shmid = 0; void *ptr = NULL; char *p = NULL; int ret = 0; struct shmid_ds ds; shmid = shmget(KEY, 0, OPEN_MODE); //shmid = shmget(KEY, 0, 0666); if (shmid == -1) { printf("line:%d, shmget key:%#x failed! errno:%d, err:%s\n", __LINE__, KEY, errno, strerror(errno)); return SHM_FAILED; } ptr = shmat(shmid, NULL, SHM_RDONLY); //ptr = shmat(shmid, NULL, 0); if (ptr == (void*) -1) { printf("line:%d, shmat shmid:%d failed! errno:%d, err:%s\n", __LINE__, shmid, errno, strerror(errno)); return SHM_FAILED; } memset(&ds, 0, sizeof(struct shmid_ds)); ret = shmctl(shmid, IPC_STAT, &ds); if (ret == -1) { printf("line:%d, shmctl shmid:%d failed! errno:%d, err:%s\n", __LINE__, shmid, errno, strerror(errno)); return SHM_FAILED; } printf("size of shmid:%d is %zd, ptr:%p\n", shmid, ds.shm_segsz, ptr); p = (char*)ptr; for (i = 0; i < ds.shm_segsz; i++) { if (*p == '\0') break; fputc(*p, stdout); p++; } fputc('\n', stdout); ret = shmdt(ptr); if (ret == -1) { printf("shmdt shmid:%d failed! errno:%d, err:%s\n", shmid, errno, strerror(errno)); return SHM_FAILED; } return SHM_OK; } int test_delete() { int shmid = 0; int ret = 0; shmid = shmget(KEY, 0, MODE); if (shmid == -1) { printf("shmget key:%#x failed! errno:%d, err:%s\n", KEY, errno, strerror(errno)); return SHM_FAILED; } ret = shmctl(shmid, IPC_RMID, NULL); if (ret == -1) { printf("shmctl RMID shmid:%d failed! errno:%d, err:%s\n", shmid, errno, strerror(errno)); return SHM_FAILED; } return SHM_OK; }
C
#include <time.h> #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define LEFT -2 #define RIGHT 2 static int cnt = 0; typedef struct _avl avl; struct _avl { int data; avl *left; avl *right; }; bool check_dup(int *data, int compare, int idx) { int i; for (i = 0; i < idx; i++) { if (data[i] == compare) { return true; } } return false; } void init_data(int *data, int num) { int i, tmp; for (i = 0; i < num; i++) { reassign: tmp = rand() % num + 1; if (check_dup(data, tmp, i)) { goto reassign; } data[i] = tmp; } } void print_arr(int *data, int num) { int i; for (i = 0; i < num; i++) { printf("%4d", data[i]); if (i % 7 == 6) { printf("\n"); } } printf("\n"); } struct avl_node_s { struct avl_node_s *left; struct avl_node_s *right; int value; }; typedef struct avl_node_s avl_node_t; struct avl_tree_s { struct avl_node_s *root; }; typedef struct avl_tree_s avl_tree_t; /* Create a new AVL tree. */ avl_tree_t *avl_create() { avl_tree_t *tree = NULL; if( ( tree = malloc( sizeof( avl_tree_t ) ) ) == NULL ) { return NULL; } tree->root = NULL; return tree; } /* Initialize a new node. */ avl_node_t *avl_create_node() { avl_node_t *node = NULL; if( ( node = malloc( sizeof( avl_node_t ) ) ) == NULL ) { return NULL; } node->left = NULL; node->right = NULL; node->value = 0; return node; } /* Find the height of an AVL node recursively */ int avl_node_height( avl_node_t *node ) { int height_left = 0; int height_right = 0; if( node->left ) height_left = avl_node_height( node->left ); if( node->right ) height_right = avl_node_height( node->right ); return height_right > height_left ? ++height_right : ++height_left; } /* Find the balance of an AVL node */ int avl_balance_factor( avl_node_t *node ) { int bf = 0; if( node->left ) bf += avl_node_height( node->left ); if( node->right ) bf -= avl_node_height( node->right ); return bf ; } /* Left Left Rotate */ avl_node_t *avl_rotate_leftleft( avl_node_t *node ) { avl_node_t *a = node; avl_node_t *b = a->left; a->left = b->right; b->right = a; return( b ); } /* Left Right Rotate */ avl_node_t *avl_rotate_leftright( avl_node_t *node ) { avl_node_t *a = node; avl_node_t *b = a->left; avl_node_t *c = b->right; a->left = c->right; b->right = c->left; c->left = b; c->right = a; return( c ); } /* Right Left Rotate */ avl_node_t *avl_rotate_rightleft( avl_node_t *node ) { avl_node_t *a = node; avl_node_t *b = a->right; avl_node_t *c = b->left; a->right = c->left; b->left = c->right; c->right = b; c->left = a; return( c ); } /* Right Right Rotate */ avl_node_t *avl_rotate_rightright( avl_node_t *node ) { avl_node_t *a = node; avl_node_t *b = a->right; a->right = b->left; b->left = a; return( b ); } /* Balance a given node */ avl_node_t *avl_balance_node( avl_node_t *node ) { avl_node_t *newroot = NULL; /* Balance our children, if they exist. */ if( node->left ) node->left = avl_balance_node( node->left ); if( node->right ) node->right = avl_balance_node( node->right ); int bf = avl_balance_factor( node ); if( bf >= 2 ) { /* Left Heavy */ if( avl_balance_factor( node->left ) <= -1 ) newroot = avl_rotate_leftright( node ); else newroot = avl_rotate_leftleft( node ); } else if( bf <= -2 ) { /* Right Heavy */ if( avl_balance_factor( node->right ) >= 1 ) newroot = avl_rotate_rightleft( node ); else newroot = avl_rotate_rightright( node ); } else { /* This node is balanced -- no change. */ newroot = node; } return( newroot ); } /* Balance a given tree */ void avl_balance( avl_tree_t *tree ) { avl_node_t *newroot = NULL; newroot = avl_balance_node( tree->root ); if( newroot != tree->root ) { tree->root = newroot; } } /* Insert a new node. */ void avl_insert( avl_tree_t *tree, int value ) { avl_node_t *node = NULL; avl_node_t *next = NULL; avl_node_t *last = NULL; /* Well, there must be a first case */ if( tree->root == NULL ) { node = avl_create_node(); node->value = value; tree->root = node; /* Okay. We have a root already. Where do we put this? */ } else { next = tree->root; while( next != NULL ) { last = next; if( value < next->value ) { next = next->left; } else if( value > next->value ) { next = next->right; /* Have we already inserted this node? */ } else if( value == next->value ) { /* This shouldn't happen. */ } } node = avl_create_node(); node->value = value; if( value < last->value ) last->left = node; if( value > last->value ) last->right = node; } avl_balance( tree ); } /* Find the node containing a given value */ avl_node_t *avl_find( avl_tree_t *tree, int value ) { avl_node_t *current = tree->root; while( current && current->value != value ) { if( value > current->value ) current = current->right; else current = current->left; } return current; } /* Do a depth first traverse of a node. */ void avl_traverse_node_dfs( avl_node_t *node, int depth ) { int i = 0; if( node->left ) avl_traverse_node_dfs( node->left, depth + 2 ); for( i = 0; i < depth; i++ ) putchar( ' ' ); printf( "%d: %d\n", node->value, avl_balance_factor( node ) ); if( node->right ) avl_traverse_node_dfs( node->right, depth + 2 ); } /* Do a depth first traverse of a tree. */ void avl_traverse_dfs( avl_tree_t *tree ) { avl_traverse_node_dfs( tree->root, 0 ); } void print_avl(avl_node_t *tree) { avl_node_t *tmp = tree; if (tmp) { print_avl(tmp->left); printf("data = %5d\t", tmp->value); if (tmp->left) { printf("left = %5d\t", tmp->left->value); } else { printf("left = NULL\t"); } if (tmp->right) { printf("right = %5d\t", tmp->right->value); } else { printf("right = NULL\t"); } printf("cnt = %5d\n", ++cnt); print_avl(tmp->right); } } int main( int argc, char **argv ) { avl_tree_t *tree = NULL; int i = 0; int data[511] = { 0 }; int len = sizeof(data) / sizeof(int); init_data(data, len); print_arr(data, len); tree = avl_create(); for( i = 0; i < len; i++ ) { avl_insert( tree, data[i] ); } print_avl(tree->root); return 0; }
C
#include "hash_tables.h" /** * hash_table_create - build hash table * @size: size hash table * Return: new pointer hash */ hash_table_t *hash_table_create(unsigned long int size) { hash_table_t *htable; unsigned int i; if (size == 0) return (NULL); htable = malloc(sizeof(hash_table_t)); if (htable == NULL) return (NULL); htable->size = size; htable->array = malloc(size * sizeof(hash_node_t *)); if (htable->array == NULL) { free(htable); return (NULL); } else { for (i = 0; i < size; i++) htable->array[i] = NULL; } return (htable); }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <windows.h> int menu(); void limpa_aposta(int *ap); void listar(int *ap); void apostas(int *ap); void sorteio(int *sorteio); int acertos(int *boletim, int *sorteio); void main() { int OpMenu; int boletim[5][7]; int chave[7]; int x; int num; float saldo; int valop1=0,valop2=0; do { OpMenu=menu(); switch(OpMenu) { case 1: { system("cls"); for(x=0;x<5;x++) limpa_aposta(boletim[x]); do{ printf("Quantas apostas vai jogar[1..5]? "); scanf("%d",&num); }while(num<1||num>5); for(x=0;x<num;x++) apostas(boletim[x]); for(x=0;x<num;x++) { listar(boletim[x]); valop1=1; } getch(); break; } case 2: { if(valop1==1) { sorteio(chave); listar(chave); valop1=1; }else printf("\nPrimeiro tem de fazer as apostas.\n"); getch(); break; } case 3: { if(valop2==1) { acertos(boletim,chave); }else printf("\nPrimeiro tem de fazer as apostas e o sorteio.\n"); system("cls"); printf("\nA P O S T A S"); for(x=0;x<num;x++) listar(boletim[x]); printf("\n\nC H A V E"); for(x=0;x<num;x++) listar(chave); printf("\n\nA C E R T O S"); for(x=0;x<num;x++) { printf("\nNa %da aposta: ",x+1); saldo=acertos(boletim[x],chave); } saldo=saldo-2.5*num; printf("\n\nO saldo do concurso foi %.2f",saldo); getch(); break; } } }while(OpMenu!=4); } void limpa_aposta(int *ap) { int n; printf("\n"); for(n=0;n<7;n++) ap[n]=0; } void listar(int *ap) { int x; printf("\n"); for(x=0;x<7;x++) { if(x==5) printf("+ %d ",ap[x]); else printf("%d ",ap[x]); } } int menu() { int op; do{ system("cls"); printf("\n\t**Euromilhoes**\n\n"); printf(" 1 - Definir Apostas\n"); printf(" 2 - Simular Sorteio\n"); printf(" 3 - Validar Acertos\n"); printf(" 4 - Sair\n\n"); printf("\tOpcao: "); fflush(stdin); scanf("%d",&op); }while((op<1)||(op>4)); return op; } void apostas(int *ap) { int x; int k,num,repetido; for(x=0;x<5;x++) { do{ repetido=0; do{ printf("\t(N %d): ",x+1); scanf("%d",&num); }while(num<1||num>50); for(k=0;k<x;k++) if(num==ap[k]) repetido=1; }while(repetido==1); ap[x]=num; } for(x=5;x<7;x++) { do{ repetido=0; do{ printf("\t(E %d): ",x-4); scanf("%d",&num); }while(num<1||num>12); if(x==6) if(ap[5]==num) repetido=1; }while(repetido==1); ap[x]=num; } } void sorteio(int *sorteio) { int aleat; int num=0; int repetido=0; int x,k; srand(time(NULL)); for(x=0;x<5;x++) { do{ repetido=0; aleat=(rand()%50+1); for(k=0;k<x;k++) if(aleat==sorteio[k]) repetido=1; }while(repetido==1); sorteio[x]=aleat; } for(x=5;x<7;x++) { do{ repetido=0; aleat=(rand()%12+1); if(x==6) if(sorteio[5]==aleat) repetido=1; }while(repetido==1); sorteio[x]=aleat; } } int acertos(int *boletim, int *sorteio) { int naposta; int nsorteio; int ncertos=0; int ecertas=0; int premio; for(naposta=0;naposta<5;naposta++) for(nsorteio=0;nsorteio<5;nsorteio++) if(boletim[naposta]==sorteio[nsorteio]) ncertos++; for(naposta=5;naposta<7;naposta++) for(nsorteio=5;nsorteio<7;nsorteio++) if(boletim[naposta]==sorteio[nsorteio]) ecertas++; printf("\n%d Numeros e %d Estrelas",ncertos,ecertas); if((ncertos==2)&&(ecertas==1)) premio=5; if((ncertos==3)&&(ecertas==1)) premio=500; if((ncertos==4)&&(ecertas==1)) premio=5000; if((ncertos==5)&&(ecertas==2)) premio=50000; getch(); return premio; }
C
# include<stdio.h> # include<string.h> long long mul(long long a,long long b,long long c) { if(b==0) { return 0; } long long regresar=mul(a,b>>1,c); regresar=(regresar+regresar)%c; if(b&1) { regresar=(regresar +a)%c; } return regresar; } int main() { int t,n,l,k; long long int temp,i,j,a,b,c; scanf("%d",&t); while(t--) { scanf("%d",&n); long long int add=0,mult=1; long long int array[n]; char s[n+1]; for(i=0;i<n;i++) { scanf("%lld",&array[i]); } scanf("%lld%lld%lld",&a,&b,&c); //lld is because of the limit so I use long long int scanf("%s",s); l=strlen(s); for(i=0;i<l;i++) { if(s[i]=='R') { j=n-1; for(k=i;k<j;k++,j--) { temp=array[k]; array[k]=array[j]; array[j]=temp; } } else if(s[i]=='A') { add=(add+a)%c; } else if(s[i]=='M') { mult=mul(mult,b,c); add=mul(add,b,c); } array[i]=mul(array[i],mult,c); array[i]=(array[i]+add)%c; printf("%lld ",array[i]); } printf("\n"); } return 0; }
C
/* <p>A robot is located at the top-left corner of a <em>m</em> x <em>n</em> grid (marked &#39;Start&#39; in the diagram below).</p> <p>The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked &#39;Finish&#39; in the diagram below).</p> <p>How many possible unique paths are there?</p> <p><img src="https://leetcode.com/static/images/problemset/robot_maze.png" /><br /> <small>Above is a 7 x 3 grid. How many possible unique paths are there?</small></p> <p><strong>Note:</strong> <em>m</em> and <em>n</em> will be at most 100.</p> <p><strong>Example 1:</strong></p> <pre> <strong>Input:</strong> m = 3, n = 2 <strong>Output:</strong> 3 <strong>Explanation:</strong> From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -&gt; Right -&gt; Down 2. Right -&gt; Down -&gt; Right 3. Down -&gt; Right -&gt; Right </pre> <p><strong>Example 2:</strong></p> <pre> <strong>Input:</strong> m = 7, n = 3 <strong>Output:</strong> 28</pre> <p>一个机器人位于一个 <em>m x n </em>网格的左上角 (起始点在下图中标记为&ldquo;Start&rdquo; )。</p> <p>机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为&ldquo;Finish&rdquo;)。</p> <p>问总共有多少条不同的路径?</p> <p><img src="/static/images/problemset/robot_maze.png"></p> <p><small>例如,上图是一个7 x 3 的网格。有多少可能的路径?</small></p> <p><strong>说明:</strong><em>m</em>&nbsp;和 <em>n </em>的值均不超过 100。</p> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> m = 3, n = 2 <strong>输出:</strong> 3 <strong>解释:</strong> 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -&gt; 向右 -&gt; 向下 2. 向右 -&gt; 向下 -&gt; 向右 3. 向下 -&gt; 向右 -&gt; 向右 </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> m = 7, n = 3 <strong>输出:</strong> 28</pre> <p>一个机器人位于一个 <em>m x n </em>网格的左上角 (起始点在下图中标记为&ldquo;Start&rdquo; )。</p> <p>机器人每次只能向下或者向右移动一步。机器人试图达到网格的右下角(在下图中标记为&ldquo;Finish&rdquo;)。</p> <p>问总共有多少条不同的路径?</p> <p><img src="/static/images/problemset/robot_maze.png"></p> <p><small>例如,上图是一个7 x 3 的网格。有多少可能的路径?</small></p> <p><strong>说明:</strong><em>m</em>&nbsp;和 <em>n </em>的值均不超过 100。</p> <p><strong>示例&nbsp;1:</strong></p> <pre><strong>输入:</strong> m = 3, n = 2 <strong>输出:</strong> 3 <strong>解释:</strong> 从左上角开始,总共有 3 条路径可以到达右下角。 1. 向右 -&gt; 向右 -&gt; 向下 2. 向右 -&gt; 向下 -&gt; 向右 3. 向下 -&gt; 向右 -&gt; 向右 </pre> <p><strong>示例&nbsp;2:</strong></p> <pre><strong>输入:</strong> m = 7, n = 3 <strong>输出:</strong> 28</pre> */ int uniquePaths(int m, int n) { }
C
#include <fcntl.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/socket.h> #include <linux/if.h> #include <linux/if_tun.h> int tun_open(char *devname){ struct ifreq ifr; int fd, err; fd = open("/dev/net/tun", O_RDWR); memset(&ifr, 0, sizeof(ifr)); ifr.ifr_flags = IFF_TUN; strncpy(ifr.ifr_name, devname, IFNAMSIZ); ioctl(fd, TUNSETIFF, (void*)&ifr); return fd; } int main(int argc, char *argv[]){ int fd, nbytes, i; unsigned char buf[1600]; fd = tun_open("asa0"); printf("device asa0 open"); while(1){ nbytes = read(fd, buf, sizeof(buf)); printf("-------------------read %d bytes from asa0\n", nbytes); for (i = 0; i < nbytes; i++){ if (i % 16 == 0){ printf("\n"); } printf("%02x ",buf[i]); } printf("\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_print_flag.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hhow-cho <hhow-cho@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/04/12 15:42:12 by hhow-cho #+# #+# */ /* Updated: 2019/04/12 16:39:57 by hhow-cho ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void ft_print_flag(t_flag *flag) { ft_printf("\n------------------\n"); ft_putchar(flag->conv); ft_putstr("\n"); // ft_putstr("length : "); // ft_putnbr(flag->length); // ft_putstr("\n"); // ft_putstr("precision : "); // ft_putnbr(flag->precision); // ft_putstr("\n"); // ft_putstr("width : "); // ft_putnbr(flag->width); // ft_putstr("\n"); // ft_putstr("zero : "); // ft_putnbr(flag->zero); // ft_putstr("\n"); // ft_putstr("plus : "); // ft_putnbr(flag->plus); // ft_putstr("\n"); // ft_putstr("minus : "); // ft_putnbr(flag->minus); // ft_putstr("\n"); // ft_putstr("space : "); // ft_putnbr(flag->space); // ft_putstr("\n"); // ft_putstr("hash : "); // ft_putnbr(flag->hash); ft_putstr("\n------------------\n"); }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/socket.h> #include <arpa/inet.h> int main(int argc, char *argv[]){ struct sockaddr_in sa = { 0 }; int len; char buff[4096]; int sock = socket(AF_INET, SOCK_DGRAM, 0); // 通信相手のソケットアドレスを作成 sa.sin_family = AF_INET; sa.sin_port = htons(atoi(argv[2])); //host 2 network short sa.sin_addr.s_addr = inet_addr(argv[1]); bind(sock, (struct sockaddr*)&sa, sizeof(struct sockaddr_in)); //add while (0 < (len = read(0, buff, 256))){ sendto(sock, buff, len - 1, 0, (struct sockaddr*)&sa, sizeof(sa)); printf("%s", buff); // add } close(sock); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* fill_arg_struct.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: awoimbee <awoimbee@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/03 17:56:45 by awoimbee #+# #+# */ /* Updated: 2020/03/06 00:53:21 by awoimbee ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" #include <libft/ft_char.h> /* ** In this file, every function has the role of filling a specific variable ** in a t_arg structure. ** They are designed to be called one after the other. */ int prtf__get_arg_option(t_arg *arg, const char **format) { arg->option = 0; while (1) { if (**format == '+' && ++(*format)) arg->option |= FLAG_PLUS; else if (**format == ' ' && ++(*format)) arg->option |= FLAG_SPACE; else if (**format == '-' && ++(*format)) arg->option |= FLAG_MINUS; else if (**format == '0' && ++(*format)) arg->option |= FLAG_ZERO; else if (**format == '#' && ++(*format)) arg->option |= FLAG_HASH; else break ; } if ((arg->option & FLAG_PLUS) && (arg->option & FLAG_SPACE)) arg->option -= FLAG_SPACE; if ((arg->option & FLAG_MINUS) && (arg->option & FLAG_ZERO)) arg->option -= FLAG_ZERO; return (1); } int prtf__get_arg_m_width(t_arg *arg, const char **format) { if ('0' <= **format && **format <= '9') arg->m_width = prtf__atoi_move(format); else arg->m_width = 0; return (1); } int prtf__get_arg_precis(t_arg *arg, const char **format) { if (**format == '.' && ++(*format)) { if (**format == '*' && ++(*format)) arg->precis = -2; else { if (!ft_isdigit(**format)) arg->precis = 0; else arg->precis = prtf__atoi_move(format); } } else arg->precis = -1; if (arg->precis > 0 && (arg->option & FLAG_ZERO)) arg->option -= FLAG_ZERO; return (1); } int prtf__get_arg_size(t_arg *arg, const char **format) { if (**format == 'h' && ++(*format)) { if (**format == 'h' && ++(*format)) arg->size = -2; else arg->size = -1; } else if ((**format == 'l' && (*format)[1] == 'l' && (*format += 2))) arg->size = 2; else if (((**format == 'L') && ++*format)) arg->size = 3; else if ((**format == 'l' || **format == 'w') && ++(*format)) arg->size = 1; else arg->size = 0; return (1); } /* ** if type is 'p', we change some parmeters and pass it down as an 'x', ** because it's easier & faster :) ** if type is 'C' we change it to 'c' with size = 1 ** this way it's easier to handle "%C" like "%lc" or "%wc" */ int prtf__get_arg_convtyp(t_arg *arg, const char **format) { char c; c = *((*format)++); if (c == 'p') { arg->option += FLAG_HASH; arg->option += FLAG_SPEP; arg->size = 1; c = 'x'; } else if ((c == 'U') && (c = 'u')) arg->size = 1; arg->conv_typ = c; if (c == 'd' || c == 'i' || c == 'o' || c == 'u' || c == 'x' || c == 'X' || c == 's' || c == 'f' || c == 'p' || c == 'c' || c == 'b' || c == 'r') return (1); else return (0); }
C
#include <stdio.h> #include <stdlib.h> #include <strings.h> #include <string.h> #include <hiredis/hiredis.h> //#include "hiredis.h" #include "csp_redis.h" int CspRedisOperation(int databaseNO,int type,char * key, char *value,redisContext * conn){ redisReply *reply =NULL; char Command[COMMANDLEN]={0}; char selectCmd[COMMANDLEN] = {0}; char valuestr[VALUELEN]; int returnval=0; if(strlen(key)> COMMANDLEN){ return 0; } /* if(strlen(key) != 0) printf("key = %s\n",key); if(strlen(value) != 0) printf("value = %s\n",value); */ switch(type){ case OPERATION_SET: if(strlen(key) == 0) return -1; if(strlen(value)==0) return -1; sprintf(selectCmd,"select %d",databaseNO); reply =(redisReply*)redisCommand(conn,"select %d",databaseNO); freeReplyObject(reply); reply = NULL; sprintf(Command,"set %s %s",key,value); #if CSP_RELEASE_DEBUG printf("command:%s\n",Command); #endif reply = (redisReply*)redisCommand(conn,"set %s %s",key,value); // freeReplyObject(reply); // reply= (redisReply*)redisCommand(conn,Command); // freeReplyObject(reply); if(NULL == reply){ printf("reply NULL .\n"); return 0; } if(reply->type == REDIS_REPLY_STATUS){ if(strcasecmp(reply->str,"OK") == 0){ returnval = 1;//set ok }else{ returnval = 3;//set not ok } } else if(reply->type == REDIS_REPLY_NIL){ returnval = 2; //not set } break; case OPERATION_GET: if(strlen(key) == 0) return -1; sprintf(selectCmd,"select %d",databaseNO); reply =(redisReply*)redisCommand(conn,"select %d",databaseNO); // fprintf(stderr,"befroe free\n"); freeReplyObject(reply); reply=NULL; sprintf(Command,"get %s",key); #if CSP_RELEASE_DEBUG printf("command:%s\n",Command); #endif // fprintf(stderr,"befroe command\n"); reply = (redisReply*)redisCommand(conn,"get %s",key); // fprintf(stderr,"after command\n"); if(NULL == reply){ printf("reply NULL .\n"); return 0; } if(reply->type == REDIS_REPLY_STRING){ // printf("%s,len = %d\n",reply->str,reply->len); memcpy(value,reply->str,reply->len); value[reply->len]='\0'; returnval = 4;//get string ok } else if(reply->type == REDIS_REPLY_NIL){ returnval = 5;//get string nil } break; default: break; } freeReplyObject(reply); reply = NULL; return returnval; } int CspRedisClear(int db,redisContext * conn){ char cmd[COMMANDLEN]={0}; redisReply *reply; if(db == -1){ sprintf(cmd,"flushall"); reply =(redisReply*)redisCommand(conn,cmd); freeReplyObject(reply); } else{ sprintf(cmd,"select %d",db); reply =(redisReply*)redisCommand(conn,cmd); freeReplyObject(reply); memset(cmd,0,sizeof(cmd)); sprintf(cmd,"flushdb"); reply =(redisReply*)redisCommand(conn,cmd); freeReplyObject(reply); } return 0; } /* int main(int argc ,char * argv[]){ char * op = argv[1]; int opp = atoi(op); char *key=NULL,*value=NULL; if (opp == 1){ value = argv[3]; } else{ value = (char *)malloc(VALUELEN); memset(value,0,VALUELEN); } key = argv[2]; CspRedisOperation(opp,key,value); if(opp !=1){ printf("%s \n",value); free(value); } return 0; } */
C
// 快速排序 // 时间复杂度O(nlogn) 空间复杂度O(logn) // 最坏情况下 时间复杂度O(n^2) 空间复杂度O(n) // 主程序,递归实现 void QuickSort(ElemType A[], int low, int high) { if (low < high) { int pivotpos = Partition(A, low, high); // 分治 QuickSort(A, low, pivotpos - 1); QuickSort(A, pivotpos + 1, high); } } // 划分操作 // 每次总是以当前表中第一个原属作为枢轴值(基准)对表进行划分 int Partition(ElemType A[], int low, int high) { ElemType pivot = A[low]; while (low < high) { while (low < high && A[high] >= pivot) --high; // 将比枢轴值小的元素移动到左端 A[low] = A[high]; while (low < high && A[low] <= pivot) ++low; // 将比枢轴值大的元素移动到右端 A[high] = A[low]; } // 枢轴元素存放到最终位置 A[low] = pivot; // 返回存放枢轴的最终位置 return low; }
C
#include <stdio.h> int main(void){ int n = 0; for(n;n<10;n++){ int i = 0; for(i;i<=n;i++){ printf("*"); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <linux/sockios.h> #include <net/if.h> #include <netinet/in.h> #include <string.h> int main(int argc, char **argv) { { int fd; struct ifreq req; fd = socket(AF_INET, SOCK_DGRAM, 0); strncpy(req.ifr_name, "eth0", IFNAMSIZ); ioctl(fd, SIOCGIFADDR, &req); { char buf[1024]; inet_ntop(req.ifr_addr.sa_family, (char *)req.ifr_addr.sa_data + 2, buf, sizeof(buf)); printf("%s\n", buf); } } return 0; }
C
#include<stdio.h> #include<math.h> int main() { int num,c=0,result; printf("Enter number "); scanf("%d",&num); result=b_num(num,c); d_num(result); return 0; } int b_num(int num,int c) { int rem,b_num=0,i=0; while(num) { rem=num%2; num=num/2; b_num=b_num+rem*pow(10,i); i++; } printf("binary number = %d",b_num); return(b_num); } void d_num(int result) { int r,j=0,d_num=0; while(result) { r=result%10; result/=10; d_num=d_num+r*pow(2,j); j++; } printf("\ndecimal number = %d",d_num); }
C
// EUHEXDMP.H // // Copyright (C) Symbian Software Ltd 1997-2005. All rights reserved. // _LIT(KTxtTwoSpaces," "); _LIT(KTxtThreeSpaces," "); _LIT(KTxtTwoSpaceStar," * "); _LIT(KTxtOneSpaceStar," *"); _LIT(KFormat1,"%S\n"); inline void hexDump(const TDesC8& aBuffer,TInt32& aAddress,TInt32& aOffset,TDes& aOutput) { TBuf<35> hexView; TBuf<16> charView; TBuf<8> hexAddress; TBuf<2> hexChar; // calculate number of leading spaces due to 16-bit boundaries TInt numLeadingSpaces = aAddress % 16; for (TInt count=0; count<16; count++) { // print space between quartets of hex values if (count==4 || count==8 || count==12) hexView.Append(' '); // display the character/hex-val or a space depending on 16-bit boundary if (count < (numLeadingSpaces)) { hexView.AppendFormat(KTxtTwoSpaces); charView.Append(' '); } else { TInt curChar = (count - numLeadingSpaces) + aOffset; // calculate which element of the descriptor to display if (curChar < aBuffer.Size()) // check to see if end of buffer has been exceeded { // Ensure hex-format of number is 2 chars long hexChar.Zero(); hexChar.AppendNumUC(aBuffer[curChar],EHex); if (hexChar.Length() < 2) hexView.Append('0'); hexView.Append(hexChar); if (aBuffer[curChar] > 31 && aBuffer[curChar] != 127) charView.Append(aBuffer[curChar]); else charView.Append('.'); } else { hexView.AppendFormat(KTxtTwoSpaces); charView.Append(' '); } } } // Set the length of aOutput to zero (ie. reset the output buffer) aOutput.Zero(); // calculate the 16-bit block address to display TInt32 prtAddress = aAddress - numLeadingSpaces; hexAddress.AppendNumUC(prtAddress,EHex); for (TInt preZeroCount=0; preZeroCount < (8-hexAddress.Length()); preZeroCount++) aOutput.Append('0'); aOutput.Append(hexAddress); aOutput.AppendFormat(KTxtThreeSpaces); // display hex-values and characters aOutput.Append(hexView); aOutput.AppendFormat(KTxtTwoSpaceStar); aOutput.Append(charView); aOutput.AppendFormat(KTxtOneSpaceStar); // update the address and offset for the descriptor aAddress += 16 - numLeadingSpaces; aOffset += 16 - numLeadingSpaces; } void printBuffer(TInt32 aAddress,const TDesC8& aBuffer) { TInt32 offset = 0; TBuf<80> outputLine; while (offset < aBuffer.Size()) { hexDump(aBuffer,aAddress,offset,outputLine); console->Printf(KFormat1, &outputLine); } }
C
#include <stdio.h> void insert_sort(int k[],int n); int main (void) { int array[] = {3,2,1,9,7,5,8,4,0,6,10}; int i; insert_sort(array,11); printf("array after sort:\n "); for(i=0;i<11;i++){ printf("%d ",array[i]); } return 0; } void insert_sort(int k[],int n) { int i, j, temp; for (i = 1; i < n; i++) { if (k[i] < k[i - 1]) { temp = k[i]; for (j = i - 1; k[j] > temp && j>= 0; j--) { k[j + 1] = k[j]; } k[j + 1] = temp; } } }
C
#include <stdlib.h> #include <stdio.h> #include <limits.h> #include "graph.h" #include "dijkstra.h" #include "heap.h" void print_array_nodes(const array* Queue) { for(int i = 0; i < Queue -> size; i++) { node * current = Queue -> nodes[i]; printf(" %d ", current -> id); } } void init_ssp(graph * g){ for(int i = 0; i < (g->nodes_len); i++){ node * current = (g -> nodes[i]); if(current != NULL){ current->dist = 1000; current->prev = 0; } } } void relax_array(node* u, node* v, edge * e){ int new_dist = u ->dist + e -> weight; int old_dist = v -> dist; if(new_dist < old_dist){ v -> dist = new_dist; v -> prev = u -> id; } } array* build_array(graph * g){ int size = g->nodes_len; node ** nodes_array = (node**)malloc(size * sizeof(node*)); // allocate memory to store the values for(int i = 0; i < size; i++){ nodes_array[i] = g->nodes[i]; } array *Q=(array *)malloc(sizeof(array)); Q -> nodes = nodes_array; Q -> size = size; Q -> original_size = size; return Q; } void remove_node_array(array* Queue, int min_index){ int size = (Queue) ->size; node * tmp = (Queue) -> nodes[min_index]; (Queue)->nodes[min_index] = (Queue)->nodes[size - 1]; (Queue)->nodes[size - 1] = tmp; (Queue)->size --; } int is_empty_array(const array* Queue){ if(Queue -> size > 0){ return 0; } else { return 1; } } node * extract_minimum_array(array * Queue){ // I must find the minimum and then remove it //print_array_nodes(*Queue); //print_array_nodes(Queue); long int min = (Queue -> nodes[0])->dist; int min_index = 0; for(int i = 1; i < Queue->size; i++){ node * tmp = Queue -> nodes[i]; if(tmp ->dist < min){ min_index = i; min = tmp ->dist; } } node * return_node = Queue->nodes[min_index]; remove_node_array(Queue, min_index); return return_node; } void dijkstra(graph *g, int a, int b){ init_ssp(g); // WE initialize all the needed values int a_i = a ; int b_i = b ; node * source = g -> nodes[a_i]; // we get the source source -> dist = 0; // and set its distance to zero array * Q = build_array(g); while(!is_empty_array(Q)){ node * u = extract_minimum_array(Q); if(u -> id == b_i) break; int n = u -> edges_len; for(int j = 0; j < n; j++){ edge * e = u -> edges[j]; int node_id = e -> node; node * v = g->nodes[node_id]; relax_array(u, v, e); } } print_path(g, b); } void dijkstra_heap(graph * g, int a, int b) { init_ssp(g); // WE initialize all the needed values int a_i = a; int b_i = b; node * source = g -> nodes[a_i]; // we get the source source -> dist = 0; // and set its distance to zero heap * Queue = BuildHeap(g); while(Queue -> size > 0) { node * u = extract_minimum_heap(Queue); if(u -> id == b_i) break; int n = u -> edges_len; for(int j = 0; j < n; j++) { edge * e = u -> edges[j]; int node_id = e -> node; node * v = g -> nodes[node_id]; int new_dist = u ->dist + e -> weight; int old_dist = v -> dist; if(new_dist < old_dist){ v -> dist = new_dist; v -> prev = u -> id; //hswap(Queue, 0, node_id); Heapify(Queue, 0); /** printf("-------------\n"); for(int i = 0; i < Queue -> size; i++) printf("%d has dist %d\n", i, Queue -> nodes[i]->dist); */ } } } //freeHeap(Queue); //freeArray(Queue); print_path(g, b); } /** void dijkstra_heap(graph * g, int a, int b) { init_ssp(g); // WE initialize all the needed values int a_i = a; int b_i = b; node * source = g -> nodes[a_i]; // we get the source source -> dist = 0; // and set its distance to zero heap * Queue = BuildHeap(g); printf("Expected 0 got %d\n ", Queue -> nodes[0] -> dist); while(Queue -> size > 0) { node * u = Queue -> nodes[0]; hswap(Queue, 0, Queue -> size - 1); Queue -> size --; //node * u = extract_minimum_heap(Queue); if(u -> id == b_i) break; int n = u -> edges_len; for(int j = 0; j < n; j++) { edge * e = u -> edges[j]; int node_id = e -> node; node * v = g -> nodes[node_id]; int new_dist = u ->dist + e -> weight; int old_dist = v -> dist; if(new_dist < old_dist){ v -> dist = new_dist; v -> prev = u -> id; Heapify(Queue, 0); /** printf("-------------\n"); for(int i = 0; i < Queue -> size; i++) printf("%d has dist %d\n", i, Queue -> nodes[i]->dist); } } } //freeHeap(Queue); //freeArray(Queue); print_path(g, b); } */ void print_path (graph *g, int i) { int n, j; node *v, *u; i = i ; v = g->nodes[i]; if (v->dist == 1000) { printf("no path\n"); return; } n = 1; u = v; while(u -> dist > 0) { n++; u = g -> nodes[u -> prev]; } int *path = malloc(n * sizeof(int)); path[n - 1] = i; j = 0; u = v; while(u -> dist > 0) { path[n - j - 2] = u -> prev; j++; u = g -> nodes[u -> prev]; } printf("%d ", v->dist); printf(" %d ", path[0]); for( int i = 1; i < n; i++) printf(" -> %d ", path[i]); printf("\n"); } void freeArray(array* Queue) { for(int i = 0; i < Queue -> original_size; i++) freeNode(Queue -> nodes[i]); free(Queue); }
C
#include<stdio.h> #define size 20 int main() { int arr[size][size],i,j,n,count1=0,count2=0,k=0; scanf("%d",&n); for(i=0;i<n;i++) for(j=0;j<n;j++) scanf("%d",&arr[i][j]); for(i=0;i<n;i++) { for(j=0;j<n;j++) printf("%3d",arr[i][j]); printf("\n"); } if(n==2) { if(arr[0][1]==0) printf("lower triangular matrix\n"); else if(arr[1][0]==0) printf("upper triangular matrix\n"); else printf("not a triangular matrix\n"); } else { for(i=0;i<n;i++) {k=k+i; for(j=0;j<n;j++) { if(i>j) { if(arr[i][j]==0) count1++; } if(j>i) { if(arr[i][j]==0) count2++; } } } //printf("%d\n",k); if(count1==k && count2==(n-1)*2 ) printf("both upper and lower triangular matix\n"); else if((count1==k)) printf("upper triangular matrix\n"); else if(count2==k) printf("lower triangular matrix\n"); else printf("not a triangular matrix\n"); } }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> int main() { char *a = malloc(6*sizeof(char)); printf("%p\n",a); strncpy(a,"hello",5); printf("%p\n",a); a[5] = '\0'; puts(a); return 0; }
C
#include <stdio.h> #ifdef __STDC_NO_ATOMICS__ #define autch 1 #else #define autch 0 #include <stdatomic.h> #endif #ifdef __STDC_NO_THREADS__ #define threadsautch 1 #else #define threadsautch 0 #include <threads.h> #endif int main () { printf("hello atomic world\n%d\n%d\n", autch, threadsautch); return 0; }
C
#include <stdio.h>; #include <math.h>; void main() { double step = 0.2; int interval[2] = { 2, 4 }; double x; double y; for (double i = interval[0]; i <= interval[1] + 0.1; i += step) { x = i; if (x <= 3) { y = log10(pow(x, 3)); } else if (3 < x < 3.5) { y = 1 / fabs(sin(x)); } else if (x <= 4) { y = 1/cos(1 / x); } else { y = 0; }; printf("x= %f; y= %f \n", x, y); } }
C
/* LIST1301.c: Day 13 Listing 13.1 */ /* Demonstrates the break statement. */ #include <stdio.h> char s[] = "This is a test string. It contains two sentences."; int main(void) { int count; printf("\nOriginal string: %s", s); for (count = 0; s[count] != '\0'; count++) if (s[count] == '.') { s[count+1] = '\0'; break; /* break ends a loop */ } printf("\nModified string: %s", s); return 0; }
C
#include<stdio.h> #define LENGTH 500 int main() { char text[LENGTH]; printf("Please choose the operation you want:\nEnter E to encrypt\nEnter D to decrypt\n"); char choice=getchar(); if(choice=='E') { printf("Please enter the text needs to be encrypted:\n"); scanf("%s",&text); for(int i=0;i<strlen(text);++i) { text[i]+=1; } printf("%s",text); } if(choice=='D') { printf("Please enter the text needs to be decrypted:\n"); scanf("%s",&text); for(int i=0;i<strlen(text);++i) { text[i]-=1; } printf("%s",text); } return 0; }
C
#include "define.h" #include <malloc.h> #include <stdio.h> #include <stdlib.h> /* |------------------------------------------------------------------------------------------------- |队列的链式存储结构 |------------------------------------------------------------------------------------------------- |入队列的时间复杂度为O(1) |出队列的时间复杂度为O(1) |------------------------------------------------------------------------------------------------- */ /** * 申请新的节点 */ ListNode static *applyNewNode() { PListNode new = (ListNode *)malloc(sizeof(ListNode)); if(new == NULL){ printf("Apply a new node failed\n"); exit(-1); } new->next = NULL; return new; } /** * 初始化 */ int static initial(PLinkQueue p) { //第一个节点 PListNode new = applyNewNode(); //head指向第一个节点 p->head = new; p->head->next = NULL; p->rear = p->head; p->length = 0; } /** * 判断空 */ int static checkEmpty(PLinkQueue p) { if(p->length == 0) return 1; else return 0; } /** * 进队列 */ int static enQueue(PLinkQueue p) { int value; printf("Input the enqueue value\n"); scanf("%d", &value); //如果现在队列为空,说明插入的是第一个节点 if(checkEmpty(p)){ p->head->data = value; } else{ PListNode new = applyNewNode(); new->data = value; p->rear->next = new; p->rear = new; } p->length++; } /** * 出队列 */ int static deQueue(PLinkQueue p) { int value; PListNode head; if(checkEmpty(p)){ printf("The queue is empty\n"); exit(0); } head = p->head; value = head->data; p->head = head->next; p->length--; free(head); printf("The dequeue value is %d\n", value); } /** * 遍历 */ int static travesal(LinkQueue queue) { PListNode index = queue.head; if(checkEmpty(&queue)){ printf("Empty queue\n"); exit(0); } printf("----------------traversal-------------------\n"); for(int i = 0; i < queue.length; i++){ printf("%d\n", index->data); index = index->next; } printf("----------------traversal-------------------\n"); } int linkQueue() { LinkQueue p; initial(&p); enQueue(&p); enQueue(&p); enQueue(&p); enQueue(&p); deQueue(&p); travesal(p); }
C
#include<stdio.h> #include<ctype.h> int contaPal (char s[]){ int conta = 0; if(s[0] != '\0') conta++; int i = 0; while (isspace(s[i]) != 0){ i++; } while (s[i] != '\0') { if (isspace(s[i]) != 0 && isspace(s[i-1]) == 0) conta++; i++; } if (isspace (s[i-1]) != 0){ conta--; } return conta; } int main(){ char s[1000]; int n = 1; while (n) { printf("String para analisar: \n"); scanf("\n%[^\n]", s); //isto lê do teclado até encontrar o caracter depois do ^, neste caso, o enter. getchar(); printf("%d\n\n", contaPal(s)); } }
C
// ce programme est pour faire un plot en html5 de la fonction du quantificateur /* gcc -Wall -o plot.exe plot_wsub2.c */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> /* fonction de quantification generique */ double quantif( double x, double q ) { double qx; int ix; if ( q == 0.0 ) return( x ); if ( x >= 0.0 ) { qx = ( x / q ) + 0.5; ix = (int) qx; qx = q * ix; return ( qx ); } else { qx = ( -x / q ) + 0.5; ix = (int) qx; qx = q * ix; return ( -qx ); } } int main( int argc, char ** argv ) { FILE * fil; double x; fil = fopen("plot_a42.js", "w" ); if ( fil == NULL ) return 1; fprintf( fil, "var plot1 = [\n"); for ( x = -1.0; x <= 1.0; x += 0.002 ) { fprintf( fil, "[%.3f,%.3f],", x, quantif( x, 0.02 ) ); } fprintf( fil, "];\nvar plot2 = [\n"); for ( x = -1.0; x <= 1.0; x += 0.002 ) { fprintf( fil, "[%.3f,%.3f],", x, quantif( x, 0.1 ) ); } fprintf( fil, "];\nvar plot3 = [\n"); for ( x = -1.0; x <= 1.0; x += 0.002 ) { fprintf( fil, "[%.3f,%.3f],", x, quantif( x, 0.4 ) ); } fprintf( fil, "];\n"); fclose( fil ); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_eight_queens_puzzle.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: awoimbee <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/07 18:13:38 by awoimbee #+# #+# */ /* Updated: 2018/07/07 18:13:45 by awoimbee ### ########.fr */ /* */ /* ************************************************************************** */ int respect_rules(int nw_q_row); int re_queen_puzzle(int queen_and_row_nb); int ft_putchar(char c); /* ** g_q_col[row] = the column of the queen at this row */ int g_q_col[8]; /* ** here is our main, recursive function */ int re_queen_puzzle(int queen_and_row_nb) { static int result = 0; int row; if (queen_and_row_nb == 8) ++result; else { row = -1; while (++row < 8) { g_q_col[queen_and_row_nb] = row; if (respect_rules(queen_and_row_nb)) re_queen_puzzle(queen_and_row_nb + 1); } } return (result); } /* ** Here we test if new queen is in the same column or diagonal as old queen */ int respect_rules(int nw_q_row) { int old_q_row; old_q_row = 0; while (old_q_row < nw_q_row) { if (g_q_col[old_q_row] == g_q_col[nw_q_row]) return (0); if ((g_q_col[old_q_row] - g_q_col[nw_q_row]) == (nw_q_row - old_q_row)) return (0); if ((g_q_col[nw_q_row] - g_q_col[old_q_row]) == (nw_q_row - old_q_row)) return (0); ++old_q_row; } return (1); } int ft_eight_queens_puzzle(void) { return (re_queen_puzzle(0)); }
C
/* Author: Golia Simone Program: An example of sorting array using Quicksort Algorithm */ #include <stdio.h> #include <stdlib.h> #define SWAP(type, a, b) {type tmp = a; a=b; b=tmp;} int* scanArray(int* dim); void printArray(int* array, int dim); void quickSort(int* array, int start, int end); int partition(int* array, int start, int end); int main(){ //Read an array of int int dimArray; int* array = scanArray(&dimArray); //Sorting the array quickSort(array, 0, dimArray-1); //Print Array printArray(array, dimArray); return 0; } /* Read from terminal, dimension of array and all elements of array. */ int* scanArray(int* dim){ int i; //Leggo il numero di elementi scanf("%d", dim); //Creo l'array di dimensione dim e lo popolo int* array = (int*) malloc(sizeof(int)*(*dim)); for(i=0; i<(*dim); i++){ scanf("%d", &array[i]); } return array; } /* Print to terminal, all element of array, one for line. */ void printArray(int* array, int dim){ int i=0; for(int i=0; i<dim; i++) printf("%d\n", array[i]); } /* Master Function of Quicksort Algorithm. Select a pivot and divide array in two parts recursively. */ void quickSort(int* array, int start, int end){ if(end>start){ int pivot = partition(array, start, end); quickSort(array, start, pivot-1); quickSort(array, pivot+1, end); } } /* Subfuction of Quicksort Algorithm Select a pivo, ad moves the smaller element of pivot to the left and the larger to the right Example: 1 9 7 4 6 3 2 (5) ==> pivot:5 ==> 1 4 3 2 (5) 9 7 6 */ int partition(int* array, int start, int end){ int i=start-1, j=start, pivot = end; for( j; j<end; j++ ){ if( array[pivot]<array[j] ){ i++; SWAP(int, array[j], array[i]); } } SWAP(int, array[pivot], array[i+1]); return i+1; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* stack.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ztisnes <ztisnes@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/01/09 19:57:20 by ztisnes #+# #+# */ /* Updated: 2018/02/03 17:48:15 by ztisnes ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" /* ** Stacks are abstract data structures which helps in the order of elements with ** popping (removing) and pushing (inserting) elements Stacks are just arrays ** */ typedef struct s_stack { struct s_list *top; } t_stack; t_stack *init_stack(void) { t_stack *node; node = (t_stack *)malloc(sizeof(t_stack)); node->top = NULL; return (node); } void push_stack(t_stack *stack, void *content) { t_list *node; node = (t_list *)malloc(sizeof(t_list)); node->content = content; node->next = stack->top; stack->top = node; } void *pop_stack(t_stack *stack) { t_list *next; void *anything; if (stack->top == NULL) return (NULL); next = stack->top->next; anything = stack->top->content; free(stack->top); stack->top = next; return (anything); } void *peek_stack(t_stack *stack) { if (stack->top == NULL) return (NULL); return (stack->top->content); } int isEmpty_stack(t_stack *stack) { return (stack->top == NULL); }
C
#include "M083040024.h" void Init_Array(int a[] , ConstInt size) //Initialize an array { int i; for( i = 0 ; i < size ; i++ ) a[i] = -1; } void Generate_Sequence_write( int a[] ) //Generate a sequence of random write number { int i; for(i = 0 ; i < REFERENCE_SIZE ; i++) { if( rand() % 3 == 0) a[i] = 1; else a[i] = 0; } } void Generate_Sequence_Random( int a[] ) //Generate a sequence of random reference number { int i; for(i = 0 ; i < REFERENCE_SIZE ; i++) a[i] = RandomNum(); } void Generate_Sequence_Locality( int a[] ) //Generate a sequence of locality reference number, consists of many consecutive sequence { int length , start , i; int index = 0; while( index < 100000 ) { length = rand() % 26 + 25; start = rand() % (500-length+1) + 1; for( i = start ; i < start + length; i++ ) { a[ index ] = i ; index++; if( index >= 100000 ) break; } } } void Generate_Sequence_special( int a[] ) // My own sequence, most of them are small numbers(1~100), the rest are big number(101~500) { int i; for(i = 0 ; i < REFERENCE_SIZE ; i++) { if(rand() % 4 == 0) a[i] = RandomNum(); else a[i] = rand() % 100 + 1; } } void Print_Array( ConstInt a[] , ConstInt Size ) //Print values of the array a[] { int i; for( i = 0 ; i < Size ; i++ ) printf( "[%d]: %3d\n" , i+1 , a[i] ); } int Check_Hit( ConstInt reference_bit , ConstInt Memory_size ) //Check whether hit or not (page fault) { int i; for( i = 0 ; i < Memory_size ; i++ ) { if( DRAM[i] == reference_bit ) { ESC_hit = i; return 1; } } ESC_hit = -1; return 0; }
C
#include "biblio.h" boolean estUnPalindrome(char *chaine) { int i; int longueur; boolean idem=TRUE; longueur=strlen(chaine); for (i=0;i<longueur/2;i++) { if (chaine[i]!=chaine[(longueur-1)-i]) { idem=FALSE; } } return idem; }
C
#include <stdio.h> #include <string.h> // strNcat kulanınca belirtilen sayı kadar karakter dest'e kopyalanır. eğer belirtilen karakterler kopyalanırken NULL karakteri ile kariılaşılırsa null karakterinden sonraki // karakterler kopyalanmazlar. // strcat belirtilen stringden dest stringine null karakterini görünceye kadar null karakteri dahil olmak karakterleri üzere kopyalar. NULL karakteri belirtilen strigde yoksa // buluncaya kadar stringin dışına taşarak karakterleri kopyalar. //?strncat dest stringine ekleyeceği yeri bulmak için dest[0] dan başlayıp NULL karakterini buluncaya kadar devam ediyor. // Bu arama sırasında dest'in sınırları içerisinde NULL karakteri olmasa bile arama işlemine evam ediliyor. // yukarı paragrafın aynısı strcat içinde geçerldir. //strNcat kullanırken n sayısı dahilinde NULL karakteri olsa bile fazladan bir NULL karakteri sona eklenilir. int main( ) { int i; char name[5]; char word[9] = "abdullah"; printf( "len word: %d\n", strlen( word ) ); for( i = 0; i < 6; i++ ) name[i] = 'x'; printf( "name=|%s|\n", name ); name[0] = 'y'; name[1] = 'u'; name[2] = 's'; name[3] = 'u'; name[4] = 'f'; name[5] = 'x'; printf( "name=|%s|\n", name ); strcat( name, word); printf( "nnnname=|%s|\n", name ); //printf( "%c\n", name[10] ); }