language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
/** * greedy.c * * Soumya Mondal * [email protected] * * CS50 Pset 1 */ # include<stdio.h> # include<cs50.h> # include<math.h> int main(void) { // Ask user for a input and verify if input is positive printf("How much change is owed?\n"); float user_input = GetFloat(); while(user_input < 0) { printf("How much change is owed?\n"); user_input = GetFloat(); } // Variables for storing calculation results int tfiveps, tenps, fiveps, paisa, tempvalues; // int total_coins = 0; // Conversion from floating point to int as cents float x = round(user_input * 100); paisa = (int) x; // counting Quarters tfiveps = paisa / 25; tempvalues = paisa % 25; // Counting Dimes & Nickles if (tfiveps == 0) { tenps = paisa / 10; tempvalues = paisa % 10; fiveps = tempvalues / 5; tempvalues = tempvalues % 5; }else if (tfiveps > 0) { tenps = tempvalues / 10; tempvalues = tempvalues % 10; fiveps = tempvalues / 5; tempvalues = tempvalues % 5; } // coins counting printf("%d\n", tfiveps + tenps + fiveps + tempvalues); }
C
#include "insertion_sort.h" void insertion_sort(int list[], int n) { int num = 0x00; int i, j; for (i = 1; i < n; i++){ num = list[i]; for (j = i-1; j >= 0 && num < list[j]; j--){ list[j+1] = list[j]; } list[j+1] = num; } return; } int main(void) { int list[5] = {9, 5, 3, 2, 8}; int size = sizeof(list)/sizeof(int), idx = 0x00; insertion_sort(list, size); for (; idx < size; idx++){ printf("%d ", list[idx]); } return 0; }
C
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * Se incluyen algunas rutinas modificadas de Numerical Recipes in C, * entre las que se encuentran reporte de errores, declaracion y * y liberacion de arreglos y matrices * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * #include <stdlib.h> #include <stdio.h> #include <math.h> */ /* Librerias a incluir */ #include "conv.h" /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Reportar el mensaje de error a stderr, y luego salir * del programa con la seal de exit(1) * * * * * * * * * * * * * * * * * * * * * * * * * * */ void nrerror(char error_text[]) { fprintf(stderr, "%s.\n", error_text); fprintf(stderr, "...saliendo del sistema...\n"); exit(1); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Asignar un arreglo con indice de n1 a nh inclusive. * * La matriz y el vector original del Numerical Recipes in C * no inicializa los elementos a cero. Esto se logra mediante * las siguientes funciones. * * * * * * * * * * * * * * * * * * * * * * * * * * */ double *AllocVector(short nl, short nh) { double *v; short i; v = (double *) malloc((unsigned) (nh - nl + 1) * sizeof(double)); if (!v) nrerror("La asignacion en el vector() fallo"); for (i = nl; i <= nh; i++) v[i] = 0.0; /* init. */ return v - nl; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Asignar una matriz con indice de columna de nrl a nrh * inclusive, e indice de columan de ncl a nch * inclusive. * * * * * * * * * * * * * * * * * * * * * * * * * * */ double **AllocMatrix(short nrl, short nrh, short ncl, short nch) { short i, j; double **m; //Asignar el tamao de la memoria double* m = (double **) malloc((unsigned) (nrh - nrl + 1) * sizeof(double *)); if (!m) nrerror("Fallo en asignacion de memoria 1 en la matriz()"); m -= nrl; for (i = nrl; i <= nrh; i++) { //Asignar el tamao de la memoria double m[i] = (double *) malloc((unsigned) (nch - ncl + 1) * sizeof(double)); if (!m[i]) nrerror("Fallo en asignacion de memoria 2 en la matriz()"); m[i] -= ncl; } //Iniciar a cero los elementos de la matriz for (i = nrl; i <= nrh; i++) for (j = ncl; j <= nch; j++) m[i][j] = 0.0; return m; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Liberar la memoria del vector * * * * * * * * * * * * * * * * * * * * * * * * * * */ void FreeVector(double *v, short nl, short nh) { free((char *) (v + nl)); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Liberar la memoria de la matriz * * * * * * * * * * * * * * * * * * * * * * * * * * */ void FreeMatrix(double **m, short nrl, short nrh, short ncl, short nch) { short i; for (i = nrh; i >= nrl; i--) free((char *) (m[i] + ncl)); free((char *) (m + nrl)); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Metodo numerico de Integracion trapezoidal * * * * * * * * * * * * * * * * * * * * * * * * * * */ //Se define FUNC(x) que sera utilizado a lo largo de la funcion #define FUNC(x) ((*func)(x)) float trapzd(float (*func) (float), float a, float b, int n) { float x, tnm, sum, del; static float s; static int it; int j; if (n == 1) { it = 1; s = 0.5 * (b - a) * (FUNC(a) + FUNC(b)); } else { tnm = it; del = (b - a) / tnm; x = a + 0.5 * del; for (sum = 0.0, j = 1; j <= it; j++, x += del) sum += FUNC(x); it *= 2; s = 0.5 * (s + (b - a) * sum / tnm); } return (s); } //Se quita la defincion de FUNC, que ya no sera utilizado #undef FUNC /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Permite al usuario cambiar EPS * Modificado para hacer al menos tres trapzd() en el caso * de los datos es ruidoso. 9/26/1994 Lihong Wang. * * * * * * * * * * * * * * * * * * * * * * * * * * */ #define JMAX 30 float qtrap(float (*func) (float), float a, float b, float EPS) { int j; float s, s_old = 0; for (j = 1; j <= JMAX; j++) { s = trapzd(func, a, b, j); if (j <= 3 || fabs(s - s_old) > EPS * fabs(s_old)) s_old = s; else break; } return (s); } #undef JMAX /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Funcion modificada de Bessel exp(-x) I0(x), para x >=0. * Fue modificado de la original bessi0(). Instead of * En ligar de I0(x) en su, regresa I0(x) exp(-x). * * * * * * * * * * * * * * * * * * * * * * * * * * */ double BessI0(double x) { double ax, ans; double y; if ((ax = fabs(x)) < 3.75) { y = x / 3.75; y *= y; ans = exp(-ax) * (1.0 + y * (3.5156229 + y * (3.0899424 + y * (1.2067492 + y * (0.2659732 + y * (0.360768e-1 + y * 0.45813e-2)))))); } else { y = 3.75 / ax; ans = (1 / sqrt(ax)) * (0.39894228 + y * (0.1328592e-1 + y * (0.225319e-2 + y * (-0.157565e-2 + y * (0.916281e-2 + y * (-0.2057706e-1 + y * (0.2635537e-1 + y * (-0.1647633e-1 + y * 0.392377e-2)))))))); } return ans; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Obtener una entrada de tipo short * * * * * * * * * * * * * * * * * * * * * * * * * * */ short GetShort(short Lo, short Hi) { char in_str[STRLEN]; short x; //Obtener la entrada gets(in_str); sscanf(in_str, "%hd", &x); //Verificar que este dentro de los intervalos permitidos while (x < Lo || x > Hi) { printf("...Parametro erroneo. Ingresar de nuevo: "); gets(in_str); sscanf(in_str, "%hd", &x); } return (x); } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * Obtener una entrada de tipo float * * * * * * * * * * * * * * * * * * * * * * * * * * */ float GetFloat(float Lo, float Hi) { char in_str[STRLEN]; float x; //Obtener la entrada gets(in_str); sscanf(in_str, "%f", &x); //Verificar que este dentro de los intervalos permitidos while (x < Lo || x > Hi) { printf("...Parametro erroneo. Ingresar de nuevo: "); gets(in_str); sscanf(in_str, "%f", &x); } return (x); }
C
#include <unistd.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #define MAXSIZE 1024 int main() { ssize_t size; char buffer[MAXSIZE]; while((size = read(STDIN_FILENO,buffer,MAXSIZE)) > 0){ if(write(STDOUT_FILENO,buffer,size) != size){ perror("write"); exit(1); } } if(size < 0){ perror("read"); } exit(0); }
C
/* * @Author: Weijie Li * @Date: 2018-06-21 22:50:06 * @Last Modified by: Weijie Li * @Last Modified time: 2018-06-21 22:50:11 */ #include <math/matrix_utils.h> #include <assert.h> #define VERBOSE 0 #define DUMP_MAT(x) if (VERBOSE) {DumpMatGf2(x);} int combined_affine_init(CombinedAffine *cm, int sub_matrix_size, int sub_matrix_number) { assert(sub_matrix_number >= 2); cm->number = sub_matrix_number; cm->sub_affine = malloc(sub_matrix_number * sizeof(AffineTransform)); cm->sub_affine_inv = malloc(sub_matrix_number * sizeof(AffineTransform)); cm->combined_affine = malloc(sizeof(AffineTransform)); cm->combined_affine_inv = malloc(sizeof(AffineTransform)); AffineTransform * aff_ptr = cm->sub_affine; AffineTransform * aff_ptr_inv = cm->sub_affine_inv; MatGf2 T,S; T = S = NULL; int counter = sub_matrix_number; while(counter--) { GenRandomAffineTransform(aff_ptr, aff_ptr_inv, sub_matrix_size); // GenIndAffineTransform(aff_ptr, aff_ptr_inv, sub_matrix_size); DUMP_MAT(aff_ptr->linear_map); DUMP_MAT(aff_ptr_inv->linear_map); aff_ptr++; aff_ptr_inv++; } counter = sub_matrix_number; aff_ptr = cm->sub_affine + sub_matrix_number - 1; aff_ptr_inv = cm->sub_affine_inv + sub_matrix_number - 1; cm->combined_affine->linear_map = GenMatGf2Diag((aff_ptr)->linear_map, (aff_ptr-1)->linear_map); aff_ptr -= 2; cm->combined_affine_inv->linear_map = GenMatGf2Diag((aff_ptr_inv)->linear_map, (aff_ptr_inv-1)->linear_map); aff_ptr_inv -= 2; counter--; while(--counter) { T = GenMatGf2Diag(cm->combined_affine->linear_map, (aff_ptr--)->linear_map); S = cm->combined_affine->linear_map; cm->combined_affine->linear_map = T; MatGf2Free(S); S = T = NULL; T = GenMatGf2Diag(cm->combined_affine_inv->linear_map, (aff_ptr_inv--)->linear_map); S = cm->combined_affine_inv->linear_map; cm->combined_affine_inv->linear_map = T; MatGf2Free(S); S = T = NULL; } DUMP_MAT(cm->combined_affine->linear_map); DUMP_MAT(cm->combined_affine_inv->linear_map); int total_dim = sub_matrix_size*sub_matrix_number; cm->combined_affine->vector_translation = GenMatGf2(total_dim, 1); cm->combined_affine_inv->vector_translation = GenMatGf2(total_dim, 1); aff_ptr = cm->sub_affine + sub_matrix_number - 1;; aff_ptr_inv = cm->sub_affine_inv + sub_matrix_number - 1;; int j = 0; while (j<total_dim) { int i; for (i=0; i<sub_matrix_size; i++,j++) { MatGf2Set(cm->combined_affine->vector_translation, j, 0, MatGf2Get((aff_ptr)->vector_translation, i, 0)); MatGf2Set(cm->combined_affine_inv->vector_translation, j, 0, MatGf2Get((aff_ptr_inv)->vector_translation, i, 0)); } aff_ptr--; aff_ptr_inv--; } DUMP_MAT(cm->combined_affine->vector_translation); DUMP_MAT(cm->combined_affine_inv->vector_translation); T = GenMatGf2Mul( cm->combined_affine_inv->linear_map, cm->combined_affine->linear_map ); DUMP_MAT(T); MatGf2Free(T); T = NULL; T = GenMatGf2Mul( cm->combined_affine_inv->linear_map, cm->combined_affine->vector_translation ); S = GenMatGf2Add(T, cm->combined_affine_inv->vector_translation ); DUMP_MAT(S); MatGf2Free(T); MatGf2Free(S); S = T = NULL; return 0; } int ind_combined_affine_init(CombinedAffine *cm, int sub_matrix_size, int sub_matrix_number) { assert(sub_matrix_number >= 2); cm->number = sub_matrix_number; cm->sub_affine = malloc(sub_matrix_number * sizeof(AffineTransform)); cm->sub_affine_inv = malloc(sub_matrix_number * sizeof(AffineTransform)); cm->combined_affine = malloc(sizeof(AffineTransform)); cm->combined_affine_inv = malloc(sizeof(AffineTransform)); AffineTransform * aff_ptr = cm->sub_affine; AffineTransform * aff_ptr_inv = cm->sub_affine_inv; MatGf2 T,S; T = S = NULL; int counter = sub_matrix_number; while(counter--) { // GenRandomAffineTransform(aff_ptr, aff_ptr_inv, sub_matrix_size); GenIndAffineTransform(aff_ptr, aff_ptr_inv, sub_matrix_size); DUMP_MAT(aff_ptr->linear_map); DUMP_MAT(aff_ptr_inv->linear_map); aff_ptr++; aff_ptr_inv++; } counter = sub_matrix_number; aff_ptr = cm->sub_affine; aff_ptr_inv = cm->sub_affine_inv; cm->combined_affine->linear_map = GenMatGf2Diag((aff_ptr)->linear_map, (aff_ptr+1)->linear_map); aff_ptr += 2; cm->combined_affine_inv->linear_map = GenMatGf2Diag((aff_ptr_inv)->linear_map, (aff_ptr_inv+1)->linear_map); aff_ptr_inv += 2; counter--; while(--counter) { T = GenMatGf2Diag(cm->combined_affine->linear_map, (aff_ptr++)->linear_map); S = cm->combined_affine->linear_map; cm->combined_affine->linear_map = T; MatGf2Free(S); S = T = NULL; T = GenMatGf2Diag(cm->combined_affine_inv->linear_map, (aff_ptr_inv++)->linear_map); S = cm->combined_affine_inv->linear_map; cm->combined_affine_inv->linear_map = T; MatGf2Free(S); S = T = NULL; } DUMP_MAT(cm->combined_affine->linear_map); DUMP_MAT(cm->combined_affine_inv->linear_map); int total_dim = sub_matrix_size*sub_matrix_number; cm->combined_affine->vector_translation = GenMatGf2(total_dim, 1); cm->combined_affine_inv->vector_translation = GenMatGf2(total_dim, 1); aff_ptr = cm->sub_affine; aff_ptr_inv = cm->sub_affine_inv; int j = 0; while (j<total_dim) { int i; for (i=0; i<sub_matrix_size; i++,j++) { MatGf2Set(cm->combined_affine->vector_translation, j, 0, MatGf2Get((aff_ptr)->vector_translation, i, 0)); MatGf2Set(cm->combined_affine_inv->vector_translation, j, 0, MatGf2Get((aff_ptr_inv)->vector_translation, i, 0)); } aff_ptr++; aff_ptr_inv++; } DUMP_MAT(cm->combined_affine->vector_translation); DUMP_MAT(cm->combined_affine_inv->vector_translation); T = GenMatGf2Mul( cm->combined_affine_inv->linear_map, cm->combined_affine->linear_map ); DUMP_MAT(T); MatGf2Free(T); T = NULL; T = GenMatGf2Mul( cm->combined_affine_inv->linear_map, cm->combined_affine->vector_translation ); S = GenMatGf2Add(T, cm->combined_affine_inv->vector_translation ); DUMP_MAT(S); MatGf2Free(T); MatGf2Free(S); S = T = NULL; return 0; } int combined_affine_free(CombinedAffine *cm) { // TODO: if (cm==NULL) return 0; int counter = cm->number; AffineTransform * aff_ptr = cm->sub_affine; AffineTransform * aff_ptr_inv = cm->sub_affine_inv; for (int i=0; i<counter; i++) { AffineTransformFree(aff_ptr++); AffineTransformFree(aff_ptr_inv++); } AffineTransformFree(cm->combined_affine); AffineTransformFree(cm->combined_affine_inv); free(cm->sub_affine); free(cm->sub_affine_inv); free(cm->combined_affine); free(cm->combined_affine_inv); return 0; }
C
/* Sudoku Solution Validator */ /* SHIVAM SINGH */ #include<pthread.h> #include<stdlib.h> #include<stdio.h> /*Example Of a Valid Sudoku Given in Book*/ int sud[9][9]={ {6,2,4,5,3,9,1,8,7}, {5,1,9,7,2,8,6,3,4}, {8,3,7,6,1,4,2,9,5}, {1,4,3,8,6,5,7,2,9}, {9,5,8,2,4,7,3,6,1}, {7,6,2,3,9,1,4,5,8}, {3,7,1,9,5,6,8,4,2}, {4,9,6,1,8,2,5,7,3}, {2,8,5,4,7,3,9,1,6} }; struct data { int row; int col; }; /*Threads for Checking row and column*/ void *row_col(void *d) { int n,m,h=0; m=(int)d; int k,i,j; for(i=0;i<9;i++){ k=1; while(k<10){ for(j=0;j<9;j++){ if(m==0 && sud[i][j]==k){ h++; goto aam; } else if(m==1 && sud[j][i]==k){ h++; goto aam; } } aam: k++; } } if(h==81) { n=1; } else { n=-1; } pthread_exit((void*)n); } /*Threads for Checking each square*/ void *sq_check(void *mn) { struct data *my_data=(struct data *)mn; int i=(*my_data).row; int j=(*my_data).col; int n,m,p; n=i+3; m=j+3; int k,h=0; for(k=1;k<10;k++){ for(i=0;i<n;i++){ for(j=0;j<m;j++){ if(sud[i][j]==k){ h++; i=n;j=m; } } } } if(h==9){ p=1; } else{ p=-1; } pthread_exit((void*)p); } int main() { struct data *p; p=(struct data*)malloc(sizeof(struct data)); pthread_t thread[11]; int i,a; void *b; int t,l,k; for(i=0;i<2;i++) { t=i; /* Creation of Threads for Checking row and column */ a=pthread_create(&thread[i],NULL,row_col,(void*)t); if(a) { printf("error"); } } /* Creation of Threads for Checking 9 squares */ for(l=0;l<=6;l=l+3){ for(k=0;k<=6;k=k+3){ (*p).row=l; (*p).col=k; a=pthread_create(&thread[i++],NULL,sq_check,(void*)p); if(a){ printf("error"); } } } int s=0; for(i=0;i<11;i++){ pthread_join(thread[i],&b); s=s+(int)b; } if(s==11){ printf("THE GIVEN SUDOKU IS VALID\n"); } else{ printf("THE GIVEN SUDOKU IS INVALID\n"); } pthread_exit(NULL); }
C
/* * By Spacebody * * * Implement the queue in circle by array * */ #include <stdio.h> #include <stdlib.h> #ifndef _QueueArray_h typedef struct QueueRecord *Queue; typedef int ElemType; #define MinQueueSize 5 int IsEmpty(Queue Q); //exam whether it is empty int IsFull(Queue Q); //exam whether it is full void MakeEmpty(Queue Q); //empty the queue Queue CreateQueue(int MinSize); //initialize the queue void EnQueue(ElemType X, Queue Q); //enqueue ElemType Front(Queue Q); //get the front element of the queue void Dequeue(Queue Q); //dequeue void Print(Queue Q); //print out the elements void Error(char s[]); //print out the error messages #endif /* QueueArray.h*/ struct QueueRecord { int Front; int Rear; int Size; int Capacity; ElemType *Array; }; //ues struct to implement the queue int main(void) { Queue Q; Q = CreateQueue(MinQueueSize); EnQueue(5, Q); EnQueue(6, Q); EnQueue(10, Q); EnQueue(25, Q); Print(Q); printf("%d\n",Front(Q)); Dequeue(Q); Dequeue(Q); Dequeue(Q); Dequeue(Q); Print(Q); return 0; } Queue CreateQueue(int MinSize) { Queue Q; Q = malloc(sizeof(struct QueueRecord)); Q->Array = (ElemType *)malloc( sizeof(ElemType) * MinSize ); Q->Capacity = MinSize; //assign the value to limit the queue MakeEmpty(Q); //empty the queue return Q; } void MakeEmpty(Queue Q) { Q->Size = 0; Q->Front = 0; Q->Rear = 0; } int IsEmpty(Queue Q) { return Q->Size == 0; } int IsFull(Queue Q) { return Q->Size == Q->Capacity; } void EnQueue(ElemType X, Queue Q) { if(IsFull(Q)) { Error("Full Queue!"); } else { Q->Size++; //increase the size of the queue if element is enqueued Q->Array[Q->Rear] = X; //assign the last value to the rear Q->Rear = (Q->Rear+1)% Q->Capacity; //change the location of the rear } } ElemType Front(Queue Q) { return Q->Array[Q->Front]; } void Dequeue(Queue Q) { if(IsEmpty(Q)) { Error("Empty Queue!"); } else { Q->Size--; //decrease the size if element is dequeued Q->Front = (Q->Front+1)%Q->Capacity; //withdraw the front } } void Error(char s[]) { printf("%s\n", s); } void Print(Queue Q) { if(IsEmpty(Q)) { Error("Empty Queue!"); } else { int i; for(i = 0; i< Q->Size; i++) { printf("%d\n", Q->Array[i]); } } }
C
/** * @file * @brief Install and uninstall distributions */ #pragma once #include "lickdir.h" #include "llist.h" #include "menu.h" #include "uniso.h" /** * @brief information about an installed distribution */ typedef struct installed_t { /// the distribution id char *id; /// the distribution human-friendly name char *name; } installed_t; /** * @brief returns a list of paths to conf files in a directory * @param path the directory to look in * @return a list of strings of absolute paths to conf files */ string_node_t *get_conf_files(const char *path); /** * @brief free the memory a installed_t is using * @param i the installed_t to free */ void free_installed(installed_t *i); /** * @brief returns a list of installed distributions * @param lick the LICK directory * @return a list of installed_t structures */ installed_node_t *list_installed(lickdir_t *lick); /** * @brief install a distribution * @param id * the id, without spaces or quotes. Note the user may have multiple * installations of the same distribution * @param name * the human-friendly name. Note the user may have multiple installations of * the same distribution * @param distro the Linux distribution the ISO is * @param iso the ISO file to extract from * @param lick the LICK directory * @param install_dir the directory to install to * @param menu the menu plugin * @return 1 on success, 0 on error */ int install(const char *id, const char *name, distro_t *distro, const char *iso, const char *install_dir, lickdir_t *lick, menu_t *menu); /** * @brief install a distribution * * see install for more information on parameters * * @param cb a function to call for extraction progress * @param cb_data extra data to call the callback with * @return 1 on success, 0 on error */ int install_cb(const char *id, const char *name, distro_t *distro, const char *iso, const char *install_dir, lickdir_t *lick, menu_t *menu, uniso_progress_cb cb, void *cb_data); /** * @brief uninstall a distribution * @param id the id * @param lick the LICK directory * @param menu the menu plugin * @return 1 on success, 0 on error */ int uninstall(const char *id, lickdir_t *lick, menu_t *menu);
C
#include<stdio.h> int main(){ int a = 2,b=2; if(&a != &b){ printf("Equal\n"); } return 0; }
C
#include <stdio.h> main() { printf("Content-Type: text/html\n\n"); printf("<H1>TITLE</H1>\n"); printf("Hello from C language\n"); }
C
#include<stdio.h> #include<limits.h> int main() { printf("Here are the ranges - \n"); printf("char- %d to %d\n",CHAR_MIN,CHAR_MAX); printf("short- %d to %d\n",SHRT_MIN,SHRT_MAX); printf("int- %d to %d\n",INT_MIN,INT_MAX); printf("long- %ld to %ld\n",LONG_MIN,LONG_MAX); printf("signed char- %d to %d\n",SCHAR_MIN,SCHAR_MAX); printf("unsigned char- %d to %d\n",0,UCHAR_MAX); printf("unsigned int- %d to %u\n",0,UINT_MAX); printf("unsigned long- %d to %lu\n",0,ULONG_MAX); return 0; }
C
#ifndef AVL_H #define AVL_H typedef struct avl_node_s avl_node_t; typedef struct avl_s avl_t; struct avl_node_s { int value; int height; // height of the subtree rooted at this node avl_node_t *link[2]; // pointers to left child and right child }; struct avl_s { avl_node_t *root; }; // core functions avl_t* avl_create(void); void avl_insert(avl_t *tree, int value); void avl_delete(avl_t *tree, int value); avl_node_t *avl_search(avl_t *tree, int value); void avl_destroy(avl_t *tree); // helper functions int avl_assert_valid(avl_t *tree); void avl_print(avl_t *tree); #endif // AVL_H
C
#include <stdio.h> #include <cs50.h> #include <string.h> #define _XOPEN_SOURCE #include <unistd.h> char *crypt(); // If the encrypted key equals the given hash, that key is the password (so terminate the program) void compare(char key[], char salt[], char hash[]); // If the encrypted key equals the given hash, that key is the password // Non-recursively loop first through all one-letter combinations, then all two-letter combos, and so forth until all five-letter combos void loopNonRecursive(int keyLength, string key, string options, string salt, string hash); // Recursively loop first through all one-letter combinations, then all two-letter combos, and so forth until all five-letter combos void loopRecursive(int keyLength, int keyIndex, string key, string options, string salt, string hash); int main(int argc, string argv[]) { // User may only input 2 command-line arguments if (argc != 2) { printf("Usage: ./crack hash\n"); return 1; } string hash = argv[1]; char salt[3] = {hash[0], hash[1], '\0'}; // salt is 2 characters + 1 for null byte //printf("salt = %s \n", salt); char options[52]; // options = {'A', 'B', ..., 'Z', 'a', 'b', ..., 'z'} for (int i = 0; i < 26; i++) { options[i] = 'A' + i; options[i+26] = 'a' + i; } char key[6] = {'\0','\0','\0','\0','\0','\0'}; // key is 5 characters + 1 for null byte /* Loop through all possible combinations, * first through all one-letter combinations (i=0), then through all two-letter passwords (i=1), * and so forth until looping finally through all five-letter passwords (i=4) */ for (int keyLength = 0; keyLength < 5; keyLength++) { loopNonRecursive(keyLength, key, options, salt, hash); // can be done recursively or non-recursively //loopRecursive(keyLength, 0, key, options, salt, hash); } return 0; } // If the encrypted key equals the given hash, that key is the password (so terminate the program) void compare(char key[], char salt[], char hash[]) { printf("key = %s \n", key); string encryptedPassword = crypt(key, salt); if (strcmp(encryptedPassword, hash) == 0) { printf("The password is: %s \n", key); exit(0); // if the key is found, terminate the program with exit code 0 } } // Non-recursively loop first through all one-letter combinations, then all two-letter combos, and so forth until all five-letter combos void loopNonRecursive(int keyLength, string key, string options, string salt, string hash) { for (int o0 = 0; o0 < 52; o0++) // 52 possible options in {'A', 'B', ..., 'Z', 'a', 'b', ...,'z'} { key[0] = options[o0]; if (keyLength < 1) // if in the one-letter loop, compare each and every ONE-LETTER combo { compare(key, salt, hash); } else // else allow for all two-letter combos { for (int o1 = 0; o1 < 52; o1++) { key[1] = options[o1]; if (keyLength < 2) // if in the two-letter loop, compare each and every TWO-LETTER combo { compare(key, salt, hash); } else // else allow for all three-letter combos { for (int o2 = 0; o2 < 52; o2++) { key[2] = options[o2]; if (keyLength < 3) // THREE-LETTER combos { compare(key, salt, hash); } else { for (int o3 = 0; o3 < 52; o3++) { key[3] = options[o3]; if (keyLength < 4) // FOUR-LETTER combos { compare(key, salt, hash); } else // FIVE-LETTER combos { for (int o4 = 0; o4 < 52; o4++) { key[4] = options[o4]; compare(key, salt, hash); } } } } } } } } } } // Recursively loop first through all one-letter combinations, then all two-letter combos, and so forth until all five-letter combos void loopRecursive(int keyLength, int keyIndex, string key, string options, string salt, string hash) { for (int o = 0; o < 52; o++) // 52 possible options in {'A', 'B', ..., 'Z', 'a', 'b', ...,'z'} { key[keyIndex] = options[o]; if (keyLength < keyIndex+1) // if in the one-letter loop, compare each and every ONE-LETTER combo; if in the second-letter loop, compare each TWO-LETTER combo, etc. compare(key, salt, hash); else loopRecursive(keyLength, keyIndex+1, key, options, salt, hash); } }
C
/*Faa um programa que receba: Quantidade de homens. Quantidade de mulheres. Quantidade de crianas. Quantidade de horas de durao de um churrasco. Calcular e mostrar uma lista de compra de 10 itens para um churrasco, considerando a quantidade de pessoas e a durao do churrasco. A lista de compras dever constar: - Quantidade de cada item (se for o caso, como quantidade de po, latas de refrigerante, pacotes, etc.. - Quilos de cada item (se for o caso), como carne, linguia, etc... A lista de compra dever ter o total a ser comprado. */ #include <stdio.h> #include <locale.h> #include <math.h> int main (){ setlocale(LC_ALL, "Portuguese"); float quant_woman, quant_man, quant_kids, quant_teens, soda, beer, garlic_bread, coal, cheese, salt, quant_hours, rib, wave, sausage; //quant de pessoas e horas printf("Quantos homens vo ao churrasco? "); scanf("%f", &quant_man); printf("Quantas mulheres vo ao churrasco? "); scanf("%f", &quant_woman); printf("Quantas crianas vo ao churrasco? "); scanf("%f", &quant_kids); printf("Quantas horas ter seu churrasco? "); scanf("%f", &quant_hours); quant_hours = (quant_hours+1)/2; //formula para no dar valores absurdos //itens da lista rib = ((quant_woman * 100 + quant_man * 100 + quant_kids * 50)/1000) * quant_hours; wave = ((quant_woman * 100 + quant_man * 100 + quant_kids * 50)/1000) * quant_hours; sausage = ((quant_woman * 100 + quant_man * 100 + quant_kids * 50)/1000) * quant_hours; soda = ((quant_woman * 400 + quant_man * 400 + quant_kids * 400)/2000) * quant_hours; beer = ((quant_woman * 700 + quant_man * 900)/350) * quant_hours; garlic_bread = ((quant_woman * 90 + quant_man * 90 + quant_kids * 90)/350)* quant_hours; salt = ((rib + wave + sausage)/20); coal = ((rib + wave + sausage)/10); cheese = ((quant_woman * 71 + quant_man * 71 + quant_kids * 71)/497)* quant_hours; printf("\n---------- Lista de compras ----------"); printf("\n\n% .1f Kg de Costela;", rib); printf("\n\n% .1f Kg de Acem;", wave); printf("\n\n% .1f Kg de Linguia;", sausage); printf("\n\n% .0f garrafas de refrigerante de 2 litros;", ceil(soda)); printf("\n\n% .0f latinhas de cerveja de 350ml;", ceil(beer)); printf("\n\n% .0f Pacotes de po de alho;", garlic_bread); printf("\n\n% .0f Pacote de sal;", ceil(salt)); printf("\n\n% .0f Pacote de carvo;", ceil(coal)); printf("\n\n% .0f Pacotes de queijo coalho.", ceil(cheese)); return 0; }
C
#include <criterion/criterion.h> #include <errno.h> #include "client_conn.h" /* Assert that we can construct and destroy a client_conn */ Test(client_conn, test_new_destroy) { struct client_conn *conn = client_conn_new(NULL, 0); cr_assert(conn != NULL); client_conn_close(&conn); cr_assert(conn == NULL); } /* Assert that the client_conn_io callback closes the connection on a fatal read * error, * but simply returns in the case of EAGAIN. */ Test(client_conn, test_io_callback_error) { errno = 0; struct client_conn *conn = client_conn_new(NULL, 1); client_conn_close(&conn); }
C
#ifndef _LCD_H_ #define _LCD_H_ #include "GPIO.h" #include "SClk.h" /** * @def MASK_BIT_LCD Mascara para iniciar os bits de output do GPIO para interagir com o LCD */ #define MASK_BIT_LCD 0x3F00 /** * @def MASK_LOW Mascara para retirar a parte baixa de um caracter */ #define MASK_LOW 0x0F /** * @def MASK_HIGH Mascara para retirar a parte alta de um caracter */ #define MASK_HIGH 0xF0 /** * @fn void LCD_Init(void) * Inicia o LCD e os perifericos necessarios ao seu funcionamento */ void LCD_Init(void); /** * @fn void LCD_WriteChar(char ch) * @param ch Caracter a escrever no LCD * Escreve o Caracter no LCD e passar o cursor para a proxima posicao */ void LCD_WriteChar(char ch); /** * @fn void LCD_WriteString(char *str) * @param *str * Escreve uma string no LCD e passar o cursor para a proxima posicao */ void LCD_WriteString(char *str); /** * @fn void LCD_Goto(int x, int y) * @param x localiza o cursor na coluna 0-15 * @param y localiza o cursor na linha 0-1 * Coloca o cursor do LCD na coordenada (X,Y) passada como parametro */ void LCD_Goto(int x, int y); /** * @fn void LCD_Clear(void) * Limpa todos os careacteres que foram escritos no LCD */ void LCD_Clear(void); /** * @fn void LCD_WriteLine(char *str) * @param *str * Escreve uma string no LCD. Caso ocupe mais que 1 linha, escreve o restante na 2ª */ void LCD_WriteLine(char *str); #endif
C
#include "http_post.h" static const char *TAG = "server station"; QueueHandle_t task_Queue = NULL; // Look at website: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/protocols/esp_http_server.html /* Our URI handler function to be called during GET /uri request */ esp_err_t get_handler(httpd_req_t *req) { /* Send a simple response */ const char resp[] = "URI GET Response"; httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN); return ESP_OK; } /* To send Post see: https://stackoverflow.com/questions/16229852/post-sending-a-post-request-in-a-url-itself */ // send: curl -v -H "Content-Type: application/json" -X POST -d '255' http://192.168.0.11:80/uri/post /* Our URI handler function to be called during POST /uri request */ esp_err_t post_handler(httpd_req_t *req) { /* Destination buffer for content of HTTP POST request. * httpd_req_recv() accepts char* only, but content could * as well be any binary data (needs type casting). * In case of string data, null termination will be absent, and * content length would give length of string */ ESP_LOGI(TAG, "handling POST request"); char content[100]; /* Truncate if content length larger than the buffer */ size_t recv_size = MIN(req->content_len, sizeof(content)); ESP_LOGI(TAG, "received %d size", recv_size); // hardcoding it into 100, CHANGE LATER!! //recv_size = sizeof(content); ESP_LOGI(TAG, "getting post data"); ESP_LOGI(TAG, "%s", req->uri); int ret = httpd_req_recv(req, content, recv_size); ESP_LOGI(TAG, "getting return"); ESP_LOGI(TAG, "return value: %d", ret); if (ret <= 0) { /* 0 return value indicates connection closed */ /* Check if timeout occurred */ if (ret == HTTPD_SOCK_ERR_TIMEOUT) { /* In case of timeout one can choose to retry calling * httpd_req_recv(), but to keep it simple, here we * respond with an HTTP 408 (Request Timeout) error */ ESP_LOGI(TAG, "Time out occured, 408 send"); httpd_resp_send_408(req); } /* In case of error, returning ESP_FAIL will * ensure that the underlying socket is closed */ httpd_resp_send_404(req); return ESP_FAIL; } ESP_LOGI(TAG, "POST request in buffer"); ESP_LOGI(TAG, "POST request is: %s", content); float float_buf [2] = {0}; if (put_in_buffer(float_buf, content, recv_size) == 0){ ESP_LOGI(TAG, "Buffer could not be converted"); return ESP_FAIL; } ESP_LOGI(TAG, "floats in buffer %f and %f", float_buf[0], float_buf[1]); /* Send a simple response */ const char resp[] = "URI POST Response"; httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN); //write method to drive motors from main, use other buffer? return ESP_OK; } /* URI handler structure for GET /uri */ httpd_uri_t uri_get = { .uri = "/uri/get", .method = HTTP_GET, .handler = get_handler, .user_ctx = NULL }; /* URI handler structure for POST /uri */ httpd_uri_t uri_post = { .uri = "/uri/post", .method = HTTP_POST, .handler = post_handler, .user_ctx = NULL }; /* Function for starting the webserver */ httpd_handle_t start_webserver(QueueHandle_t queue) { // assign the queue task_Queue = queue; /* Generate default configuration */ // server port 80 httpd_config_t config = HTTPD_DEFAULT_CONFIG(); /* Empty handle to esp_http_server */ httpd_handle_t server = NULL; /* Start the httpd server */ if (httpd_start(&server, &config) == ESP_OK) { /* Register URI handlers */ httpd_register_uri_handler(server, &uri_get); httpd_register_uri_handler(server, &uri_post); ESP_LOGI(TAG, "server has been started"); } /* If server failed to start, handle will be NULL */ return server; } /* Function for stopping the webserver */ void stop_webserver(httpd_handle_t server) { if (server) { /* Stop the httpd server */ ESP_LOGI(TAG, "stopping server"); httpd_stop(server); } } int put_in_buffer(float *pointer_float_buf, char* buf, size_t len){ char intermediate_one [32]; char intermediate_two [32]; int i = 0; while (*(buf) != '&' && i + 1 < len) { intermediate_one [i] = *(buf++); i++; } buf++; int j=0;; while(*(buf) != '&' && j + i + 1 < len){ intermediate_two [j] = *(buf++); j++; } float one_buf = strtof(intermediate_one, NULL); float two_buf = strtof(intermediate_two, NULL); *pointer_float_buf = one_buf; *(pointer_float_buf+1) = two_buf; if(xQueueSendToBack( task_Queue, ( float * ) &two_buf, 0 ) && xQueueSendToBack( task_Queue, ( float * ) &one_buf, 0 )){ ESP_LOGI(TAG, "put data in the queue"); } else{ ESP_LOGI(TAG, "FAILED to put data in the queue"); return 0; } return 1; }
C
#include <stdlib.h> #include <stdio.h> #include "dames.h" #include "dames_intermediate.h" struct game *new_game(int xsize, int ysize){ // On alloue de la mémoire pour créer la structure du jeu struct game *jeu = (struct game *) malloc(sizeof(struct game)); if(jeu == NULL){ // Si le malloc a échoué printf("Mémoire insuffisante pour créer le jeu.\n"); exit(EXIT_FAILURE); } int i; jeu -> board = (int **) malloc(xsize*sizeof(int *)); if ((jeu->board) == NULL){ // Si le malloc a échoué printf("Mémoire insuffisante pour créer le plateau de jeu.\n"); exit(EXIT_FAILURE); } for(i = 0 ; i < xsize ; i++){ // On alloue de la mémoire pour le plateau de jeu. *((jeu -> board) + i) = (int *) malloc(ysize*sizeof(int)); if((jeu -> board) + i == NULL){ // Si le malloc a échoué printf("Mémoire insuffisante pour créer le plateau de jeu.\n"); exit(EXIT_FAILURE); } } jeu -> moves = NULL; jeu -> xsize = xsize; jeu -> ysize = ysize; jeu -> cur_player = PLAYER_WHITE; int j; for(i = 0 ; i < xsize ; i++){ for(j = 0 ; j < ysize ; j++){ if( ( (j % 2 == 0) && (i % 2 == 0) ) || ( (j % 2 != 0) && (i % 2 != 0) ) ){ // *(*((jeu -> board) + j) + i) = 0x0; (jeu -> board)[i][j] = 0x0; } else{ if(j < 4){ *(*((jeu -> board) + i) + j) = 0x1; } else if (j < 6){ *(*((jeu -> board) + i) + j) = 0x0; } else { *(*((jeu -> board) + i) + j) = 0x5; } } } } nPieces[PLAYER_WHITE] = 20; nPieces[PLAYER_BLACK] = 20; return jeu; } struct game *load_game(int xsize, int ysize, const int **board, int cur_player){ // Vérification de la taille du plateau de jeu if (xsize != 10 || ysize != 10) return NULL; // Vérification du plateau de jeu donné if (board == NULL) return NULL; // Vérification du tour du joueur donné if ((cur_player != PLAYER_BLACK) && (cur_player != PLAYER_WHITE)) return NULL; struct game *jeu = (struct game *) malloc(sizeof(struct game)); if(jeu == NULL){ // Si le malloc a échoué printf("Mémoire insuffisante pour créer le jeu.\n"); exit(EXIT_FAILURE); } // On initialise toutes les variables de la structure. jeu -> xsize = xsize; jeu -> ysize = ysize; // On recréé un plateau de jeu pour le jeu chargé // L'opération est nécessaire, pour éviter de libérer deux fois le même plateau, // Dans le cas où on libère un jeu créé et un jeu chargé à partir de ce dernier. jeu -> board = (int **) malloc(xsize*sizeof(int *)); if ((jeu->board) == NULL){ // Si le malloc a échoué printf("Mémoire insuffisante pour créer le plateau de jeu.\n"); exit(EXIT_FAILURE); } int i, j; for(i = 0 ; i < xsize ; i++){ // On alloue de la mémoire pour le plateau de jeu. *((jeu -> board) + i) = (int *) malloc(ysize*sizeof(int)); if((jeu -> board) + i == NULL){ // Si le malloc a échoué printf("Mémoire insuffisante pour créer le plateau de jeu.\n"); exit(EXIT_FAILURE); } } nPieces[PLAYER_WHITE] = 0; nPieces[PLAYER_BLACK] = 0; // On recopie le tableau passé en arguments pour le mettre dans le tableau du jeu for(i = 0 ; i < xsize ; i++){ for(j = 0 ; j < ysize ; j++){ if( *(*((board) + i) + j) != 0x0 && *(*((board) + i) + j) != 0x1 && *(*((board) + i) + j) != 0x5 && *(*((board) + i) + j) != 0x3 && *(*((board) + i) + j) != 0x7){ printf("Le tableau passé en argument est incorrect...\n"); return NULL; } (jeu->board)[i][j] = *(*((board) + i) + j); // On incrémente les variables globales de compteurs de pions quand nécessaire if(getColor((jeu->board)[i][j]) == PLAYER_BLACK){ nPieces[PLAYER_BLACK]++; } else if(getColor((jeu->board)[i][j]) == PLAYER_WHITE){ nPieces[PLAYER_WHITE]++; } } } jeu -> cur_player = cur_player; jeu -> moves = NULL; return jeu; } int getColor(int piece){ if(piece == 0x0){ return 2; } if ((piece != 0x1) && (piece != 0x5) && (piece != 0x3) && (piece != 0x7)){ printf("Pièce non valide, impossible de récupérer la couleur"); exit(EXIT_FAILURE); } // On récupère le bit de couleur return ((piece & 0x4) >> 2) & 1; } int isOutOfBoard(const struct move_seq *seq){ struct coord c_avant = seq -> c_old; struct coord c_apres = seq -> c_new; // On vérifie si les coordonnées sont en dehorsdu tableau ou non if (((c_avant.x >= 0) && (c_avant.x < 10) && (c_avant.y) >= 0 && (c_avant.y < 10) && (c_apres.x >= 0) && (c_apres.x < 10) && (c_apres.y) >= 0 && (c_apres.y) < 10) == 1) return 0; else return 1; } int isDame(int piece){ return (piece & 0x2) == 0x2; } int isCoordInBoard(int x, int y){ return x < 10 && x >= 0 && y < 10 && y >= 0; } int isValidMovePiece(const struct game *jeu, int x, int y, int color){ int **plateau = jeu -> board; int yMoveValue; //Si la couleur de la piece qu'on verifie n'est pas la couleur du joueur actuel, on retourne 0 direct if(getColor(plateau[x][y]) != color){ return 0; } //Si le joueur actuel est PLAYER_WHITE, il avance de base vers le haut (y diminue, donc yMoveValue = -1) if(getColor(plateau[x][y]) == PLAYER_WHITE){ yMoveValue = -1; } //Si le joueur actuel est PLAYER_BLACK, il avance de base vers le bas (y augmente, donc yMoveValue = 1) else{ yMoveValue = 1; } //On regarde s'il y a des cases libres dans les cases adjacentes, "devant" la pièce if((isCoordInBoard(x+1, y + yMoveValue) && (plateau[x+1][y + yMoveValue] == 0)) || (isCoordInBoard(x-1, y + yMoveValue) > 0 && (plateau[x-1][y + yMoveValue] == 0))){ return 1; } //Si c'est une dame if(isDame(plateau[x][y])){ //On vérifie les cases "derrière elle" aussi if((isCoordInBoard(x+1, y - yMoveValue) && (plateau[x+1][y - yMoveValue] == 0)) || (isCoordInBoard(x-1, y - yMoveValue) > 0 && (plateau[x-1][y - yMoveValue] == 0))){ return 1; } } //S'il n'y a pas de case libre adjacente à la pièce else{ //On regarde si on peut sauter au-dessus d'un pion, par l'avant EST if(isCoordInBoard(x+2, y + 2*yMoveValue) && (getColor(plateau[x+1][y + yMoveValue]) != color)){ if(plateau[x+2][y + 2*yMoveValue] == 0x0){ return 1; } } //Par l'avant OUEST if(isCoordInBoard(x-2, y + 2*yMoveValue) && (getColor(plateau[x-1][y + yMoveValue]) != color)){ if(plateau[x-2][y + 2*yMoveValue] == 0x0){ return 1; } } //Par l'arrière EST if(isCoordInBoard(x+2, y - 2*yMoveValue) && (getColor(plateau[x+1][y - yMoveValue]) != color)){ if(plateau[x+2][y + 2*yMoveValue] == 0x0){ return 1; } } //Par l'arrière OUEST if(isCoordInBoard(x-2, y - 2*yMoveValue) && (getColor(plateau[x-1][y - yMoveValue]) != color)){ if(plateau[x-2][y + 2*yMoveValue] == 0x0){ return 1; } } } //Si aucun des tests n'a réussi, c'est qu'il n'y a aucun mouvement valide pour cette pièce. return 0; } int canPlay(const struct game *jeu, int color){ int i,j; for(i = 0 ; i < jeu -> xsize ; i++){ for(j = 0 ; j < jeu -> ysize ; j++){ //On verifie si la piece aux coordonnees i,j peut jouer actuellement if(isValidMovePiece(jeu, i, j, color)){ //Si la pièce peut effectuer un mouvement valide, on retourne 1 return 1; } } } //Si aucune pièce ne peut jouer actuellement, retourne 0 return 0; } int getDiagonal(struct coord c_avant, struct coord c_apres){ //On regarde si les coordonnées forment une diagonale ou non if(c_apres.x - c_avant.x > 0 && c_apres.y - c_avant.y > 0){ return SUDEST; } else if(c_apres.x - c_avant.x > 0 && c_apres.y - c_avant.y < 0){ return NORDEST; } else if(c_apres.x - c_avant.x < 0 && c_apres.y - c_avant.y > 0){ return SUDOUEST; } else if(c_apres.x - c_avant.x < 0 && c_apres.y - c_avant.y < 0){ return NORDOUEST; } else{ return 0; } } int pieceBienPrise(const struct game *jeu, struct coord *prise, struct coord c_avant, struct coord c_apres){ int piecePrise = (jeu -> board)[prise -> x][prise -> y]; int pieceQuiJoue = (jeu -> board)[c_avant.x][c_avant.y]; // On vérifie que la pièce qui joue et la pièce prise sont de couleurs différentes if((getColor(piecePrise) ^ getColor(pieceQuiJoue)) == 0x1){ // On vérifie que la pièce qui joue a bien sauté au-dessus de la pièce prise : return ( (c_avant.x + c_apres.x)/2 == prise -> x ) && ( (c_avant.y + c_apres.y)/2 == prise -> y ); } // Sinon, la prise de pièce n'est pas valide else{ return 0; } } int isDiagonal(struct coord c_avant, struct coord c_apres){ int valAbs = abs(c_apres.x - c_avant.x); if(valAbs == abs(c_apres.y - c_avant.y)){ return valAbs; } else{ return 0; } } int isCorrectMovePion(const struct game *jeu, struct coord c_avant, struct coord c_apres, struct coord *taken){ // On récupère a valeur de isDiagonal int valeurMove = isDiagonal(c_avant, c_apres); //Si on bouge de 0 ou de + de 2 cases, c'est une erreur if(valeurMove == 0 || valeurMove > 2){ return 0; } // Donc ici, on sait que ValeurMove vaut 1 ou 2 (prise de pion ou non) // Si valeurMove vaut 2 (mouvement de 2 cases), c'est qu'il doit y avoir prise de pion if(valeurMove == 2){ int piecePrise; // On récupère l'orientation du mouvement int diagonale = getDiagonal(c_avant, c_apres); // On vérifie en fonction de la direction du mouvement if(diagonale == SUDEST){ piecePrise = (jeu -> board)[c_avant.x + 1][c_avant.y + 1]; // Vérifions que la pièce prise n'est ni une case vide, ni un pion de sa propre couleur if(piecePrise == 0x0 || getColor(piecePrise) == jeu -> cur_player){ return 0; } taken -> x = c_avant.x + 1; taken -> y = c_avant.y + 1; } else if(diagonale == SUDOUEST){ piecePrise = (jeu -> board)[c_avant.x - 1][c_avant.y + 1]; if(piecePrise == 0x0 || getColor(piecePrise) == jeu -> cur_player){ return 0; } taken -> x = c_avant.x - 1; taken -> y = c_avant.y + 1; } else if(diagonale == NORDEST){ piecePrise = (jeu -> board)[c_avant.x + 1][c_avant.y - 1]; if(piecePrise == 0x0 || getColor(piecePrise) == jeu -> cur_player){ return 0; } taken -> x = c_avant.x + 1; taken -> y = c_avant.y - 1; } else{ piecePrise = (jeu -> board)[c_avant.x - 1][c_avant.y - 1]; if(piecePrise == 0x0 || getColor(piecePrise) == jeu -> cur_player){ return 0; } taken -> x = c_avant.x - 1; taken -> y = c_avant.y - 1; } // Déplacement valide avec capture de pièce : on retourne 2 return 2; } // Si on est ici, c'est que valeurMove vaut 1 // On recupere la valeur de la piece qui joue int piece = (jeu -> board)[c_avant.x][c_avant.y]; // Si la pièce est un pion blanc, on regarde si son mouvement est correct (mouvement en diagonale) if(getColor(piece) == PLAYER_WHITE){ // Déplacement correct : on retourne 1 return (c_apres.x - c_avant.x == -valeurMove && c_apres.y - c_avant.y == -valeurMove) || (c_apres.x - c_avant.x == valeurMove && c_apres.y - c_avant.y == -valeurMove); } // Si c'est un pion noir, même chose, sauf que le sens de déplacement a changé else{ // Déplacement correct : on retourne 1 return (c_apres.x - c_avant.x == -valeurMove && c_apres.y - c_avant.y == valeurMove) || (c_apres.x - c_avant.x == valeurMove && c_apres.y - c_avant.y == valeurMove); } } int isCorrectMoveDame(const struct game *jeu, struct coord c_avant, struct coord c_apres, struct coord *taken){ // On récupère la valeur de isDiagonal (nombre de cases qu'on parcourt) int valeurMove = isDiagonal(c_avant, c_apres); // Si la dame ne bouge pas en diagonale if(valeurMove == 0){ return 0; } // On récupère la direction du mouvement int diagonale = getDiagonal(c_avant, c_apres); int prise = 0; int i; int position; for(i = 1 ; i <= valeurMove ; i++){ if(diagonale == SUDEST){ position = (jeu -> board)[c_avant.x + i][c_avant.y + i]; } else if(diagonale == SUDOUEST){ position = (jeu -> board)[c_avant.x - i][c_avant.y + i]; } else if(diagonale == NORDEST){ position = (jeu -> board)[c_avant.x + i][c_avant.y - i]; } else{ position = (jeu -> board)[c_avant.x - i][c_avant.y - i]; } // Si on arrive sur une case d'une pièce de la même couleur que nous if(position != 0x0 && getColor(position) == getColor((jeu -> board)[c_avant.x][c_avant.y])){ // On ne peut pas, on retourne 0 return 0; } // Sinon, si on n'est pas sur une case vide et donc qu'on passe au-dessus d'une ennemi else if(position != 0x0 && i != valeurMove){ // Si on ne l'a jamais fait if(prise == 0){ // On dit qu'on a pris une pièce if(diagonale == SUDEST){ position = (jeu -> board)[c_avant.x + i][c_avant.y + i]; taken -> x = c_avant.x + i; taken -> y = c_avant.y + i; prise = 1; } else if(diagonale == SUDOUEST){ position = (jeu -> board)[c_avant.x - i][c_avant.y + i]; taken -> x = c_avant.x - i; taken -> y = c_avant.y + i; prise = 1; } else if(diagonale == NORDEST){ position = (jeu -> board)[c_avant.x + i][c_avant.y - i]; taken -> x = c_avant.x + i; taken -> y = c_avant.y - i; prise = 1; } else{ position = (jeu -> board)[c_avant.x - i][c_avant.y - i]; taken -> x = c_avant.x - i; taken -> y = c_avant.y - i; prise = 1; } } // Si on l'a déjà fait lors de la même séquence else{ // On n'a pas le droit de le faire, on retourne donc 0 return 0; } } } // Si on atterit sur une case non vide au final, erreur if(position != 0x0) return 0; // Si on a passé tous les tests (avec prise), la séquence est valide, on retourne 2 if(prise == 1) return 2; // Si on a passé tous les tests (sans prise), la séquence est valide, on retourne 1 return 1; } int isMoveValid(const struct game *jeu, struct coord c_avant, struct coord c_apres, int piece, struct coord *taken){ // On vérifie si la pièce atterit sur une case vide if((jeu -> board)[c_apres.x][c_apres.y] != 0){ return 0; } // Si la pièce est un pion if(!isDame(piece)){ return isCorrectMovePion(jeu, c_avant, c_apres, taken); } // Sinon, la pièce est une dame else{ return isCorrectMoveDame(jeu, c_avant, c_apres, taken); } } int is_move_seq_valid(const struct game *game, const struct move_seq *seq, const struct move_seq *prev, struct coord *taken){ if(prev != NULL && (seq == NULL || (prev -> c_new).x != (seq -> c_old).x || (prev -> c_new).y != (seq -> c_old).y) ){ return 0; } struct coord c_avant = seq -> c_old; struct coord c_apres = seq -> c_new; // On récupère la valeur de la pièce qui joue. int pieceQuiJoue = (game -> board)[c_avant.x][c_avant.y]; //On récupère le 3eme bit de la pièce qui joue et on le compare au joueur qui doit jouer if(getColor(pieceQuiJoue) != game -> cur_player){ return 0; } // Si la pièce avant ou après le mouvement se trouve en dehors du tableau, c'est invalide if(isOutOfBoard(seq)){ return 0; } return isMoveValid(game, c_avant, c_apres, pieceQuiJoue, taken); } void push_seq(struct game *jeu, const struct move_seq *seq, struct coord *piece_taken, int old_orig, int piece_value){ if(seq == NULL){ printf("Aucune sequence a rajouter dans push_seq\n"); return; } if(jeu == NULL){ printf("Aucun jeu auquel rajouter une séquence (pointeur NULL)\n"); } struct move_seq *newSeq; newSeq = (struct move_seq*) malloc(sizeof(struct move_seq)); if(newSeq == NULL){ printf("Erreur d'allocation de mémoire dans push_seq\n"); return; } newSeq -> next = (jeu -> moves) -> seq; newSeq -> c_old = seq -> c_old; newSeq -> c_new = seq -> c_new; newSeq -> piece_value = piece_value; newSeq -> old_orig = old_orig; if(piece_taken != NULL){ newSeq -> piece_taken = *piece_taken; } (jeu -> moves) -> seq = newSeq; } int transformDame(struct game *jeu, struct coord c){ // On récupère la valeur de la pièce int piece = (jeu -> board)[c.x][c.y]; // Si ce n'est pas une dame if(!isDame(piece)){ // Si le pion est blanc et qu'il est en haut du plateau if(getColor(piece) == PLAYER_WHITE && c.y == 0){ (jeu -> board)[c.x][c.y] = (jeu -> board)[c.x][c.y] | 0x2; return 1; } // Si le pion est noir et qu'il est en bas du plateau else if(getColor(piece) == PLAYER_BLACK && c.y == 9){ (jeu -> board)[c.x][c.y] = (jeu -> board)[c.x][c.y] | 0x2; return 1; } else{ return 0; } } return 0; } void push_move(struct game *jeu){ struct move *newMove = (struct move *) malloc(sizeof(struct move)); newMove -> next = jeu -> moves; newMove -> seq = NULL; jeu -> moves = newMove; } void free_move_seq(struct move_seq * seq){ struct move_seq *precedent = seq; while(precedent != NULL){ seq = seq -> next; free(precedent); precedent = seq; } } struct move *pop_move(struct game *jeu){ if(jeu == NULL || jeu -> moves == NULL){ return NULL; } struct move *mouvement = jeu -> moves; jeu -> moves = (jeu -> moves) -> next; return mouvement; } int apply_moves(struct game *game, const struct move *moves){ const struct move *current = moves; struct move_seq *sequence = NULL; struct coord prise = {-1,-1}; struct coord *taken = &prise; struct move_seq *previousSeq = NULL; struct coord c_avant; struct coord c_apres; int ennemy; // Variable qui retient la couleur du pion qui se fait capturer, s'il y en a un int previousValid = 3; // Variable qui retient la valeur retournée par l'appel de is_move_seq_valid sur la séquence précédente int isValid = 3; // Variable qui retient la valeur qui sera retournée par l'appel de is_move_seq_valid sur la séquence en cours int playerPiece; // Valeur de la pièce jouée lors de la séquence en cours int gotDame= 0; // Détermine si le joueur a récupéré une dame lors de la séquence précédente ; 1: oui, 0: non // On parcourt la liste de moves while(current != NULL){ push_move(game); sequence = current -> seq; // On parcourt la liste de séquences du move while(sequence != NULL){ if(previousValid == 1 || gotDame == 1){ // On annule alors tout ce qu'on a appliqué jusqu'ici et on stocke le résultat de undo_moves int res = undo_moves(game, 1); // On re-inverse la couleur du joueur actuel si undo_moves l'a inversé (si res != -1) if(res != -1){ game -> cur_player = ~(game -> cur_player) & 1; } return -1; } isValid = is_move_seq_valid(game, sequence, previousSeq, taken); // Si la séquence n'est pas valide, le move n'est pas valide if(isValid == 0){ // On annule alors tout ce qu'on a appliqué jusqu'ici et on stocke le résultat de undo_moves int res = undo_moves(game, 1); // On re-inverse la couleur du joueur actuel si undo_moves l'a inversé (si res != -1) if(res != -1){ game -> cur_player = ~(game -> cur_player) & 1; } return -1; } // S'il n'y a pas de capture else if(isValid == 1){ c_avant = sequence -> c_old; c_apres = sequence -> c_new; // On récupère la pièce playerPiece = (game -> board)[c_avant.x][c_avant.y]; // On met ennemy à 0 ennemy = 0x0; // On fait avancer la piece (game -> board)[c_apres.x][c_apres.y] = (game -> board)[c_avant.x][c_avant.y]; // On vide la case ou était la pièce (game -> board)[c_avant.x][c_avant.y] = 0x0; } // S'il y a capture de pièce else{ c_avant = sequence -> c_old; c_apres = sequence -> c_new; // On récupère la valeur de la pièce playerPiece = (game -> board)[c_avant.x][c_avant.y]; // On fait avancer la pièce (game -> board)[c_apres.x][c_apres.y] = playerPiece; (game -> board)[c_avant.x][c_avant.y] = 0x0; // On récupère la valeur de la pièce prise ennemy = (game -> board)[taken -> x][taken -> y]; // On vide la case de la pièce prise (game -> board)[taken -> x][taken -> y] = 0x0; // On diminue le nombre de pièces de l'adversaire nPieces[getColor(ennemy)]--; } push_seq(game, sequence, taken, playerPiece, ennemy); //Si le joueur adverse n'a plus de mouvement possible previousSeq = sequence; // On récupère une dame si nécessaire et on récupère le résultat gotDame = transformDame(game, c_apres); sequence = sequence -> next; previousValid = isValid; } // Créer une fonction pour voir si le joueur peut encore jouer apres ou non (moves encore possibles,...) current = current -> next; // Comme on change de move, ce n'est plus le même joueur qui joue, donc on réinitialise previousValid. previousValid = 3; // On inverse le joueur qui joue game -> cur_player = ~(game -> cur_player) & 1; // Peut-il encore jouer ? if(!canPlay(game, game -> cur_player)){ game -> cur_player = ~(game -> cur_player) & 1; // On retourne 1 pour dire qu'il a perdu return 1; } } return 0; } int undo_seq(struct game *jeu, struct move_seq *sequence){ if(sequence == NULL || jeu == NULL){ return -1; } (jeu -> board)[(sequence -> c_old).x][(sequence -> c_old).y] = sequence -> old_orig; (jeu -> board)[(sequence -> c_new).x][(sequence -> c_new).y] = 0x0; if(sequence -> piece_value != 0x0){ (jeu -> board)[(sequence -> piece_taken).x][(sequence -> piece_taken).y] = sequence -> piece_value; nPieces[getColor(sequence -> piece_value)]++; } return 0; } int undo_moves(struct game *game, int n){ if(game == NULL || n <= 0){ return -1; } int i; struct move *mouvement = game -> moves; if(mouvement == NULL){ return -1; } struct move_seq *current; for(i = 0 ; i < n && mouvement != NULL ; i++){ // On sort le mouvement de la pile de mouvements mouvement = pop_move(game); current = mouvement -> seq; if(current == NULL){ free(mouvement); return -1; } while(current != NULL){ undo_seq(game, current); mouvement -> seq = (mouvement -> seq) -> next; free(current); current = mouvement -> seq; } // On inverse le joueur qui doit jouer game -> cur_player = ~(game -> cur_player) & 1; free(mouvement); mouvement = game -> moves; } return 0; } void print_board(const struct game *game){ int i,j; char carac; printf(" "); for(j = 0 ; j < 10 ; j++){ printf("%d ", j); } printf("\n"); for(j = 0 ; j < 10 ; j++){ printf("%d ", j); for(i = 0 ; i < 10 ; i++){ // On affiche un caractère différent en fonction de la valeur de la case if((game -> board)[i][j] == 0x0){ carac = 'X'; } else if((game -> board)[i][j] == 0x1){ carac = 'n'; } else if((game -> board)[i][j] == 0x5){ carac = 'b'; } else if((game -> board)[i][j] == 0x3){ carac = 'N'; } else if((game -> board)[i][j] == 0x7){ carac = 'B'; } else{ printf("erreur de damier...\n"); return; } printf("%c ", carac); } printf("\n"); } if(game -> cur_player == PLAYER_BLACK){ printf("C'est au joueur noir de jouer.\n"); } else if(game -> cur_player == PLAYER_WHITE){ printf("C'est au joueur blanc de jouer.\n"); } else{ printf("Erreur : impossible de déterminer le joueur qui doit jouer...\n"); } printf("Pieces restantes : %d noires, %d blanches.\n", nPieces[PLAYER_BLACK], nPieces[PLAYER_WHITE]); } void free_game(struct game *game){ if(game == NULL){ printf("Il n'y a pas de jeu à libérer\n"); exit(EXIT_FAILURE); } int i; // On libère le tableau de jeu for(i = 0 ; i < 10 ; i++){ free(*((game -> board) + i)); } struct move *precedent = game -> moves; while(precedent != NULL){ game -> moves = (game -> moves) -> next; free_move_seq(precedent -> seq); free(precedent); precedent = game -> moves; } // On libère le double pointeur free(game->board); // On libère la structure du jeu free(game); }
C
/* ** search.c for search sources in /home/styvaether/Epitech/PSU/PSU_2015_malloc/src ** ** Made by Nicolas Gascon ** Login <[email protected]> ** ** Started on Sat Jan 30 17:32:53 2016 Nicolas Gascon ** Last update Sun Feb 14 21:56:00 2016 Nicolas Gascon */ #include "../include/rbtree.h" /* ** Work in progress : Iterative mode */ t_node *search_free_block(t_node *node, size_t size) { t_node *tmp; return (NULL); if (!node || node == SENTINEL) return (NULL); if (node->free && size < node->size && node->magic == MAGIC) return (node); tmp = search_free_block(node->left, size); if (!tmp) tmp = search_free_block(node->right, size); return (tmp); } t_node *search(t_node *node, t_node *research) { while (node && node != SENTINEL && (void *)node < g_malloc.end) { if (node == research && node->magic == MAGIC) return (node); if (research < node) node = node->left; else node = node->right; } return (NULL); } t_node *search_last_node() { t_node *tmp; tmp = g_malloc.root; if (tmp == SENTINEL) return (NULL); while (tmp->right != SENTINEL) tmp = tmp->right; return (tmp); }
C
/* * Banner.c * This example demonstrates several important points. It uses the Win32 Console API * instead of common stdio functions, including alternatives to cursor handling and * gets(). * * 1) The primary thread allocates memory with HeapAlloc() and the worker thread frees * the memory with HeapFree(). The memory management functions in the C run-time * library are not safe to call without the multithreaded library * * 2) All of the random numbers are generated in the primary thread. The run-time * function rand() must maintain state between calls. * * 3) An event object is used to simultaneously signal all threads when it is time * to shut down. * * 4) The sample program does not link with the multithreaded run-time library, nor * does it need to. * Notice the worker threads may safely use string handling functions such as * strcpy() because these functions operate entirely on the stack. * * We use: CreteThread() instead of _beginthreadex() * ReadConsole(), WriteConsole() instead of ReadFile(),WriteFile() */ #include <windows.h> #include <stdlib.h> #include <time.h> #include "MtVerify.h" #define MAX_THREADS 256 #define INPUT_BUF_SIZE 80 #define BANNER_SIZE 12 #define OUTPUT_TEXT_COLOR BACKGROUND_BLUE | \ FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE void MainLoop(void); void ClearScreen(void); void ShutDownThreads(void); void Prompt(LPCSTR str); int StripCr(LPSTR buf); DWORD WINAPI BannerProc(LPVOID pParam); HANDLE hConsoleIn; HANDLE hConsoleOut; HANDLE hRunObject; HANDLE ThreadHandles[MAX_THREADS]; int nThreads; CONSOLE_SCREEN_BUFFER_INFO csbiInfo; typedef struct { TCHAR buf[INPUT_BUF_SIZE]; SHORT x; SHORT y; } DataBlock; int main() { /* Get display screen information & clear the screen */ hConsoleIn = GetStdHandle(STD_INPUT_HANDLE); hConsoleOut = GetStdHandle(STD_OUTPUT_HANDLE); GetConsoleScreenBufferInfo(hConsoleOut, &csbiInfo); ClearScreen(); /* Create the event object that keeps threads running */ MTVERIFY( hRunObject = CreateEvent( NULL, // security TRUE, // manual reset 0, // clear on creation NULL) // no name ); /* start waiting for keyboard input to dispatch threads on exit */ MainLoop(); ShutDownThreads(); ClearScreen(); CloseHandle(hRunObject); CloseHandle(hConsoleIn); CloseHandle(hConsoleOut); return EXIT_SUCCESS; } // main void ShutDownThreads(void) { if(nThreads > 0) { /* Since this is a manual event, all threads will be woken up at once */ MTVERIFY( SetEvent(hRunObject) ); MTVERIFY( WaitForMultipleObjects( nThreads, ThreadHandles, TRUE, INFINITE) != WAIT_FAILED ); while(--nThreads) MTVERIFY( CloseHandle(ThreadHandles[nThreads]) ); } } /* Dispatch and count threads */ void MainLoop(void) { TCHAR buf[INPUT_BUF_SIZE]; DWORD bytesRead; DataBlock *data_block; DWORD thread_id; srand( (unsigned int) time(NULL)); for(;;) { Prompt("Type string to display or ENTER to exit: "); MTVERIFY( ReadFile(hConsoleIn, buf, INPUT_BUF_SIZE - 1, &bytesRead, NULL) ); /* ReadFile is binary , not line oriented, so terminate the string */ buf[bytesRead] = '\0'; MTVERIFY( FlushConsoleInputBuffer(hConsoleIn) ); if( StripCr(buf) == 0 ) break; if(nThreads < MAX_THREADS) { /* Use the Win32 HeapAlloc() instead of malloc() because we would need the multithread library if the worker thread had to call free(). */ data_block = HeapAlloc( GetProcessHeap(), HEAP_ZERO_MEMORY, sizeof(DataBlock)); strcpy(data_block->buf, buf); /* Pick a random place on the screen to put this banner. You may not call rand in the worker thread because it is one of the functions that must maintain state between calls */ data_block->x = rand() * (csbiInfo.dwSize.X - BANNER_SIZE) / RAND_MAX; data_block->y = rand() * (csbiInfo.dwSize.Y - 1) / RAND_MAX + 1; MTVERIFY( ThreadHandles[nThreads++] = CreateThread( NULL, 0, BannerProc, data_block, 0, &thread_id) ); } } } int StripCr(LPSTR buf) { int len = strlen(buf); for(;;) { if(len <= 0) return 0; else if(buf[--len] == '\r') buf[len] = ' '; else if(buf[len] == '\n') buf[len] = ' '; else break; } return len; } void ClearScreen(void) { DWORD dummy; COORD Home = {0, 0}; FillConsoleOutputAttribute(hConsoleOut, csbiInfo.wAttributes, csbiInfo.dwSize.X * csbiInfo.dwSize.Y, Home, &dummy); FillConsoleOutputCharacter(hConsoleOut, ' ', csbiInfo.dwSize.X * csbiInfo.dwSize.Y, Home, &dummy); } void Prompt(LPCSTR str) { COORD Home = {0, 0}; DWORD dummy; int len = strlen(str); SetConsoleCursorPosition(hConsoleOut, Home); WriteFile(hConsoleOut, str, len, &dummy, FALSE); Home.X = len; FillConsoleOutputCharacter(hConsoleOut, ' ', csbiInfo.dwSize.X - len, Home, &dummy); } /* Routines from here down are used only by worker threads */ DWORD WINAPI BannerProc( LPVOID pParam ) { DataBlock *thread_data_block = pParam; COORD TopLeft = {0,0}; COORD Size = {BANNER_SIZE ,1}; int i, j; int len; int ScrollPosition = 0; TCHAR OutputBuf[INPUT_BUF_SIZE+BANNER_SIZE]; CHAR_INFO CharBuf[INPUT_BUF_SIZE+BANNER_SIZE]; SMALL_RECT rect; rect.Left = thread_data_block->x; rect.Right = rect.Left + BANNER_SIZE; rect.Top = thread_data_block->y; rect.Bottom = rect.Top; /* Set up the string so the output routine * does not have figure out wrapping. */ strcpy(OutputBuf, thread_data_block->buf); len = strlen(OutputBuf); for (i=len; i<BANNER_SIZE; i++) OutputBuf[i] = ' '; if (len<BANNER_SIZE) len = BANNER_SIZE; strncpy(OutputBuf+len, OutputBuf, BANNER_SIZE); OutputBuf[len+BANNER_SIZE-1] = '\0'; MTVERIFY( HeapFree( GetProcessHeap(), 0, pParam ) ); do { for (i=ScrollPosition++, j=0; j<BANNER_SIZE; i++, j++) { CharBuf[j].Char.AsciiChar = OutputBuf[i]; CharBuf[j].Attributes = OUTPUT_TEXT_COLOR; } if (ScrollPosition == len) ScrollPosition = 0; MTVERIFY( WriteConsoleOutput( hConsoleOut, CharBuf, Size, TopLeft, &rect) ); /* * This next statement has the dual purpose of * being a choke on how often the banner is updated * (because the timeout forces the thread to wait for * awhile) as well as causing the thread to exit * when the event object is signaled. */ } while ( WaitForSingleObject( hRunObject, 125L ) == WAIT_TIMEOUT ); return 0; }
C
/*Вывести числовой квадрат заданного размера. Выведенные числа начинаются с единицы и постоянно увеличиваются. В каждой строке числа разделены пробелами. Размер считать с клавиатуры. Пример ввода 2 Пример вывода 1 2 3 4*/ #include <stdio.h> int main() { int size; int value = 0; scanf("%d", &size); for ( int row = 0; row < size; row++ ) { for ( int col = 1; col < size; col++ ) { value += 1; printf("%d ", value); } value += 1; printf("%d\n", value); } return 0; }
C
#include <unistd.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #define BUF_SIZE 8192 char buffer[BUF_SIZE]; ssize_t read_to_buffer() { ssize_t bytes = read(0, buffer, BUF_SIZE); if (bytes < 0) { printf("failed to read\n"); exit(1); } return bytes; } int tree(int position) { if (buffer[position] == '.') { return 0; } else if (buffer[position] == '#') { return 1; } else { printf("unknown character\n"); exit(1); } } int file_position(int x, int y, int line_length) { return (line_length + 2) * y + x; } int buffer_position(int x, int y, int line_length, int buffer_start) { return file_position(x % line_length, y, line_length) - buffer_start; } int find_trees() { int buffer_start = 0; int line_length = 0; int x = 0; int y = 0; ssize_t bytes = read_to_buffer(); int trees_hit = tree(0); while (buffer[line_length] != '\r') { line_length++; } int i = 2; while (bytes) { while (buffer_position(x + 3, y + 1, line_length, buffer_start) < bytes) { y += 1; x += 3; trees_hit += tree(buffer_position(x, y, line_length, buffer_start)); } buffer_start += bytes; bytes = read_to_buffer(); } return trees_hit; } int main() { printf("%d\n", find_trees()); }
C
#include<stdio.h> #include<math.h> main(){ float x1,x2,y1,y2,distance; printf("veuillez entrer les coordonnes de A(x et y):\n"); scanf("%f%f",&x1,&y1); printf("veuillez entrer les coordonnes de B(x et y) : \n"); scanf("%f%f",&x2,&y2); distance=sqrt(pow((x1-x2),2)+pow((y1-y2),2)); printf("la distance entre A et B est :\n%d metre",distance); }
C
Train Journey - Initial Boarding Count In a train journey, there are N stations between station A and B (The train starts from station A). The number of passengers who alighted in station B is passed as the input. The number of passengers who alighted and boarded in the N stations in between is also passed as the input. The program must print the number of passengers who boarded the train at station A. Input Format: The first line contains N and the number of passengers who alighted at station B (which is the last station), separated by a space. N lines containing the number of passengers who alighted and boarded the train in the N stations in between A and B, with the values separated by a space. Output Format: The first line contains the number of passengers who boarded the train at station A. Boundary Conditions: 1 <= N <= 50 Example Input/Output 1: Input: 3 50 30 40 40 10 60 30 Output: 100 Explanation: There are 3 stations in between A and B. 100 passengers boarded the train at station A. In the 2nd station (first after A), 30 got down and 40 boarded the train. So now passengers in the train is 100-30+40 = 110 In the 3rd station (second after A), 40 got down and 10 boarded. So passengers left in the train = 110-40+10 = 80 In the 4th station, passengers left in the train = 80-60+30 = 50. These 50 passengers will alight in the last station which is station B. #include <stdio.h> int main() { int n,b,i,s,n1,n2; scanf("%d %d",&n,&b); for(i=0;i<n;i++) { scanf("%d %d",&n1,&n2); s=b+n1-n2; b=s; } printf("%d",s); }
C
#include<stdio.h> #include <unistd.h> /* Our structure */ struct rec { int x,y,z; }; int main(int argc,char* argv[]) { /* This is a mock binary that simulates a binary that processes jpg files. In particular it processes files that have the four magic bytes 0xFF0xD80xFF0xE0. */ unsigned char ch; unsigned char magic_bytes[4]; int counter; FILE *ptr_myfile; struct rec my_record; int dupped_stdin = dup(0); FILE *dupped_stdin_stream = fdopen(dupped_stdin,"r"); fread(magic_bytes,1,4,dupped_stdin_stream); if(!(magic_bytes[0]==0xFF&&magic_bytes[1]==0xD8&&magic_bytes[2]==0xFF&&magic_bytes[3]==0xE0)){ printf("No JPG file"); return 0; } printf("Magic Bytes\n"); for(int i=0;i<4;++i){ printf("%02X ",magic_bytes[i]); } printf("\n$$$\n"); for(int i=0;i<20;++i) { ch = fgetc(stdin); printf("%02X ",ch); if( !(i % 16) ){ putc('\n', stdout); } } printf("\n"); return 0; }
C
// // Created by 范兴国 on 2019-10-28. // #include <stdlib.h> #ifndef DSC_STACK_NUM_H #define DSC_STACK_NUM_H #endif //DSC_STACK_NUM_H #define SN 20 #define DataType float typedef struct{ DataType data[SN]; int top; }Stack_float; void initStack_float(Stack_float *ST){ ST->top=-1; } void Push_float(Stack_float *ST,DataType x){ if(ST->top>=SN-1){ printf("OverFlow"); } else{ ST->data[++ST->top]=x; } } void Pop_num(Stack_float *ST,DataType *x){ if(ST->top==-1){ printf("UnderFlow"); } else{ *x=ST->data[ST->top--]; } } DataType Top_float(Stack_float *ST){ if(ST->top==-1){ printf("UnderFlow"); exit(0); } else{ return ST->data[ST->top]; } } int Sempty_float(Stack_float* St){ if(St->top==-1){ return 1; } else{ return 0; } }
C
#include <stdio.h> int main(){ char c; printf("Enter a character: "); scanf("%c", &c); if (c >= 97 && c <= 122){ printf("Character is Lowercase\n"); } else if (c >= 65 && c <= 90) { printf("Character is Uppercase\n"); } else { printf("Invalid Character\n"); } return 0; }
C
#include <stdio.h> #include <conio.h> #include <stdlib.h> int main (){ int vetx[]={1,02,38,14,55,96,73,87,9,10}; int x,y,i=0,k=0; printf ("digite valor que serar pesquisado no vetor: "); scanf("%d",&x); for(y=0;y<=9;y++){ if (x == vetx[y]){ i=1;} if (x == vetx[y]){ break; } } if (i == 1) printf ("o valor esta na posicao %d do vetor", y+1); else printf ("nao encontrado"); getch(); return 0; }
C
#include <conio.h> #include <stdio.h> #include <stdlib.h> #include <locale.h> main() { system("color f1") ; setlocale(LC_ALL,"") ; int tipoDVD, dia ; float DVDCOMUM = 5.0 , DVDLANCAMENTO = 5.75 ; //esses valores so aleatrios, poderiam ser quaisquer outros. printf("\n\t\t\t\t*************\n\t\t\t\t* MOVIE STAR * \t\t \n\t\t\t\t*************\n\t\t\tleve o cinema para sua casa!!! \n\n\t\n\t\t\t 1- DVD COMUM = 5,00 R$ \n\n\t\t\t 2- LANAMENTO = 5,75 R$ " ); printf("\t\t\n\n\n Digite uma das opes ===> "); scanf("%d", &tipoDVD) ; system("cls"); printf("\n\n\t\t Dia da semana que est locando o dvd: \n 1- Domingo\n\n 2- Segunda\n\n 3- Tera\n\n 4- Quarta\n\n 5- Quinta\n\n 6- Sexta\n\n 7- Sbado\n\n\t\t\t\t\t =====> " ); scanf("%d", &dia) ; if (tipoDVD > 2 || tipoDVD < 1 || dia > 7 || dia < 1 ) printf("Opo de dia ou tipo de dvd invlida \n") ; if (dia==2 && tipoDVD == 1) printf(" \nO preo da locao para dia de segunda, dvd normal de: %.2f R$\n",DVDCOMUM-= 0.4*DVDCOMUM); else if(dia==2 && tipoDVD == 2) printf(" O preo da locao para dia de segunda, dvd lancamento de : %.2fR$\n\n", DVDLANCAMENTO-=0.4*DVDCOMUM);else if(dia==3 && tipoDVD == 1) printf(" O preo da locao para dia de tera, dvd normal de: %.2fR$\n\n",DVDCOMUM-=0.4*DVDCOMUM); else if(dia==3 && tipoDVD == 2) printf(" O preo da locao para dia de tera, dvd lancamento de : %.2fR$\n\n", DVDLANCAMENTO-=0.4*DVDCOMUM);else if(dia==5 && tipoDVD == 1) printf(" O preo da locao para dia de quinta, dvd normal de: %.2fR$\n\n",DVDCOMUM-=0.4*DVDCOMUM); else if(dia==5 && tipoDVD == 2) printf(" O preo da locao para dia de quinta, dvd lancamento de : %.2fR$\n\n", DVDLANCAMENTO-=0.4*DVDCOMUM);else if(dia==4 && tipoDVD == 1) printf(" O preo da locao para dia de quarta, dvd normal de : %.2fR$\n\n",DVDCOMUM) ; else if(dia==4 && tipoDVD == 2) printf(" O preo da locao para dia de quarta, dvd lanamento de: %.2fR$\n\n",DVDLANCAMENTO) ; else if(dia==6 && tipoDVD == 1) printf(" O preo da locao para dia de sexta, dvd normal de : %.2fR$\n\n",DVDCOMUM) ; else if(dia==6 && tipoDVD == 2) printf(" O preo da locao para dia de sexta, dvd lanamento de: %.2fR$\n\n",DVDLANCAMENTO) ; else if (dia==7 && tipoDVD == 1) printf(" O preo da locao para dia de sbado, dvd normal de : %.2fR$\n\n",DVDCOMUM) ; else if(dia==7 && tipoDVD == 2) printf(" O preo da locao para dia de sbado, dvd lanamento de: %.2fR$\n\n",DVDLANCAMENTO) ; else if(dia==1 && tipoDVD == 1) printf(" O preo da locao para dia de domingo, dvd normal de : %.2fR$\n\n",DVDCOMUM) ; else if(dia==1 && tipoDVD == 2) printf(" O preo da locao para dia de domingo, dvd lanamento de: %.2fR$\n\n",DVDLANCAMENTO) ; system("pause") ; }
C
/* Scrivere un programma C “scrivi.c” che utilizzando la funzione primitiva “write”, scriva in un file “alfabeto.txt” la seguente stringa di caratteri: “ABCDEFGHILMNOPQRSTUVZ” */ #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <string.h> #include <unistd.h> int main(int argc, char const *argv[]){ char *nomefile = "alfabeto.txt"; unlink(nomefile); int fd = open(nomefile, O_CREAT | O_TRUNC | O_WRONLY, 777); if(fd > 0){ char *stringa = "ABCDEFGHILMNOPQRSTUVZ"; int bytesWritten = write(fd,stringa,strlen(stringa)); printf("Scritti %d bytes\n", bytesWritten ); } close(fd); return 0; }
C
#include "sortingMethods.h" void mergeSort(int input_arr[], int arr_size); /* Function to print an array */ void printArray(int arr[], int size) { int i; printf("["); for (i=0; i < size; i++) printf("%d ", arr[i]); printf("]\n"); } // A utility function to swap two elements void swap(int* a, int* b) { int t = *a; *a = *b; *b = t; } void mergeSort(int input_arr[], int arr_size){ int i, j, currentValue, leftIndex = 0; for(i=1; i<arr_size; i++){ currentValue = input_arr[i]; leftIndex = i-1; while(leftIndex > 0 && currentValue < input_arr[leftIndex]){ input_arr[leftIndex+1] = input_arr[leftIndex]; leftIndex--; } input_arr[leftIndex+1] = currentValue; } } int main(void){ int arr_size = 7; int input_arr[7] = {10,40,80,70,50,20,15}; printArray(input_arr, arr_size); mergeSort(input_arr, arr_size); printArray(input_arr, arr_size); return 0; }
C
/*#include <stdio.h> #include <stdlib.h> #define MAX_SIZE 10 int main() { int arr[MAX_SIZE] = { 69, 10, 30, 2, 16, 8, 31, 22, 13, 31 }; int temp, key, j; printf(" : "); for (int k = 0; k < MAX_SIZE; k++) { printf("%d ", arr[k]); } printf("\n"); printf("<<<<< >>>>> \n"); for (int i = 0; i < MAX_SIZE; i++) { key = arr[i]; j = i - 1; if (j >= 0 && key < arr[j]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } for (int parkmin = 0; parkmin < MAX_SIZE; parkmin++) { printf("%d ", arr[parkmin]); } } for (int parkmin = 0; parkmin < MAX_SIZE; parkmin++) { printf("%d ", arr[parkmin]); } system("pause"); return 0; }*/
C
/* Print the context information of FILENAME, and return true iff the context could not be obtained. */ static bool ATTRIBUTE_WARN_UNUSED_RESULT out_file_context (char *pformat, size_t prefix_len, char const *filename) { char *scontext; bool fail = false; if ((follow_links ? getfilecon (filename, &scontext) : lgetfilecon (filename, &scontext)) < 0) { error (0, errno, _("failed to get security context of %s"), quote (filename)); scontext = NULL; fail = true; } strcpy (pformat + prefix_len, "s"); printf (pformat, (scontext ? scontext : "?")); if (scontext) freecon (scontext); return fail; }
C
#define _CRT_SECURE_NO_WARNINGS 1 float a = 12.5 ᱨ12.5Ĭdoubleͣ float a = 12.5f long a = 10L дΪ10l ############################################################################### 2019 - 10 - 9 shift + Ҽ 㿪powershellڱ ջȽ 쳣ʱ쳣 ʱ쳣 ע⣺쳣ʱ򽫲ִСͣmain 쳣ϸ / ĸһΪ0ᷢ쳣 %: ԶС 10.0%1.5 1.0 ԶԸ ++ int a = 10; a = a++; System.out.println(a); //10 //οࣺjavap -c Test(˾ῼ) &&߼룺 ʽ1 && ʽ2 ע⣺ʽboolean || ߼ ߼ǣ !ʽ ʽΪboolean ·ԣ System.out.println(10 > 20 && 10 / 0 == 0); // ӡ falseʽ2ִ System.out.println(10 < 20 || 10 / 0 == 0); // ӡ truʽ2ִ λ & | ߵıʽboolean͵Ļõͬ&& || ûж· λ&ͬΪ1Ϊ1Ϊ0 λ | ֻҪһΪ1Ϊ1 λ^ͬΪ0һΪ1 λȡ~0Ϊ11Ϊ0 λ >> :ƣ൱ڳ << : ƣ൱ڳ˷ >> >:޷ƣܷλǼͨͨ0 : nѸΪԭ8 ע ĵעͣһǰ߷ǰ棬˵Ĺ /** */ עͣ /* */ עͣ// javaĸʽҪд if (a > 10) { } else if { } ⣺switch(Щͣ ԣbyte char short int String ö ԣlong float double boolean
C
#include <p18cxxx.h> #include <delays.h> #include <sw_i2c.h> far unsigned char I2C_BUFFER; // temp buffer for R/W operations far unsigned char BIT_COUNTER; // temp bufffer for bit counting /******************************************************************** * Function Name: unsigned int SWReadI2C(void) * * Return Value: data byte or error condition * * Parameters: void * * Description: Read single byte from I2C bus. * ********************************************************************/ signed int SWReadI2C( void ) { BIT_COUNTER = 8; // set bit count for byte SCLK_LAT = 0; // set clock pin latch to 0 do { CLOCK_LOW; // set clock pin output to drive low DATA_HI; // release data line to float high Delay10TCY(); // user may need to modify based on Fosc CLOCK_HI; // release clock line to float high Delay1TCY(); // user may need to modify based on Fosc Delay1TCY(); if ( !SCLK_PIN ) // test for clock low { if ( Clock_test( ) ) // clock wait routine { return ( -2 ); // return with error condition } } I2C_BUFFER <<= 1; // shift composed byte by 1 I2C_BUFFER &= 0xFE; // clear bit 0 if ( DATA_PIN ) // is data line high I2C_BUFFER |= 0x01; // set bit 0 to logic 1 } while ( --BIT_COUNTER ); // stay until 8 bits have been acquired return ( (unsigned int) I2C_BUFFER ); // return with data }
C
#include <stdio.h> void selection_sort(int a[], int n) { int i, j, k; for (i = 0; i < n - 1; i++) { k = i; for (j = i + 1; j < n; j++) { if (a[k] > a[j]) k = j; } if (k != i) { int tmp = a[i]; a[i] = a[k]; a[k] = tmp; } } }
C
/*******************************************************************/ /* slibtool: a skinny libtool implementation, written in C */ /* Copyright (C) 2016--2021 SysDeer Technologies, LLC */ /* Released under the Standard MIT License; see COPYING.SLIBTOOL. */ /*******************************************************************/ #include <stdio.h> #include <limits.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #include <sys/wait.h> #include <slibtool/slibtool.h> #include "slibtool_spawn_impl.h" static void slbt_dump_machine_child( char * program, int fd[2]) { char * compiler; char * argv[3]; close(fd[0]); if ((compiler = strrchr(program,'/'))) compiler++; else compiler = program; argv[0] = compiler; argv[1] = "-dumpmachine"; argv[2] = 0; if ((fd[0] = openat(AT_FDCWD,"/dev/null",O_RDONLY,0)) >= 0) if (dup2(fd[0],0) == 0) if (dup2(fd[1],1) == 1) execvp(program,argv); _exit(EXIT_FAILURE); } int slbt_dump_machine( const char * compiler, char * machine, size_t buflen) { ssize_t ret; pid_t pid; pid_t rpid; int code; int fd[2]; char * mark; char program[PATH_MAX]; /* setup */ if (!machine || !buflen || !--buflen) { errno = EINVAL; return -1; } if ((size_t)snprintf(program,sizeof(program),"%s", compiler) >= sizeof(program)) return -1; /* fork */ if (pipe(fd)) return -1; if ((pid = fork()) < 0) { close(fd[0]); close(fd[1]); return -1; } /* child */ if (pid == 0) slbt_dump_machine_child( program, fd); /* parent */ close(fd[1]); mark = machine; for (; buflen; ) { ret = read(fd[0],mark,buflen); while ((ret < 0) && (errno == EINTR)) ret = read(fd[0],mark,buflen); if (ret > 0) { buflen -= ret; mark += ret; } else if (ret == 0) { close(fd[0]); buflen = 0; } else { close(fd[0]); return -1; } } /* execve verification */ rpid = waitpid( pid, &code, 0); if ((rpid != pid) || code) { errno = ESTALE; return -1; } /* newline verification */ if ((mark == machine) || (*--mark != '\n')) { errno = ERANGE; return -1; } *mark = 0; /* portbld <--> unknown synonym? */ if ((mark = strstr(machine,"-portbld-"))) memcpy(mark,"-unknown",8); /* all done */ return 0; }
C
#pragma once #include <Windows.h> typedef struct __uint128 { unsigned __int64 LowPart; unsigned __int64 HighPart; __uint128(__int64 init_x64Var) { this->LowPart = init_x64Var; this->HighPart = NULL; } __uint128& operator=(__uint128 a) { LowPart = a.LowPart; HighPart = a.HighPart; return *(__uint128*)this; } __uint128 operator+(unsigned __int64 a) //limited to 64-Bits { unsigned __int64 bitmask2; unsigned __int64 bitmask1; bitmask1 = bitmask2 = NULL; unsigned __int64 one = 1; //compiler converts that to a 32bit limited o.O BYTE uebertrag = 0; for (DWORD i = 0; i < 64; i++) { bitmask1 = one << i; BYTE AddBitBit = (a & bitmask1)==bitmask1; BYTE CurrentBit = (LowPart & bitmask1)==bitmask1; BYTE NewBit = CurrentBit + AddBitBit + uebertrag; if ( NewBit == 1 ) { uebertrag = 0; } else if ( NewBit == 2 ) { NewBit = 0; uebertrag = 1; } else if ( NewBit == 3 ) { NewBit = 1; uebertrag = 1; } else //error uebertrag = 0; if ( CurrentBit != NewBit ) { LowPart = LowPart ^ bitmask1; } } for (DWORD i = 0; i < 64; i++) { bitmask1 = one << i; BYTE CurrentBit = (HighPart & bitmask1)==bitmask1; BYTE NewBit = CurrentBit + uebertrag; if ( NewBit == 1 ) { uebertrag = 0; } else if ( NewBit == 2 ) { NewBit = 0; uebertrag = 1; } else if ( NewBit == 3 ) { NewBit = 1; uebertrag = 1; } else //error uebertrag = 0; if ( CurrentBit != NewBit ) { HighPart = HighPart ^ bitmask1; } } return *this; } __uint128 operator+=(unsigned __int64 a) { *(__uint128*)this = *(__uint128*)this + a; return *(__uint128*)this; } __uint128 operator-(unsigned __int64 a) //limited to 64-Bits { unsigned __int64 bitmask1; bitmask1 = NULL; unsigned __int64 one = 1; //compiler converts that to a 32bit limited o.O BYTE uebertrag = 0; for (DWORD i = 0; i < 64; i++) { bitmask1 = one << i; BYTE SubBitBit = (a & bitmask1)==bitmask1; BYTE CurrentBit = (LowPart & bitmask1)==bitmask1; BYTE NewBit = CurrentBit; if ( uebertrag == 1 ) //first the "übertrag" { if ( NewBit == 1 ) { NewBit = 0; uebertrag = 0; } else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( SubBitBit == 1 ) //then take care about the actual sub bit { if ( NewBit == 1 ) NewBit = 0; else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( CurrentBit != NewBit ) { LowPart = LowPart ^ bitmask1; } } for (DWORD i = 0; i < 64; i++) { bitmask1 = one << i; BYTE CurrentBit = (HighPart & bitmask1)==bitmask1; BYTE NewBit = CurrentBit; if ( uebertrag == 1 ) //first the "übertrag" { if ( NewBit == 1 ) { NewBit = 0; uebertrag = 0; } else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( CurrentBit != NewBit ) { HighPart = HighPart ^ bitmask1; } } return *this; } __uint128 operator-=(unsigned __int64 a) { *(__uint128*)this = *(__uint128*)this - a; return *(__uint128*)this; } __uint128 operator-(__uint128 a) { unsigned __int64 bitmask; bitmask = NULL; unsigned __int64 one = 1; //compiler converts that to a 32bit limited o.O BYTE uebertrag = 0; for (DWORD i = 0; i < 64; i++) { bitmask = one << i; BYTE SubBitBit = (a.LowPart & bitmask)==bitmask; BYTE CurrentBit = (LowPart & bitmask)==bitmask; BYTE NewBit = CurrentBit; if ( uebertrag == 1 ) //first the "übertrag" { if ( NewBit == 1 ) { NewBit = 0; uebertrag = 0; } else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( SubBitBit == 1 ) //then take care about the actual sub bit { if ( NewBit == 1 ) NewBit = 0; else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( CurrentBit != NewBit ) { LowPart = LowPart ^ bitmask; } } for (DWORD i = 0; i < 64; i++) { bitmask = one << i; BYTE SubBitBit = (a.HighPart & bitmask)==bitmask; BYTE CurrentBit = (HighPart & bitmask)==bitmask; BYTE NewBit = CurrentBit; if ( uebertrag == 1 ) //first the "übertrag" { if ( NewBit == 1 ) { NewBit = 0; uebertrag = 0; } else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( SubBitBit == 1 ) //then take care about the actual sub bit { if ( NewBit == 1 ) NewBit = 0; else if ( NewBit == 0 ) { NewBit = 1; uebertrag = 1; } } if ( CurrentBit != NewBit ) { HighPart = HighPart ^ bitmask; } } return *(__uint128*)this; } __uint128 operator-=(__uint128 a) { *(__uint128*)this = *(__uint128*)this - a; return *(__uint128*)this; } __uint128 operator+(__uint128 a) { unsigned __int64 bitmask; bitmask = NULL; unsigned __int64 one = 1; //compiler converts that to a 32bit limited o.O BYTE uebertrag = 0; for (DWORD i = 0; i < 64; i++) { bitmask = one << i; BYTE AddBitBit = (a.LowPart & bitmask)==bitmask; BYTE CurrentBit = (LowPart & bitmask)==bitmask; BYTE NewBit = CurrentBit + AddBitBit + uebertrag; if ( NewBit == 1 ) { uebertrag = 0; } else if ( NewBit == 2 ) { NewBit = 0; uebertrag = 1; } else if ( NewBit == 3 ) { NewBit = 1; uebertrag = 1; } else //error uebertrag = 0; if ( CurrentBit != NewBit ) { LowPart = LowPart ^ bitmask; } } for (DWORD i = 0; i < 64; i++) { bitmask = one << i; BYTE AddBitBit = (a.HighPart & bitmask)==bitmask; BYTE CurrentBit = (HighPart & bitmask)==bitmask; BYTE NewBit = CurrentBit + AddBitBit + uebertrag; if ( NewBit == 1 ) { uebertrag = 0; } else if ( NewBit == 2 ) { NewBit = 0; uebertrag = 1; } else if ( NewBit == 3 ) { NewBit = 1; uebertrag = 1; } else //error uebertrag = 0; if ( CurrentBit != NewBit ) { HighPart = HighPart ^ bitmask; } } return *this; } __uint128 operator+=(__uint128 a) { *(__uint128*)this = *(__uint128*)this - a; return *(__uint128*)this; } bool operator==(__uint128 a) { if ( this->LowPart == a.LowPart && this->HighPart == a.HighPart ) return true; return false; } bool operator==(unsigned __int64 a) { if ( this->LowPart == a && this->HighPart == NULL ) return true; return false; } bool operator!=(__uint128 a) { if ( this->LowPart != a.LowPart && this->HighPart != a.HighPart ) return true; return false; } DWORD BitsToHex( char* pOutString, bool bDontShowZerosBeforeNumber = true, bool Lower = false ); DWORD BitsToString( char* pOutString ); } UInt128;
C
#include <R.h> #include <Rdefines.h> #include "SynExtend.h" /* * Author: Aidan Lakshman * Contact: [email protected] * * This is a set of C functions that apply an R function to all internal * nodes of a dendrogram object. This implementation runs roughly 2x * faster than base `stats::dendrapply`, and deals with dendrograms * with high numbers of internal branches. Notably, this implementation * unrolls the recursion to prevent any possible stack overflow errors. * */ /* * Linked list struct * * Each node of the tree is added with the following args: * - node: tree node, as a pointer to SEXPREC object * - v: location in parent node's list * - isLeaf: Counter encoding unmerged children. 0 if leaf or leaf-like subtree. * - origLength: original length of the node before applying function * - parent: pointer to node holding the parent node in the tree * - next: next linked list element * */ typedef struct ll_S_dendrapply { SEXP node; int v; unsigned int remove : 1; signed int isLeaf : 7; unsigned int origLength; struct ll_S_dendrapply *parent; struct ll_S_dendrapply *next; } ll_S_dendrapply; /* Global variable for on.exit() free */ ll_S_dendrapply *dendrapply_ll; static SEXP leafSymbol; static PROTECT_INDEX headprot; /* * Frees the global linked list structure. * * Called using on.exit() in R for cases where * execution is stopped early. */ void free_dendrapply_list(){ ll_S_dendrapply *ptr = dendrapply_ll; while(dendrapply_ll){ dendrapply_ll = dendrapply_ll->next; free(ptr); ptr=dendrapply_ll; } return; } /* Function to allocate a LL node */ ll_S_dendrapply* alloc_link(ll_S_dendrapply* parentlink, SEXP node, int i, short travtype){ ll_S_dendrapply *link = malloc(sizeof(ll_S_dendrapply)); SEXP ls; if(travtype == 0){ link->node = NULL; link->isLeaf = -1; link->origLength = 0; } else if (travtype == 1){ SEXP curnode; curnode = VECTOR_ELT(node, i); link->node = curnode; ls = getAttrib(curnode, leafSymbol); link->isLeaf = (isNull(ls) || (!LOGICAL(ls)[0]) )? length(curnode) : 0; link->origLength = link->isLeaf; } link->next = NULL; link->v = i; link->parent = parentlink; link->remove = 0; return link; } /* * Main workhorse function. * * This function traverses the tree according to the traversal style * specified, applying the R function as necessary. R ensures that the * dendrogram isn't a leaf, so this function assmes the dendrogram has * at least two members. */ SEXP new_apply_dend_func(ll_S_dendrapply *head, SEXP f, SEXP env, short travtype){ ll_S_dendrapply *ptr, *prev, *parent; SEXP node, call, newnode, leafVal; if(travtype == 0){ call = PROTECT(lang2(f, head->node)); REPROTECT(head->node = R_forceAndCall(call, 1, env), headprot); UNPROTECT(1); } int n, nv; ptr = head; prev = head; while(ptr){ R_CheckUserInterrupt(); /* lazily populate node, apply function to it as well */ if (travtype==0 && ptr->isLeaf==-1){ parent = ptr->parent; newnode = VECTOR_ELT(parent->node, ptr->v); leafVal = getAttrib(newnode, leafSymbol); ptr->isLeaf = (isNull(leafVal) || (!LOGICAL(leafVal)[0])) ? length(newnode) : 0; ptr->origLength = ptr->isLeaf; call = PROTECT(lang2(f, newnode)); newnode = PROTECT(R_forceAndCall(call, 1, env)); n = length(ptr->parent->node); nv = ptr->v; while(nv < n){ /* trying to replicate a weird stats::dendrapply quirk */ SET_VECTOR_ELT(parent->node, nv, newnode); nv += ptr->parent->origLength; } UNPROTECT(2); /* double ELT because it avoids a protect */ ptr->node = VECTOR_ELT(parent->node, ptr->v); } if (ptr->remove){ /* these are nodes flagged for deletion */ prev->next = prev->next->next; free(ptr); ptr = prev->next; } else if(ptr->isLeaf == 0){ /* * If the LL node is a leaf or completely merged subtree, * apply the function to it and then merge it upwards */ while(ptr->isLeaf == 0 && ptr != head){ /* * merge upwards, * protection unneeded since parent already protected */ prev = ptr->parent; if(travtype == 0){ SET_VECTOR_ELT(prev->node, ptr->v, ptr->node); } else if(travtype == 1){ call = PROTECT(LCONS(f, LCONS(ptr->node, R_NilValue))); newnode = PROTECT(R_forceAndCall(call, 1, env)); prev = ptr->parent; SET_VECTOR_ELT(prev->node, ptr->v, newnode); UNPROTECT(2); } prev->isLeaf -= 1; /* flag node for deletion later */ ptr->remove = 1; ptr = prev; prev = ptr; R_CheckUserInterrupt(); } /* go to the next element so we don't re-add */ ptr = ptr->next; } else { /* ptr->isLeaf != 0, so we need to add nodes */ node = ptr->node; n = ptr->origLength; leafVal = getAttrib(node, leafSymbol); if(isNull(leafVal) || (!LOGICAL(leafVal)[0])){ ll_S_dendrapply *newlink; /* * iterating from end to beginning to ensure * we traverse depth-first instead of breadth */ for(int i=n-1; i>=0; i--){ newlink = alloc_link(ptr, node, i, travtype); newlink->next = ptr->next; ptr->next = newlink; } } prev = ptr; ptr = ptr->next; } } if (travtype == 1){ call = PROTECT(lang2(f, head->node)); REPROTECT(head->node = R_forceAndCall(call, 1, env), headprot); UNPROTECT(1); } return head->node; } /* * Main Function * * Calls helper functions to build linked list, * apply function to all nodes, and reconstruct * the dendrogram object. Attempts to free the linked list * at termination, but note memory free not guaranteed to * execute here due to R interrupts. on.exit() used in R to * account for this. */ SEXP do_dendrapply(SEXP tree, SEXP fn, SEXP env, SEXP order){ /* 0 for preorder, 1 for postorder */ leafSymbol = install("leaf"); short travtype = INTEGER(order)[0]; SEXP treecopy; PROTECT_WITH_INDEX(treecopy = duplicate(tree), &headprot); /* Add the top of the tree into the list */ dendrapply_ll = malloc(sizeof(ll_S_dendrapply)); dendrapply_ll->node = treecopy; dendrapply_ll->next = NULL; dendrapply_ll->parent = NULL; dendrapply_ll->isLeaf = length(treecopy); dendrapply_ll->origLength = dendrapply_ll->isLeaf; dendrapply_ll->v = -1; dendrapply_ll->remove = 0; /* Apply the function to the list */ treecopy = new_apply_dend_func(dendrapply_ll, fn, env, travtype); /* Attempt to free the linked list and unprotect */ free_dendrapply_list(); UNPROTECT(1); return treecopy; }
C
#include "pocklington.h" #define LIMIT sizeof(primes) / sizeof(unsigned int) //Tableau de nombres premiers pour la recherche de a const unsigned int primes[] = { 2,3,5,7,11,13,17,19,23,29, 31,37,41,43,47,53,59,61,67,71, 73,79,83,89,97,101,103,107,109,113, 127,131,137,139,149,151,157,163,167,173, 179,181,191,193,197,199,211,223,227,229, 233,239,241,251,257,263,269,271,277,281, 283,293,307,311,313,317,331,337,347,349, 353,359,367,373,379,383,389,397,401,409, 419,421,431,433,439,443,449,457,461,463, 467,479,487,491,499,503,509,521,523,541, 547,557,563,569,571,577,587,593,599,601, 607,613,617,619,631,641,643,647,653,659, 661,673,677,683,691,701,709,719,727,733, 739,743,751,757,761,769,773,787,797,809, 811,821,823,827,829,839,853,857,859,863, 877,881,883,887,907,911,919,929,937,941, 947,953,967,971,977,983,991,997, }; /* * Test de primalité de Pocklington * On teste si n est premier * avec f une liste de facteurs premiers de n-1 */ int pocklington(mpz_t n, facteursPremiers *f) { mpz_t n_; //n-1 mpz_t a, q, tmp; int i, i_min, j, res; res = -1; mpz_init(n_); mpz_init(a); mpz_init(q); mpz_init(tmp); //n_ = n-1 mpz_set(n_, n); mpz_sub_ui(n_, n_, 1); //Il faut que q > sqrt(n)-1 mpz_sqrt(tmp, n); mpz_sub_ui(tmp, tmp, 1); i_min = 0; for (i = 0; i < f->longueur; i++) { if (mpz_cmp(tmp, f->facteurs[i]) < 0) { i_min = i; break; } } for (j = 0; j < LIMIT; j++) { mpz_set_ui(a, primes[j]); //On verifie si a = n (si oui, n est premier) if (mpz_cmp(n, a) == 0) { printf("n = a = %i\n", primes[j]); res = 2; break; } //On verifie si a|n (si oui, n n'est pas premier) if (mpz_divisible_p(n, a)) { printf("a = %i divise n\n", primes[j]); res = 0; break; } //Test de Fermat entre a et n (si non, n n'est pas premier) mpz_powm(tmp, a, n_, n); //tmp = a^(n-1) mod n if (mpz_cmp_ui(tmp, 1) != 0) { printf("Echec du test de Fermat : a = %i et n ne sont pas premier entre eux.\n", primes[j]); res = 0; break; } for (i = i_min; i < f->longueur; i++) { mpz_set(q, f->facteurs[i]); //On verifie si pgcd(a^((n-1)/q)-1, n) = 1 (si oui, n est premier) mpz_divexact(tmp, n_, q); mpz_powm(tmp, a, tmp, n); mpz_sub_ui(tmp, tmp, 1); mpz_gcd(tmp, tmp, n); if (mpz_cmp_ui(tmp, 1) != 0) { if (mpz_cmp(tmp, n) < 0) { printf("Echec du test de Pocklington\n"); res = 0; break; } } else { gmp_printf("Succes du test de Pocklington : q = %Zd, a = %i\n", f->facteurs[i], primes[j]); res = 2; break; } } if (res != -1) { break; } } if (res == -1) { printf("La primalité est indécidée.\n"); res = 1; } mpz_clear(n_); mpz_clear(a); mpz_clear(q); mpz_clear(tmp); clearFacteursPremiers(*f); return res; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int par(int a[],int low,int heigh) { int i = low; int j = heigh; int temp = a[i]; while(i < j) { while(j > i && a[j] >= temp) j--; a[i] = a[j]; while(i < j && a[i] < temp) i++; a[j] = a[i]; } a[i] = temp; return i; } void quickSort(int a[],int low,int heigh) { if(low >= heigh) return; int mid; mid = par(a,low,heigh); quickSort(a,low,mid-1); quickSort(a,mid+1,heigh); } int main(int argc, char* argv[]) { int arr[100] = {8,9,3,5,12,78,1,2,905,1,7,8,9,3,2,1,4,5,6,7,0}; int i; int n = 20; quickSort(arr,0,n-1); for(i =0; i < n; i++) printf("%d%c",arr[i],i == n-1 ? '\n' : ' '); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> long long findNb(long long volume) { int length = 0; while (volume >= 0) { if (volume == 0) { return length; } length++; volume -= pow(length, 3); } return -1; }
C
/* INPUT FORMAT: 3 <- The number of students Joe Math990112 89 <- Name IDNumber Grades apiece listed Mike CS991301 100 Mary EE990830 95 OUTPUT FORMAT: Mike CS991301 Joe Math990112 */ #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_SIZE 200 // When the MAX_SIZE was changed from 100 to 200, there is no more segfault typedef struct StudentInfo // Define a data structure of student: name, id number and grades { char name[11]; char idnum[11]; int grades; }StudInfo; void get_info(StudInfo *grades_list, int stud_num); // To get information from input infos void Sort(StudInfo *grades_list, int len); // Bubble sort the sequence of the array of Student struct adhering to their grades void PrintMaxAndMin(StudInfo *grades_list, int end);// To print out the information of the students with the maximum grades and minimum grades //void PrintAll(StudInfo *grades_list, int stud_num); int unused __attribute__((unused)); // Under this code, the compiler using gcc will not display warning info about 'Ignoring return value of scanf' int main(int argc, char *argv[]) { int stud_num; StudInfo grades_list[MAX_SIZE]; unused = scanf("%d", &stud_num); // To get how many numbers of the information of Students are gonna be displayed get_info(grades_list, stud_num); Sort(grades_list, stud_num); //PrintAll(grades_list, stud_num); PrintMaxAndMin(grades_list, stud_num); return 0; } void get_info(StudInfo *grades_list, int stud_num) { int i; for (i = 0; i < stud_num; i++) { unused = scanf("%s%s%d", grades_list[i].name, grades_list[i].idnum, &grades_list[i].grades); } } void Sort(StudInfo *grades_list, int len) { int i, j; for (i = 0; i < len - 1; i++) { for (j = 0; j < len -i -1; j++) { if ( grades_list[j].grades < grades_list[j + 1].grades ) { StudInfo temp = grades_list[j]; grades_list[j] = grades_list[j + 1]; grades_list[j + 1] = temp; } } } } void PrintMaxAndMin(StudInfo *grades_list, int end) { printf("%s %s\n", grades_list[0].name, grades_list[0].idnum); printf("%s %s\n", grades_list[end - 1].name, grades_list[end - 1].idnum); } void PrintAll(StudInfo *grades_list, int stud_num) { int i; for (i = 0; i < stud_num; i++) { printf("%s %s %d\n", grades_list[i].name, grades_list[i].idnum, grades_list[i].grades); } }
C
#include <stdlib.h> #include <stdio.h> #include <strings.h> #include <sys/timeb.h> #include "library.h" void random_array(char *array, long bytes){ for (int i = 0; i < bytes; i++){ array[i] = 'A' + (rand() % 26); } } int get_histogram(FILE *file_ptr, long hist[], int block_size, long *milliseconds, long *total_bytes_read){ if (file_ptr){ for (int i = 0; i < 26; i++){ hist[i] = 0; } char buf[block_size]; int index; *total_bytes_read = 0; *milliseconds = 0; struct timeb start_time; struct timeb end_time; while(!feof(file_ptr)){ ftime(&start_time); bzero(buf, block_size); fread(buf, 1, block_size, file_ptr); ftime(&end_time); *milliseconds += (end_time.time * 1000 + end_time.millitm) - (start_time.time * 1000 + start_time.millitm); for (long i = 0; i < block_size; i++){ index = buf[i] - 'A'; if (index >= 0 && index < 26){ (*total_bytes_read)++; hist[index]++; } } } return 0; }else{ return -1; } }
C
#include "monty.h" /** * get_op_func - function to select correct operation function * @token1: 1st bytecode input (opcode) * Return: pointer to correct operation function */ void (*get_op_func(char *token1))(stack_t **stack, unsigned int line_number) { instruction_t instruction_s[] = { {"pop", pop}, {"pall", pall}, {"pint", pint}, {"swap", swap}, {"add", _add}, {"sub", _sub}, {"mul", _mul}, {"div", _div}, {"mod", _mod}, {"pchar", pchar}, {"pstr", pstr}, {"nop", nop}, {"rotl", rotl}, {"rotr", rotr}, {NULL, NULL} }; int i = 0; while (instruction_s[i].f != NULL) { if (strcmp(token1, instruction_s[i].opcode) == 0) return (instruction_s[i].f); i++; } return (NULL); }
C
#include<stdio.h> int main() { int ddoDDo = 70; int ggoGGo = 30; int exchange; int haveMoney = 1000; int a = ddoDDo * 2; int b = ggoGGo * 3; int num500, num100, num50, num10, temp; printf("ǶǸ ü ݾ : %d\n", a); printf("Dzǹ ü ݾ : %d\n", b); exchange = haveMoney - a - b; printf("Ž : %d\n", exchange); printf("Ž ּ ...\n"); num500 = exchange / 500; temp = exchange % 500; num100 = temp / 100; temp = temp % 100; num50 = temp / 50; temp = temp % 50; num10 = temp / 10; printf("500 %d, 100 %d, 50 %d, 10 %d\n", num500, num100, num50, num10); return 0; }
C
#include "pair.h" #include <stdio.h> #include <stdlib.h> typedef struct E { int key, value; } E; typedef struct R { int sum, a, b; } R; static int cmpE(const void *x, const void *y) { E *a = (E *) x, *b = (E *) y; if (a->key < b->key) return -1; if (a->key > b->key) return 1; if (a->value < b->value) return -1; if (a->value > b->value) return 1; return 0; } static int cmpR(const void *x, const void *y) { R *a = (R *) x, *b = (R *) y; #ifdef INC if (a->sum < b->sum) return -1; if (a->sum > b->sum) return 1; if (a->a < b->a) return -1; if (a->a > b->a) return 1; if (a->b < b->b) return -1; if (a->b > b->b) return 1; #else if (a->sum > b->sum) return -1; if (a->sum < b->sum) return 1; if (a->a > b->a) return -1; if (a->a < b->a) return 1; if (a->b > b->b) return -1; if (a->b < b->b) return 1; #endif return 0; } void pairPrint(int A[], int n) { E *e = (E*) malloc(sizeof(E) * n); R *r = (R*) malloc(sizeof(R) * n/2); for (int i = 0; i < n; i++) e[i].key = A[i], e[i].value = i; qsort(e, n, sizeof(E), cmpE); int m = 0; for (int i = 0, j = n-1; i < j; i++, j--) { r[m].sum = e[i].key + e[j].key; r[m].a = e[i].value, r[m].b = e[j].value; if (r[m].a > r[m].b) { int t = r[m].a; r[m].a = r[m].b; r[m].b = t; } m++; } qsort(r, m, sizeof(R), cmpR); for (int i = 0; i < m; i++) { #ifdef INC printf("%d = numbers[%d] + numbers[%d]\n", r[i].sum, r[i].a, r[i].b); #else printf("%d = numbers[%d] + numbers[%d]\n", r[i].sum, r[i].b, r[i].a); #endif } }
C
#include "gdb.h" #include <stdio.h> void insert_breakpoint(t_env *e) { t_node_break *curr = e->lst_break.begin; while(curr) { long tmp = ptrace(PTRACE_PEEKDATA, e->child, curr->addr, NULL); curr->opcode = tmp & 0b11111111; // printf("opcode -> 0x%x at addr -> 0x%lx\n", curr->opcode, curr->addr); tmp = tmp - (tmp & 0b11111111) + 0xcc; // printf("opcode -> 0x%lx\n", tmp); ptrace(PTRACE_POKEDATA, e->child, curr->addr, tmp); curr = curr->next; } } void do_father(t_env *e) { int status; // long tmp; waitpid(e->child, &status, WUNTRACED); if (!WIFSTOPPED(status)) exit(-1); ptrace(PTRACE_SEIZE, e->child, 0, 0); ptrace(PTRACE_SETOPTIONS, e->child, 0, PTRACE_O_TRACEEXEC); wait_event(e, &status); e->is_running = 1; insert_breakpoint(e); wait_event(e, &status); } void do_child(char **argv) { kill(getpid(), SIGSTOP); execvp(argv[0], argv); int error = errno; perror("execvp"); exit(error); } int start_trace(char **argv, t_env *e) { e->child = fork(); if (e->child < 0) { int error = errno; perror("fork"); return error; } else if (!e->child) do_child(argv); else do_father(e); return 0; } void gdb(char **argv) { int ret; t_env e; line_editor_init(); load_sym(argv[0], &e); e.is_running = 0; bzero(&e.lst_break, sizeof(t_lst_break)); while (1) { char *line = get_line().line; printf("\n"); if (!strcmp(line, "r")) ret = start_trace(argv, &e); else if (!strcmp(line, "q")) break; else if (!strcmp(line, "bt")) back_trace(&e); else if (!strncmp(line, "b ", 2)) breakpoint(&e, line + 2); else if (!strcmp(line, "c")) cont(&e); } line_editor_end(); exit(ret); }
C
//airplane queue #include<stdio.h> #include<stdlib.h> #include<string.h> #define N 4 int rear=-1; int front=-1; struct plane { char name[10]; }; struct plane arr[N-1]; int isempty() { if(rear==-1 && front==-1) return 1; else return 0; } int isfull() { if((rear+1)%N==front) return 1; else return 0; } void enqueue(char n[]) { if(isfull()) { printf("The RunWay is full\n"); return; } if(front==-1 && rear==-1) { front=front+1; rear=rear+1; } else rear=(rear+1)%N; strcpy(arr[rear].name,n); printf("The airplane to %s is on the runway\n",arr[rear].name); return; } void dequeue() { if(isempty()) { printf("No Airplane on the runway\n"); return; } if(front==rear) { printf("The airplane to %s has successfully taken off\n",arr[front].name); front=-1; rear=-1; return; } printf("The airplane to %s has successfully taken off\n",arr[front].name); front=(front+1)%N; return; } void display() { int f,r,c=0; f=front; r=rear; if(isempty()) { printf("No Airplane on the runway\n"); return; } if(front==rear && !isempty()) { puts(arr[rear].name); return; } while(f!=(r+1)%N || isfull() && c<4) { puts(arr[f].name); f=(f+1)%N; c++; } return; } void main() { int option; char nam[10]; while(1) { printf("Select an operation\n"); printf(".........MENU..........\n"); printf("1.Open Runway(ENQUEUE)\n2.Take Off(DEQUEUE)\n3.Display\n4.EXIT\n\n"); scanf("%d",&option); switch(option) { case 1: printf("Enter the name of route of AIRPLANE\n"); scanf("%s",nam); enqueue(nam); break; case 2: dequeue(); break; case 3: display(); break; case 4: return; default: printf("Operation Failed\nPlease Try again\n\n"); break; } } }
C
#include <signal.h> #include <stdio.h> #include <unistd.h> void hand(int signum){ signal(SIGINT, SIG_DFL); printf("press again ctrl + c\n"); } struct sigaction action; int main(){ action.sa_handler = SIG_IGN; sigaction(SIGINT, &action, NULL); sigaction(SIGQUIT, &action, NULL); printf("ignoring (SIGINT, SIGQUIT)\n"); sleep(5); action.sa_handler = SIG_DFL; sigaction(SIGINT, &action, NULL); sigaction(SIGQUIT, &action, NULL); printf("restore (SIGINT, SIGQUIT)\n"); sleep(5); return 0; }
C
/* ============================================================================ Name : Tp_[1].c Author : Molinari German Description : Calculadora ============================================================================ */ #include <stdio.h> #include <stdlib.h> #include "bibliotecaTp1.h" int main(void) { setbuf(stdout,NULL); char seguir = 's'; int a=0; int b=0; int flagOperandoA = 0; int flagOperandoB = 0; int flagCalculos = 0; int DivisionOk = 0; int resultadoSuma; int resultadoResta; int resultadoMultiplicacion; int resultadoFactorial; int resultadoFactorialB; float resultadoDivicion; do { system("cls"); switch(selecionarOpcion(a,b)) { case 1: // ingresa el primer operando a = ingresarOperando(); flagOperandoA = 1; break; case 2: // ingresa el segundo operando b = ingresarOperando(); flagOperandoB = 1; break; case 3: // opera con los operandos if(flagOperandoA == 1 && flagOperandoB ==1) { resultadoSuma = sumarEnteros(a,b); resultadoResta = restarEnteros(a,b); resultadoMultiplicacion = multiplicarEnteros(a,b); DivisionOk = dividirEnteros(a,b,&resultadoDivicion); resultadoFactorial = factoriarNumero(a); resultadoFactorialB = factoriarNumero(b); flagCalculos = 1; } else if(flagOperandoB == 0 && flagOperandoA == 0) { printf("Por favor, ingrese ambos operandos y luego calcule. \n"); system("pause"); } else if(flagOperandoB == 1 && flagOperandoA == 0) { printf("Por favor, ingrese el operando A y luego calcule. \n"); system("pause"); } else { printf("Por favor, ingrese el operando B y luego calcule. \n"); system("pause"); } break; case 4: // muestra los resultados if(flagCalculos == 1) { printf("El resultado de la suma es: %d \n", resultadoSuma); printf("El resultado de la resta es: %d \n", resultadoResta); printf("El resultado de la multiplicacion es: %d \n", resultadoMultiplicacion); if (DivisionOk == 1) { printf("El resultado de la division es: %.2f \n", resultadoDivicion); } else { printf("No se puede dividir por 0. \n"); } printf("El factorial de %d, es: %d y el factorial de %d es : %d\n",a,resultadoFactorial,b,resultadoFactorialB); system("pause"); } else if(flagOperandoB == 0 && flagOperandoA == 0) { printf("Por favor, ingrese ambos operandos y luego calcule. \n"); system("pause"); } else if(flagOperandoB == 1 && flagOperandoA == 0) { printf("Por favor, ingrese el operando A y luego calcule. \n"); system("pause"); } else if(flagOperandoB == 0 && flagOperandoA == 1) { printf("Por favor, ingrese el operando B y luego calcule. \n"); system("pause"); } else { printf("Por favor, calcule antes de mostrar los valores. \n"); system("pause"); } break; case 5: // sale del bucle seguir = 'n'; break; default: printf("Error... seleccione una opcion valida \n" ); system("pause"); break; } } while (seguir == 's'); return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char *argv[]) { char *s1 = "Hello World!\n"; //s1[0] = 'h'; // runtime error; printf(s1); return 0; }
C
#include "../Headers/huff_tree.h" node* create_node() { node* new_node = (node*) malloc(sizeof(node)); new_node->priority = 0; new_node->left = NULL; new_node->right = NULL; new_node->next = NULL ; return new_node; } //PEGA OS 2 CARACTERES DE MENOR FREQUÊNCIA E COLOCA A SOMA DELES NOVAMENTE NA FILA node *create_huff(pq *pq) { node *huff = create_node(); while (pq->size > 1) { node *left = dequeue(pq); //Pega o primeiro elemento da fila que é de menor frequência node *right = dequeue(pq); // || huff = create_huff_node(left, right);//Manda os dois menores para formar um novo nó pai e eles enqueue(pq, huff); // serão folhas } //Coloca em fila a cada parte da árvore até que sobre return pq->head; // somente a raiz } //CONSTRÓI A ÁRVORE COM A SOMA DOS CARACTERES DE MENOR FREQUÊNCIA E OS COLOCA COMO FOLHAS node *create_huff_node(node *left, node *right) { node *huff = (node*) malloc(sizeof(node)); huff->priority = ((int) left->priority) + ((int) right->priority);//Soma dos dois de menor frequência huff->left = left; huff->right = right; huff->charac = '*'; huff->next = NULL; return huff; } //VERIFICA SE A ÁRVORE ESTÁ VAZIA int isEmpty(node *tree) { return (tree == NULL); } //VERIFICA SE O NÓ É UMA FOLHA int isLeaf(node *tree) { return ((tree->left == NULL) && (tree->right == NULL)); } void print_huff_tree(node *node) { if(isEmpty(node)) { printf("()"); return; } else { printf("(%u", node->charac); print_huff_tree(node->left); print_huff_tree(node->right); printf(")"); } } void print_huff_tree_in_file(node *tree, FILE *new_file){ if(!isEmpty(tree)){ if(isLeaf(tree) && (tree->charac == '*' || tree->charac == 92)) { unsigned char c = 92; fputc(c, new_file); } unsigned char byte = tree->charac; fputc(byte, new_file); print_huff_tree_in_file(tree->left, new_file); print_huff_tree_in_file(tree->right, new_file); } }
C
#ifndef _NBL_LEDS_H_ #define _NBL_LEDS_H_ #include "nbd/leds.h" static inline const char * nbl_leds_state_cstr(enum led_state state) { char* ret = NULL; if(state == led_state_off) { ret = "off"; } else if(state == led_state_on) { ret = "on"; } else if(state == led_state_unchanged) { ret = "unchanged"; } else if(state == led_state_toggle) { ret = "toggle"; } else { /* blink status */ if(rand() % 2 == 0) { ret = "on"; } else { ret = "off"; } } return ret; } static inline const char * nbl_leds_brightness_cstr(void) { if (nbd_leds_get_mode() == led_mode_disable ) { return "off"; } else { return "on"; } } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_stacks.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aashara- <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/07/21 13:40:37 by aashara- #+# #+# */ /* Updated: 2020/09/06 10:37:35 by aashara- ### ########.fr */ /* */ /* ************************************************************************** */ #include "checker.h" static void print_head(void) { ft_putstr(" __________________________ \n"); ft_putstr("| | |\n"); ft_putstr("| a | b |\n"); ft_putstr("| | |\n"); ft_putstr("|_____________|____________|\n"); } static void print_nums(t_stack_int *stack_a, t_stack_int *stack_b) { int big_size; t_list_int *head_a; t_list_int *head_b; big_size = ft_max(stack_a->size, stack_b->size) + 1; head_a = stack_a->stack; head_b = stack_b->stack; while (--big_size) { if (head_a) { ft_printf("| {cyan}%-11d{eoc}|", head_a->value); head_a = head_a->next; } else ft_printf("| |"); if (head_b) { ft_printf(" {cyan}%-11d{eoc}|\n", head_b->value); head_b = head_b->next; } else ft_printf(" |\n"); } } void print_stacks(t_stack_int *stack_a, t_stack_int *stack_b) { print_head(); print_nums(stack_a, stack_b); ft_putstr("|_____________|____________|\n"); }
C
#include <include/types.h> #include <include/task.h> #include <include/limits.h> #include <include/string.h> #include <include/system.h> #include <include/stdarg.h> #include <include/io.h> #include <dev/console.h> #include <mm/memory.h> #define _PUSH(esp, value) do{ \ (esp)-=sizeof(u32); \ *(u32*)(esp)=value; \ } while(0) task_struct task_list[MAX_TASK]; /* 任务队列 */ timer_struct timer_list[MAX_TIMER]; /* 定时器队列 */ regs tmp; u32 current=0; /* 当前任务 */ u32 jiffies=0; /* 开机后的滴答数 */ u32 last_task=0; void scheduler(u8 cpl, regs *pregs) { u32 next; /* 先给时间片 */ task_list[current].counter = 1; /* 遍历任务队列,找个可以调度的任务 */ if (current == MAX_TASK-1) next=0; else next = current+1; while (1) { if (task_list[next].counter > 0 && task_list[next].state == TASK_RUNNING) break; if (next == MAX_TASK-1) next=0; else next++; } /* 修改陷阱帧 */ task_list[current].cpl = cpl; memcpy(&task_list[current].t_regs, pregs, sizeof(regs)); memcpy(pregs, &task_list[next].t_regs, sizeof(regs)); current = next; } void timer_handler(u8 cpl, regs *pregs) { ++jiffies; if (3 == cpl) { //对进程进行计时 task_list[current].user_time++; //用户态的执行时间 } else { task_list[current].system_time++; //内核态的执行时间 } //spring_timer(); //触发定时器 if ((--task_list[current].counter) == 0) { //如果时间片被用完则需要进行调度 scheduler(cpl, pregs); return; //need_resched = 1; } else { //如果时间片没有用完则继续执行 return; } if (cpl == 3) { //如果进程在用户态下被中断 //scheduler(); //进行调度 } } void testfun() { int sleep=1000000; while(1) { sleep=1000000; cli(); con_write("2\x06",2); sti(); while (--sleep){}; } } /* 初始化任务队列,定时器队列,系统滴答数 */ void init_task() { int i; for (i = 0; i < MAX_TIMER; i++) { timer_list[i].state = TIMER_NULL; /* 将所有定时器置为空 */ } for (i = 0; i < MAX_TASK; i++) { task_list[i].state = TASK_NULL; /* 将任务队列中所有项置为空 */ } current = 0; /* 捏造一个0号任务 */ task_list[0].state = TASK_RUNNING; task_list[0].counter = 1; /* 其实不需要时间片,因为没有出现第二个任务 */ task_list[0].father = 0; task_list[0].user_time = 0; task_list[0].system_time = 0; task_list[0].start_time = 0; task_list[0].pgd = PAGE_DIR; jiffies = 0; /* 滴答声初始化 */ task_list[1].state = TASK_RUNNING; task_list[1].counter = 1; /* 其实不需要时间片,因为没有出现第二个任务 */ task_list[1].father = 0; task_list[1].user_time = 0; task_list[1].system_time = 0; task_list[1].start_time = 0; task_list[1].pgd = PAGE_DIR; memset(&(task_list[1].t_regs),0,sizeof(regs)); task_list[1].t_regs.ds = 0x10; task_list[1].t_regs.gs = 0x10; task_list[1].t_regs.es = 0x10; task_list[1].t_regs.fs = 0x10; task_list[1].t_regs.kesp = 0xC0070000; _PUSH(task_list[1].t_regs.kesp, 0x200); _PUSH(task_list[1].t_regs.kesp, 0x08); _PUSH(task_list[1].t_regs.kesp, testfun); //set_system_gate(0x80,&system_call); }
C
#include "HeaderTrabalho.h" #define x3 5000 #define x4 50000 #define x5 500000 int main() { //vetores principais não modificados durante a execução das funçoes int v1[x3],v2[x4],v3[x5]; //vetores auxiliares modificados durante a execução das funçoes int x,vaux1[x3], vaux2[x4], vaux3[x5], indice; //vetores responsaveis por recolher as interações e trocas de cada função float processador[14], armazena[48]; //amostra dos vetores ordenado, aleatorio e decrescente int amostra1[10], amostra2[10], amostra3[10]; //vetor que recebe o tempo de execução de cada função float total[21]; //variaveis de tempo clock_t start_t , end_t; //preparando vetores que recebam os resultados for(int j; j < 48; j++) { armazena[j] = 0.00; } for(int j; j < 14; j++) { processador[j] = 0.00; } for(int j; j < 21 ; j++) { total[j] = 0.00; } for(int j; j < 10; j++) { amostra1[j] = 0.00; amostra2[j] = 0.00; amostra3[j] = 0.00; } //recebe o apção da função menu x=menu(); switch(x) { case 1: indice = 0; geraValores(v1,x3); while(indice <= 14) { /*faz com que aconteção tres testes na sequite ordem * O Primeiro teste e o teste de variaveis aleatorias no vetor * O Segundo teste e o teste de variaveis decrecentes no vetor * O ultimo teste e o de variaveis crescentes no vetor */ if(indice==0) printf("Teste Aleatorio\t"); if(indice==7) { shellSort(v1,processador,x3); ordemDecrecente(v1 ,vaux1 ,x3); printf("\nTeste Decrecente"); recarrega(v1,v1,x3); } if(indice==14) { quickSort(v1,processador,0,x3,0.0); printf("\nTeste Crescente\t"); } //++++++++++++++++++++++ recarrega(vaux1,v1,x3); //********************** //Método da Bolha start_t = clock(); bubleSort(vaux1, processador,x3); end_t = clock(); total[0 + indice ] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux1, v1, x3); //********************** // Método da Bolha melhorado start_t = clock(); bubleSortM(vaux1, processador,x3); end_t = clock(); total[1 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux1, v1, x3); //********************** //Método de Ordenação Troca e Partição start_t = clock(); quickSort(vaux1, processador,0,x3,0.0); end_t = clock(); total[2 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux1, v1, x3); //********************** //Método de Ordenação Inserção Direta start_t = clock(); inserctSort(vaux1, processador,x3); end_t = clock(); total[3 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor' //++++++++++++++++++++++ recarrega(vaux1, v1, x3); //********************** //Método de Ordenação por Incrementos decrecentes start_t = clock(); shellSort(vaux1, processador, x3); end_t = clock(); total[4 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux1, v1, x3); //********************** //Método de Ordenação por inserção direta start_t = clock(); selectSort(vaux1, processador, x3); end_t = clock(); total[5 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux1,v1,x3); //********************** //Método de Ordenação tipo arvore start_t = clock(); heapSort(vaux1, processador, x3); end_t = clock(); total[6 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; indice = indice + 7; if(indice == 7) { for(int j = 0; j < 14 ; j++) { armazena[j] = processador [j]; } recolheAmostra(vaux1,amostra1,10); } if(indice == 14) { int k = 14 ; for(int j = 0; j < 14 ; j++ , k++) { armazena[k] = processador [j]; } recolheAmostra(vaux1,amostra2,10); } if(indice == 21) { int k = 29 ; for(int j = 0; j < 14 ; j++ , k++) { armazena[k] = processador [j]; } recolheAmostra(vaux1, amostra3, 10); } } x = subMenu(); switch(x) { case 1: mostraTempoGasto(total , 1); //break; case 2: mostraQtdTrocas(armazena , 1); //break; case 3: mostraQtdInteracao(armazena, 1); //break; case 4: printf("\n"); puts("vetor aleatorio"); imprimVetor(amostra1, 10); printf("\n"); puts("vetor decrescente"); imprimVetor(amostra2, 10); printf("\n"); puts("vetor crescente"); imprimVetor(amostra3, 10); printf("\n"); case 5: mostraTempoGasto(total , 1); mostraQtdTrocas(armazena , 1); mostraQtdInteracao(armazena, 1); printf("\n"); puts("vetor aleatorio"); imprimVetor(amostra1, 10); printf("\n"); puts("vetor decrescente"); imprimVetor(amostra2, 10); printf("\n"); puts("vetor crescente"); imprimVetor(amostra3, 10); printf("\n"); } //break; case 2: indice = 0; geraValores(v2,x4); recolheAmostra(v2,amostra1,10); while(indice <= 14) { /*faz com que aconteção tres testes na sequite ordem * O Primeiro teste e o teste de variaveis aleatorias no vetor * O Segundo teste e o teste de variaveis decrecentes no vetor * O ultimo teste e o de variaveis crescentes no vetor * */ if(indice==0)printf("Teste Aleatorio\t"); if(indice==7) { shellSort(v2,processador,x4); ordemDecrecente(v2 ,vaux2 ,x4); printf("\nTeste Decrecente"); recolheAmostra(vaux2,amostra2,10); } if(indice==14) { quickSort(v2,processador,0,x4,0.0); printf("\nTeste Crescente\t"); } //++++++++++++++++++++++ recarrega(vaux2,v2,x4); //********************** //Método da Bolha start_t = clock(); bubleSort(vaux2, processador,x4); end_t = clock(); total[0 + indice ] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux2, v2, x4); //********************** // Método da Bolha melhorado start_t = clock(); bubleSortM(vaux2, processador,x4); end_t = clock(); total[1 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux2, v2, x4); //********************** //Método de Ordenação Troca e Partição start_t = clock(); quickSort(vaux2, processador,0,x4,0.0); end_t = clock(); total[2 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux2, v2, x4); //********************** //Método de Ordenação Inserção Direta start_t = clock(); inserctSort(vaux2, processador,x4); end_t = clock(); total[3 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux2, v2, x4); //********************** //Método de Ordenação por Incrementos decrecentes start_t = clock(); shellSort(vaux2, processador, x4); end_t = clock(); total[4 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; recolheAmostra(vaux2, amostra3, 10); //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux2, v2, x4); //********************** //Método de Ordenação por inserção direta start_t = clock(); selectSort(vaux2, processador, x4); end_t = clock(); total[5 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux2,v2,x4); //********************** //Método de Ordenação tipo arvore start_t = clock(); heapSort(vaux2, processador, x4); end_t = clock(); total[6 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; indice = indice + 7; if(indice == 7) { for(int j = 0; j < 14 ; j++) { armazena[j] = processador [j]; } } if(indice == 14) { int k = 14 ; for(int j = 0; j < 14 ; j++ , k++) { armazena[k] = processador [j]; } } if(indice == 21) { int k = 29 ; for(int j = 0; j < 14 ; j++ , k++) { armazena[k] = processador [j]; } } } x = subMenu(); switch(x) { case 1: mostraTempoGasto(total , 2); //break; case 2: mostraQtdTrocas(armazena , 2); //break; case 3: mostraQtdInteracao(armazena, 2); //break; case 4: printf("\n"); puts("vetor aleatorio"); imprimVetor(amostra1, 10); printf("\n"); puts("vetor decrescente"); imprimVetor(amostra2, 10); printf("\n"); puts("vetor crescente"); imprimVetor(amostra3, 10); printf("\n"); case 5: mostraTempoGasto(total , 2); mostraQtdTrocas(armazena , 2); mostraQtdInteracao(armazena, 2); printf("\n"); puts("vetor aleatorio"); imprimVetor(amostra1, 10); printf("\n"); puts("vetor decrescente"); imprimVetor(amostra2, 10); printf("\n"); puts("vetor crescente"); imprimVetor(amostra3, 10); printf("\n"); } //break; case 3: indice = 0; geraValores(v3,x5); recolheAmostra(v3,amostra1,10); while(indice <= 14) { /*faz com que aconteção tres testes na sequite ordem * O Primeiro teste e o teste de variaveis aleatorias no vetor * O Segundo teste e o teste de variaveis decrecentes no vetor * O ultimo teste e o de variaveis crescentes no vetor * */ if(indice==0)printf("Teste Aleatorio\t"); if(indice==7) { shellSort(v3,processador,x5); ordemDecrecente(v3 ,vaux3 ,x5); printf("\nTeste Decrecente"); recolheAmostra(vaux3,amostra2,10); } if(indice==14) { quickSort(v3,processador,0,x5,0.0); printf("\nTeste Crescente\t"); } //++++++++++++++++++++++ recarrega(vaux3,v3,x5); //********************** //Método da Bolha //#pragma omp parallel start_t = clock(); bubleSort(vaux3, processador,x5); end_t = clock(); total[0 + indice ] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux3, v3, x5); //********************** // Método da Bolha melhorado //printf("Rodando Buble Sort Melhorado \n"); start_t = clock(); //#pragma omp parallel bubleSortM(vaux3, processador,x5); end_t = clock(); total[1 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux3, v3, x5); //********************** //Método de Ordenação Troca e Partição //printf("Rodando Quick Sort \n"); start_t = clock(); quickSort(vaux3, processador,0,x5,0.0); end_t = clock(); total[2 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux3, v3, x5); //********************** //Método de Ordenação Inserção Direta //printf("Rodando Inserct Sort \n"); start_t = clock(); inserctSort(vaux3, processador,x5); end_t = clock(); total[3 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux3, v3, x5); //********************** //Método de Ordenação por Incrementos decrecentes //printf("Rodando Shell Sort\n"); start_t = clock(); shellSort(vaux3, processador, x5); end_t = clock(); total[4 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; recolheAmostra(vaux3, amostra3, 10); //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux3, v3, x5); //********************** //Método de Ordenação por inserção direta //printf("Rodando Select sort\n"); start_t = clock(); selectSort(vaux3, processador, x5); end_t = clock(); total[5 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; //Recanrregando o vetor //++++++++++++++++++++++ recarrega(vaux3,v3,x5); //********************** //Método de Ordenação tipo arvore //printf("Rodando Heap Sort\n"); start_t = clock(); heapSort(vaux3, processador, x5); end_t = clock(); total[6 + indice] = (double) (end_t - start_t) / CLOCKS_PER_SEC * 1000; indice = indice + 7; if(indice == 7) { for(int j = 0; j < 14 ; j++) { armazena[j] = processador [j]; } } if(indice == 14) { int k = 14 ; for(int j = 0; j < 14 ; j++ , k++) { armazena[k] = processador [j]; } } if(indice == 21) { int k = 29; for(int j = 0; j < 14 ; j++ , k++) { armazena[k] = processador [j]; } } } x = subMenu(); switch(x) { case 1: mostraTempoGasto(total , 1); //break; case 2: mostraQtdTrocas(armazena , 1); //break; case 3: mostraQtdInteracao(armazena, 1); //break; case 4: printf("\n"); puts("vetor aleatorio"); imprimVetor(amostra1, 10); printf("\n"); puts("vetor decrescente"); imprimVetor(amostra2, 10); printf("\n"); puts("vetor crescente"); imprimVetor(amostra3, 10); printf("\n"); case 5: mostraTempoGasto(total , 3); mostraQtdTrocas(armazena , 3); mostraQtdInteracao(armazena, 3); printf("\n"); puts("vetor aleatorio"); imprimVetor(amostra1, 10); printf("\n"); puts("vetor decrescente"); imprimVetor(amostra2, 10); printf("\n"); puts("vetor crescente"); imprimVetor(amostra3, 10); printf("\n"); } break; } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* check_file.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: agardina <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/11/29 12:23:00 by agardina #+# #+# */ /* Updated: 2019/12/03 14:48:16 by agardina ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" int get_line(char *buffer, char line[6], int start) { int i; i = 0; while (i < 6) { line[i] = '\0'; i++; } i = 0; while (buffer[start + i] && i < 5) { line[i] = buffer[start + i]; if (buffer[start + i] == '\n') return (1); i++; } return (1); } int check_line(char line[6], int line_nb) { int i; if (line_nb % 5 == 0) { if (!(ft_strlen(line) == 1 && (line[0] == '\n' || line[0] == '\0'))) return (0); } else { i = 0; if (ft_strlen(line) != 5) return (0); while (i < 5) { if (i < 4) if (!(line[i] == '.' || line[i] == '#')) return (0); if (i == 4 && line[i] != '\n') return (0); i++; } } return (1); } int count_adj_blocs(t_tetri tetri, t_point p) { int res; res = 0; if (p.y > 0) if ((tetri.tab)[p.y - 1][p.x] == '#') res++; if (p.y < 3) if ((tetri.tab)[p.y + 1][p.x] == '#') res++; if (p.x > 0) if ((tetri.tab)[p.y][p.x - 1] == '#') res++; if (p.x < 3) if ((tetri.tab)[p.y][p.x + 1] == '#') res++; return (res); } int check_tetri(t_tetri *tetri) { int blocs_nb; int adj_blocs; t_point p; int res; blocs_nb = 0; adj_blocs = 0; p.x = -1; p.y = -1; while (++p.y < 4) { while (++p.x < 5) { if ((tetri->tab)[p.y][p.x] == '#') { blocs_nb++; if (!(res = count_adj_blocs(*tetri, p))) return (0); adj_blocs += res; } } p.x = -1; } return ((blocs_nb == 4 && adj_blocs >= 6) ? 1 : 0); } int check_list(t_tetri *head) { t_tetri *to_check; to_check = head; while (to_check) { if (!check_tetri(to_check)) return (0); get_first_block(to_check); (to_check->path)[3] = '\0'; get_path(to_check, to_check->first, 0, 0); to_check = to_check->next; } return (1); }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> /* */ int main(int argc, char *argv[]) { system ("color 0a"); setlocale(LC_ALL, "Portuguese"); float denominador, numerador, soma = 0.0, n; printf ("Insira um nmero inteiro positivo n:\n"); scanf ("%f", &n); if (n <= 0.0){ printf ("Erro! Insira um nmero inteiro positivo n:\n"); scanf ("%d", &n); } for (denominador = n, numerador = 1; numerador <= n; denominador--, numerador++){ soma = soma + (numerador/denominador); } printf ("Valor da soma: %.3f\n", soma); system ("pause"); return 0; }
C
#include <avr/pgmspace.h> #include <util/delay.h> #include <stdlib.h> #include <string.h> #include "lib/enc28j60.h" #include "lib/ethernet.h" #include "config.h" #include "net.h" /** * Note: Network Packets Headers (Ethernet II) * Basics: * [14 bytes] Ethernet II header * [20 bytes] IPv4 header * [.. bytes] TCP / UDP / .. packet * * For UDP and IPv4 that is: * ------------ Ethernet ------------ * [ 6 bytes] [ 0 - 5] Destination MAC * [ 6 bytes] [ 6 - 11] Source MAC * [ 2 bytes] [12 - 13] Layer 3 Type (IPv4) * -------------- IPv4 -------------- * [ 1 byte ] [13 - 13] Version + Header Length * [ 1 byte ] [14 - 14] Type of service * [ 2 bytes] [15 - 16] Total length * [ 2 bytes] [17 - 18] Identification * [ 2 bytes] [19 - 20] Flags + Fragment Offset * [ 1 byte ] [21 - 21] Time to Live * [ 1 byte ] [22 - 22] Protocol (0x11 for UDP) * [ 2 bytes] [23 - 24] Header checksum * [ 4 bytes] [25 - 28] Source IPv4 address * [ 4 bytes] [29 - 32] Destination IPv4 address * --------------- UDP -------------- * [ 2 bytes] [33 - 34] Source Port * [ 2 bytes] [35 - 36] Destination Port */ // Handles default packets and returns others // Return value: length of packet or 0 if none available // buf = pointer to data storage of packet uint16_t getpacket(uint8_t *buf, uint16_t maxsize) { // Retrieve packet from ENC28J60 uint16_t len = enc28j60_receivePacket(maxsize, buf); if(len == 0) return 0; // Answer ARP packets if(eth_is_arp(buf, len)) arp_reply(buf); // Answer ICMP pings else if (buf[IP_PROTO]==IP_ICMP && buf[ICMP_TYPE]==ICMP_REQUEST) icmp_reply(buf, len); // Ignore non-IP packets other than ARP else if (eth_is_ip(buf, len)) return len; return 0; } // Returns true if buf is a UDP packet // Sets port to UDP destination port bool decode_udp(uint8_t *buf, uint16_t *port) { if (buf[IP_PROTO] != IP_UDP) return false; *port = (buf[UDP_DST_PORT] << 8) + buf[UDP_DST_PORT+1]; return true; } // Initializes ENC28J60 with IP void network_init(uint8_t *mac, uint8_t *ip) { enc28j60_init(mac); enc28j60_clk(2); _delay_us(10); // LED configuration enc28j60_writePhy(PHLCON, 0x3742); _delay_us(10); network_set(mac, ip); }
C
#include "memlib.h" #include "memlib_ext.h" #include "../drv/display.h" #include "../drv/hwio.h" #include "bitmap.h" #define E820_LOC 0x10000 #define E820_COUNT_LOC 0x1400 #define K_PAGE_SIZE 40 unsigned int lowMemSize = 0x0; unsigned int highMemLocation = 0x0; unsigned int highMemSize = 0x0; unsigned int bucketStartLocation = 0x0; unsigned int bitmapStartLocation = 0x0; k_bitmap memBitmap; unsigned int memInUse = 0; unsigned int memMaxUse = 0; void* memcpy(void* restrict dstptr, const void* restrict srcptr, int size) { unsigned char* dst = ((unsigned char*) dstptr); const unsigned char* src = ((const unsigned char*) srcptr); for (int i = 0; i < size; i++) { *dst = *src; dst++; src++; } return dstptr; } int memcmp(const void* restrict ptr1, const void* restrict ptr2, unsigned int size) { int cmp = 0; for(unsigned int i = 0; i < size; i++) { cmp = ((char*)ptr1)[i] - ((char*)ptr2)[i]; if(cmp!=0) return cmp; } return 0; } void memset(const void* restrict ptr1, unsigned char val, int size) { unsigned char* dst = ((unsigned char*) ptr1); for (int i = 0; i < size; i++) { *dst = val; dst++; } } //Kernel memory allocation void* kmalloc(unsigned int size) { unsigned int numOfPage = (size+8) / K_PAGE_SIZE + ((size+8) % K_PAGE_SIZE != 0); int start = findNumMemLoc(numOfPage); start *= K_PAGE_SIZE; //p_serial_printf("SIZE %i, PAGES %i\n", size, numOfPage); if(start < 0) { disp_printstring("Error allocating memory, no space available"); p_serial_printf("Error allocating memory of size %i\n", size); return 0; } void* ret = (void*)(highMemLocation + start + 8); for(int i = 0; i < numOfPage; i++) { mem_markbitmap(i + (start/K_PAGE_SIZE), 1); } memset((ret-8), 0, numOfPage * K_PAGE_SIZE); unsigned int* pt_numPage = (unsigned int*)(highMemLocation + start); *pt_numPage = numOfPage; pt_numPage = (unsigned int*)(highMemLocation + start + 4); *pt_numPage = (start / K_PAGE_SIZE); return ret; } void kfree(void* pointer) { unsigned int size = *(unsigned int*)(pointer-8); unsigned int bmapLoc = *(unsigned int*)(pointer-4); for(int i = 0; i < size; i++) { mem_markbitmap(bmapLoc + i, 0); } memset((pointer-8), 0, size * K_PAGE_SIZE); return; } unsigned int mem_getUsedMem() { return memInUse; } unsigned int mem_getFreeMem() { return mem_getMemSize() - mem_getUsedMem(); } unsigned int mem_getPeakUse() { return memMaxUse; } unsigned int mem_getMemSize() { return bitmapStartLocation - highMemLocation; } int findNumMemLoc(unsigned int num) { unsigned int start = 0; unsigned int maxCon = 0; for(int i = 0; i < mem_getMemSize(); i++) { if(mem_checkbitmap(i) == 0) { maxCon += 1; if(maxCon == num) { return start; } } else { maxCon = 0; start = (i+1); } } return -1; } void mem_markbitmap(unsigned int loc, unsigned char status) { //unsigned int byte = 0; //unsigned char bit = 0; //byte = loc / 8; //bit = loc % 8; //unsigned char* bMap = (unsigned char*)(bitmapStartLocation + byte); if(status == 0) { //bMap[0] = bMap[0] ^ (1 << bit); bitmap_clear_bit(memBitmap, loc); memInUse -= K_PAGE_SIZE; memset((void*)(loc*K_PAGE_SIZE+highMemLocation), 0, K_PAGE_SIZE); } else { //bMap[0] = bMap[0] | (1 << bit); bitmap_set_bit(memBitmap, loc); memInUse += K_PAGE_SIZE; if(memInUse > memMaxUse) memMaxUse = memInUse; } } unsigned char mem_checkbitmap(unsigned int loc) { //unsigned int byte = 0; //unsigned char bit = 0; //byte = loc / 8; //bit = loc % 8; //unsigned char* bMap = (unsigned char*)(bitmapStartLocation + byte); //return ((bMap[0] & (1 << bit)) > 0); return bitmap_is_bit_set(memBitmap, loc); } //Reads the e820 map that was loaded during the boot sequence //It then take the important information out of it and stores the sizes above void mem_read_e820() { int count = *((int*)(E820_COUNT_LOC)); for(int i = 0; i < count; i++) { unsigned int baseAddress = 0x0; for(int j = 0; j < 4; j++) { baseAddress += (((unsigned char) *((int*)(E820_LOC + (24*i) + j))) << (j*8)); } unsigned int size = 0x0; for(int j = 0; j < 4; j++) { size += ((unsigned char) *((int*)(E820_LOC + (24*i) + (8) + j))) << (j*8); } unsigned char type = (unsigned char) *((int*)(E820_LOC + (24*i) + (16))); /* disp_printc('\n'); disp_phex8(i); disp_printc(' '); disp_phex32(baseAddress); disp_printc(' '); disp_phex32(size); disp_printc(' '); disp_phex8(type); */ if(type == 1) { //See if we have found the upper memory location if(baseAddress > 0x9FC00) { highMemLocation = baseAddress; highMemSize = size; bucketStartLocation = baseAddress; bitmapStartLocation = (size + baseAddress) - (size / K_PAGE_SIZE / 8); //nextBucketLocation = bucketStartLocation; //nextPageLocation = bucketStartLocation - (sizeof(struct kbucket) * ((size / 4096))); } else { lowMemSize = size; } } } /* disp_phex32(bitmapStartLocation); disp_printc('\n'); disp_phex32(bucketStartLocation); disp_printc('\n'); disp_phex32(highMemSize); disp_printc('\n'); disp_phex32(highMemSize+bucketStartLocation); disp_printc('\n'); disp_phex32(lowMemSize); disp_printc('\n'); */ p_serial_printf("Start location %xi, Size %xi, bitmapStartLocation %xi\n", highMemLocation, highMemSize, bitmapStartLocation); memBitmap = (k_bitmap) bitmapStartLocation; } void dumpMemLoc(unsigned int loc, unsigned int amount) { for(int i = 0; i < amount; i++) { p_serial_printf("%xi: %xi\n", ((unsigned int*)((unsigned int*)loc + i)), *((unsigned int*)((unsigned int*)loc + i))); } } unsigned int getBitmapStart() { return bitmapStartLocation; }
C
/* Calculates fibonacci's sequence using recursion. As the sequence starts like so: 0, 1, 1, 2 We hande this by checking index against specific values Otherwise we want to check above a 1th index Formulae: (index - 1) + (index - 2) Else return -1 (as per pdf) */ int ft_fibonacci(int index) { if (index == 0) return (0); else if (index == 1) return (1); else if (index > 1) return (ft_fibonacci(index - 1) + ft_fibonacci(index - 2)); else return (-1); }
C
//program to print only unique elements present in an array. //this program takes 2.844s for 10million random inputs. #include<stdio.h> #include<stdlib.h> #include<math.h> #include<time.h> #include<inttypes.h> #define ENABLE_DEBUGGING #define HASH_CELL_SIZE 1000 #define HASH_TABLE_SIZE 1000 #define SIZE 10 //cell for storing values with count struct cell{ long long int number; long long int count; }; //hash_cell with array of chains to handle collision struct hash_cell{ struct cell chains[HASH_CELL_SIZE]; }; long long int a=35,b=9,prime=1000000007; //linear hash function long long int getHash(long long int num) { return ((a*num+b)%prime)%HASH_TABLE_SIZE; } /* methods checks count for empty cells and checks num for already present cell in a particular hash cell array of chains */ void addHashCell(struct hash_cell *HashTable,long long int hashVal,long long int num) { long long int i; for(i=0;i<HASH_CELL_SIZE;i++) { if(HashTable[hashVal].chains[i].count==0) break; else if(HashTable[hashVal].chains[i].number==num) break; } HashTable[hashVal].chains[i].number=num; HashTable[hashVal].chains[i].count+=1; //printf("\n%d, %d, %d, %d\n",hashVal,i,HashTable[hashVal].chains[i].number,HashTable[hashVal].chains[i].count); } /* method looks for count of every element wrt its hash cell chain and checks its uniqueness by count */ long long int checkCount(struct hash_cell *HashTable,long long int hashVal,long long int num) { long long int i; for(i=0;i<HASH_CELL_SIZE;i++) { if(HashTable[hashVal].chains[i].number==num) break; } if(HashTable[hashVal].chains[i].count==1) return 1; else return 0; } //initialize count to 0 to check empty cells later void init(struct hash_cell *HashTable) { printf("\ninside init\n"); long long int i,j; for(i=0;i<HASH_TABLE_SIZE;i++) { for(j=0;j<HASH_CELL_SIZE;j++) { HashTable[i].chains[j].count=0; } } } int main() { long long int *input=(long long int*)malloc(sizeof(long long int)*SIZE); //printf("input created\n"); long long int i=0; //printf("\n--\n"); for(i=0;i<SIZE;i++) { scanf("%lld",&input[i]); //input[i]=rand(); } struct hash_cell *Hash_Table=(struct hash_cell*)malloc(sizeof(struct hash_cell)*HASH_TABLE_SIZE); printf("\nHash created\n"); init(Hash_Table); printf("\nInitialized\n"); //finding timestamp in ms before processing the input #ifdef ENABLE_DEBUGGING long long int ms; time_t s; struct timespec spec; clock_gettime(CLOCK_REALTIME,&spec); s=spec.tv_sec; ms= (spec.tv_nsec / 1.0e06); printf("Time before execution - %"PRIdMAX".%03lld\n",(intmax_t)s,ms); #endif long long int hashVal; //making of hash table from input for(i=0;i<SIZE;i++) { hashVal=getHash(input[i]); addHashCell(Hash_Table,hashVal,input[i]); } //printing the output int flag=1; for(i=0;i<SIZE;i++) { hashVal=getHash(input[i]); if(checkCount(Hash_Table,hashVal,input[i])) { printf("%lld ",input[i]); flag=0; } } if(flag) { printf("\nNo Unique elements\n"); } printf("\n"); //finding timestamp in ms after processing the input clock_gettime(CLOCK_REALTIME,&spec); s=spec.tv_sec; ms= (spec.tv_nsec / 1.0e06); printf("Time after Execution - %"PRIdMAX".%03lld",(intmax_t)s,ms); //deallocating the memory free(input); free(Hash_Table); return 0; }
C
//Anupreet Singh roll no.11911063 #include<stdio.h> #include<stdlib.h> //Structure of Tree struct tree{ int data; struct tree *left; struct tree *right; }; //Creating a new tree node struct tree *newNode(int data){ struct tree *node = (struct tree*)malloc(sizeof(struct tree)); node->data = data; node->left = NULL; node->right = NULL; return node; } //Structure of Stack node struct stack{ struct tree *t; struct stack *next; }; //push function void push(struct stack **stack,struct tree *tree){ struct stack *newTree = (struct stack*) malloc (sizeof(struct stack)); newTree->t = tree; newTree->next = (*stack); (*stack) = newTree; } //to check if stack is empty int isEmpty(struct stack *stack){ return (stack==NULL); } //pop function that returns a tree node struct tree *pop(struct stack** stack){ struct stack *temp; struct tree *root; temp = *stack; root = temp->t; *stack = temp->next; free(temp); return root; } //InOrder Traversal void InOrder(struct tree *root){ struct tree* curr = root; struct stack *s = NULL; //Stack is initialized NULL int flag = 0; while(!flag){ if(curr != NULL){ push(&s,curr); //Push the current tree node to stack curr = curr->left; //change the current tree to to left side } else{ if(!isEmpty(s)){ curr = pop(&s); //pop the stack printf("%d\t",curr->data); curr = curr->right; //shift the curr tree node to the right of it } else{ flag = 1; } } } } //Calculating Max Height of the tree int height(struct tree *root){ if(root == NULL){ return 0; } else{ int lst; int rst; lst = height(root->left); rst = height(root->right); //max(lst,rst)+1 is the max height if(rst>lst){ return rst+1; }else{ return lst+1; } } } int main(){ struct tree *root = newNode(2); root->left = newNode(5); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(1); root->right->left = newNode(8); printf("InOrder Tree Traversal without recursion:\n"); InOrder(root); printf("\n Height of Tree is = %d\n",height(root)); return 0; }
C
#include <stdio.h> #include <omp.h> int main(){ double start=omp_get_wtime(); usleep(1000); double end=omp_get_wtime(); double wtick=omp_get_wtick(); printf("start=%.16g\nend=%.16g\ndiff=%.16g\n",start,end,wtick); return 0; }
C
#include "libft.h" static char *tmp_line_return(char **line, int n, char **buffer) { char *tmp; tmp = NULL; tmp = malloc((n + 1) * sizeof(char)); if (!tmp) return (NULL); tmp = ft_tmpcpy(tmp, *line, n); *line = ft_strtrim(*line, n); if (!*line) { free (*buffer); free (tmp); return (NULL); } if (*buffer) free(*buffer); return (tmp); } static char *ft_line_check(char **line, char **buffer) { int n; char *tmp; tmp = NULL; n = 0; n = ft_strchr(*line, '\n'); if (n >= 0) return (tmp_line_return(&(*line), n, &(*buffer))); else { tmp = ft_strdup(*line); free (*line); *line = NULL; if (*buffer) free(*buffer); return (tmp); } } static char *ft_read_processing(int byte_read, char **buffer, char **line) { if (byte_read < 0) { if (*buffer) free(*buffer); return (NULL); } if (*line && byte_read == 0) return (ft_line_check(&(*line), &(*buffer))); else { if (*buffer) free(*buffer); if (*line) free(*line); } return (NULL); } char *get_next_line(int fd) { static char *line; char *buffer; int n; int byte_read; if (fd < 0 || BUFFER_SIZE <= 0) return (NULL); buffer = malloc((BUFFER_SIZE + 1) * sizeof(char)); if (!buffer) return (NULL); byte_read = read(fd, buffer, BUFFER_SIZE); while (byte_read > 0) { buffer[byte_read] = '\0'; if (!line) line = ft_strdup(buffer); else line = ft_strjoin(line, buffer); n = ft_strchr(line, '\n'); if (n >= 0) return (tmp_line_return(&line, n, &buffer)); byte_read = read(fd, buffer, BUFFER_SIZE); } return (ft_read_processing(byte_read, &buffer, &line)); }
C
/* adder.c * demonstrate the use of GetInt, from CS50 Library * 09/25/2013 * bagustris, [email protected] */ #include <cs50.h> #include <stdio.h> int main(void) { //ask for user input printf("Give me an integer:"); int x = GetInt(); printf("Give me another integer:"); int y = GetInt(); //do math printf("So, you give me %d and %d, the sum of both are = %d!\n", x, y, x+y); }
C
#include <stdio.h> #include <stdlib.h> #define MAX 10 #define TRUE 0 #define FALSE -1 struct queue { int items[MAX]; int front, rear; int size; }; void create(struct queue *pq) { pq->front = pq->size = 0; pq->rear = MAX - 1; } int isFull(struct queue *pq) { return ((pq->size == MAX) ? TRUE : FALSE) ; } int isEmpty(struct queue* pq) { return ((pq->size == 0) ? TRUE : FALSE); } void enqueue(struct queue * pq, int items) { if (TRUE == isFull(pq)) { printf("Queue is full, enqueue is not possible\n"); return; } pq->rear = (pq->rear + 1) % MAX; pq->items[pq->rear] = items; pq->size = pq->size + 1; // cout << items << " enqueued to queue\n"; printf("items : %d enqueued to queue\n", items); } int dequeue(struct queue *pq) { if (TRUE == isEmpty(pq)) { printf("Queue is empty : "); return FALSE; } int items = pq->items[pq->front]; pq->front = (pq->front + 1) % MAX; pq->size = pq->size - 1; return items; } int front(struct queue *pq) { if (isEmpty(pq)) return FALSE; return pq->items[pq->front]; } int rear(struct queue *pq) { if (isEmpty(pq)) return FALSE; return pq->items[pq->rear]; } int main() { int i; struct queue q; create(&q); for(i = 0; i<=MAX; i++) { enqueue(&q, (rand()%(MAX * 10))); } for(i = 0; i<=MAX; i++) { printf("Dequeued value = %d\n", dequeue(&q)); } return 0; }
C
/** * Copies a BMP piece by piece, just because. * with resize * * more comfortable version */ #include <stdio.h> #include <stdlib.h> #include "bmp.h" const int SIZE_OF_HEADER=54; const int SIZE_OF_BMP_INFO=40; const int BITS_PER_PIXEL=24; const int NO_COMPRESSION=0; const int PARAGRAPH_WIDTH=4; const int NEED_ARGUMENTS=4; const int MORE_PRECISION=100; const WORD START_BMP=0x4d42; const BYTE MAX_COLOR=0xff; const BYTE MIN_COLOR=0x00; //================================================================================================================================== CHECKARGUMENTS checkArguments(int argc, char* argv[]) { CHECKARGUMENTS answer; answer.is_bad=0; answer.factor=0; if (argc != NEED_ARGUMENTS) { fprintf(stderr, "Usage: ./copy n infile outfile\n"); answer.is_bad=1; } // remember factor //float factor; //ensure second argument is digit if (sscanf(argv[1],"%f",&answer.factor)==0) { fprintf(stderr, "Usage: ./copy n infile outfile\n"); answer.is_bad=1; } //check for digits range if(answer.factor<0 || answer.factor>100) { fprintf(stderr, "Factor is must bein range 0.0...100.0\n"); answer.is_bad=1; } return answer; } //================================================================================================================================== void printPadding(int out_padding, FILE *outptr) { for (int p = 0; p < out_padding; p++) { fputc(0x00, outptr); } } //================================================================================================================================== void printRaw(float factor,RGBTRIPLE *buffer,LONG image_width, FILE *outptr, int padding) { for (int r = 0; r < factor; r++) { // write RGB triple to outfile fwrite(buffer, sizeof(RGBTRIPLE), image_width, outptr); // write padding to outfile printPadding(padding,outptr); } } //================================================================================================================================== int flowBuffer(float factor, int raw_element, RGBTRIPLE *buffer, RGBTRIPLE triple) { for (int k = 0; k < factor; k++) { buffer[raw_element++] = triple; } return raw_element; } //================================================================================================================================== int main(int argc, char *argv[]) { CHECKARGUMENTS argument=checkArguments(argc,argv); // ensure proper usage if(argument.is_bad==1) { return 1; } int precision=argument.factor*MORE_PRECISION; // remember filenames char *infile = argv[2]; char *outfile = argv[3]; // open input file FILE *inptr = fopen(infile, "r"); if (inptr == NULL) { fprintf(stderr, "Could not open %s.\n", infile); return 2; } // open output file FILE *outptr = fopen(outfile, "w"); if (outptr == NULL) { fclose(inptr); fprintf(stderr, "Could not create %s.\n", outfile); return 3; } // read infile's BITMAPFILEHEADER BITMAPFILEHEADER bf; fread(&bf, sizeof(BITMAPFILEHEADER), 1, inptr); // read infile's BITMAPINFOHEADER BITMAPINFOHEADER bi; fread(&bi, sizeof(BITMAPINFOHEADER), 1, inptr); // ensure infile is (likely) a 24-bit uncompressed BMP 4.0 if (bf.bfType != START_BMP || bf.bfOffBits != SIZE_OF_HEADER || bi.biSize != SIZE_OF_BMP_INFO || bi.biBitCount != BITS_PER_PIXEL || bi.biCompression != NO_COMPRESSION) { fclose(outptr); fclose(inptr); fprintf(stderr, "Unsupported file format.\n"); return 4; } // determine padding for scanlines infile int in_padding = (PARAGRAPH_WIDTH - (bi.biWidth * sizeof(RGBTRIPLE)) % PARAGRAPH_WIDTH) % PARAGRAPH_WIDTH; //old width for reading input file LONG in_width=bi.biWidth; LONG in_height=bi.biHeight; //calculate new width and height bi.biWidth=argument.factor*precision*bi.biWidth/precision; bi.biHeight=argument.factor*precision*bi.biHeight/precision; // determine padding for scanlines outfile int out_padding = (PARAGRAPH_WIDTH - (bi.biWidth * sizeof(RGBTRIPLE)) % PARAGRAPH_WIDTH) % PARAGRAPH_WIDTH; //calculate total file size bi.biSizeImage=(sizeof(RGBTRIPLE)*bi.biWidth+out_padding)*abs(bi.biHeight); bf.bfSize=bi.biSizeImage+sizeof(bf)+sizeof(bi); // write outfile's BITMAPFILEHEADER fwrite(&bf, sizeof(BITMAPFILEHEADER), 1, outptr); // write outfile's BITMAPINFOHEADER fwrite(&bi, sizeof(BITMAPINFOHEADER), 1, outptr); // temporary storage RGBTRIPLE triple; RGBTRIPLE *buffer = malloc(sizeof(RGBTRIPLE) * bi.biWidth); int raw_element; // iterate over infile's scanlines for (int i = 0, biHeight = abs(in_height); i < biHeight; i++) { raw_element=0; // iterate over pixels in scanline for (int j = 0; j < in_width; j++) { // read RGB triple from infile fread(&triple, sizeof(RGBTRIPLE), 1, inptr); if(j*precision%(int)(precision/argument.factor)==0) { raw_element=flowBuffer(argument.factor, raw_element, buffer, triple); } } // skip over padding fseek(inptr, in_padding, SEEK_CUR); //row print to file if(i*precision%(int)(precision/argument.factor)==0) { printRaw(argument.factor, buffer, bi.biWidth, outptr, out_padding); } } //free raw buffer free(buffer); // close infile fclose(inptr); // close outfile fclose(outptr); // success return 0; } //==================================================================================================================================
C
/* ** EPITECH PROJECT, 2018 ** my_getnbr ** File description: ** */ int my_getnbr(char const *str) { int i = 0; if (str[i] > 48 && str[i] < 57) { my_putchar(str[i]); i++; } if (str[i] >= 9 && str[i] <= 13 || str[i] == 32) { my_putchar(str[i]); i++; } else { return(0); } my_putchar(); } int main() { my_getnbr(618); return(0); }
C
#include <stdio.h> int main(void){ int n1,n2,n3,n4; double d1,d2,d3,d4; n1=5/2; n2=5.0/2.0; n3=5.0/2; n4=5/2.0; d1=5/2; d2=5.0/2.0; d3=5.0/2; d4=5/2.0; printf("n1=%d\n",n1); printf("n2=%d\n",n2); printf("n3=%d\n",n3); printf("n4=%d\n\n",n4); printf("d1=%lf\n",d1); printf("d2=%lf\n",d2); printf("d3=%lf\n",d3); printf("d4=%lf\n",d4); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<stdbool.h> #define N 100 int stack[N]; int top=-1; int ctr=0; void push(int item) { stack[++top]=item; } int pop() { return stack[top--]; } int peek() { return stack[top]; } bool isEmpty(){ return top==-1; } void addEdge(int v,int adjMatrix[][v],int start,int end) { adjMatrix[start][end]=1; adjMatrix[end][start]=1; } int getAdjUnvisVertex(int visited[],int index,int v,int adjMatrix[][v]) { int i; for(i=1;i<=v;i++) { if(adjMatrix[index][i]==1 && visited[i]==0) return i; } return -1; } void depthFirstSearch(int v,int new,int visited[],int adjMatrix[][v]) { int i; visited[new]=1; push(new); while(!isEmpty()) { int unvisitedVertex=getAdjUnvisVertex(visited,peek(),v,adjMatrix); if(unvisitedVertex==-1) pop(); else { visited[unvisitedVertex]=1; push(unvisitedVertex); } } ctr++; } int main() { int i,j; int v,e,start,end,new; scanf("%d%d",&v,&e); int adjMatrix[v+1][v+1]; int visited[v+1]; for(int i=1;i<=v;i++) visited[i]=0; for(i=1;i<=v;i++) { for(j=1;j<=v;j++) adjMatrix[i][j]=0; } for(int i=0;i<e;i++) { scanf("%d%d",&start,&end); addEdge(v,adjMatrix,start,end); } for(int i=1;i<=v;i++) { if(visited[i]==0) depthFirstSearch(v,i,visited,adjMatrix); } printf("%d",ctr); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <time.h> #define EV_MSC 0x04 #define MSC_GESTURE 0x02 #define WAKE_TIME 2 #define INPUT_DEVICE "/dev/input/by-path/platform-f9924000.i2c-event" struct input_event { struct timeval time; unsigned short type; unsigned short code; unsigned int value; }; void err_log(char *str) { fprintf(stderr, "%s\n", str); } int poll_fd(int fd, int timeout) { struct timeval tv; fd_set set; FD_ZERO(&set); FD_SET(fd, &set); tv.tv_sec = timeout; tv.tv_usec = 0; return select(fd + 1, &set, NULL, NULL, &tv); } void turn_display_on() { system("mcetool -D on"); } void turn_display_off() { system("mcetool -D off"); } int event_loop(char *device_name) { struct input_event event; int result, poll_result; time_t now, wake_lock_till = 0; int fd = open(device_name, O_RDONLY); if (fd == -1) { err_log("opening input device failed"); return -1; } while(1) { if (wake_lock_till) { now = time(NULL); if (now >= wake_lock_till) { turn_display_off(); wake_lock_till = 0; } } poll_result = poll_fd(fd, 1); if (poll_result == -1) { err_log("poll failed"); return -1; } if (poll_result == 1) { result = read(fd, &event, sizeof(struct input_event)); if (result != sizeof(struct input_event)) { err_log("failed to read input event"); return -1; } if (event.type == EV_MSC && event.code == MSC_GESTURE) { if (!wake_lock_till) { turn_display_on(); } wake_lock_till = time(NULL) + WAKE_TIME; } } } } int main() { event_loop(INPUT_DEVICE); }
C
#include<stdio.h> #include<math.h> int main( int argc, char const* argv []){ int j=4, e, signo=1; double pi, suma; for(e=1; e<=99999; e+=2){ suma= signo*((double)j/e); pi = pi + suma; signo= signo* -1; } printf("Pi es: \n%1.54f", pi); return 0; }
C
#include"my_pthread_rwlock2.h" #include<unistd.h> #include<string.h> //验证读优先 my_pthread_rwlock_t rwlock=MY_PTHREAD_RWLOCK_INITIALIZER; void* thread1(void* arg) { my_pthread_rwlock_wrlock(&rwlock); printf("I an the thread1 wrlock\n"); printf("thread1 is in wrlock!\n"); sleep(2); printf("thread1 is wake up!\n"); my_pthread_rwlock_unlock(&rwlock); } void* thread2(void* arg) { my_pthread_rwlock_wrlock(&rwlock); printf("I am wrlock!\n"); my_pthread_rwlock_unlock(&rwlock); } void* thread3(void* arg) { my_pthread_rwlock_rdlock(&rwlock); printf("I am rdlock!\n"); my_pthread_rwlock_unlock(&rwlock); } int main() { pthread_t tid,tid1,tid2; pthread_create(&tid,NULL,thread1,NULL); sleep(1); pthread_create(&tid1,NULL,thread3,NULL); pthread_create(&tid2,NULL,thread2,NULL); pthread_join(tid,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); return 0; }
C
/* * GCC file */ #include <pthread.h> #include <stdio.h> #include <time.h> #include <stdlib.h> #define BIG_NUM 600000000LL static void *do_nothing_loop(void *d) { volatile long long * a; a = (long long *) d; while(*a < BIG_NUM) ++*a; return NULL; } int main() { pthread_t thread[2]; long long a[100000]; a[0] = a[1] = a[99999] = 0; FILE * handler = fopen("result_2.txt", "w"); // near counters clock_t start_time = clock(); pthread_create(&thread[0], NULL, &do_nothing_loop, &a[0]); pthread_create(&thread[1], NULL, &do_nothing_loop, &a[1]); // wait threads pthread_join(thread[0], NULL); pthread_join(thread[1], NULL); fprintf(handler, "Near:\t%.3f\n", (float)(clock() - start_time) / CLOCKS_PER_SEC); a[0] = 0; // far counters start_time = clock(); pthread_create(&thread[0], NULL, &do_nothing_loop, &a[0]); pthread_create(&thread[1], NULL, &do_nothing_loop, &a[99999]); // wait threads pthread_join(thread[0], NULL); pthread_join(thread[1], NULL); fprintf(handler, "Far:\t%.3f\n", (float)(clock() - start_time) / CLOCKS_PER_SEC); fclose(handler); return 0; }
C
/*Write a program to read the following data as it is and display on the screen by using scanf() and printf() function: �Ram� 120 �a� 123.2.*/ #include<stdio.h> int main() { char alpha; printf("\nEnter the aplphabet "); scanf("%c",&alpha); printf("\nThe alphabet you enter is %c",alpha); }
C
#include <Python.h> #include <numpy/arrayobject.h> #include <numpy/ndarrayobject.h> #include <numpy/noprefix.h> static PyObject *test_transpose(PyObject *self, PyObject *args) { PyObject *input, *output; // Declaration group intp *dimsin; intp *dimsout; intp *SIZE; void *output_data; int type; int i,j; // Allocation group dimsin = malloc(2*sizeof(intp)); dimsout = malloc(2*sizeof(intp)); SIZE = malloc(sizeof(intp)); if (!PyArg_ParseTuple(args, "O", &input)) return NULL; dimsin=PyArray_DIMS(input); type=PyArray_TYPE(input); *SIZE=PyArray_SIZE(input); dimsout[0]=dimsin[1]; dimsout[1]=dimsin[0]; printf("%i\n",*dimsout); printf("%i\n",*SIZE); printf("%i\n",sizeof(long)); // output_data = malloc(PyArray_ITEMSIZE(input)*sizeof(PyArray_SIZE(input))); // output = PyArray_SimpleNewFromData(2,sizeout,type,output_data); // Just allocates the array // output = PyArray_SimpleNew(2,sizeout,type); return Py_BuildValue("s","all done"); } static PyMethodDef TestMethods[] = { {"transpose", test_transpose, METH_VARARGS,"Transpose a numpy array"}, {NULL, NULL, 0, NULL} }; PyMODINIT_FUNC inittest(void) { PyObject *m; m = Py_InitModule("test", TestMethods); }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include<sys/wait.h> #define PARAMS // this allows running commands with paramenters, but still limited to foreground execution #define MAX_ARGS 128 //#define AUDIT int gets(char*); char* s = " "; int main(int argc, char** argv) { char command_line[4096]; char* p; char* args[MAX_ARGS]; int pid, status; int i; printf("Welcome to mini-shell\n"); while(1) { printf("Type a command line: "); #ifndef PARAMS scanf("%s",command_line); #else gets(command_line); p = (char*)strtok(command_line,s); i = 0; args[i] = p; while(p){ #ifdef AUDIT printf("%s " ,p); #endif fflush(stdout); p = (char*)strtok(NULL,s); args[++i] = p; } args[++i] = NULL; printf("\n"); #endif pid = fork(); if ( pid == -1 ) { printf("Unable to spawn new process\n"); exit(1); } if ( pid == 0 ){ #ifndef PARAMS execlp(command_line,command_line,0); #else execvp(args[0],args); #endif printf("Unable to run the typed command\n"); } else wait(&status); } }
C
///////////////////////////////////////////////////////////////////////////////////////////////////// // Write a program which accept two numbers from user and display position // of common ON bits from that two numbers. // Input : 10 15 (1010 1111) // Output : 2 4 // Author : Annaso Chavan ///////////////////////////////////////////////////////////////////////////////////////////////////// #include<stdio.h> #include<stdlib.h> typedef unsigned int UINT; void CommonBits(UINT iNo1,UINT iNo2) { int count=1; while(iNo1 != 0 && iNo2 != 0) { if((iNo1 & 1) == 1 && (iNo2 & 1) == 1) { printf(" %d ",count); } count++; iNo1 = iNo1 >> 1; iNo2 = iNo2 >> 1; } } int main() { unsigned int No1,No2; printf("please enter first no :"); scanf("%u",&No1); printf("please enter second no :"); scanf("%u",&No2); CommonBits(No1,No2); return 0; }
C
/******************************************************** * Filename: core/comm.c * * Author: jtlim, RTOSLab. SNU. * * Description: message queue management. ********************************************************/ #include <core/eos.h> void eos_init_mqueue(eos_mqueue_t *mq, void *queue_start, int16u_t queue_size, int8u_t msg_size, int8u_t queue_type) { mq->queue_size = queue_size; mq->msg_size = msg_size; mq->queue_start = queue_start; mq->queue_type = queue_type; mq->front = queue_start; mq->rear = queue_start; // initializing semaphore eos_init_semaphore(&mq->putsem, queue_size, queue_type); eos_init_semaphore(&mq->getsem, 0, queue_type); } int8u_t eos_send_message(eos_mqueue_t *mq, void *message, int32s_t timeout) { // PRINT("Send message called!\n"); // if failed to acquireing semaphore, just return if (eos_acquire_semaphore(&mq->putsem, timeout) == 0) { return 0; } int i; /* * critical section for message queue */ // copy message to mq's rear for (i = 0; i < mq->msg_size; i++) { *(char *)(mq->rear) = *(char *)(message + i); // PRINT("message: %c\n", *(char*)(message + i)); mq->rear++; // PRINT("queue_start: 0x%x, rear: 0x%x\n", mq->queue_start, mq->rear); // if reach to end of queue, back to start of queue if (mq->rear - mq->queue_start == mq->msg_size * mq->queue_size) { mq->rear = mq->queue_start; } } // end of critcial section // // for debugging // for (i = 0; i < mq->msg_size * mq->queue_size; i++) { // printf("message queue content: %c\n", *(char*)(mq->queue_start + i)); // } eos_release_semaphore(&mq->getsem); } int8u_t eos_receive_message(eos_mqueue_t *mq, void *message, int32s_t timeout) { // PRINT("Recieve message called!\n"); // if failed to acquiring semaphore, just return if (eos_acquire_semaphore(&mq->getsem, timeout) == 0) { return 0; } int i; /* * critical section for message queue */ // copy message from queue for (i = 0; i < mq->msg_size; i++) { *(char *)(message + i) = *(char *)(mq->front); *(char *)(mq->front) = NULL; // PRINT("message: %c\n", *(char*)(message + i)); mq->front++; // PRINT("queue_start: 0x%x, front: 0x%x\n", mq->queue_start, mq->front); if (mq->front - mq->queue_start == mq->msg_size * mq->queue_size) { mq->front = mq->queue_start; } } // end of cirtical section // // for debugging // for (i = 0; i < mq->msg_size * mq->queue_size; i++) { // printf("message queue content: %c\n", *(char*)(mq->queue_start + i)); // } eos_release_semaphore(&mq->putsem); }
C
/***************************************************************************** * tile.c . . . * * Methodes to deal with DTED files and tiles, the . . /\ . . * * memory representation of a DTED file . / \ . /\ .* * . . / \/\ / \ . * * panoramaMaker . / / \ \ * * Guillaume Communie - [email protected] / / \ \ * *****************************************************************************/ #include "tile.h" #include "error.h" #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <math.h> #include <errno.h> #include <string.h> /* * Conversion of altitude from DTED file representation to little endian * 2's complement representation. * param x: DTED file data. * return: Data in little endian and negative in 2's complement. */ static int16_t toLittleEndian(int16_t x) { x = ((uint16_t) x >> 8) | ((uint16_t) x << 8); x = x & 0x8000 ? -1 * (x & 0x7FFF) : x; return x; } /* * Free the memory associated to a tile. * param tile: Pointer to a tile. */ void freeTile(Tile* tile) { free(tile->data); free(tile); } /* * Open a DTED file, read and store the altitude data. * param fileName: Path to a DTED file. * return: Pointer to the tile. */ Tile* openTile(char* fileName) { FILE* dtedFile; long fileSize, expectedSize; char headerData[10]; Tile* tile; int nbLon, nbLat, pt, coverage; // Open file. if (!(dtedFile = fopen(fileName, "r"))) { errPrintf("Unable to open %s >", fileName); } fprintf(stdout, "Opening of %s\n", fileName); // Get the number of points. fseek(dtedFile, DTED_DSI_NBLAT, SEEK_SET); fread(&headerData, 4, 1, dtedFile); nbLat = 1000 * (headerData[0] - 48) + 100 * (headerData[1] - 48) + 10 * (headerData[2] - 48) + (headerData[3] - 48); fseek(dtedFile, DTED_DSI_NBLON, SEEK_SET); fread(&headerData, 4, 1, dtedFile); nbLon = 1000 * (headerData[0] - 48) + 100 * (headerData[1] - 48) + 10 * (headerData[2] - 48) + (headerData[3] - 48); // Check file. fseek(dtedFile, 0, SEEK_END); fileSize = ftell(dtedFile); fprintf(stdout, "Size: %ld bytes\n", fileSize); expectedSize = DTED_DATA + (nbLat * 2 + 12) * nbLon; if (fileSize != expectedSize) { errPrintf("The file has an incorrect size. %ld bytes where expected", expectedSize); } fseek(dtedFile, DTED_DSI_DATACOV, SEEK_SET); fread(&headerData, 2, 1, dtedFile); coverage = 10 * (headerData[0] - 48) + (headerData[1] - 48); coverage = coverage ? coverage : 100; printf("File covers %d%% of the region.\n", coverage); // Memory allocation. if (!(tile = malloc(sizeof(Tile)))) { errPrintf("Unable to allocate memory for the tile >"); } if (!(tile->data = malloc(nbLat * nbLon * sizeof(uint16_t)))) { errPrintf("Unable to allocate memory for the tile data >"); } // Data storage. tile->latitudeDimension = nbLat; tile->longitudeDimension = nbLon; fseek(dtedFile, 3428, SEEK_SET); for (int i = 0 ; i < nbLon ; i++) // Longitude goes W to E. { fseek(dtedFile, 8, SEEK_CUR); for (int j = 0 ; j < nbLat ; j++) // Lat goes S to N. { pt = i * nbLon + j; fread(&tile->data[pt], 2, 1, dtedFile); tile->data[pt] = toLittleEndian(tile->data[pt]); } fseek(dtedFile, 4, SEEK_CUR); } fclose(dtedFile); return tile; } /* * Create a space, data structure that will contain the tiles around the * origin. * param originLon: longitude of the origin, center of the space. * param originLat: latitude of the origin, center of the space. * return: pointer to the space. */ Space* initSpace(double originLon, double originLat) { Space* space; char fileName[35]; char lonDir; char latDir; int lonDeg; int latDeg; // Init Space if (!(space = malloc(sizeof(Space)))) { errPrintf("Unable to allocate memory for the space >"); } space->originLon = originLon; space->originLat = originLat; memset(space->tiles, 0, SIZE_SPACE * sizeof(Tile*)); // Open the DTED file corresponding to origin lonDir = originLon > 0 ? 'e' : 'w'; latDir = originLat > 0 ? 'n' : 's'; lonDeg = (int) originLon; lonDeg = lonDeg > 0 ? lonDeg : -(lonDeg - 1); latDeg = (int) originLat; latDeg = latDeg > 0 ? latDeg : -(latDeg - 1); sprintf(fileName, DATA_DIR "%c%02d_%c%03d_1arc_v3.dt2", latDir, latDeg, lonDir, lonDeg); space->tiles[SIZE_SPACE / 2] = openTile(fileName); return space; } /* * Free space associated to a space. * param space: the space to be freed */ void freeSpace(Space* space) { for (int i = 0 ; i < SIZE_SPACE ; i++) { if (space->tiles[i]) { freeTile(space->tiles[i]); } } free(space); }
C
/* Copyright (c) 2009 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ /** @file * @defgroup blinky_example_pca10001_main main.c * @{ * @ingroup blinky_example_pca10001 * * @brief Blinky Example Application main file. * * This file contains the source code for a sample application using GPIO to drive LEDs. * */ #include <stdbool.h> #include <stdint.h> #include "nrf_delay.h" #include "nrf_gpio.h" #include "boards.h" static void gpio_init(void) { nrf_gpio_cfg_input(BUTTON_0, BUTTON_PULL); nrf_gpio_cfg_output(22); //nrf_gpio_pin_write(22, BUTTON_0); //처음에 led를 on으로 시작하는 경우 // Enable interrupt: NVIC_EnableIRQ(GPIOTE_IRQn); NRF_GPIOTE->CONFIG[0] = (GPIOTE_CONFIG_POLARITY_Toggle << GPIOTE_CONFIG_POLARITY_Pos) | (0 << GPIOTE_CONFIG_PSEL_Pos) | (GPIOTE_CONFIG_MODE_Event << GPIOTE_CONFIG_MODE_Pos); NRF_GPIOTE->INTENSET = GPIOTE_INTENSET_IN0_Set << GPIOTE_INTENSET_IN0_Pos; } /** @brief Function for handling the GPIOTE interrupt which is triggered on pin 0 change. */ void GPIOTE_IRQHandler(void) { // Event causing the interrupt must be cleared. if ((NRF_GPIOTE->EVENTS_IN[0] == 1) && (NRF_GPIOTE->INTENSET & GPIOTE_INTENSET_IN0_Msk)) { NRF_GPIOTE->EVENTS_IN[0] = 0; } //nrf_gpio_pin_toggle(8); nrf_gpio_pin_toggle(22); //nrf_gpio_pin_toggle(18); } /** * @brief Function for application main entry. */ int main(void) { // Configure LED-pins as outputs nrf_gpio_cfg_output(LED_0); nrf_gpio_cfg_output(LED_1); nrf_gpio_cfg_output(22); gpio_init(); // LED 0 and LED 1 blink alternately. while(true) { /* nrf_gpio_pin_clear(LED_0); nrf_gpio_pin_set(LED_1); nrf_gpio_pin_clear(22); nrf_delay_ms(500); nrf_gpio_pin_clear(LED_1); nrf_gpio_pin_set(LED_0); nrf_gpio_pin_set(22); nrf_delay_ms(500); */ } } /** *@} **/
C
/************************************************************************/ /* The code creates a balanced binary tree. */ /* The code has been tested by a little data, so it can not ensure */ /* that it can deal with all case!!!. */ /* The data for testing can find on Page 234 of the book. */ /* If you can not work for some cases, please report it to me. */ /* Author: John Lee */ /* E-mail: [email protected] */ /* Date : 2004-11-27 */ /************************************************************************/ #include <stdio.h> typedef int TreeElemType; typedef struct AVLNode{ TreeElemType data; int bf; /*balance factor*/ struct AVLNode *lchild,*rchild; }AVLNode,*AVLTree; typedef enum{FOUND,NOFOUND} Status; #define YES 1 #define NO 0 void R_Rotate(AVLTree *p){ AVLNode *q,*T; T=*p; q=T->lchild; T->lchild=q->rchild; q->rchild=T; *p=q; } void L_Rotate(AVLTree *p){ AVLNode *q,*T; T=*p; q=T->rchild; T->rchild=q->lchild; q->lchild=T; *p=q; } void LeftBalance(AVLTree *ptr_T){ AVLNode *T,*lc,*rd; T=*ptr_T; lc=T->lchild; switch(lc->bf){ case 1: T->bf=lc->bf=0; R_Rotate(ptr_T); break; case -1: rd=lc->rchild; switch(rd->bf){ case 1: T->bf=-1; lc->bf=0; break; case 0: T->bf=0; lc->bf=0; break; case -1: T->bf=0; lc->bf=-1; break; } rd->bf=0; L_Rotate(&T->lchild);/*(&lc) is error,why?*/ R_Rotate(ptr_T); break; default: printf("Balance factor error!!\n"); exit(0); } } void RightBalance(AVLTree *ptr_T){ AVLNode *T,*lc,*rd; T=*ptr_T; rd=T->rchild; switch(rd->bf){ case -1: T->bf=rd->bf=0; L_Rotate(ptr_T); break; case 1: lc=rd->lchild; switch(lc->bf){ case 1: T->bf=0; rd->bf=-1; break; case 0: T->bf=0; rd->bf=0; break; case -1: T->bf=1; rd->bf=0; break; } lc->bf=0; R_Rotate(&T->rchild); L_Rotate(ptr_T); break; default: printf("Balance factor error!!\n"); exit(0); } } Status searchAVL(AVLTree *ptr_T,int key,AVLNode **ptr_key_pos, int *taller){ AVLNode *p,*T; T=*ptr_T; if(T==NULL) { /***** No found, insert a node**********/ p=(AVLNode*)malloc(sizeof(AVLNode)); p->data=key; p->rchild=p->lchild=NULL; p->bf=0; *ptr_T=p; /***** Insert over*********************/ *taller=YES; return NOFOUND; } else if(T->data==key) { *ptr_key_pos=T; return FOUND; } else if(key<T->data) { if(searchAVL(&T->lchild,key,ptr_key_pos,taller)==FOUND) return FOUND; if(*taller==YES){ switch(T->bf){ case 1: LeftBalance(ptr_T); *taller=NO; break; case 0: T->bf=1; *taller=YES; break; case -1: T->bf=0; *taller=NO; break; }/*end swith*/ } return NOFOUND; }/*end if(key<T->data)*/ else /*(key>T->data)*/ { if(searchAVL(&T->rchild,key,ptr_key_pos,taller)==FOUND) return FOUND; if(*taller==YES){ switch(T->bf){ case 1: T->bf=0; *taller=NO; break; case 0: T->bf=-1; *taller=YES; break; case -1: RightBalance(ptr_T); *taller=NO; break; }/*end swith*/ } return NOFOUND; }/*end else key>T->data*/ } void PreOrderTrans(AVLTree T){ if(T!=NULL){ printf("%d ",T->data); PreOrderTrans(T->lchild); PreOrderTrans(T->rchild); } } void InOrderTrans(AVLTree T){ if(T!=NULL){ InOrderTrans(T->lchild); printf("%d ",T->data); InOrderTrans(T->rchild); } } void main(){ AVLTree T=NULL; /* Initailizing is necessary*/ AVLNode *position; int key,i,taller; int record[]={13,24,37,90,53};/*can finded in Page 234*/ int total=5;/*The number of records*/ printf("The test data is (can modified in the program) :\n"); for(i=0;i<total;i++) printf("%d\t",record[i]); printf("\n"); /**** Create a AVL tree by searching******************/ for(i=0;i<total;i++) searchAVL(&T,record[i],&position,&taller); /********Verify the result of creating BST*****/ printf("Pre-order transverse:\n"); PreOrderTrans(T); printf("\n"); printf("In-order transverse:\n"); InOrderTrans(T); printf("\n"); printf("Please input a key to search:\n"); scanf("%d",&key); if(searchAVL(&T,key,&position,&taller)==NOFOUND) printf("No found a key: (%d) from the Tree, Insert it!\n",key); else printf("The record is :%d\n",position->data); /********Verify over!!!************************/ getch(); }
C
#include <ruby.h> // Allocate a variable for the factorial module. Ruby values are all of type VALUE. Qnil is the C representation of Ruby's nil. // The Ruby module where the fast_fibonacci will reside is called egotistically MyMath VALUE MyMath = Qnil; // This is the module that will be responsible for fast computation of Fibonacci sequence VALUE FastFibonacci = Qnil; // This is run when the file is loaded and performa initialization void Init_mymath_fast_fibonacci(); // Functions that operate on Ruby values all take and return VALUE as parameters // Compute the fibonacci sequence up to fibonacci_to_compute, this binds the ruby method and types to C function and types VALUE method_fast_fibonacci(VALUE self, VALUE fibonacci_to_compute); // The C recursive method that will compute the fibonacci_number in location fibonacci_to_compute, i.e. get me the fibonacci_to_compute's sequence in the series unsigned long fast_fibonacci(unsigned long fibonacci_to_compute); // rb_define_module() defines a ruby module // rb_define_module_under() creates a module under one that is provided, this is your namespacing way to go about these things // rb_define_singleton_method(), well guess what it does, it binds a c method to a module and a method, this effectively exposes the C function a method on the module, the last parameter is the method's arity, which for us is just 1 void Init_mymath_fast_fibonacci(){ // Defines a Ruby module MyMath MyMath = rb_define_module("MyMath"); // Defines a module within MyMath::FastFibonacci FastFibonacci = rb_define_module_under(MyMath, "FastFibonacci"); // Defines a method in FastFibonacci called compute, use as MyMath::FastFibonacci.compute(number_in_sequence) rb_define_singleton_method(FastFibonacci, "compute", method_fast_fibonacci, 1); } // Pass through function that will cast the parameters from their C types to Ruby VALUE method_fast_fibonacci(VALUE self, VALUE fibonacci_to_compute){ // Without converting to C int type the results here are very strange, the casting will attempt to do something but it CAN NOT be trusted // For example in the below printout implicitly casting a Ruby value into an unsigned long C type // The result when fibonacci_to_compute is 1 the prinf statement will print 3 //printf("Input to %s %lu\n", self, fibonacci_to_compute); // Cast to C INT and call the recursive Fibonacci function unsigned long computed = fast_fibonacci(NUM2INT(fibonacci_to_compute)); // Same when converting back the C type to Ruby number, always do it explicitly return INT2NUM(computed); } // Standard recursive function to compute a fibonacci number unsigned long fast_fibonacci(unsigned long fibonacci_to_compute){ //printf("%lu\n", fibonacci_to_compute); if(fibonacci_to_compute == 0){ return 0; } else if (fibonacci_to_compute == 1){ return 1; } else{ return (fast_fibonacci(fibonacci_to_compute-1) + fast_fibonacci(fibonacci_to_compute-2)); } }
C
// Sudoku Guesser //#include <stdlib.h> #include <stdio.h> #include "header.h" int main(int argc, char const *argv[]) { int sudoku[9][9]; FILE *fp; fp = fopen(argv[1], "r"); char c; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { c = fgetc(fp); if (c == ' ' || c == '\n' || c == '\t') c = fgetc(fp); if (c == '?') { sudoku[i][j] = 0; } else { sudoku[i][j] = (int)c - 48; } } } printf("==========INPUT==========\n"); for (int i = 0; i < 9; ++i) { if (i%3 == 0) { printf("-------------------\n"); } for (int j = 0; j < 9; ++j) { if (j%3 == 0) printf("|"); if (sudoku[i][j] == 0) { printf("?"); } else { printf("%d", sudoku[i][j]); } if (j%3 != 2) printf(" "); if (j == 8) printf("|"); } printf("\n"); } printf("-------------------\n"); int sudokuCopy[9][9]; for (int i = 0; i < 9; ++i) { for (int j = 0; j < 9; ++j) { sudokuCopy[i][j] = sudoku[i][j]; } } printf("==========OUTPUT==========\n"); int success = backtrack(0, 0, sudokuCopy); if (success) { for (int i = 0; i < 9; ++i) { if (i%3 == 0) { printf("-------------------\n"); } for (int j = 0; j < 9; ++j) { if (j%3 == 0) printf("|"); if (sudokuCopy[i][j] == 0) { printf("?"); } else { printf("%d", sudokuCopy[i][j]); } if (j%3 != 2) printf(" "); if (j == 8) printf("|"); } printf("\n"); } printf("-------------------\n"); } return 0; }
C
/* This program illustrates the use of the vfork() system call to create a child process. The vfork() is an * optimization over the fork() call in that it does not replicate the parent's text and data regions in the * child's address space. The parent and child reference the same data and text regions. * * Author: Naga Kandasamy * Date created: December 22, 2008 * Date modified: January 3, 2020 * * Compile as follows: gcc -o simple_fork_v3 simple_fork_v3.c -std=c99 -Wall * Execute as follows: ./simple_fork_v3 */ /* Feature test macro to ensure that the compiler does not throw up a warning when using vfork () */ #define _BSD_SOURCE || _SVID_SOURCE || \\ (_XOPEN_SOURCE >= 500 || _XOPEN_SOURCE && _XOPEN_SOURCE_EXTENDED) && \\ !(_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) #include <stdio.h> #include <string.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdlib.h> int global_variable = 10; int main (int argc, char **argv) { int pid; /* Process ID returned by vfork */ int status; int local_variable = 100; if ((pid = vfork ()) < 0) { /* Fork the process. vfork does not replicate the address space */ perror ("fork"); exit (EXIT_FAILURE); } else if (pid == 0) { /* Child code */ global_variable++; /* Increment global variable */ local_variable++; /* Increment local variable */ printf ("Child: Global variable = %d, Local variable = %d\n", global_variable, local_variable); exit (EXIT_SUCCESS); /* Child exits */ } /* Parent code */ pid = waitpid (pid, &status, 0); /* Wait for child to terminate */ printf ("Parent: Global variable = %d, Local variable = %d\n", global_variable, local_variable); exit (EXIT_SUCCESS); }
C
/* $Id: Loading.C,v 1.28 2005-08-01 21:58:35 wilsonp Exp $ */ /* (Potential) File sections: * Service: constructors, destructors * Input: functions directly related to input of data * xCheck: functions directly related to cross-checking the input * against itself for consistency and completeness * Preproc: functions directly related to preprocessing of input * prior to solution * Solution: functions directly related to the solution of a (sub)problem * Utility: advanced member access such as searching and counting */ #include "Loading.h" #include "Mixture.h" #include "Component.h" #include "CoolingTime.h" #include "Calc/topScheduleT.h" #include "Output/Result.h" #include "Output/Output_def.h" /*************************** ********* Service ********* **************************/ /** When called with no arguments, it creates an blank list head with no problem data. Otherwise, it creates and fills the storage for 'zoneName' ,'mixName', 'userVol', 'userVolFlag' and initializes next to NULL. */ Loading::Loading(const char *name, const char *mxName, bool inUserVolFlag, double inUserVol) { volume = 0; zoneName = NULL; mixName = NULL; mixPtr = NULL; if (name != NULL) { zoneName = new char[strlen(name)+1]; memCheck(zoneName,"Loading::Loading(...) constructor: zoneName"); strcpy(zoneName,name); } if (mxName != NULL) { mixName = new char[strlen(mxName)+1]; memCheck(mixName,"Loading::Loading(...) constructor: mixName"); strcpy(mixName,mxName); } userVolFlag=inUserVolFlag; userVol=inUserVol; nComps = 0; outputList = NULL; total = NULL; next = NULL; } /** This constructor is identical to default constructor. Therefore, 'zoneName' and 'mixName' are copied, but the 'outputList' and 'total' are initialized to NULL successive list item 'next' is not. */ Loading::Loading(const Loading &l) { volume = l.volume; mixPtr = l.mixPtr; userVol = l.userVol; userVolFlag = l.userVolFlag; zoneName = NULL; mixName = NULL; if (l.zoneName != NULL) { zoneName = new char[strlen(l.zoneName)+1]; memCheck(zoneName,"Loading::Loading(...) copy constructor: zoneName"); strcpy(zoneName,l.zoneName); } if (l.mixName != NULL) { mixName = new char[strlen(l.mixName)+1]; memCheck(mixName,"Loading::Loading(...) copy constructor: mixName"); strcpy(mixName,l.mixName); } nComps = 0; outputList = NULL; total = NULL; next = NULL; } Loading::~Loading() { delete mixName; delete zoneName; delete [] outputList; delete next; } /** This assignment operator behaves similarly to the copy constructor. The correct implementation of this operator must ensure that previously allocated space is returned to the free store before allocating new space into which to copy the object. Note that 'next' is NOT copied, the left hand side object will continue to be part of the same list unless explicitly changed. */ Loading& Loading::operator=(const Loading &l) { if (this == &l) return *this; volume = l.volume; mixPtr = l.mixPtr; userVol = l.userVol; userVolFlag = l.userVolFlag; delete zoneName; delete mixName; zoneName = NULL; mixName = NULL; if (l.zoneName != NULL) { zoneName = new char[strlen(l.zoneName)+1]; memCheck(zoneName,"Loading::operator=(...): zoneName"); strcpy(zoneName,l.zoneName); } if (l.mixName != NULL) { mixName = new char[strlen(l.mixName)+1]; memCheck(mixName,"Loading::operator=(...): mixName"); strcpy(mixName,l.mixName); } nComps = 0; delete [] outputList; outputList = NULL; delete total; total = NULL; return *this; } /**************************** *********** Input ********** ***************************/ /******* get a list of material loadings *******/ /* called by Input::read(...) */ /** The material loadings are expected to appear as a single group in the correct order. This function reads from the first loading until keyword 'end'. */ void Loading::getMatLoading(istream& input) { char name[64],token[64],usv[64]; bool busv; Loading *ptr = this; bool isusv(char* Usv); verbose(2,"Reading the material loading for this problem."); /* read list of zone/mixture x-refs until keyword "end" */ input >> token; while (strcmp(token,"end")) { input >> name; clearComment(input); input >> usv; clearComment(input); busv=isusv(usv)?TRUE:FALSE; ptr->next = new Loading(token,name,busv,strtod(usv,NULL)); memCheck(next,"Loading::getMatLoading(...): next"); ptr = ptr->next; verbose(3,"Adding zone %s with mixture%s.",token,name); if (busv) input >> token; else strcpy(token,usv); } if (ptr->head()) warning(170,"Material Loading is empty."); } //********* Function isusv declared in Loading::getMatLoading********** bool isusv(char* Usv) { //Checks wheter argument points to real number. If this were the case //then this is assume to be userVol and the function returns TRUE. char* strptr=new char[64]; char* *pcharptr=&strptr; strtod(Usv,pcharptr); if (strptr[0]=='\0') return TRUE; else return FALSE; } /******* get a list of material loadings *******/ /* called by Input::read(...) */ /** These lists are cross-referenced with the master list in xCheck(). */ void Loading::getSolveList(istream& input) { char token[64]; Loading *ptr = this; verbose(2,"Reading the zones to solve/skip for this problem."); /* read list of zone/mixture x-refs until keyword "end" */ input >> token; while (strcmp(token,"end")) { ptr->next = new Loading(token,"on"); memCheck(next,"Loading::getSolveList(...): next"); ptr = ptr->next; verbose(3,"Adding zone %s to solve/skip list.",token); clearComment(input); input >> token; } } /*************************** ********* xCheck ********** **************************/ /* called by Input::xCheck(...) */ /** If a mixture does not exist, it will generate an error and the program will halt. The argument is a pointer to a Mixture object, and should be the head of the mixture list. */ void Loading::xCheck(Mixture *mixListHead, Loading *solveList, Loading *skipList) { Loading *ptr = this; verbose(2,"Checking for all mixtures referenced in material loading."); /* for each zone */ while (ptr->next != NULL) { ptr=ptr->next; /* check for this zone in explicit solve list or skip list */ if ( ( solveList->nonEmpty() && solveList->findZone(ptr->zoneName)==NULL ) || skipList->findZone(ptr->zoneName)!=NULL ) { delete ptr->mixName; ptr->mixName = new char[5]; strcpy(ptr->mixName,"void"); } else if (strcmp(ptr->mixName,"void")) { /* search for the mixture referenced in this zone */ ptr->mixPtr = mixListHead->find(ptr->mixName); if ( ptr->mixPtr == NULL) error(370, "Zone %s is loaded with a non-existent mixture: %s", ptr->zoneName,ptr->mixName); else { ptr->nComps = ptr->mixPtr->getNComps(); ptr->outputList = new Result[ptr->nComps+1]; } } } verbose(3,"All mixtures referenced in material loading were found."); } /***************************** ********* PostProc ********** ****************************/ /** The tallying is weighted by the second argument. This is used to tally the results of each interval in to the total zone results, weighted by the interval volume. */ void Loading::tally(Result *volOutputList, double vol) { int compNum; volume += vol; /* tally the results for each of the components */ for (compNum=0;compNum<nComps;compNum++) volOutputList[compNum].postProc(outputList[compNum],vol); /* tally the total results */ volOutputList[compNum].postProc(outputList[compNum],vol); } /** The first argument indicates which kind of response is being written and the second indicates whether a mixture component breakdown was requested. The third argument points to the list of after-shutdown cooling times. The fourth argument indicates the kza of the target isotope for a reverse calculation and is simply passed on the the Result::write(). The final argument indicates what type of normalization is being used, so that the correct output information can be given. */ void Loading::write(int response, int writeComp, CoolingTime* coolList, int targetKza, int normType) { Loading *head = this; Loading *ptr = head; int zoneCntr = 0; double volFrac, volume_mass, density; /* for each zone */ while (ptr->next != NULL) { ptr = ptr->next; /* write header info */ cout << endl; cout << "Zone #" << ++zoneCntr << ": " << ptr->zoneName << endl; debug(5,"Loading::userVol=%f",ptr->userVol); if (ptr->mixPtr != NULL) { if (normType > 0) cout << "\tRelative Volume: " << ptr->volume << endl; else cout << "\tMass: " << ptr->volume*ptr->mixPtr->getTotalDensity() << endl; cout << "\tContaining mixture: " << ptr->mixName << endl << endl; /* write the component breakdown if requested */ if (writeComp && response != OUTFMT_SRC) { /* get the list of components for this mixture */ Component *compPtr = ptr->mixPtr->getCompList(); int compNum=0; compPtr = compPtr->advance(); /* for each component */ while (compPtr != NULL) { volFrac = compPtr->getVolFrac(); volume_mass = ptr->volume*volFrac; /* write component header */ cout << "Constituent: " << compPtr->getName() << endl; if (normType < 0) { cout << "\tVolume Fraction: " << volFrac << "\tRelative Volume: " << volume_mass; density = compPtr->getDensity(); volume_mass *= density; cout << "\tDensity: " << density << "\tMass: " << volume_mass; } else if (normType == OUTNORM_VOL_INT) { /* The loading responses are volume weighted sums already. For volume integrated results, don't renormalize */ cout << "\tVolume Fraction: " << volFrac << "\tAbsolute Volume: " << ptr->userVol; volume_mass /= ptr->userVol; cout << "\tVolume Integrated "; } else { cout << "\tVolume Fraction: " << volFrac << "\tRelative Volume: " << volume_mass; } cout << endl; ptr->outputList[compNum].write(response,targetKza,ptr->mixPtr, coolList,ptr->total,volume_mass); compPtr = compPtr->advance(); compNum++; } } volFrac = ptr->mixPtr->getVolFrac(); /* if components were written and there is only one */ if (writeComp && ptr->nComps == 0 && volFrac == 1.0) /* write comment refering total to component total */ cout << "** Zone totals are the same as those of the single constituent." << endl << endl; else { /* otherwise write the total response for the zone */ volume_mass = ptr->volume * volFrac; cout << "Total (All constituents) " << endl; cout << "\tCOMPACTED" << endl; if (normType < 0) { density = ptr->mixPtr->getTotalDensity(); /* different from constituent: mixture densities already take volume fraction into account */ cout << "\tVolume Fraction: " << volFrac << "\tRelative Volume: " << volume_mass; volume_mass = ptr->volume * density; cout << "\tDensity: " << density << "\tMass: " << volume_mass; } else if (normType == OUTNORM_VOL_INT) { /* The loading responses are volume weighted sums already. For volume integrated results, don't renormalize */ cout << "\tVolume Fraction: " << volFrac << "\tAbsolute Volume: " << ptr->userVol; volume_mass /= ptr->userVol; cout << "\tVolume Integrated "; } else { cout << "\tVolume Fraction: " << volFrac << "\tRelative Volume: " << volume_mass; } cout << endl; ptr->outputList[ptr->nComps].write(response, targetKza, ptr->mixPtr, coolList, ptr->total, volume_mass); } } } /** WRITE TOTAL TABLE **/ /* reset zone pointer and counter */ ptr = head; zoneCntr = 0; int resNum,nResults = topScheduleT::getNumCoolingTimes()+1; char isoSym[15]; cout << endl; cout << "Totals for all zones." << endl; cout << Result::getReminderStr() << endl; /* write header for totals */ coolList->writeTotalHeader("zone"); /* for each zone */ while (ptr->next != NULL) { ptr = ptr->next; cout << ++zoneCntr << "\t"; if (ptr->mixPtr != NULL) for (resNum=0;resNum<nResults;resNum++) { sprintf(isoSym,"%-11.4e ",ptr->total[resNum]); cout << isoSym; } cout << "\t" << ptr->zoneName << " (" << ptr->mixName << ")" << endl; } coolList->writeSeparator(); cout << endl << endl; } /****************************** *********** Utility ********** *****************************/ /** If found, returns a pointer to that zone loading description, otherwise, NULL. */ Loading* Loading::findZone(char *srchZone) { Loading *ptr=this; while (ptr->next != NULL) { ptr = ptr->next; if (!strcmp(ptr->zoneName,srchZone)) return ptr; } return NULL; } /** If found, returns a pointer to that zone loading description, otherwise, NULL. Note: this returns the first occurence after a the object through which it is called - if called through the list head, this is the absolute occurence. By successive calls through the object returned by the previous call, this will find all the occurences. */ Loading* Loading::findMix(char *srchMix) { Loading *ptr=this; while (ptr->next != NULL) { ptr = ptr->next; if (!strcmp(ptr->mixName,srchMix)) return ptr; } return NULL; } /* count number of zones in material loading */ int Loading::numZones() { int numZones = 0; Loading *ptr=this; while (ptr->next != NULL) { ptr = ptr->next; numZones++; } return numZones; } /* reset the output info for next target */ void Loading::resetOutList() { int compNum; Loading *ptr = this; while (ptr->next != NULL) { ptr = ptr->next; ptr->volume = 0; if (ptr->outputList != NULL) for (compNum=0;compNum<=ptr->nComps;compNum++) ptr->outputList[compNum].clear(); } }
C
/*========================================================= 8-2-4 OjMk Fib_Search() OjM禡 a[ARR_NUM] jM ARR_NUM jMƼƥ(}Cjp) ========================================================= */ #include <stdio.h> #include <stdlib.h> #define MAX_NUM 12 #define Fib_NUM 20 int Fib_Search(int [],int ,int ,int); void PrintArray(int [],int); int F[Fib_NUM]; void Init_Fib(); int Find_Point(int); int main(int argc, char *argv[]) { int a[MAX_NUM]={6,33,39,41,52,55,69,77,78,81}; int n = 10; int data,locate,k; Init_Fib(); k = Find_Point(n); PrintArray(a,n); while (1) { printf("\nпJjMƤe (0 to stop)=> "); scanf("%d",&data); if ( data == 0) break; if((locate=Fib_Search(a,n,data,k)) == -1) printf("OjMk䤣\n!!!"); else printf("OjMk %d %d Ӧm(0_)\n",data,locate); } system("PAUSE"); return 0; } void Init_Fib() { int i; F[0] = 0; F[1] = 1; for ( i=2; i<=Fib_NUM ; i++) F[i] = F[i-1] + F[i-2]; } int Find_Point(int n) { int k; for (k=0; k<Fib_NUM; k++) if ( (n > F[k]-1) && ( n <= F[k+1]-1)) break; return k+1; } /*ba[0..n-1]}CMkey,öǦ^m ,ϥFibonacci Search*/ int Fib_Search(int a[], int n, int key, int k) //]wF[k-1]-1 < n <= F[k]-1 { int l = 0, r = n-1, m, i; for ( i=n; i< F[k]-1; i++) //J dummy key a[i] = a[n-1]; while (l <= r) { m = l + F[k-1] - 1 ; //Skΰk if (key == a[m]) { if ( m < n ) //not dummy return (m); //,Ǧ^m else return (n-1); } if (key < a[m]) //b,ܥk { r = m-1; k = k - 1 ; } else //kb,ܥ { l = m+1; k = k - 2 ; } } return(-1); //ѶǦ^-1 } void PrintArray(int a[], int n) { int i; for (i=0; i<n; i++) printf("%d ",a[i]); }
C
/* * Interrrupts.c * * Created: 7/25/2021 2:45:21 PM * Author : ferez */ //If F_CPU not defined #ifndef F_CPU //Because ATMEGA128 runs at 16MHz , UL - Unsigned Long #define F_CPU 16000000UL #endif #define PORT_LED0 PORTC #define PIN_LED0 PINC0 #define PORT_LED1 PORTC #define PIN_LED1 PINC1 #define SWITCH_K0 !(PIND & (1<<PIND0)) #define SWITCH_K1 !(PIND & (1<<PIND1)) // !(PIND & (1 << PIND0) == (1 << PIND0)) #include <avr/io.h> #include <util/delay.h> #include <avr/interrupt.h> void pinSet(volatile uint8_t *port, uint8_t pin); void pinReset(volatile uint8_t *port, uint8_t pin); /*Interrupt Service Routine for INT0*/ ISR(INT1_vect) { pinReset(&PORT_LED0, PIN_LED0); pinReset(&PORT_LED1, PIN_LED1); } ISR(INT0_vect) { pinSet(&PORT_LED0, PIN_LED0); pinSet(&PORT_LED1, PIN_LED1); } int main() { DDRC = 0xFF; PORTC = 0; DDRD &= ~(1 << PIND1) | ~(1 << PIND0); //Pins for input (both pins to 0) PORTD |= (1 << PIND1) | (1 << PIND0); //Pull-up resistors EIMSK |= (1 << INT1) | (1 << INT0); //Allow ext interrupts EICRA |= (1 << ISC01) | (1 << ISC11); //External interrupt configuration register sei(); //Allow global interrupts while (1) continue; } void pinSet(volatile uint8_t *port, uint8_t pin){ *port |= 1 << pin; } void pinReset(volatile uint8_t *port, uint8_t pin){ *port &= ~(1 << pin); }
C
#include<stdio.h> int main() { double s0, v0, t; printf("Digite os valores de s0, v0 e t, respectivamente: "); scanf("%lf %lf %lf", &s0, &v0 &t); return 0; }
C
#include <stdio.h> #include <string.h> #include <malloc.h> #include <stdlib.h> int main() { char *buffer = NULL; size_t bufsize = 32; size_t characters; buffer = (char *)malloc(bufsize * sizeof(char)); if (buffer == NULL) { exit(1); } printf("Type something: "); characters = getline(&buffer, &bufsize, stdin); printf("%zu characters were read.\n", characters); printf("You typed: %s\n", buffer); return 0; }
C
//Price Shoemaker - Systems II - DePaul /*-------------------------------------------------------------------------* *--- ---* *--- stringLangServer.c ---* *--- ---* *--- This file defines a C program that gets file-sys commands ---* *--- from client via a socket, executes those commands in their own ---* *--- threads, and returns the corresponding output back to the ---* *--- client. ---* *--- ---* *--- ---- ---- ---- ---- ---- ---- ---- ---- ---* *--- ---* *--- Version 1a Joseph Phillips ---* *--- ---* *-------------------------------------------------------------------------*/ // Compile with: // $ gcc stringLangServer.c -o stringLangServer -lpthread //--- Header file inclusion ---// #include "clientServer.h" #include <pthread.h> // For pthread_create() //--- Definition of constants: ---// #define STD_OKAY_MSG "Okay" #define STD_ERROR_MSG "Error doing operation" #define STD_BYE_MSG "Good bye!" #define THIS_PROGRAM_NAME "stringLangServer" const int ERROR_FD = -1; //--- Definition of global vars: ---// // PURPOSE: To be non-zero for as long as this program should run, or '0' // otherwise. //--- Definition of functions: ---// // PURPOSE: To: // (1) create a pipe // (2) fork() a child process. This child process will: // (2a) close() its file descriptor to stdout, // (2b) send its output from the pipe to the close stdout file descriptor // (2c) Run the program STRING_LANG_PROGNAME with cPtr on the cmd line // (2d) Send an error message back to the client on file descriptor 'fd' // if the execl() failed. // (3) get input from the pipe, put the '\0' char at the end // (4) wait() for the child process to end // (5) send the input back to the client using file descriptor 'fd' void stringLangFile(int socketFd, const char *cPtr) { // I. Application validity check: // II. Apply string language file: // YOUR CODE HERE // III. Finished: } // PURPOSE: To cast 'vPtr' to the pointer type coming from 'doServer()' // that points to two integers. Then, to use those two integers, // one as a file descriptor, the other as a thread number, to fulfill // requests coming from the client over the file descriptor socket. // Returns 'NULL'. // void *handleClient(void *vPtr) // { // // I. Application validity check: // // II. Handle client: // // YOUR CODE HERE // int fd = 0; // <-- CHANGE THAT 0! // int threadNum = 0; // <-- CHANGE THAT 0! // // YOUR CODE HERE // // III. Finished: // printf("Thread %d quitting.\n", threadNum); // return (NULL); // } void *handleClient(void *vPtr) { //printf("\n..entered handle client..\n"); int *hcPtr = (int *)vPtr; int fd = hcPtr[0]; int thread = hcPtr[1]; free(vPtr); // II.B. Read command: char buffer[BUFFER_LEN]; char command; char *textPtr; int shouldContinue = 1; const int PIPE_READ = 0; const int PIPE_WRITE = 1; pid_t child; printf("\n Thread %d starting.\n", thread); while (shouldContinue) { read(fd, buffer, BUFFER_LEN); printf("Thread %d received: %s\n", thread, buffer); command = buffer[0]; textPtr = buffer + 2; if (command == STRING_LANG_CMD_CHAR) { //printf("\n...command received: %c\n", command); int ctoP[2]; pipe(ctoP); if ((ctoP[PIPE_READ] == -1) || (ctoP[PIPE_WRITE] == -1)) { //printf("\n ..pipe error..\n"); write(fd, STD_ERROR_MSG, strlen(STD_ERROR_MSG)); //exit(EXIT_FAILURE); } //printf("\n ..pipe success..\n"); child = fork(); if (child == 0) { //printf("\n ..entered child process..\n"); close(1); dup(ctoP[PIPE_WRITE]); execl(STRING_LANG_PROGNAME, STRING_LANG_PROGNAME, &hcPtr, NULL); write(fd, STD_ERROR_MSG, strlen(STD_ERROR_MSG)); exit(EXIT_FAILURE); } else { read(ctoP[PIPE_WRITE], &textPtr, strlen(textPtr)); wait(NULL); strcat(buffer, "\0"); write(fd, buffer, strlen(buffer)); } } else if (command == QUIT_CMD_CHAR) { write(fd, STD_BYE_MSG, strlen(STD_BYE_MSG)); shouldContinue = 0; } } printf("Thread %d quitting.\n", thread); return (NULL); } // PURPOSE: To run the server by 'accept()'-ing client requests from // 'listenFd' and doing them. void doServer(int listenFd) { //printf("\n..entered do server with fd: %d\n", listenFd); // I. Application validity check: // II. Server clients: pthread_t threadId; pthread_attr_t threadAttr; int threadCount = 0; pthread_attr_init(&threadAttr); while (1) { // YOUR CODE HERE //printf("\n..entered while loop..\n"); int fd = accept(listenFd, NULL, NULL); int *ints; ints = (int *)calloc(2, sizeof(int)); ints[0] = fd; ints[1] = threadCount; threadCount++; pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED); pthread_create(&threadId, &threadAttr, handleClient, (void *)ints); } // YOUR CODE HERE // III. Finished: } // PURPOSE: To decide a port number, either from the command line arguments // 'argc' and 'argv[]', or by asking the user. Returns port number. int getPortNum(int argc, char *argv[]) { // I. Application validity check: // II. Get listening socket: int portNum; if (argc >= 2) portNum = strtol(argv[1], NULL, 0); else { char buffer[BUFFER_LEN]; printf("Port number to monopolize?"); fgets(buffer, BUFFER_LEN, stdin); portNum = strtol(buffer, NULL, 0); } // III. Finished: return (portNum); } // PURPOSE: To attempt to create and return a file-descriptor for listening // to the OS telling this server when a client process has connect()-ed // to 'port'. Returns that file-descriptor, or 'ERROR_FD' on failure. int getServerFileDescriptor(int port) { //printf("\n ATTEMPTING TO SET FD SERVER PORT TO %d\n", port); // I. Application validity check: // II. Attempt to get socket file descriptor and bind it to 'port': // II.A. Create a socket int socketDescriptor = socket(AF_INET, // AF_INET domain SOCK_STREAM, // Reliable TCP 0); if (socketDescriptor < 0) { perror(THIS_PROGRAM_NAME); return (ERROR_FD); } // II.B. Attempt to bind 'socketDescriptor' to 'port': // II.B.1. We'll fill in this datastruct struct sockaddr_in socketInfo; // II.B.2. Fill socketInfo with 0's memset(&socketInfo, '\0', sizeof(socketInfo)); // II.B.3. Use TCP/IP: socketInfo.sin_family = AF_INET; // II.B.4. Tell port in network endian with htons() socketInfo.sin_port = htons(port); // II.B.5. Allow machine to connect to this service socketInfo.sin_addr.s_addr = INADDR_ANY; // II.B.6. Try to bind socket with port and other specifications int status = bind(socketDescriptor, // from socket() (struct sockaddr *)&socketInfo, sizeof(socketInfo)); if (status < 0) { perror(THIS_PROGRAM_NAME); return (ERROR_FD); } // II.B.6. Set OS queue length: listen(socketDescriptor, 5); // III. Finished: return (socketDescriptor); } int main(int argc, char *argv[]) { // I. Application validity check: // II. Do server: int port = getPortNum(argc, argv); //printf("\n PORT SET TO %d\n", port); int listenFd = getServerFileDescriptor(port); //printf("\n LISTENFD CREATED %d\n", listenFd); int status = EXIT_FAILURE; if (listenFd >= 0) { //printf("\ncreating server...\n"); doServer(listenFd); close(listenFd); status = EXIT_SUCCESS; } // III. Finished: return (status); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* push_swap.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: kmashao <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/09/28 08:16:51 by kmashao #+# #+# */ /* Updated: 2018/09/28 08:16:53 by kmashao ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef PUSH_SWAP_H # define PUSH_SWAP_H # include "libft/libft.h" # include <stdlib.h> typedef struct s_stack { int num; struct s_stack *next; } t_stack; void push(t_stack **stack_a, t_stack *node); void sa_sb(t_stack **stack_a, t_stack **stack_b); void swap(t_stack **stack); void rotate(t_stack **stack); void ra_rb(t_stack **stack_a, t_stack **stack_b); void rev_rotate(t_stack **stack); void rev_rotate_ab(t_stack **stack_a, t_stack **stack_b); int check_args(int ac,char **av); int is_num(char *str); int empty(char *str); int sorted(t_stack *stack); int has_dup(char **av); char **split_args(int ac, char **args); int exceeds_max(char *av); int valid(char **av); t_stack *make_stack(int ac, char **av); void del_stack(t_stack **stack); void print_stack(t_stack **stack); void do_op_2(char *op, t_stack **stack_a, t_stack **stack_b); void do_op(char *op, t_stack **stack_a, t_stack **stack_b); int check_desc(t_stack **stack); void sort_b(t_stack **stack_a, t_stack **stack_b); void sort_a(t_stack **stack_a, t_stack **stack_b); void sort_all(t_stack **stack_a, t_stack **stack_b); int check_ops(char *op); t_stack *get_stack(int ac, char **av); #endif
C
#include <stdio.h> int main (void) { void scalarMultiply (int matrix[3][5], int scalar); void displayMatrix (int matrix[3][5]); int sampleMatrix[3][5] = { {7,16, 55, 13, 12}, {12,10,52,0,7}, {-2, 1, 2, 4, 9} }; printf("Original matrix:\n"); displayMatrix (sampleMatrix); scalarMultiply (sampleMatrix, 2); printf("\nMultipled by 2:\n"); displayMatrix (sampleMatrix); scalarMultiply (sampleMatrix, -1); printf("\nThen multiplied by -1:\n"); displayMatrix (sampleMatrix); return 0; } // Function to multiply a 3x5 array by a scalar void scalarMultiply (int matrix[3][5], int scalar) { int row, column; for (row=0; row<3; ++row) for (column=0; column<5; ++column) matrix[row][column] *= scalar; } void displayMatrix (int matrix[3][5]) { int row, column; for (row=0; row<3; ++row) { for ( column=0; column<5; ++column) printf("%5i", matrix[row][column]); printf("\n"); } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jechoi <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/02 17:08:34 by jechoi #+# #+# */ /* Updated: 2020/11/04 17:12:45 by jechoi ### ########.fr */ /* */ /* ************************************************************************** */ #include <stdlib.h> int is_charset(char c, char *charset) { while (*charset) { if (c == *charset) return (1); charset++; } return (0); } long long get_str_cnt(char *str, char *charset) { long long ret; int is_start; ret = 0; is_start = 0; while (*str) { if (!is_charset(*str, charset) && !is_start) { ret++; is_start = 1; } else if (is_charset(*str, charset)) is_start = 0; str++; } return (ret); } void ft_strncpy(char *dest, char *src, long long n) { long long idx; idx = 0; while (idx++ < n) *(dest++) = *(src++); *dest = 0; } char **ft_split(char *str, char *charset) { char **ret; char *st; long long idx; long long word_size; ret = (char **)malloc(sizeof(char *) * (get_str_cnt(str, charset) + 1)); idx = 0; while (*str) { st = str; word_size = 0; while (*str && !is_charset(*(str++), charset)) word_size++; if (word_size == 0) continue; ret[idx] = (char *)malloc(sizeof(char) * (word_size + 1)); ft_strncpy(ret[idx++], st, word_size); } ret[idx] = 0; return (ret); }
C
#include <stdio.h> int swap_count = 0; int shift_count= 0; void swap(int *a, int *b) { int temp; temp = *a; *a = *b; *b = temp; swap_count++; } void print_ar(int ar_size, int * ar) { int i; for(i = 0; i < ar_size; i++) { printf("%d ", ar[i]); } } int insertionSort(int ar_size, int * ar) { int i,j, available; int count = 0; for(i = 0; i < ar_size; i++) { int value = ar[i]; available = i; for(j=i-1; j >= 0; j--) { if(value < ar[j]) { ar[available] = ar[j]; available = j; count++; }else{ break; } } ar[available] = value; } return count; } void quickSort(int ar_size, int *ar) { int pivot = ar[ar_size - 1]; int l_len = 0, i; for(i = 0; i < ar_size; i++) { if(ar[i] <= pivot) { swap(&ar[i], &ar[l_len]); if(i != ar_size -1) l_len++; } } if(l_len > 1) { quickSort(l_len, ar); } if(ar_size - l_len - 1 > 1) { quickSort(ar_size - l_len - 1, ar+l_len+1); } } int main(int argc, char* argv[]) { int _ar_size, i; scanf("%d", &_ar_size); int ar[_ar_size], ar2[_ar_size]; for(i = 0; i < _ar_size; i++) { scanf("%d", &ar[i]); ar2[i] = ar[i]; } quickSort(_ar_size, ar); shift_count = insertionSort(_ar_size, ar2); printf("%d", shift_count - swap_count); //print_ar(_ar_size, ar); //printf("\n[%d]\n", swap_count); return 0; }
C
#include "future.h" #include "err.h" typedef void *(*function_t)(void *); typedef struct runnable_arg { struct callable callable; struct future *future; } runnable_arg_t; typedef struct map_arg { struct future *from; void *(*mapping_fn)(void *, size_t, size_t *); } map_arg_t; static void runnable_wrapper(void *runnable_arg, size_t argsz __attribute__((unused))) { int err; runnable_arg_t *arg = runnable_arg; future_t *future = arg->future; callable_t callable = arg->callable; void *value = callable.function(callable.arg, callable.argsz, &future->size); future->value = value; if ((err = sem_post(&future->status)) != 0) syserr(err, "sem_post"); free(runnable_arg); } static void *map_wrapper(void *map_arg, size_t argsz __attribute__((unused)), size_t *size) { map_arg_t *arg = map_arg; void *from_result = await(arg->from); void *result = arg->mapping_fn(from_result, arg->from->size, size); free(map_arg); return result; } int async(thread_pool_t *pool, future_t *future, callable_t callable) { int err; runnable_t runnable; runnable_arg_t *runnable_arg; if ((err = sem_init(&future->status, 0, 0)) != 0) syserr(err, "sem_init"); if ((runnable_arg = malloc(sizeof(*runnable_arg))) == NULL) return MALLOC_FAILURE; runnable_arg->future = future; runnable_arg->callable = callable; runnable.function = runnable_wrapper; runnable.arg = (void *) runnable_arg; runnable.argsz = sizeof(*runnable_arg); return defer(pool, runnable); } int map(thread_pool_t *pool, future_t *future, future_t *from, void *(*function)(void *, size_t, size_t *)) { map_arg_t *map_arg; callable_t callable; if ((map_arg = malloc(sizeof(*map_arg))) == NULL) return MALLOC_FAILURE; map_arg->from = from; map_arg->mapping_fn = function; callable.arg = map_arg; callable.argsz = sizeof(*map_arg); callable.function = map_wrapper; return async(pool, future, callable); } void *await(future_t *future) { int err; void *result; if ((err = sem_wait(&future->status)) != 0) syserr(err, "sem_wait"); result = future->value; if ((err = sem_destroy(&future->status)) != 0) syserr(err, "mutex_unlock"); return result; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: hsamatha <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/24 22:47:57 by hsamatha #+# #+# */ /* Updated: 2021/06/09 12:55:27 by hsamatha ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_H # define LIBFT_H # include <unistd.h> # include <stddef.h> # include <stdlib.h> int ft_atoi(const char *str); //convert char(input -- string) to int void *ft_calloc(size_t count, size_t size); //mem allocation -- for specified number elements multiplied by its size int ft_isalnum(int c); int ft_isalpha(int c); int ft_isascii(int c); int ft_isdigit(int c); int ft_isprint(int c); void ft_putchar_fd(char c, int fd); void ft_putstr_fd(char *s, int fd); //put char by char, output str to the file descriptor fd. void ft_putendl_fd(char *s, int fd); //put str + add ending \n void ft_putnbr_fd(int n, int fd); //recursion, output int n to the standard output char *ft_strchr(const char *s, int c); //find void *ft_bzero(void *s, size_t n); //memset with zeros void *ft_memchr(const void *s, int c, size_t n); // mem function, returns pointer when found char *ft_strdup(const char *s1); //duplicate string using malloc size_t ft_strlen(const char *s); void ft_lstadd_back(t_list **lst, t_list *new); t_list *ft_lstnew(void *content); int ft_lstsize(t_list *lst); //count len until no tmp->next int ft_strncmp(const char *s1, const char *s2, size_t n); //returns int if 2 strings are not identical char *ft_strrchr(const char *s, int c); int ft_tolower(int c); int ft_toupper(int c); void *ft_memcpy(void *dst, const void *src, size_t n); //mem function, coping src to dest void *ft_memccpy(void *dst, const void *src, int c, size_t n); //mem functions, coping src to dest for specified length void *ft_memmove(void *dst, const void *src, size_t len); //<3 mem function, copies in itself, !! if dest >> src copies from the end int ft_memcmp(const void *s1, const void *s2, size_t n); //mem function, returns if different size_t ft_strlcpy(char *dst, const char *src, size_t size); // write no more bytesthat in dest,preventing buff overflow, "size-bounded string copying" size_t ft_strlcat(char *dst, const char *src, size_t size); // "size-bounded strings catination" char *ft_strnstr(const char *haystack, const char *needle, size_t len); char *ft_substr(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); //join 2 strings in final char *ft_strmapi(char const *s, char (*f)(unsigned int, char)); //Applies the function f to each character of the string passed as argument by giving its index as first argument to create a “fresh” new string (with malloc(3)) resulting from the successive applications of f. char *ft_strtrim(char const *s1, char const *set); //Allocates (with malloc(3)) and returns a copy of the string given as argument without whitespaces at the beginning or at the end of the string. Will be considered as whitespaces the following characters ’ ’, ’\n’ and ’\t’. If s has no whitespaces at the beginning or at the end, the function returns a copy of s. If the allocation fails the function returns NULL. char *ft_itoa(int n); //convert int to char(output -- string) char **ft_split(char const *s, char c); //split a string by specified character, write to array void *ft_memset(void *b, int c, size_t len); // fill with specified int #endif
C
#include <stdio.h> #include <netdb.h> #include <netinet/in.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <time.h> #include <signal.h> void servicePlayers(int,int); int main(int argc, char *argv[]){ char message[100]; pid_t pid1; int sd, client1,client2, portNumber, i; int count=1; socklen_t len; struct sockaddr_in servAdd; if((sd = socket(AF_INET, SOCK_STREAM, 0))<0){ fprintf(stderr, "Could not create socket\n"); exit(1); } servAdd.sin_family = AF_INET; servAdd.sin_addr.s_addr = INADDR_ANY; sscanf(argv[1], "%d", &portNumber); servAdd.sin_port = 50000; bind(sd, (struct sockaddr *) &servAdd, sizeof(servAdd)); listen(sd, 5); while(1){ client1=accept(sd,(struct sockaddr*)NULL,NULL); printf("Player%d is ready\n", count); count ++; client2=accept(sd,(struct sockaddr*)NULL,NULL); printf("Player%d is ready\n", count); count ++; if(fork() == 0){ servicePlayers(client1,client2); } } } void servicePlayers(int client1,int client2) { int received_integer[2]; int total[2]={0}, i =0; int client[2]={client1,client2}; while(1) { write(client[i%2], "You can play now", 100); if (read(client[i%2], &received_integer[i%2], sizeof(received_integer))<0){ fprintf(stderr, "read() error\n"); exit(3); } total[i%2] += ntohl(received_integer[i%2]); if(total[i%2]>100){ write(client[i%2], "Game over: you won the game", 100); write(client[(i+1)%2], "Game over: you lost the game", 100); break; } i++; sleep(1); } close(client[0]); close(client[1]); kill(getpid(), SIGTERM); }