language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <string.h> #include "sprite_extract.h" #include "../globals.h" /*-[ CONSTANTS AND MACROS ]---------------------------------------------------*/ #define VSWAP_FILE "VSWAP.ext" ///< File containing the sprites. #define TRANSPARENCY 0xFF ///< Colour for transparent texels. // Error codes #define SE_FILE_NOT_FOUND 1 ///< Error opening file. #define SE_MALLOC_FAIL 2 ///< Error trying to allocate memory. /** Open the VSWAP file and keep it open for use. */ #define LOAD_VSWAP_HEADER \ char vswap_fname[] = VSWAP_FILE; \ change_extension(vswap_fname, extension); \ FILE *vswap = fopen(vswap_fname, "rb"); \ if (vswap == NULL) { \ fprintf(stderr, "Error: could not load file \"%s\".\n", vswap_fname);\ return SE_FILE_NOT_FOUND; \ } \ /** Prepare the VSWAP file for extraction. */ #define PREPARE_VSWAP_FILE \ if (load_vswap_header() != 0) {\ return 0; \ } \ LOAD_VSWAP_HEADER \ /*-[ TYPE DEFINITIONS ]-------------------------------------------------------*/ /** Structure holding the location and position of a chunk. */ struct vswap_chunk_header { uint32_t offset; ///< Offset of the chunk relative to the beginning of the file. word length; ///< Length of the chunk in bytes ??? }; /*-[ VARIABLE DECLARATIONS ]--------------------------------------------------*/ static int16_t number_of_chunks; ///< Total number of chunks in the file. static int16_t sprite_start; ///< Offset to the first sprite chunk in the file. static int16_t sound_start; ///< Offset to the first sound chunk in the file. static struct vswap_chunk_header *headers; // Array of chunk headers. /*-[ FUNCTION DECLARATIONS ]--------------------------------------------------*/ /** Loads the VSWAP file header and set variables. * * @return 0 if everything went right, otherwise an error code. */ static int load_vswap_header(void); /*-[ IMPLEMENTATIONS ]--------------------------------------------------------*/ static int load_vswap_header(void) { LOAD_VSWAP_HEADER // read the number of chunks and offset fread(&number_of_chunks, sizeof number_of_chunks, 1, vswap); fread(&sprite_start, sizeof sprite_start, 1, vswap); fread(&sound_start, sizeof sound_start, 1, vswap); // read the chunk headers free(headers); if ((headers = malloc(number_of_chunks * sizeof(struct vswap_chunk_header))) == NULL) { fprintf(stderr, "Error: Could not allocate memory to hold VSWAP chunk headers.\n"); return SE_MALLOC_FAIL; } for (int i = 0; i < number_of_chunks; ++i) { fread(&headers[i].offset, sizeof(uint32_t), 1, vswap); } for (int i = 0; i < number_of_chunks; ++i) { fread(&headers[i].length, sizeof(word), 1, vswap); } fclose(vswap); vswap = NULL; DEBUG_PRINT(1, "Loaded VSWAP header.\n"); return 0; } size_t extract_texture(byte **buffer, uint magic_number) { PREPARE_VSWAP_FILE if (magic_number >= sprite_start) { fprintf(stderr, "Error: invalid magic number for textures, must be within range [0, %i).\n", sprite_start); fclose(vswap); return 0; } if ((*buffer = malloc(headers[magic_number].length * sizeof(byte))) == NULL) { fprintf(stderr, "Error: could not allocate memory to hold compressed sprite.\n"); return 0; } fseek(vswap, headers[magic_number].offset, SEEK_SET); fread(*buffer, sizeof(byte), headers[magic_number].length, vswap); fclose(vswap); return 64 * 64 * sizeof(byte); } size_t extract_sprite(byte **buffer, uint magic_number) { PREPARE_VSWAP_FILE magic_number += sprite_start; // always add the constant sprite offset if (magic_number < sprite_start || magic_number >= sound_start) { fprintf(stderr, "Error: invalid magic number for sprites, must be within range [0, %i).\n", sound_start - sprite_start); fclose(vswap); return 0; } byte *compressed_chunk; word first_column, last_column; // first and last column of the sprite with non-transparent texels (left->right) word *column_offsets; // sequence of offsets to the column instructions. // Read the compressed chunk from the file and close it if ((compressed_chunk = malloc(headers[magic_number].length * sizeof(byte))) == NULL) { fprintf(stderr, "Error: could not allocate memory to hold compressed sprite.\n"); return 0; } fseek(vswap, headers[magic_number].offset, SEEK_SET); fread(compressed_chunk, sizeof(byte), headers[magic_number].length, vswap); fclose(vswap); DEBUG_PRINT(1, "Read compressed chunk of size %i bytes.\n", headers[magic_number].length) // fill the variables. first_column = (word)compressed_chunk[0] | (word)(compressed_chunk[1])<<8; last_column = (word)compressed_chunk[2] | (word)(compressed_chunk[3])<<8; DEBUG_PRINT(1, "First column: %i, last column: %i.\n", first_column, last_column); if ((column_offsets = malloc((last_column - first_column + 1) * sizeof(word))) == NULL) { fprintf(stderr, "Error: could not allocate memory for column instruction offsets.\n"); return 0; } for (int i = 0; i <= last_column - first_column; ++i) { column_offsets[i] = (word)compressed_chunk[4+2*i] | (word)(compressed_chunk[4+2*i+1])<<8; } DEBUG_PRINT(1, "Read column instruction offsets.\n"); free(*buffer); if ((*buffer = malloc(64 * 64 * sizeof(byte))) == NULL) { fprintf(stderr, "Error: could not allocate memory to hold decompressed sprite."); *buffer = NULL; free(column_offsets); return 0; } memset(*buffer, TRANSPARENCY, 64*64); // fill all the holes DEBUG_PRINT(1, "Set up the buffer.\n"); word *column_offset_reader = column_offsets; // read-head that will traverse the column offsets for (word column = first_column; column <= last_column; ++column) { DEBUG_PRINT(2, "Drawing column %i...\n", column); word *drawing_instructions = (word *)(compressed_chunk + *column_offset_reader); uint idx = 0; while (drawing_instructions[idx] != 0) { for (int row = drawing_instructions[idx+2] / 2; row < drawing_instructions[idx] / 2; ++row) { DEBUG_PRINT(2, "\tDrawing row %i...\n", row); (*buffer)[column + (63 - row) * 64] = compressed_chunk[drawing_instructions[idx+1]+ row]; //(*buffer)[column + (63 - row) * 64] = compressed_chunk[i]; DEBUG_PRINT(2, "Drew at position %i + (63 - %i) * 64 = %i.\n", column, row, column + (63-row)*64) //++i; } idx += 3; } ++column_offset_reader; // advance the read-head } free(compressed_chunk); return 64 * 64 * sizeof(byte); }
C
/* * Copyright (C) 2012 Trevor Woerner * (see LICENSE file included in this repository) */ #include <stdio.h> #include <stdlib.h> int my_add (int a, int b); int main (int argc, char *argv[]) { int a, b; if (argc != 3) { printf ("usage\n"); return 1; } a = atoi (argv[1]); b = atoi (argv[2]); printf ("my_add: %d + %d = %d\n", a, b, my_add (a, b)); return 0; } int my_add (int a, int b) { int answer; answer = a + b; return answer; }
C
#include "holberton.h" void swap_int(int *a, int *b); /** * reverse_array - reverse the order of integers in an array * @a: array of integers of any length * @n: number of elements in the array * * Return: void */ void reverse_array(int *a, int n) { int i; for (i = 0; i < n / 2; i++) { swap_int(&a[i], &a[n - i - 1]); } } /** * swap_int - swap the values of two variables outside the function * @a: pointer with an integer target value * @b: pointer with a different integer target value * * Return: void */ void swap_int(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; }
C
#include "holberton.h" /** * onedigit - Short description, single line * @i: Description of parameter x * @j: Description of parameter x * @n: Description of parameter x * Return: Description of the returned value */ void onedigit(int i, int j, int n) { _putchar(i * j + '0'); if (j != n) { _putchar(','); _putchar(' '); _putchar(' '); } if (i * (j + 1) < 10) { if (j != n) _putchar(' '); } } /** * twodigit - Short description, single line * @i: Description of parameter x * @j: Description of parameter x * @n: Description of parameter x * Return: Description of the returned value */ void twodigit(int i, int j, int n) { _putchar(i * j / 10 + '0'); _putchar(i * j % 10 + '0'); if (j != n) { _putchar(','); _putchar(' '); } if (i * (j + 1) < 100) { if (j != n) _putchar(' '); } } /** * threedigit - Short description, single line * @i: Description of parameter x * @j: Description of parameter x * @n: Description of parameter x * Return: Description of the returned value */ void threedigit(int i, int j, int n) { _putchar(i * j / 100 + '0'); _putchar(i * j % 100 / 10 + '0'); _putchar(i * j % 100 % 10 + '0'); if (j != n) { _putchar(','); _putchar(' '); } } /** * print_times_table - Short description, single line * @n: Description of parameter x (* a blank line * Description: Longer description of the function)? (* section header: Section description)* * Return: Description of the returned value */ void print_times_table(int n) { int i, j; if (n > 15 || n < 0) return; for (i = 0 ; i <= n ; ++i) { for (j = 0 ; j <= n ; ++j) { if (i * j <= 9) { onedigit(i, j, n); } else if (i * j < 100) { twodigit(i, j, n); } else { threedigit(i, j, n); } } _putchar('\n'); } }
C
#include "peripherals.h" #include "osObjects.h" #include "trace.h" #include "stdio.h" osThreadDef (thread1, osPriorityIdle, 300); osThreadId tid_thread1; extern int getCurrentCeiling(); int Init_thread1 (void) { tid_thread1 = osThreadCreate (osThread(thread1), NULL); if (tid_thread1 == NULL) { return(-1); } printf("created thread1\n\r"); return(0); } int Terminate_thread1 (void) { if (osThreadTerminate(tid_thread1) != osOK) { return(-1); } return(0); } void thread1 (void const *argument) { osThreadId curr_th = osThreadGetId(); printf("Task 1: Hello! . My priority is %d\n\r",curr_th->priority); printf("Task 1: Locking Server 2\n\r"); if (osPcpSemaphoreWait (sid_Semaphore2, osWaitForever) >= 0 ) // { printf("Task 1: Server 2 locked . My priority is %d\n\r",curr_th->priority); printf("The current priority ceiling is %d\n\r",getCurrentCeiling()); printf("Task 1: I am doing something in Server 2 . My priority is %d\n\r",curr_th->priority); printf("Task 1: unlock Server2 . My priority is %d\n\r",curr_th->priority); osPcpSemaphoreRelease (sid_Semaphore2); printf("Task 1: Byebye . My priority is %d\n\r",curr_th->priority); printf("The current priority ceiling is %d\n\r",getCurrentCeiling()); osThreadSetPriority(tid_thread1,osPriorityIdle); } else { printf("Task 1 failed to lock Server 2 \n\r"); stop_cpu; } }
C
#include <gsl/gsl_linalg.h> #include <stdio.h> #include <math.h> #include <stdlib.h> //Krance #define xmax 5 #define xmin -5 //Prototypy void wyznacz_M(double *xw, double *yx, gsl_vector *m, int n, double alfa, double beta); double wyznacz_Sx(double *xw, double *yx, gsl_vector *m, int n, double x); //Dane funkcje f1(x) oraz f2(x) double f_1(double x) { return 1.0/(1.0 + pow(x, 2)); } double f_2(double x) { return cos(2.0*x); } double deriv(double x, double dx) { return (f_1(x - dx) - 2*f_1(x) + f_1(x + dx)) / pow(dx, 2); } void printVector(gsl_vector *v, int n); void printVectorAcc(gsl_vector *v, int n); void printMatrix(gsl_matrix *M, int n); int main() { /* FILE *f1; f1 = fopen("f1.dat","w"); if(f1 == NULL) exit(1); */ FILE *fdrv; /* FILE *f2; f2 = fopen("f2.dat","w"); if(f2 == NULL) exit(1); */ fdrv = fopen("pochodne.dat","w"); if(fdrv == NULL) { printf("Error!"); exit(1); } //Ustalone wartosci alfa i beta double alfa = 0; double beta = 0; //Liczba wezlow. Poczatkowo rowna 5 int n = 10; //Tablica polozen wezlow double xw[n]; //Tablica wartosci funkcji double yx[n]; //Stala delta double deltax = ((double)xmax - (double)xmin) / ((double)n - 1.0); int i,f; //delta x potrzebna do liczenia pochodnych podwojnych double dx = 0.01; //Wypelnianie tablcy wedlug wzoru (11) for(i=0;i<n;i++) xw[i] = (double)xmin + deltax*i; //Wypelnienie wektora wartosci funkcji for(i=0;i<n;i++) { //yx[i] = f_2(xw[i]); //f = 2; yx[i] = f_1(xw[i]); f = 1; } /*printf("\nDla yx[i] = f%d(x[i]).\n" , f); for(i=0;i<n;i++) printf("| %d | %f | %1.8f |\n" , i, xw[i], yx[i] ); */ //Alokacja wektora wypelnionego zerami gsl_vector *m = gsl_vector_calloc(n); wyznacz_M(xw, yx, m, n, alfa, beta); /* for(double x = (double)xmin; x<= (double)xmax; x+= 0.01) { double temp = wyznacz_Sx(xw, yx, m, n, x); fprintf(f2,"%f %f\n",x, temp); //printf("%1.3f %2.7e\n", x, temp); } fprintf(f2, "\n\n");*/ if(f == 1 && n == 10) { double temp; for(i=0;i<n;i++) { temp = deriv(xw[i] , dx); fprintf(fdrv,"%f %f %f\n", xw[i], gsl_vector_get(m, i), temp); //printf("%f %f %f\n", xw[i], gsl_vector_get(m, i), temp); } } gsl_vector_free(m); //fclose(f2); //fclose(f2); fclose(fdrv); return 0; } void wyznacz_M(double *xw, double *yx, gsl_vector *m, int n, double alfa, double beta) { //Alokacja macierzy ukladu, wektora wyrazow wolnych oraz zmiennych gsl_matrix * A = gsl_matrix_alloc(n, n); gsl_vector * d = gsl_vector_alloc(n); //Odleglosci miedzywezlowe sa w naszym przypadku stale, wiec h jest stale double h_i = ((double)xmax - (double)xmin) / ((double)n - 1.0); //co za tym idzie stale i niezalezne od n sa zmienne lambda i mu double lambda = h_i / (h_i + h_i); double mu = 1.0 - lambda; //Ustawiam wartosci alfa oraz beta kolejno na poczatku i koncu wektora gsl_vector_set(d, 0, alfa); gsl_vector_set(d, n-1, beta); //Pozostale wartosci ustawiam wedlug wzoru (7) double value; for(int i = 1; i < n-1; i++) { value = (6.0 / (h_i + h_i)) * ( (yx[i+1] - yx[i]) / h_i - (yx[i] - yx[i-1]) / h_i); gsl_vector_set(d, i, value); } //printf("\nWektor d dla n = %d\n" , n); //printVector(d,n); //Ustawiam wszystkie elementy macierzy A na zero gsl_matrix_set_zero(A); //Ustawiam diagonale wedlug wzoru (7) for(int i = 0; i < n; i++) gsl_matrix_set(A, i, i, 2); //Ustawianie diagonali cont. gsl_matrix_set(A, 0, 0, 1); gsl_matrix_set(A, n-1, n-1, 1); //Wypelnianie odpowiednimi wartosciami ze wzoru (7) elementow pod i nad diagonala for(int i = 1; i < n-1; i++) { for(int j = 1; j < n-1 ; j++) { if(i == j) { gsl_matrix_set(A, i, j-1, mu); gsl_matrix_set(A, i, j+1, lambda); } } } //printf("\nMacierz A dla n = %d" , n); //printMatrix(A,n); //transformacja Householder'a gsl_linalg_HH_svx( A, d); //Przypisanie wektorowi m wartosci wektora wynikowego d for(int i=0; i<n;i++) gsl_vector_set(m, i, gsl_vector_get(d, i)); //printf("\nWektor m\n"); //printVectorAcc(m, n); //zwalnianie pamieci gsl_matrix_free(A); gsl_vector_free(d); } double wyznacz_Sx(double *xw, double *yx, gsl_vector *m, int n, double x) { int przedzial; //zmienna wynikowa Sx double Sx; //stala double h_i = ((double)xmax - (double)xmin) / ((double)n - 1.0); //Szukanie danego przedzialu = i-1 for(int i=1; i<n; i++) { if(xw[i-1] <= x && x <= xw[i]) { przedzial = i-1; break; } } //Wyznaczanie stalych A_i oraz B_i double A_i; double B_i; double tmp1 = gsl_vector_get(m , przedzial + 1); double tmp2 = gsl_vector_get(m , przedzial); A_i =( (yx[przedzial+1] - yx[przedzial]) / h_i ) - (h_i/6.0) * ( tmp1 - tmp2); tmp1 = gsl_vector_get(m , przedzial); B_i = yx[przedzial] - tmp1 * ( (pow(h_i,2)) / 6.0 ); //Wyznaczanie wzoru (8), stopniowo, zeby sie nie pogubic Sx = gsl_vector_get(m , przedzial); Sx *= (pow((xw[przedzial+1] - x), 3) / (6.0*h_i)); Sx += gsl_vector_get(m , przedzial + 1) * (pow((x - xw[przedzial]), 3) / (6.0*h_i)); //Sx *= pow((x - xw[przedzial]), 3) / 6.0*h_i; Sx += A_i * (x - xw[przedzial]); //Sx *= (x - xw[przedzial]); Sx += B_i; return Sx; } void printVector(gsl_vector *v, int n) { puts(""); double temp; for(int i=0; i<n ; i++) { temp = gsl_vector_get(v , i); printf("| %.7f |\n", temp); } } void printVectorAcc(gsl_vector *v, int n) { puts(""); double temp; for(int i=0; i<n ; i++) { temp = gsl_vector_get(v , i); printf("| %.7e |\n", temp); } } void printMatrix(gsl_matrix *M, int n) { double temp; for(int i=0; i<n ; i++) { puts(""); for(int j=0;j<n;j++) { temp = gsl_matrix_get(M , i, j); //printf(" %2.2f ", temp); printf("Value for [%d][%d] = %2.2f\n",i,j, temp); } } puts(""); }
C
#include <stdio.h> void a(const char *const); int main() { const char *const x = "Hello"; a(x); return 0; } void a(const char *const x) { // OK const char *const words[] = {"Hi", x, "Dog"}; // XXX: Warning: "Initalization discards const qaulifier from // pointer target type" char *const more[] = {x, "Pizza"}; // Why does this bring up a warning? // The type char *const indicates that the pointer (to a a // character) should not be allowed to change, but how am I // changing the pointer? // // more --> [0][1] // | | // | `---> [H][e][l][l][o] // `------> [P][i][z][z][a] // ^ // | // x ------------------' // // Are we actually *changing* the x pointer, or are we simply // making another thing point to it? // // TODO: Try to break it. If I *can* in some way modify // the value (through the pointer), then it isn't right // This issues more warnings, but still allows us to change the // array. char *p = more; p[0] = "A"; int i; for (i = 0; i < 2; i++) { printf("%s\n", more[i]); } // printf("%c\n", *x); // OK const char *even_more[] = {"One" "Two", x}; }
C
#include <stdio.h> #include <time.h> #include <stdlib.h> int rand_init(void) { srand(time(NULL)); return rand() % 10 +1; } void while_test(int num) { int cnt = 0; while(num--) { cnt++; } printf("cnt = %d\n",cnt); } void find_even(int num) { int cnt = 1; while(cnt <= num) { if(!(cnt % 2)) { printf("%4d",cnt); } } } int main(void) { int num = rand_init(); printf("num = %d\n",num); while_test(num); find_even(num); return 0; }
C
#include <stdio.h> #include <string.h> #include <ctype.h> void shift_cipher(char *, char); void read_file(), write_file(char); FILE *filePtr; #define MAX 1000 // max size of data char letters[27]="abcdefghijklmnopqrstuvwxyz ", fname[100];; void main() { char data[MAX]; int option, ch; puts("e - encrypt"); puts("d - derypt"); puts("x - to exit cipher"); while (option != 'x') { printf("Your option: "); while((option = getchar()) == '\n'); // reduce '\n' character from nowhere (happen when finish encrypt and come back to this option)? while((ch = getchar()) != '\n'); // reduce noise switch (option) { case 'e': read_file(data); shift_cipher(data, 'e'); break; case 'd': read_file(data); shift_cipher(data, 'd'); break; case ' ': case '\t': case 'x': break; default: puts("Wrong input. Try again!"); break; } } } void shift_cipher(char *data, char option) { long int key, location; char *locationPtr; printf("Enter your key: "); scanf("%d", &key); printf("Your text: "); write_file(option); // encryption for (int i = 0; i < strlen(data); i ++) { locationPtr = strchr(letters, data[i]); // return address of text in letters if (locationPtr == NULL) { // if not found on list on letter ==> ignore that printf("%c", data[i]); fprintf(filePtr, "%c", data[i]); continue; } location = locationPtr - letters; // find postion in array letters // encrypt || decrypt location = (location + (option == 'e'? key: -key) ) % 27; location += location < 0 ? 27 : 0; // convert to text and save to file printf("%c", letters[location]); fprintf(filePtr, "%c", letters[location]); } fclose(filePtr); printf("\nEnd of cryptation\n"); } void write_file(char option) { char name[100], *token, out_fname[100] = ""; // adding "" to prevent stupid error of C ? strcat(out_fname, option == 'e' ? "output/en_" : "output/de_"); // extracting file name token = strtok (fname, "/"); while (token) { strcpy(name, token); token = strtok (NULL, "/"); } strcat(out_fname, name); filePtr = fopen(out_fname, "w"); if (filePtr == NULL) puts("Error when loading file. Failed to write file"); } void read_file(char *data) { int i = -1; printf("Enter location to your file: "); scanf("%s", fname); filePtr = fopen(fname, "r"); if (filePtr == NULL) { puts("File name is not correct. Try again!"); read_file(data); } else { fgets(data, MAX, filePtr); } while (data[++i]) { data[i] = tolower(data[i]); // lower all character } fclose(filePtr); }
C
#include <stdio.h> int main(){ int casos,conta; int a,b,c,e,f; int config[100][2]; c = 0; scanf("%d",&casos); int numeros[casos][200]; while(c!=casos){ a = 0; scanf("%d %d",&config[c][0],&config[c][1]); while(a != config[c][1]){ scanf("%d",&numeros[c][a]); a++; } c++; } while(c!=casos){ int hash[200][200]={}; for(b=0;b!=config[c][1];b++){ a = 0; conta = numeros[c][b] % config[c][0]; while((hash[conta][a]) > 0){ a++; } hash[conta][a] = numeros[c][b]; hash[conta][a+1] = -1; } for(e=0;e!=config[c][0];e++){ a = 1; if (hash[e][0] <= 0){ printf("%d -> \\\n",e); } else{ printf("%d -> %d",e,hash[e][0]); while(hash[e][a] > 0){ if(hash[e][a]<=0){ break; } printf(" -> %d",hash[e][a]); a++; } printf(" -> \\\n"); } } if(casos-1==c){ break; } printf("\n"); c++; } return 0; }
C
#include <stdio.h> void print_arr(int *arr, int size) { int i; i = 0; while(i != size) { printf("[%i]", arr[i]); i++; } printf("\n"); } // each with each /*void sort_int_tab(int *tab, unsigned int size) { int tmp; unsigned int i; unsigned int j; i = 0; while (i < size - 1) { j = i; while (j < size) { if (tab[i] > tab[j]) { tmp = tab[i]; tab[i] = tab[j]; tab[j] = tmp; (tab, 4); } j += 1; } i += 1; } }*/ // buble sort void sort_int_tab(int *tab, unsigned int size) { unsigned int i; int buf; i = 0; while (i != size) { if (tab[i] > tab[i + 1]) { buf = tab[i]; tab[i] = tab[i + 1]; tab[i + 1] = buf; while (i != 0 && tab[i - 1] > tab[i]) { buf = tab[i - 1]; tab[i - 1] = tab[i]; tab[i] = buf; i--; } } i++; } } int main(void) { int tab[4] = {8,10,10,1}; sort_int_tab(tab, 4); print_arr(tab, 4); }
C
/** This program returns 1 to 999 in Japanese Romaji. Returns it through a combo of for and switch statements. @author Saito, SaitoShin07 @assignement ICS 212 Assignment 7 @date 2021 - 02 - 11 */ #include <stdio.h> int main(void) { //variable declaration //how high the program will count up to int i = 1; //int variables to store the digit places int one = 0; int ten = 0; int hundred = 0; //initiate the for loop puts("This program will print the Romaji pronounciation of Japanese counting from 1 to 999"); for(i = 1; i < 1000; i++) { //formula to store the hundredth place hundred = (i/100) % 10; //formula to check the tenth place ten = (i/10) % 10; //formula to check the ones digit one = i % 10; //Print statement for the current i count printf("%d = ",i); //switch the hundredth digit to accordingly switch(hundred) { case 1: printf("hyaku"); break; case 2: printf("nihyaku"); break; case 3: printf("sanbyaku"); break; case 4: printf("yonhyaku"); break; case 5: printf("gohyaku"); break; case 6: printf("roppyaku"); break; case 7: printf("nanahyaku"); break; case 8: printf("happyaku"); break; case 9: printf("kyuhyaku"); break; default: break; } //switch the ten to accordingly switch(ten) { case 1: printf(" jyuu"); break; case 2: printf(" nijyuu"); break; case 3: printf(" sanjyuu"); break; case 4: printf(" yonjyuu"); break; case 5: printf(" gojyuu"); break; case 6: printf(" rokujyuu"); break; case 7: printf(" nanajyuu"); break; case 8: printf(" hachijyuu"); break; case 9: printf(" kyujyuu"); break; default: break; } //switch one to accordingly switch(one) { case 1: printf(" ichi \n"); break; case 2: printf(" ni \n"); break; case 3: printf(" san \n"); break; case 4: printf(" yon \n"); break; case 5: printf(" go \n"); break; case 6: printf(" roku \n"); break; case 7: printf(" nana \n"); break; case 8: printf(" hachi \n"); break; case 9: printf(" kyu \n"); break; default: printf("\n"); break; } } return 0; } /* ./program < program.txt This will print out the text of counting from 1 to 999 in Japanese. */
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/wait.h> #include <signal.h> #include <netdb.h> #define SERVER_PORT_A 21143 #define SERVER_PORT_B 22143 #define SERVER_PORT_C 23143 #define HOST "localhost" int resultA; int resultB; int resultC; int final_result; char reduction_type[3]; #define MYPORT_TCP 25143 #define MYPORT_UDP 24143 #define BACKLOG 1 // how many pending connections queue will hold int sockfd_AWS_TCP, childfd_TCP; // listen on sock_fd, new connection on childfd_TCP struct sockaddr_in aws_addr, aws_addr_UDP; // my address information struct sockaddr_in client_addr_TCP; // connector's address information int sin_size; struct sigaction sa; int yes=1; int TCP_buffer_LENGTH = 10000; int buffer_TCP[10000]; int num_of_numbers; int buff_to_serverA[10000]; int buff_to_serverB[10000]; int buff_to_serverC[10000]; int function; int sockfd_AWS_UDP; struct sockaddr_in serverA_UDP, serverB_UDP, serverC_UDP; // connector's address information int serverA_len_UDP = sizeof(serverA_UDP); int serverB_len_UDP = sizeof(serverB_UDP); int serverC_len_UDP = sizeof(serverC_UDP); struct hostent *serverA, *serverB, *serverC; int numbytes; int msg[] = {1, 3, 5, 7, 2, 4}; /********************************************************************************************** Most of functions are self-explained by its name. Some more specific information will be added above function declarations*/ /**********************************************************************************************/ /*create a TCP socket for AWS, and set its option*/ void create_and_set_TCP_socket() { sockfd_AWS_TCP = socket(AF_INET, SOCK_STREAM, 0); if (sockfd_AWS_TCP < 0) { perror("AWS can't create a socket"); exit(1); } if (setsockopt(sockfd_AWS_TCP,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) < 0) { perror("AWS setsockopt failed"); exit(1); } printf("The AWS is up and running.\n"); } /*set address info for struct sockaddr_in of TCP*/ void pre_set_TCP() { aws_addr.sin_family = AF_INET; // host byte order aws_addr.sin_port = htons(MYPORT_TCP); // short, network byte order aws_addr.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(&(aws_addr.sin_zero), '\0', 8); // zero the rest of the struct } /*bind for TCP socket*/ void bind_TCP_socket() { if (bind(sockfd_AWS_TCP, (struct sockaddr *)&aws_addr, sizeof(struct sockaddr)) < 0) { perror("AWS bind failed"); exit(1); } } /*set address info for struct sockaddr_in of UDP*/ void pre_set_UDP() { aws_addr_UDP.sin_family = AF_INET; // host byte order aws_addr_UDP.sin_port = htons(MYPORT_UDP); // short, network byte order aws_addr_UDP.sin_addr.s_addr = INADDR_ANY; // automatically fill with my IP memset(&(aws_addr_UDP.sin_zero), '\0', 8); // zero the rest of the struct } /*bind for UDP socket*/ void bind_UDP_socket() { if(bind(sockfd_AWS_UDP, (struct sockaddr *)&aws_addr_UDP, sizeof(struct sockaddr)) < 0){ perror("AWS bind UDP failed"); exit(1); } } /*listen for TCP client*/ void listen_TCP() { if (listen(sockfd_AWS_TCP, BACKLOG) < 0) { perror("AWS listen failed"); exit(1); } } /*segment file into three parts*/ void segment_nums() { int i; for(i = 0; i < ((num_of_numbers) / 3); i++){ buff_to_serverA[i + 2] = buffer_TCP[i + 2]; } buff_to_serverA[0] = (num_of_numbers) / 3; buff_to_serverA[1] = function; for(i = 0; i < ((num_of_numbers) / 3 + 2); i++){ buff_to_serverB[i + 2] = buffer_TCP[i + (num_of_numbers)/ 3 + 2]; } buff_to_serverB[0] = (num_of_numbers) / 3; buff_to_serverB[1] = function; for(i = 0; i < ((num_of_numbers) / 3); i++){ buff_to_serverC[i + 2] = buffer_TCP[i + (num_of_numbers)/3 * 2 + 2]; } buff_to_serverC[0] = (num_of_numbers) / 3; buff_to_serverC[1] = function; } void aws_send_UDP(); void receive_from_servers(); void get_final_result(); void send_final_result(); /*accept and receive TCP connection, entering a loop for providing contiguous service, which contains segmentating file, sending file to three backend servers. receiving from three backend servers, doing some computation in AWS, sending back to client*/ void main_process() { int count = 1; while(1) { // main accept() loop sin_size = sizeof(struct sockaddr_in); childfd_TCP = accept(sockfd_AWS_TCP, (struct sockaddr *)&client_addr_TCP, &sin_size); if(childfd_TCP < 0){ perror("AWS accept failed"); } int recv_Val = recv(childfd_TCP, buffer_TCP, 10000, 0); if(recv_Val < 0){ perror("AWS receive failed"); exit(0); } //in case of binding repeatedly if(count == 1){ pre_set_UDP(); bind_UDP_socket(); count++; } num_of_numbers = buffer_TCP[0]; function = buffer_TCP[1]; printf("The AWS has received %d numbers from the client using TCP over port %d\n", num_of_numbers, MYPORT_TCP); segment_nums(); aws_send_UDP(); receive_from_servers(); get_final_result(); send_final_result(); /*clean buffer*/ final_result = 0; resultA = 0; resultB = 0; resultC = 0; close(childfd_TCP); } } /*******************UDP*************************/ void create_UDP_socket_and_get_serverinfo() { if ((serverA = gethostbyname(HOST)) == NULL) { // get the host info perror("AWS gethostbyname A failed"); exit(1); } if ((serverB = gethostbyname(HOST)) == NULL) { // get the host info perror("AWS gethostbyname B failed"); exit(1); } if ((serverC = gethostbyname(HOST)) == NULL) { // get the host info perror("AWS gethostbyname C failed"); exit(1); } sockfd_AWS_UDP = socket(AF_INET, SOCK_DGRAM, 0); if (sockfd_AWS_UDP == -1){ perror("AWS UDP created socket failed"); exit(1); } } /*In UDP transmission, AWS is a client. This function is to set address information for its servers, which are three backend servers*/ void prepset() { serverA_UDP.sin_family = AF_INET; // host byte order serverA_UDP.sin_port = htons(SERVER_PORT_A); // short, network byte order serverA_UDP.sin_addr = *((struct in_addr *)serverA->h_addr); memset(&(serverA_UDP.sin_zero), '\0', 8); // zero the rest of the struct serverB_UDP.sin_family = AF_INET; // host byte order serverB_UDP.sin_port = htons(SERVER_PORT_B); // short, network byte order serverB_UDP.sin_addr = *((struct in_addr *)serverB->h_addr); memset(&(serverB_UDP.sin_zero), '\0', 8); // zero the rest of the struct serverC_UDP.sin_family = AF_INET; // host byte order serverC_UDP.sin_port = htons(SERVER_PORT_C); // short, network byte order serverC_UDP.sin_addr = *((struct in_addr *)serverC->h_addr); memset(&(serverC_UDP.sin_zero), '\0', 8); // zero the rest of the struct } /*send files to three servers separately*/ void aws_send_UDP() { /***************************send to A*************************************/ if ((numbytes = sendto(sockfd_AWS_UDP, &buff_to_serverA, sizeof(buff_to_serverA), 0, (struct sockaddr *)&serverA_UDP, sizeof(struct sockaddr))) == -1) { perror("AWS UDP sendto failed"); exit(1); } printf("The AWS has sent %d numbers to Backend-Server A\n", num_of_numbers / 3); /***************************send to B*************************************/ if ((numbytes = sendto(sockfd_AWS_UDP, &buff_to_serverB, sizeof(buff_to_serverB), 0, (struct sockaddr *)&serverB_UDP, sizeof(struct sockaddr))) == -1) { perror("AWS UDP sendto failed"); exit(1); } printf("The AWS has sent %d numbers to Backend-Server B\n", num_of_numbers / 3); /***************************send to C*************************************/ if ((numbytes = sendto(sockfd_AWS_UDP, &buff_to_serverC, sizeof(buff_to_serverC), 0, (struct sockaddr *)&serverC_UDP, sizeof(struct sockaddr))) == -1) { perror("AWS UDP sendto failed"); exit(1); } printf("The AWS has sent %d numbers to Backend-Server C\n", num_of_numbers / 3); } /*receive from three backend servers in UDP connection*/ void receive_from_servers() { /*******************receive from serverA***********************/ if(recvfrom(sockfd_AWS_UDP, &resultA, sizeof(resultA), 0, (struct sockaddr *)&serverA_UDP, &serverA_len_UDP) < 0){ perror("AWS UDP recvfrom serverA failed"); exit(1); } /*******************receive from serverB***********************/ if(recvfrom(sockfd_AWS_UDP, &resultB, sizeof(resultB), 0, (struct sockaddr *)&serverB_UDP, &serverB_len_UDP) < 0){ perror("AWS UDP recvfrom serverB failed"); exit(1); } /*******************receive from serverc***********************/ if(recvfrom(sockfd_AWS_UDP, &resultC, sizeof(resultC), 0, (struct sockaddr *)&serverC_UDP, &serverC_len_UDP) < 0){ perror("AWS UDP recvfrom serverC failed"); exit(1); } } /*do computation for getting final result*/ void get_final_result() { if(function == 0){ strcpy(reduction_type, "MIN"); final_result = (resultA < resultB)? resultA : resultB; final_result = (final_result < resultC)? final_result : resultC; }else if(function == 1){ strcpy(reduction_type, "MAX"); final_result = (resultA > resultB)? resultA : resultB; final_result = (final_result > resultC)? final_result : resultC; }else { if(function == 2){ strcpy(reduction_type, "SUM"); }else{ strcpy(reduction_type, "SOS"); } final_result = (resultA + resultB + resultC); } printf("The AWS received reduction result of %s from Backend-Server A using UDP over port 24143 and it is %d\n", reduction_type, resultA); printf("The AWS received reduction result of %s from Backend-Server B using UDP over port 24143 and it is %d\n", reduction_type, resultB); printf("The AWS received reduction result of %s from Backend-Server C using UDP over port 24143 and it is %d\n", reduction_type, resultC); printf("The AWS has successfully finished the reduction %s: %d\n", reduction_type, final_result); } /*send final result to client over TCP connection*/ void send_final_result() { if(send(childfd_TCP, &final_result, sizeof(int), 0) < 0){ perror("AWS send final result failed"); exit(0); } printf("The AWS has successfully finished sending the reduction value to client.\n"); } /*******************main*************************/ int main(void) { create_and_set_TCP_socket(); pre_set_TCP(); bind_TCP_socket(); create_UDP_socket_and_get_serverinfo(); prepset(); listen_TCP(); main_process(); return 0; }
C
#include <unistd.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main () { size_t sizel = 700000000; char * begin = (char *)malloc(sizel); if(begin == NULL){ printf("error : malloc failed"); } pid_t fpid; //fpid表示fork函数返回的值 int count=0,i = 0; fpid=fork(); printf("father %d----chlid %d\n",getpid(),fpid); if (fpid < 0) printf("error in fork!"); else if (fpid == 0) { sleep(60); printf("i am the child process, my process id is %d\n",getpid()); memset(begin,'a',sizel); printf("\ntest ------%c----",begin[10000000]); sleep(60); count++; } else { sleep(70); printf("i am the parent process, my process id is %d\n",getpid()); count++; } printf("统计结果是: %d\n",count); return 0; }
C
/*============================================================================= * Author: Fernando Prokopiuk <[email protected]> * Date: 2021/09/02 *===========================================================================*/ /*=====[Definition macros of private constants]==============================*/ // typedef enum // { // LED_OFF, // LED_ON // } led_state_t; // The maximum number of tasks required at any one time during the execution // of the program. MUST BE ADJUSTED FOR EACH NEW PROJECT #define SCHEDULER_MAX_TASKS (10) /*=====[Inclusions of function dependencies]=================================*/ #include "sapi.h" #include "seos_pont.h" #include "../../../RTOS1/A3/inc/keys.h" /*==================[declaraciones de funciones internas]====================*/ void task_led(void *pkey); void keys_service_task(void *pkey); /*==================[declaraciones de variables externas]====================*/ extern dbn_t keys_struct[MAX_KEYS]; //Array de estructuras de teclas extern dbn_t *pkey; //Puntero a estructuras de teclas /*=====[Main function, program entry point after power on or reset]==========*/ int main(void) { boardInit(); /* inicializo el modulo de tecla */ keys_init(); // Initialize scheduler schedulerInit(); // Se agrega la tarea keys_service_task al planificador schedulerAddTask(keys_service_task, // Function that implements the task update. 0, // Parameter passed into the task update. 0, // Execution offset in ticks. DEBOUNCE_TIME // Periodicity of task execution in ticks. ); // Initialize task scheduler each 1ms. schedulerStart(1); while (true) { // Dispatch (execute) tasks that are mark to be execute by scheduler. schedulerDispatchTasks(); } // YOU NEVER REACH HERE, because this program runs directly or on a // microcontroller and is not called by any Operating System, as in the // case of a PC program. return 0; } /*==================[definiciones de funciones internas]=====================*/ /** * @brief Funcion que según led_state * * @param pkey */ void task_led(void *pkey) //Funcion que según el estado del LED hace algo { dbn_t* pkey_ = (dbn_t*) pkey; if (pkey_->led_state == LED_OFF) { /* toggle del led */ gpioToggle(pkey_->led_name); /* cambio de estado al led */ pkey_->led_state = LED_ON; /* planifico el apagado del led con un offset=tiempo que estuvo pulsado el botón*/ schedulerAddTask(task_led, // funcion de tarea a agregar pkey_, // parametro de la tarea pkey_->key_time_diff, // offset de ejecucion en ticks 0 // periodicidad de ejecucion en ticks ); } else if (pkey_->led_state == LED_ON) { /* toggle del led */ gpioToggle(pkey_->led_name); /* cambio de estado al led */ pkey_->led_state = LED_OFF; pkey_->key_time_diff = KEY_INVALID_TIME; } } /** * @brief Funcion que se ejecuta cada DEBOUNCE_TIME ticks. * * @param param */ void keys_service_task(void *param) { for (pkey = keys_struct; pkey < keys_struct + MAX_KEYS; pkey++) //Recorre el array de estructuras de teclas { keys_update(pkey); //Actualiza el estado de la FSM if (pkey->key_event == EVENT_KEY_DOWN) { /* no hago nada */ } else if (pkey->key_event == EVENT_KEY_UP) //Al soltarse el botón se agrega tarea task_led // @suppress("Field cannot be resolved") { pkey->key_event = EVENT_KEY_NONE; /* planifico que la tarea de LED se ejecute en 0 ticks */ schedulerAddTask(task_led, // funcion de tarea a agregar pkey, // parametro de la tarea 0, // offset -> 0 = "ejecutate inmediatamente" 0 // periodicidad de ejecucion en ticks ); } } } /*==================[definiciones de funciones externas]=====================*/
C
/* You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. Example 1: coins = [1, 2, 5], amount = 11 return 3 (11 = 5 + 5 + 1) Example 2: coins = [2], amount = 3 return -1. Note: You may assume that you have an infinite number of each kind of coin. Credits: Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases. Subscribe to see which companies asked this question */ //have to judge whether amount k is reachable or not!!! #define coinsCount(a) ( (a<0)? (int32MAX-1): coinsCount[a]) #define min(a,b) (a<b?a:b) #define int32MAX 2147483647 #define int32MIN -2147483648 int coinChange(int* coins, int coinsSize, int amount) { int *coinsCount; int i,j; int minCount, temp; if(amount == 0) return 0; coinsCount = (int*) malloc(sizeof(int) * (amount+1)); memset(coinsCount, 0, sizeof(int) * (amount+1) /sizeof(char)); for(i = 1; i <= amount; i ++) { minCount = int32MAX; for(j = 0; j < coinsSize; j++) { if(coinsCount(i-coins[j]) == int32MAX) //if the amount(i-coins[j]) is unreachable, just skip this coin; continue; temp = coinsCount(i-coins[j]) + 1; minCount = min(minCount, temp); } coinsCount[i] = minCount; } free(coinsCount ); if(minCount == int32MAX) return -1; else return minCount; }
C
#include <sys/utsname.h> #include <unistd.h> #include <time.h> #include <stdio.h> #include "../error-handle.h" int main(int argc, char *argv[]) { struct utsname buf; struct tm *pt = NULL; time_t t = 0; char buff[128] = { 0 }; if (uname(&buf) < 0) { err_exit("uname failed!\n"); } printf("sysname--%s\n", buf.sysname); printf("nodename--%s\n", buf.nodename); printf("release--%s\n", buf.release); printf("version--%s\n", buf.version); printf("machine--%s\n", buf.machine); // time time(&t); pt = localtime(&t); if (strftime(buff, sizeof(buff), "%Y 年 %m 月 %d 日 %X %Z", pt) == 0) { err_exit("buff size not enough!\n"); } printf("time(&t) t = %ld\n", t); printf("%s\n", buff); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <sys/wait.h> #include "../include/process.h" #include "../include/mutex.h" #include "../../common/include/utils.h" #include "../../common/include/error.h" #include "../../common/include/const.h" #include "../../common/include/socket.h" /* Global variables */ Process Processes[MAX_PROCESS]; MutexCV* mcvProcess; int PROCESS_COLLECTOR_ALIVE = 1; /* Function: initProcess * Initialize processes. */ int initProcess() { for (int i = 0; i < MAX_PROCESS; i++) { Processes[i].running = 0; Processes[i].pid = -1; } mcvProcess = createMutexCV(); if (mcvProcess == NULL) return INIT_PROCESS_ERR; return 0; } /* Function: processIndex * Return the first available index in Processes vector. */ int processIndex() { for (int i = 0; i < MAX_PROCESS; i++) { if (Processes[i].running == 0) { return i; } } return PROCESS_UNAVAILABLE; } /* Function: startProcess * Start a new process. */ int startProcess(void* (*f)(void*), void* data, int sock) { pid_t pid = fork(); if (pid < 0) { return FORK_ERROR; } else if (pid > 0) { mutexLock(mcvProcess->mutex); int index = processIndex(); if (index < 0) return index; Processes[index].pid = pid; Processes[index].running = 1; Processes[index].socketIndex = sock; mutexUnlock(mcvProcess->mutex); return pid; } signal(SIGCHLD, SIG_IGN); signal(SIGHUP, SIG_IGN); signal(SIGINT, SIG_IGN); f((void*) data); exit(0); } /* Function: processCollector * Collect the ended processes. */ void* processCollector(void* input) { int status; while (PROCESS_COLLECTOR_ALIVE == 1) { mutexLock(mcvProcess->mutex); for (int i = 0; i < MAX_PROCESS; i++) { if (Processes[i].running == 1 && waitpid(Processes[i].pid, &status, WNOHANG) == -1) { //printlog("Process with id %d is now collected\n", i, NULL); Processes[i].running = 0; decrementSocket(Processes[i].socketIndex); Processes[i].socketIndex = -1; } } mutexUnlock(mcvProcess->mutex); usleep(100000); } return NULL; } /* Function: stopProcessCollector * Stop process collector. */ void stopProcessCollector() { PROCESS_COLLECTOR_ALIVE = 0; } /* Function: destroyProcess * Destroy all processes. */ void destroyProcess() { int status = 0, err = 0; for (int i = 1; i < MAX_PROCESS; i++) { if (Processes[i].pid > 0) { err = waitpid(Processes[i].pid, &status, 0); if (err == -1) throwError(WAITPID_ERROR); Processes[i].pid = -1; } } destroyMutexCV(mcvProcess); }
C
#include <stdio.h> #include <stdlib.h> #include <pthread.h> typedef struct node node; typedef struct queue queue; struct node { int data; node* next; }; struct queue { node* head; node* tail; }; queue* push(queue* q, int data) { node* temp = malloc(sizeof(node)); if (temp == NULL) { return; } temp->data = data; temp->next = NULL; if (q->tail != NULL) { q->tail->next = temp; } q->tail = temp; if (q->head == NULL) { q->head = temp; } return q; } int pop(queue* q) { node* temp = malloc(sizeof(node)); if (q->head == NULL) { //printf("Cannot pop, Queue is empty\n"); return -1; } temp->data = q->head->data; q->head = q->head->next; return temp->data; } //~ int head(queue* q) { //~ if (q->head != NULL) { //~ printf("HEAD : %s\n", q->head->data); //~ } //~ else { //~ printf("Cannot print head, queue is empty\n"); //~ } //~ return q->head->data; //~ } void init(queue* q) { q->head = NULL; q->tail = NULL; } //Used for testing //~ void main(int argc, char** argv) { //~ queue* q = malloc(sizeof(queue)); //~ init(q); //~ //~ char* test = "test"; //~ char* test2 = "test2"; //~ //~ push(q, test); //~ printf("Head data : %s\n", q->head->data); //~ push(q, test2); //~ printf("Head data : %s\n", q->head->next->data); //~ pop(q); //~ printf("Head data : %s\n", q->head->data); //~ //~ pop(q); //~ printf("Head data : %s\n", q->head->data); //~ //~ //~ }
C
//WAP in C to generate the Fibonacci series using recursive Function. #include<stdio.h> int fibo(int); int main(){ int x,n,i=0,c; printf("Enter your number: "); scanf("%d",&n); for (c=1;c<=n;c++){ printf("%d\t",fibo(i)); i++; } return 0; } int fibo(int n) { if(n==0){ return 0; } else if(n==1){ return 1; } else{ return ( fibo(n-1) + fibo(n-2) ); } }
C
#include <stdio.h> /* Question 8.a * Rewrite it using no goto & breaks statement * @uthor: Ernest Mujambere * Class: Programming Language Concept -> Spring 2020 */ int main() { int j = -3; int i; for(i = 0; i < 3; i++){ int k = j + 2; if(k == 3){ // Nothing } if(k == 2){ // Decrement j j--; } if(k == 0){ // Increment j by 2 j += 2; } if(j > 0) // Do nothing j = 3 - i; } }
C
#include <assert.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sudoku3/ftype.h> static ushort_t _s; static f_t* _nums; static f_t* _complements; __attribute__((constructor)) static void _init() { long s = sizeof(f_t) * 8; _nums = malloc(sizeof(f_t) * s); _complements = malloc(sizeof(f_t) * s); _s = (ushort_t) s; long idx, v; for(idx=0,v=1; idx<s; idx++,v++) { _nums[idx] = 1 << idx; _complements[idx] = (f_t) ~ _nums[idx]; } }; __attribute__((destructor)) static void _deinit() { free(_nums); _nums = 0; free(_complements); _complements = 0; } __attribute__((hot)) ushort_t ft_isset(f_t* s, ushort_t pos) { assert(pos <= _s); return *s & _nums[pos-1]; } ushort_t ft_is_listunset(f_t* s, ushort_t n, ushort_t pos[]) { ushort_t idx; f_t t; t = *s; for (idx = 0; idx < n; idx++) { ft_unset(&t, pos[idx]); } ushort_t r = t == *s; return r; } ushort_t ft_is_listset(f_t* s, ushort_t n, ushort_t pos[]) { ushort_t idx; f_t t; t = 0; for (idx = 0; idx < n; idx++) { ft_set(&t, pos[idx]); } ushort_t r = (t & *s) == t; return r; } ushort_t ft_is_listsetn(f_t* s, ushort_t n, ...) { va_list sa; va_start(sa, n); ushort_t idx; f_t t; t = 0; for (idx = 0; idx < n; idx++) { int pos = va_arg(sa, int); ft_set(&t, (ushort_t)pos); } va_end(sa); ushort_t r = (t & *s) == t; return r; } ushort_t ft_is_listunsetn(f_t* s, ushort_t n, ...) { va_list sa; va_start(sa, n); ushort_t idx; f_t t; t = *s; for (idx = 0; idx < n; idx++) { int pos = va_arg(sa, int); ft_unset(&t, (ushort_t)pos); } va_end(sa); ushort_t r = t == *s; return r; } void ft_set(f_t* s,ushort_t pos) { assert(pos <= _s); *s = *s | _nums[pos-1]; } void ft_unset(f_t* s, ushort_t pos) { assert(pos <= _s); *s = *s & _complements[pos-1]; } ushort_t ft_allset(f_t* s) { return 0 == (f_t) ~ (*s); } ushort_t ft_noneset(f_t* s) { return 0 == *s; } ushort_t ft_list_set_ct(f_t* s, ushort_t par_s) { ushort_t ps = par_s < _s ? par_s : _s; ushort_t idx, pos, i; for(idx = 0, i = 0, pos = 1; idx < ps; idx++, pos++) { if (ft_isset(s, pos)) i++; } return i; } ushort_t ft_list_set(f_t* s, ushort_t** par, ushort_t par_s) { assert(par); ushort_t ps = par_s < _s ? par_s : _s; ushort_t ploc[ps]; memset(ploc, 0, sizeof(ploc)); ushort_t idx, pos, i; for(idx = 0, i = 0, pos = 1; idx < ps; idx++, pos++) { if (ft_isset(s, pos)) ploc[i++] = pos; } long ploc_s = sizeof(ushort_t) * i; *par = malloc(ploc_s); memcpy(*par, ploc, ploc_s); return i; } ushort_t ft_list_unset(f_t* s, ushort_t** par, ushort_t par_s) { assert(par); ushort_t ploc[_s]; memset(ploc, 0, sizeof(ploc)); ushort_t idx, pos, i; for(idx = 0, i = 0, pos = 1; idx < _s && idx < par_s; idx++, pos++) { if (ft_isset(s, pos) == 0) ploc[i++] = pos; } long ploc_s = sizeof(ushort_t) * i; *par = malloc(ploc_s); memcpy(*par, ploc, ploc_s); return i; }
C
#include <stdio.h> int soma(int* v,int n){ if(n==0){ return 0; } return v[0] + soma(&v[1],n-1); } int soma2(int* v,int n){ if(n==0){ return 0; } return v[n-1] + soma(v,n-1); } int soma3(int* v, int n){ return v[n]+soma3(v,n-1); } int main(void){ int v[] = {1,3,4,2,6,5}; printf("Soma de v = %d\n",soma(v,6)); printf("Soma de v = %d\n",soma2(v,6)); printf("Soma de v = %d\n",soma3(v,5)); return 0; }
C
/*****************************************************************/ /* Class: Computer Programming, Fall 2019 */ /* Author: 胡紹宇 */ /* ID: 108820008 */ /* Date: 2019.11.27 */ /* Purpose: parlindrome */ /* Change History: log the change history of the program */ /*****************************************************************/ #include<stdio.h> #define N 10 void max_min(int a[], int n, int *max, int *min) { int *p; // initialize *a to *min and *max *max=*min=*a; for(p=a;p<a+n;p++) { if(*p>*max) // renew *max if *p is larger *max=*p; if(*p<*min) // renew *min if *p is smaller *min=*p; } } int main() { int b[N], i, big, small; // input printf("Enter %d numbers: ", N); for(i=0;i<N;i++) scanf("%d",&b[i]); // assign max and min to *big and *small max_min(b, N, &big, &small); // output max and min printf("Largest: %d\n",big); printf("Smallest: %d\n",small); return 0; }
C
int main() { char dna[256]; int n; scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%s",&dna); for(int j=0;;j++) { if(dna[j]=='A') printf("T"); else if(dna[j]=='T') printf("A"); else if(dna[j]=='G') printf("C"); else if(dna[j]=='C') printf("G"); else if(dna[j]=='\0') break; } printf("\n"); } }
C
#include <stdio.h> #include <string.h> int main() { char s[100], r[100]; int i; printf("Enter a string:\n"); gets(s); int end = strlen(s); int n = end; for (i = 0; i < n; i++) { r[i] = s[end - 1]; end--; } r[i] = '\0'; printf("%s\n", r); return 0; }
C
#include <stdio.h> #include <stdlib.h> //srand está nessa biblioteca #include <locale.h> #include <string.h> #include <time.h> //time está nessa biblioteca #include "Jogo_da_Forca_.h" //variáveis globais char palavra[TAM_PALAVRA]; // Vai ser a palavra escolhida pelo programa char letrasTotal[26]; //letrasTotal[] é um vetor que guarda o alfabeto int tentativas = 0; void cabecalho() { printf("\n******************************\n"); printf("*Bem vindo ao Jogo de Forca *\n"); printf("******************************\n\n"); } void captura_palpites() { char palpite; printf("Qual seu palpite, jogador? "); scanf(" %c", &palpite); printf("\n"); if(letraExiste(palpite)){ printf("Você acertou: a palavra tem a letra %c\n\n", palpite); }else{ printf("\nVocê errou: a palavra NÃO tem a letra %c\n\n", palpite); } letrasTotal[tentativas] = palpite; //palpite é chute de uma letra (tentativas)++; //Conta quantas vezes o jogador chutou até acertar a palavra secreta } int letraJaChutada(char letrachutada) {// não vou passar o ponteiro da variável tentativas, pois não pretendo alterar o conteúdo dela. int achou = 0; int j; for(j = 0; j < tentativas; j++) { if(letrasTotal[j] == letrachutada) { achou = 1; break; } } return (achou); } void desenhaForca() { int erros = chutesErrados(); //IF's ternários aqui: printf(" _______ \n"); printf(" |/ | \n"); printf(" | %c%c%c \n", (erros >= 1 ? '(' : ' '), (erros >= 1 ? '_' : ' '), (erros >= 1 ? ')' : ' ')); printf(" | %c%c%c \n", (erros >= 3 ? '\\' : ' '), (erros >= 2 ? '|' : ' '), (erros >= 3 ? '/' : ' ')); printf(" | %c \n", (erros >= 2 ? '/' : ' ')); printf(" | %c%c \n", (erros >= 4 ? '/' : ' '), (erros >= 4 ? '\\' : ' ')); printf(" | \n"); printf("_|___ \n"); printf("\n\n"); for (int i = 0; i < strlen(palavra); i++) { int achou = letraJaChutada(palavra[i]); if (achou){ printf("%c ", palavra[i]); } else{ printf("_ "); } } printf("\n"); } void adicionaPalavra() { char quer; printf("Hey! Você deseja adicionar uma nova palavra no jogo? (S/N) "); scanf(" %c", &quer); if (quer == 'S'){ char novaPalavra[TAM_PALAVRA]; printf("\n\nQual a nova palavra?\n"); scanf("%s", novaPalavra); FILE* f; f = fopen("Frutas.txt", "r+"); if(f == 0){ printf("Desculpe! Banco de dados indisponível.\n\n"); exit(1); } int qtd; fscanf(f, "%d", &qtd); qtd++; fseek(f, 0, SEEK_SET); fprintf(f, "%d", qtd); fseek(f, 0, SEEK_END); fprintf(f, "\n%s", novaPalavra); fclose(f); } } void escolhePalavra() { FILE* f; f = fopen("Frutas.txt", "r"); if(f == 0){ printf("Desculpe! Banco de dados indisponível.\n\n"); exit(1); } int qtdPalavras; fscanf(f, "%d", &qtdPalavras); srand(time(0)); int randomico = rand() % qtdPalavras; int i; for(i = 0; i <= randomico; i++){ fscanf(f, "%s", palavra); } fclose(f); } int acertou() { int i; for(i = 0; i <strlen(palavra); i++){ if(!letraJaChutada(palavra[i])){ return (0); } } return (1); } int letraExiste(char letrasTotal) { int j; for(j = 0; j <strlen(palavra); j++){ if (letrasTotal == palavra[j]){ return 1; } } return (0); } int chutesErrados() { int erros = 0; int i; for(i = 0; i < tentativas; i++){ if (!letraExiste(letrasTotal[i])){ erros++; } } return(erros); } int morreu() { return(chutesErrados()) >= 5; } int main() { escolhePalavra(); cabecalho(); do { desenhaForca(); captura_palpites(); } while (!acertou() && !morreu()); if(acertou()){ printf("Parabéns! Você acertou!!\n"); printf("────────────────█████████─────────────── \n"); printf("──────────────█████████████───────────── \n"); printf("───────────███████████████████────────── \n"); printf("──────────────────────────────────────── \n"); printf("────────████████████████████████──────── \n"); printf("────────████████████████████████──────── \n"); printf("──────────────────────────────────────── \n"); printf("█████████─████████████████████─█████████ \n"); printf("█████████─████████████████████─█████████ \n"); printf("███───────████████────████████───────███ \n"); printf("███───────██████───██───██████───────███ \n"); printf("─███──────█████──████────█████──────███─ \n"); printf("──███─────████─────██─────████─────███── \n"); printf("───███────████─────██─────████────███─── \n"); printf("────███───█████────██────█████───███──── \n"); printf("─────███──█████────██────█████──███───── \n"); printf("──────███─███████──────███████─███────── \n"); printf("───────██─████████████████████─██─────── \n"); printf("────────█─████████████████████─█──────── \n"); printf("──────────────────────────────────────── \n"); printf("──────────████████████████████────────── \n"); printf("───────────██████████████████─────────── \n"); printf("─────────────██████████████───────────── \n"); printf("───────────────███████████────────────── \n"); printf("──────────────────────────────────────── \n"); printf("────────────────█████████─────────────── \n"); printf("──────────────█████████████───────────── \n"); adicionaPalavra(); }else{ printf("Poxa! Você perdeu!!\n"); printf("A palavra era %s\n", palavra); printf("Tente novamente!"); printf("\n"); printf(" ___________.._______ \n"); printf(" | .__________))______| \n"); printf(" | | / / || \n"); printf(" | |/ / || \n"); printf(" | | / ||.-''. \n"); printf(" | |/ |/ _ \\ \n"); printf(" | | || `/,| \n"); printf(" | | (\\`_.' \n"); printf(" | | .-`--'. \n"); printf(" | | /Y . . Y\\ \n"); printf(" | | // | | \\\\ \n"); printf(" | | // | . | \\\\ \n"); printf(" | | ') | | (` \n"); printf(" | | ||'|| \n"); printf(" | | || || \n"); printf(" | | || || \n"); printf(" | | || || \n"); printf(" | | / | | \\ \n"); printf(" |'|'''''''| `-' `-' |'| \n"); printf(" |'|''''''\\ \\ |'| \n"); printf(" | | \\ \\ | | \n"); printf(" : : \\ \\ : : \n"); printf(" . . `' . . \n"); printf("\n"); adicionaPalavra(); } }
C
#include <stdio.h> int main() { int arr[3][4] = { {1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12} }; int i = 1,j = 2; printf("\n arr = %p",arr); printf("\n *arr = %p",*arr); printf("\n (arr+i) = %p",(arr+i)); printf("\n *(arr+i) = %p",*(arr+i)); printf("\n *(arr+i)+j = %p",*(arr+i)+j); printf("\n *(*(arr+i)+j) = %d",*(*(arr+i)+j)); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main() { printf("\nCollatz Conjecture \n"); int num; int process; printf("Enter a number greater than 0 to run the Collatz Conjecture.\n"); scanf("%d", &num); if (num <0){ printf("This number is a negative number!.\n"); } else{ process = fork(); if(process <0){ printf("Child process is not created.\n"); return 1; } else if( process ==0){ printf("Child process is running.\n"); printf( "\n%d \n", num); do{ if(num %2 != 0){ num = (num*3)+1; printf( "%d \n", num); } else{ num = num/2; printf( "%d \n", num); } }while(num != 1); } else{ printf("Parent is waiting on child process.\n"); wait(NULL); printf("Parent process is done.\n"); } } return 1; }
C
// Ilias Mastoras 05/08/2018 #include <stdint.h> #include <stdbool.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <stdio.h> #include "inc/hw_memmap.h" #include "inc/hw_types.h" #include "inc/hw_ints.h" #include "driverlib/gpio.h" #include "driverlib/pin_map.h" #include "driverlib/pwm.h" #include "driverlib/sysctl.h" #include "driverlib/uart.h" #include "driverlib/interrupt.h" #include "driverlib/timer.h" #include "Laser.h" //This includes the Laser struct #include "utils/uartstdio.h" // This include statement helps us use the UART functions. #include "inits/inits.h" // This include statement helps us use the initialization functions. void outputFun(char*, char*,char*); // This function handles all output for this program. bool checkChoice(char [], char); // This function checks for valid inputed choice. void printSelectionMenu(); // This prints a menu of choices to the screen. void printLaserMenu(char*); void initsConfirmation(); void clearPuttyTerminal(); void printTaskMenu(); void terminateFunction(); char InputFun(); //InputFun - Gets input . void PinGenConfig(); // This function configures the pins and the generators. void laserCommands(char*); void delay(int); Laser pd0LaserA; // . Laser pd1LaserB; // This configures the PWM generator 0, using PD1. int main(void){ initializeAll(); //Initializes all the important hardware. This function is in inits file. initsConfirmation(); printTaskMenu(); initializeFreqDuty(&pd0LaserA); // for laser A initializeFreqDuty(&pd1LaserB); // for laser B int delayTime = 90000; //local delayTime for loop. char arrTask[3] = {'S','C','E'};// This array is for the select task menu. You can add more char to compare, if more tasks are added. char arr[5] = {'A','B','C','X','E'}; char laserChoice[1], taskChoice; bool wait = false, taskWait = false; while(1){ taskWait = true; wait = true; while(taskWait){ printTaskMenu(); bool check = true; while(check){ taskChoice = toupper(InputFun()); // Get the input from the user,convert it to // upper case and then store it to taskChoice. check = checkChoice(arrTask,taskChoice); if(check){ printTaskMenu(); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); } else { if (taskChoice == 'S'){ clearPuttyTerminal(); taskWait = false; } if(taskChoice =='C'){ clearPuttyTerminal(); } if(taskChoice =='E'){ terminateFunction(); } } } }// end of while(taskWait) while(wait){ printSelectionMenu(); bool check = true; while(check){ laserChoice[0] = toupper(InputFun()); check = checkChoice(arr,laserChoice[0]); if(check){ printSelectionMenu(); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); } } // You execute the command based on the input choice. if( (laserChoice[0] == 'A') || (laserChoice[0] == 'B') ){ clearPuttyTerminal(); laserCommands( laserChoice); } if(laserChoice[0] =='C'){ clearPuttyTerminal(); } if(laserChoice[0] =='X'){ clearPuttyTerminal(); wait = false; } if(laserChoice[0] =='E'){ terminateFunction(); } }//end of while(wait) }//end of while(1) }//end of main // This function controls the Freq Command. void laserCommands(char* laserChoice){ int delayTime = 90000; //local delayTime for loop. char choice; bool wait = true; char freq; int32_t freqTotal; char duty; int32_t dutyTotal; char arr[4] = {'F','D','X','E'}; char buffer[5]; bool back; wait = true; int j; int count; int decades; int pass; printLaserMenu(laserChoice); bool check = true; while(check){ choice = toupper(InputFun()); check = checkChoice(arr,choice); if(check){ printLaserMenu(laserChoice); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); } } while(wait){ if(choice =='F'){ outputFun("\n(aaa007) Type the Frequency for laser",laserChoice," and PRESS ENTER.( between 0Hz and 1000Hz)"); freqTotal = 0; count = 4; decades = 1000; pass = 1; for(j=0; j<=4; j++){ freq = InputFun(); if(freq == 13){ // 13 is the ASCII number of Enter. '\n' doesn't work. break; } else if(isdigit(freq)){ freqTotal += (freq -'0') * decades; decades /= 10; count--; } else { clearPuttyTerminal(); printLaserMenu(laserChoice); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); choice = 'F'; pass = 0; break; } } if(pass == 1){ while(count>0){ freqTotal /= 10; count--; } ltoa(freqTotal,buffer); outputFun("\n(aaa090) You entered ",buffer,"Hz"); if((freqTotal < 0) || (freqTotal > 1000)){ clearPuttyTerminal(); printLaserMenu(laserChoice); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); }else { if(laserChoice[0] == 'A'){ back = setFrequency(&pd0LaserA, laserChoice[0], freqTotal); } else { back = setFrequency(&pd1LaserB,laserChoice[0], freqTotal); } if(back){ outputFun("(aaa111) Laser's", laserChoice," frequency was changed successfully.\n"); } wait = false; //Exit frequency loop if input is valid } }// end if pass }// end if F if(choice =='D'){ outputFun("\n(aaa008) Type the Duty Cycle for laser",laserChoice," and PRESS ENTER.( between 0% and 100% )"); dutyTotal = 0; count = 3; decades = 100; pass = 1; for(j=0; j<=3; j++){ duty = InputFun(); if(duty == 13){ // 13 is the ASCII number of Enter. '\n' doesn't work. break; } else if(isdigit(duty)){ dutyTotal += (duty -'0') * decades; decades /= 10; count--; } else { clearPuttyTerminal(); printLaserMenu(laserChoice); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); choice = 'D'; pass = 0; break; } }//end for loop if(pass == 1){ while(count>0){ dutyTotal /= 10; count--; } ltoa(dutyTotal,buffer); outputFun("\n(aaa090) You entered ",buffer,"%"); if((dutyTotal < 0) || (dutyTotal > 100)){ clearPuttyTerminal(); printLaserMenu(laserChoice); delay(delayTime); outputFun("\n(aaa999)"," Invalid Entry, Please try again!",""); } else { if(laserChoice[0] == 'A'){ back = setDutyCycle(&pd0LaserA, laserChoice[0], dutyTotal); } else { back = setDutyCycle(&pd1LaserB, laserChoice[0], dutyTotal); } if(back){ outputFun("(aaa222) Laser's", laserChoice," duty cycle was changed successfully.\n"); } wait = false; //Exit duty loop if input is valid } }// end if pass }//end if D if(choice == 'X'){ clearPuttyTerminal(); wait = false; } if(choice == 'E'){ terminateFunction(); } }// end while(wait) }//end laserCommands method //OutputFun - Handles output messages with identifiers void outputFun(char* ident, char* str, char* optional ){ UARTprintf("%s%s%s%s%s", ident, " ", str,optional, "\n"); } //InputFun - Gets input . char InputFun(){ return UARTgetc(); } bool checkChoice(char arr[], char c){ int i; for(i=0; i<sizeof(arr); i++){ if(arr[i]==c) return false; } clearPuttyTerminal(); return true; } void printTaskMenu(){ clearPuttyTerminal(); outputFun("(aaa300) --- S E L E C T ","T A S K ---","\n"); outputFun("(aaa039)"," Press s to", " set the Laser's."); outputFun("(aaa012)"," Press c ","- for clearing the screen"); outputFun("(aaa300)"," Press e ","- for Exit"); } //This function prints out the MENU void printSelectionMenu(){ outputFun("(aaa100) --- S E L E C T I O N ","M E N U ---","\n"); outputFun("(aaa009)"," Which Laser you want to", " operate with?\n"); outputFun("(aaa010)"," Press a ","- for Laser number 1"); outputFun("(aaa011)"," Press b ","- for Laser number 2"); outputFun("(aaa012)"," Press c ","- for clearing the screen"); outputFun("(aaa250)"," Press x ","- Go back to Task Menu"); outputFun("(aaa300)"," Press e ","- for Exit"); } void printLaserMenu(char* laserChoice){ char freqBuffer[5]; char dutyBuffer[5]; if( laserChoice[0] == 'A'){ // laserChoice is a pointer and works like a string of chars. It is like an array with one element. ltoa(pd0LaserA.frequency,freqBuffer); ltoa(pd0LaserA.dutyCycle,dutyBuffer); } else { ltoa(pd1LaserB.frequency,freqBuffer); ltoa(pd1LaserB.dutyCycle,dutyBuffer); } outputFun("(aaa101) --- L A S E R -",laserChoice," - M E N U ---"); outputFun("\t\t\t\t\t(aaa050) Laser",laserChoice," Current Status"); outputFun("\t\t\t\t\t(aaa051) Frequency: ",freqBuffer," Hz"); outputFun("\t\t\t\t\t(aaa052) Duty Cycle: ",dutyBuffer," %\n"); outputFun("(aaa020)", "f - Change PWM Frequency",""); outputFun("(aaa021)", "d - Change PWM Duty Cycle",""); outputFun("(aaa250)", "x - Go Back to Main Menu",""); outputFun("(aaa300)", "e - Exit",""); } void initsConfirmation(){ UARTEchoSet(false); //This disables the display of anything typed during the initialization. int delayTime = 3500000; //local delayTime for loop. outputFun("\033\143","",""); // \033\143 this command clears the Putty terminal. This may not work for other terminals. delay(delayTime); outputFun("(aaa000)", " UART initialized...",""); delay(delayTime); outputFun("(aaa001)", " Clock initialized...",""); delay(delayTime); outputFun("(aaa002)", " Timer initialized...",""); delay(delayTime); outputFun("(aaa003)", " Timer0IntHandler initialized...",""); delay(delayTime); outputFun("(aaa004)", " Interrupt initialized...",""); delay(delayTime); outputFun("(aaa005)", " GPIO and PWM's initialized...","\n"); delay(delayTime); outputFun("(aaa006)", " Initialization Completed.!",""); delay(delayTime*2); clearPuttyTerminal(); UARTEchoSet(true); // This enables the display of anything that will be typed from now on. UARTFlushRx(); // This clears the input buffer from anything typed (but not displayed) during initialization. } void terminateFunction(){ int delayTime = 900000; UARTEchoSet(false); //This disables the display of anything typed during the initialization. clearPuttyTerminal(); int count = 0; do{ UARTprintf("%s",". "); delay(delayTime); count++; }while(count < 5); clearPuttyTerminal(); outputFun("\n(aaa500)","System Terminated.","\a"); delay(delayTime); exit(0); } void clearPuttyTerminal(){ // \033\143 this command clears the Putty terminal.This may not work for other terminals. outputFun("\033\143","",""); } void delay(int time){ int i; for( i=0; i<time; i++){ //delay } }
C
// Implements a dictionary's functionality #include <ctype.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dictionary.h" //Define node structure with word and pointer to next node typedef struct node { char word[LENGTH + 1]; struct node *next; } node; //Default hash size (can be manipulated to adjust performance/memory usage) #define HASH_SIZE 5381 //Array of nodes to create a chained hash table node *hashTable[HASH_SIZE]; //Global variable to keep track of size of file unsigned int word_count = 0; //Function to return a hash value //Using the djb2 hash function by Dan Bernstein unsigned int hashFunc(char *str) { unsigned long hash = 5381; int c = 0; while ((c = *str++)) { hash = ((hash << 5) + hash) + c; /* hash * 33 + c */ } return hash % HASH_SIZE; } // Returns true if word is in dictionary else false bool check(const char *word) { int len = strlen(word); char lower_case[len + 1]; //Convert string to all lower case for (int i = 0; i < len; i++) { lower_case[i] = tolower(word[i]); } lower_case[len] = '\0'; //Get index from hash function unsigned int index = hashFunc(lower_case); //create traversal pointer at the index from hash function node *trav = hashTable[index]; //Traverse the node untill we reach null pointer while (trav != NULL) { //if words match if (strcmp(trav->word, lower_case) == 0) { return true; } //else move onto next word else { trav = trav->next; } } return false; } // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { //Set array to all NULL values for (int i = 0; i < HASH_SIZE; i++) { hashTable[i] = NULL; } //Open file for reading and check if it openend properly FILE *file = fopen(dictionary, "r"); if (!file) { printf("File could not be opened"); return false; } while (true) { //Dynamically allocate memory for new node node *new_node = malloc(sizeof(node)); //If new node could not be created, exit if (!new_node) { return false; } //Add values to new node fscanf(file, "%s", new_node->word); new_node->next = NULL; //If end of file is reached if (feof(file)) { free(new_node); break; //free node and exit } word_count++;//Increment word count after each successful addition //Get index from hash function unsigned int index = hashFunc(new_node->word); node *check = hashTable[index]; //If index location is empty, insert new node if (check == NULL) { hashTable[index] = new_node; } //Else new node points to the current index location and becomes the index location itself else { new_node->next = hashTable[index]; hashTable[index] = new_node; } } fclose(file); return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { // TODO return word_count; //Global variable updated in load function } // Unloads dictionary from memory, returning true if successful else false bool unload(void) { //Free all nodes for (int i = 0; i < HASH_SIZE; i++) { node *trav = hashTable[i]; while (trav != NULL) { node *temp = trav; trav = trav->next; free(temp); } } return true; }
C
// simple shell example using fork() and execlp() #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <sys/stat.h> #include <fcntl.h> #define CMD "ps" int main(void) { pid_t k; char buf[100]; int status; int len; int fd; int cfd; char cbuf[500]; // client create the cfifopid char cfifo[sizeof "cfifo11111"]; sprintf(cfifo,"cfifo%d",getpid()); char *cf = cfifo; mkfifo(cf,0666); // the server's fifo char *scf = "cmdfifo"; char msg[100]; sprintf(msg,"$%d$%s",getpid(),CMD); printf("msg %s\n",msg); // open cmdfifo fd = open(scf,O_WRONLY); //cfd = open(cfifo,O_RDONLY); //open client fifo file // write $clientpid$command to cmdfifo int wid = write(fd,msg,sizeof(msg)); close(fd); printf("wid %d,Try to open cfifo %s \n",wid,cfifo); cfd = open(cf,O_RDONLY); //open client fifo file //perror("open:"); printf("cfifo = %d \n",cfd); if (-1 == cfd) //print the content in cfifo { printf("Failed to open and read the file.\n"); exit(1); } printf("Try to read cfifo \n"); read(cfd,cbuf,500); perror("Read:"); close(cfd); printf("received msg \n"); printf("%s \n",cbuf); //unlink(scf); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> int main() { int rand; if ((rand = open("/dev/random", O_RDONLY)) < 0) { printf("ne nashel"); exit(1); } else { char string[20]; ssize_t result = read(rand, string, sizeof(string)); printf("%s", string); } close(rand); }
C
#include <pebble.h> static Window *window; static Layer *window_layer; static TextLayer *text_layer; static ScrollLayer *s_scroll_layer; static TextLayer *s_text_layer; static GBitmap *s_bitmap; static BitmapLayer *s_bitmap_layer; #define apidata 0 static void inbox_received_callback(DictionaryIterator *iterator, void *context) { // Destroy loading image layer. bitmap_layer_destroy(s_bitmap_layer); // Store incoming information static char departure_buffer[400]; // Read tuples for data Tuple *departure_tuple = dict_find(iterator, apidata); // If all data is available, use it if(departure_tuple) { snprintf(departure_buffer, sizeof(departure_buffer), "%s", departure_tuple->value->cstring); } // Get window bounds. GRect bounds = layer_get_bounds(window_layer); // Create scroll layer. s_scroll_layer = scroll_layer_create(bounds); scroll_layer_set_click_config_onto_window(s_scroll_layer, window); scroll_layer_set_paging(s_scroll_layer, true); layer_add_child(window_layer, scroll_layer_get_layer(s_scroll_layer)); // Create and populate text layer. s_text_layer = text_layer_create(GRect(bounds.origin.x, bounds.origin.y, bounds.size.w, 2000)); text_layer_set_text_color(s_text_layer, GColorFromRGB(255, 255, 255)); text_layer_set_background_color(s_text_layer, GColorFromRGB(0, 0, 85)); text_layer_set_text_alignment(s_text_layer, GTextAlignmentCenter); text_layer_set_font(s_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18_BOLD)); text_layer_set_text(s_text_layer, departure_buffer); // Add text to scroll layer. scroll_layer_add_child(s_scroll_layer, text_layer_get_layer(s_text_layer)); scroll_layer_set_content_size(s_scroll_layer, text_layer_get_content_size(s_text_layer)); // Enable text flow. text_layer_enable_screen_text_flow_and_paging(s_text_layer, 5); } static void handle_init() { // Setup window layer. window = window_create(); window_layer = window_get_root_layer(window); GRect bounds = layer_get_bounds(window_layer); window_set_background_color(window, GColorFromRGB(0, 0, 85)); window_stack_push(window, true); // Display app image. s_bitmap = gbitmap_create_with_resource(RESOURCE_ID_POWERED_BY); s_bitmap_layer = bitmap_layer_create(bounds); bitmap_layer_set_bitmap(s_bitmap_layer, s_bitmap); bitmap_layer_set_compositing_mode(s_bitmap_layer, GCompOpSet); bitmap_layer_set_background_color(s_bitmap_layer, GColorFromRGB(255, 255, 255)); layer_add_child(window_layer, bitmap_layer_get_layer(s_bitmap_layer)); // Register callbacks app_message_register_inbox_received(inbox_received_callback); // Open AppMessage app_message_open(app_message_inbox_size_maximum(), app_message_outbox_size_maximum()); } void handle_deinit(void) { // Destroy the text layer text_layer_destroy(text_layer); // Destroy scroll layer scroll_layer_destroy(s_scroll_layer); // Destroy the window window_destroy(window); } int main(void) { handle_init(); app_event_loop(); handle_deinit(); }
C
/* putchar is the only external dependency for this file, if you have a working putchar, leave it commented out. If not, uncomment the define below and replace outbyte(c) by your own function call. */ #define putchar(c) outbyte(c) #include <stdarg.h> /* va_list, va_arg() */ #include "do_printf.h" /***************************************************************************** * PRINTF You must write your own putchar() *****************************************************************************/ static int vprintf_help(unsigned c, void **ptr){ extern int putchar(int c); ptr = ptr; /* to avoid unused varible warning */ putchar(c); return 0; } static int vsprintf_help(unsigned int c, void **ptr){ char *dst = *ptr; *dst++ = c; *ptr = dst; return 0 ; } int vsprintf(char *buffer, const char *fmt, va_list args){ int ret_val = do_printf(fmt, args, vsprintf_help, (void *)buffer); buffer[ret_val] = '\0'; return ret_val; } int sprintf(char *buffer, const char *fmt, ...){ va_list args; int ret_val; va_start(args, fmt); ret_val = vsprintf(buffer, fmt, args); va_end(args); return ret_val; } int vprintf(const char *fmt, va_list args){ return do_printf(fmt, args, vprintf_help, (void *)0); } int printf(const char *fmt, ...){ va_list args; int ret_val; va_start(args, fmt); ret_val = vprintf(fmt, args); va_end(args); return ret_val; }
C
#include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <termios.h> int main (int argc, char** argv){ int device = -1; //open device device = open("/dev/ttyS0", O_RDWR | O_NOCTTY | O_NONBLOCK); if (device == -1){ printf("Failed to open device\r\n"); printf("Error: %s\n",strerror(errno)); return -1; } //setup struct termios conf; tcgetattr(device, &conf); cfsetspeed(&conf, B115200); cfmakeraw(&conf); conf.c_cflag &= ~CSTOPB; conf.c_cflag |= CLOCAL; conf.c_cflag |= CREAD; conf.c_cc[VTIME]=0; conf.c_cc[VMIN]=0; conf.c_iflag = 0; conf.c_oflag = 0; conf.c_lflag = 0; if(tcsetattr(device, TCSANOW,&conf) < 0) { printf("Failed to configur device\r\n"); printf("Error: %s\n",strerror(errno)); return -1; } if(tcsetattr(device, TCSAFLUSH, &conf) < 0) { printf("Failed to configure device\r\n"); printf("Error: %s\n",strerror(errno)); return -1; } char initText[] = "ATI[0]"; write(device, initText, strlen(initText)+1); int count = 0; int count2 = 0; char received[100]; char in; char out; int i=0; while(out!='x'){ count2 = read(STDIN_FILENO, &out, 1); if(count2!=0){ write(device, &out, 1); received[i]=out; i++; if(out==0) {break;} }; }; close(device); return (EXIT_SUCCESS); }
C
#include "headerfiles.h" void bg(char *cmd,struct Job JOBS[100], int numchild) { char *tok = strtok(cmd," "); tok = strtok(NULL," "); int jobnum = atoi(tok),jobid; int present = 0; for(int c = 0 ; c < numchild ; c++ ) { if(JOBS[c].jobnumber == jobnum && JOBS[c].terminated == 0) { present = 1; jobid = JOBS[c].procid; //Get the pid of the process specified break; } } if(present == 0) { printf("No Such Job Exists\n"); return; } if(present == 1) { int check = kill(jobid, SIGCONT); if(check == 0) printf("PID %d has been pushed to the Background\n",jobid); } }
C
// This is very simple input generator. // A separate process generates input at 1 second // time intervals. Input is characters A B C, ..., Z. #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include<fcntl.h> #include <errno.h> #include <sys/time.h> int OpenChatFellow() { pid_t pid; int fd_arr[2]; int i; char chr; //This part is done only by parent pipe(fd_arr); pid = fork(); if (pid < 0) { perror("Process creation error"); } if (pid > 0) { close (fd_arr[1]); // parent closes it's read end of the pipe return fd_arr[0]; } if (pid == 0) { // this is child close (fd_arr[0]); // writing to the pipe for( i = 0 ; i < 26 ; i++) { chr = 'a' + i; write(fd_arr[1], &chr, 1); sleep(1); } close(fd_arr[1]); exit (0); } } int main(void) { int fellow_desc; char chr_fellow; char chr_kb; int file_flags,result; fellow_desc=OpenChatFellow(); fd_set fdset; int n; while(1){ FD_ZERO(&fdset); FD_SET(0,&fdset); FD_SET(fellow_desc,&fdset); n=select(fellow_desc+1,&fdset,NULL,NULL,NULL); if(n>0){ if(FD_ISSET(0,&fdset)){ //keyboard is ready read(0,&chr_kb,1); if(chr_kb=='Q'||chr_kb=='q') exit(0); else{ printf("%c",chr_kb); fflush(stdout); } } if(FD_ISSET(fellow_desc,&fdset)){ result=read(fellow_desc,&chr_fellow,1); if(result>0){ printf("%c",chr_fellow); fflush(stdout);} if(result==-1&&errno!=EAGAIN) perror("Fellow error"); if(result==0) exit(0); } } } return EXIT_SUCCESS; }
C
#include <stdio.h> #include <stdlib.h> #include "vector.c" #include "LinkedList.c" #include "Stack.c" #include "Queue.c" int main() { ///////////////////////////////PART I////////////////////////////////////////////////////// ///////////////////////////////////////PART A/////////////////////////////////////////////////////////////////////////////////// int i; printf("\n--------------------------------------------------VECTOR-------------------------------------------------------------\n"); Vector *vec=createVector(); printf("\nIntially Vector max_size is %d & used_size is %d\n",vec->max_size,vec->current_size); //Loop 1 :inserting 20 integer data srand(time(NULL)); //seed the random number generator only once for(i=0;i<20;i++){ int randomNumber=rand()%20; //Generate random number between 0-19 Data new_Data; new_Data.number=randomNumber; vectorInsert(vec,i,new_Data); } printf("After insert Vector - max_size %d & used_size %d\n\n",vec->max_size,vec->current_size); //printf("Enter index and value:"); /*int index1; Data value1; scanf("%d",&x); scanf("%d",&y); vectorInsert(geo_vec,x,y);*/ //Loop 2 :reading & printing the vector for(i=0;i < vec->current_size;i++) { int value_at_index=vectorRead(vec,i); if(value_at_index==-1) { printf("There is no such index\n"); break; } else printf("INDEX : %d VALUE : %d\n",i,value_at_index); } printf("\n"); //Loop 3 : removing all the assigned values for(i=0;i< vec->current_size;i++) { printf("DELETED INDEX : %d VALUE : %d\n",i,vec->arr[i].number); vectorRemove(vec,i); } free(vec->arr); free(vec); ////////////////////////////////////////PART B//////////////////////////////////////////////////////////////////////////////// printf("\n=======================PART B===============================\n"); struct timeval start, stop; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// gettimeofday(&start, NULL); Vector *geo_vec=createVector(); printf("\nIntially Vector max_size is %d & used_size is %d\n",geo_vec->max_size,geo_vec->current_size); //insert 10000 values srand(time(NULL)); //seed the random number generator only once for(i=0;i<10000;i++){ int randomNumber=rand()%20; //Generate random number between 0-19 Data new_Data; new_Data.number=randomNumber; vectorInsert(geo_vec,i,new_Data); } printf("After insert Vector - max_size %d & used_size %d\n",geo_vec->max_size,geo_vec->current_size); for(i=0;i< geo_vec->current_size;i++) vectorRemove(geo_vec,i); free(geo_vec->arr); free(geo_vec); gettimeofday(&stop, NULL); time_t start_time = (start.tv_sec* 1000000) + start.tv_usec; time_t stop_time = (stop.tv_sec* 1000000) + stop.tv_usec; time_t geo_final_time = stop_time - start_time; printf("TIME OF GEOMETRIC EXPANSION : %d microseconds\n",geo_final_time); /////////////////////////////////////////////////////////////////////////////////////// gettimeofday(&start, NULL); Vector *inc_vec=createVector(); printf("\nIntially Vector max_size is %d & current_size is %d\n",inc_vec->max_size,inc_vec->current_size); //insert 10000 values srand(time(NULL)); //seed the random number generator only once for(i=0;i<10000;i++) { int randomNumber=rand()%20; //Generate random number between 0-19 Data new_Data; new_Data.number=randomNumber; vectorIncInsert(inc_vec,i,new_Data); } printf("After insert Vector - max_size %d & current_size %d\n",inc_vec->max_size,inc_vec->current_size); for(i=0;i< inc_vec->current_size;i++) vectorRemove(inc_vec,i); free(inc_vec->arr); free(inc_vec); gettimeofday(&stop, NULL); start_time = (start.tv_sec* 1000000) + start.tv_usec; stop_time = (stop.tv_sec* 1000000) + stop.tv_usec; time_t inc_final_time = stop_time - start_time; printf("TIME OF INCREMENTAL EXPANSION : %d microseconds\n",inc_final_time); ////////////////////////////PART II : LINKED LIST////////////////////////////////////////////////////// printf("\n----------------------------------------------------LINKED LISTS-----------------------------------------------------\n"); //Generate 10 random numbers to be inserted List *list=createList(); for(i=0;i<10;i++) { Data new_data; new_data.number=rand()%20; insertData(list,i,new_data); display(list); } //insert number at index 20 Data new_data; new_data.number=rand()%20; printf("Trying to add a node with value %d at index 20\n",new_data.number); insertData(list,20,new_data); display(list); //search for a number in the list Forward and backwards int search_num; printf("Enter the value to be searched:\n"); scanf("%d",&search_num); int forward,backward; forward=searchForward(list,search_num); backward=searchBackward(list,search_num); printf("FORWARD POSITION : %d\nBACKWARD POSITION : %d\n",forward,backward); //Delete a data from particular index int remove; remove=rand()%12; int Return=removeNode(list,remove); while(Return!=0) //0 is returned if list is empty { printf("Index being removed : %d\n",remove); if(Return==1) { printf("After deleting data at index %d\n",remove); display(list); } remove=rand()%11; Return=removeNode(list,remove); } free(list); list=NULL; ///////////////////////////////////////PART III A/////////////////////////////////////////////////// printf("\n--------------------------------------------------STACK--------------------------------------------------------------\n"); Stack *stack=createStack(); printf("Enter 5 values to be pushed\n"); for(i=0;i<5;i++) { int new_data; printf("NEXT ELEMENT : "); scanf("%d",&new_data); push(stack,new_data); show(stack); } for(i=0;i<5;i++) { int poped; poped=pop(stack); printf("poped [%d]",poped); show(stack); } free(stack); ///////////////////////////////////////PART B/////////////////////////////////////////////////////// printf("\n--------------------------------------------------QUEUE--------------------------------------------------------------\n"); Queue *queue=createQueue(); printf("Enter 5 values to be appended\n"); for(i=0;i<5;i++) { int new_data; printf("NEXT ELEMENT : "); scanf("%d",&new_data); enqueue(queue,new_data); Qshow(queue); } for(i=0;i<5;i++) { int remov; remov=dequeue(queue); printf("removed [%d]",remov); Qshow(queue); } free(queue); printf("\n-------------------------------------------------THE END-------------------------------------------------------------\n"); //////////////////////////////////////////////////////////////////////////////////////////////////// return 0; }
C
// to find the difference between the sum of nodes at odd level and nodes at even level #include<bits/stdc++.h> using namespace std; struct node { int data; node* left; node* right; }; void insert(node** root,int key) { if((*root)==NULL) { (*root)=(struct node*)malloc(sizeof(struct node)); (*root)->data=key; (*root)->left=NULL; (*root)->right=NULL; } else if((*root)->data>key) insert((&(*root)->left),key); else insert((&(*root)->right),key); return; } pair<int,int> level(node* root) { int sum1=0,sum2=0; queue< pair<node*,int> >q; node* curr=root; q.push(make_pair(curr,1)); while(!q.empty()) { curr=q.front().first; int h=q.front().second; q.pop(); if(h%2!=0) sum1+=curr->data; else sum2+=curr->data; if(curr->left) q.push(make_pair(curr->left,h+1)); if(curr->right) q.push(make_pair(curr->right,h+1)); } return make_pair(sum1,sum2); } int main() { node* r=NULL; insert(&r,10); insert(&r,20); insert(&r,8); insert(&r,4); insert(&r,9); pair<int,int>p1=level(r); cout<<abs(p1.first-p1.second)<<endl; return 0; }
C
#include"stdio.h" struct date { int nam; int thang; int ngay; char thu[4]; }d; main() { int kich_thuoc; kich_thuoc=sizeof(struct date); printf("\n- Kich thuoc cau truc date la:%d bytes",kich_thuoc); kich_thuoc=sizeof d; printf("\n- Kich thuoc cua bien cau truc d la:%d bytes",kich_thuoc); getch(); }
C
// // Created by lugi1 on 2018-07-05. // #include "Hitbox.h" #include <malloc.h> #include <stdio.h> #include <math.h> #include <Vector.h> #include <Hitbox.h> #include "Hitbox.h" #include "Vector.h" #include "JamError.h" /* The following functions mostly break the "don't use a return * statement anywhere but the last line rule" for the sake of * performance since collisions are generally quite heavy. Just * know that anytime a return happens in the middle of a function * it is strictly because the function knows for certain that either * a collision is or isn't taking place. */ // This is made automatically when you try to check a poly-to-rectangle // collision. It stores a 4-sides polygon whos values are updated instead // of making a new polygon every time a poly-rect collision is checked. // It is freed whenever a hitbox is freed. // tl;dr micro-optimizations static JamPolygon* gRectPolyCache; ////////////////////////////////////////////////// static bool _circRectColl(double cX, double cY, double cR, double rX, double rY, double rW, double rH) { // Is the circle's centre in the rectangle if (pointInRectangle(cX, cY, rX, rY, rW, rH)) return true; // Check if the circle is touching a vertex of the rectangle if (pointDistance(cX, cY, rX, rY) < cR) return true; if (pointDistance(cX, cY, rX + rW, rY) < cR) return true; if (pointDistance(cX, cY, rX, rY + rH) < cR) return true; if (pointDistance(cX, cY, rX + rW, rY + rH) < cR) return true; // Now if the circle is along the edge if (pointInRectangle(cX, cY, rX - cR + 1, rY + 1, rH + cR * 2 - 2, rH - 2)) return true; if (pointInRectangle(cX, cY, rX + 1, rY - cR + 1, rH - 2, rH + cR * 2 - 2)) return true; return false; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// static inline double _cast1DShadow(double x, double y, double m) { return y - m * x; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// static bool _satCheckGap(JamPolygon* p1, JamPolygon* p2, double x1, double y1, double x2, double y2) { unsigned int i, j; double slope; double min1, min2, max1, max2; register bool done1; register bool done2; register double currentVal; // For each edge on polygon 1 for (i = 0; i < p1->vertices; i++) { done1 = false; done2 = false; if (i == 0) slope = (p1->yVerts[0] - p1->yVerts[p1->vertices - 1]) / (p1->xVerts[0] - p1->xVerts[p1->vertices - 1]); else slope = (p1->yVerts[i] - p1->yVerts[i - 1]) / (p1->xVerts[i] - p1->xVerts[i - 1]); // Record min/max of polygon 1 for (j = 0; j < p1->vertices; j++) { currentVal = _cast1DShadow(p1->xVerts[j] + x1, p1->yVerts[j] + y1, slope); if (currentVal > max1 || !done1) max1 = currentVal; if (currentVal < min1 || !done1) min1 = currentVal; done1 = true; } // Record min/max of polygon 2 for (j = 0; j < p2->vertices; j++) { currentVal = _cast1DShadow(p2->xVerts[j] + x2, p2->yVerts[j] + y2, slope); if (currentVal > max2 || !done2) max2 = currentVal; if (currentVal < min2 || !done2) min2 = currentVal; done2 = true; } // Check if the two ranges don't intersect if (max1 < min2 || max2 < min1) return true; } return false; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// bool jamHitboxPolygonCollision(JamPolygon *poly1, JamPolygon *poly2, double x1, double y1, double x2, double y2) { // Make sure the polygons exist and they are at least a triangle if (poly1 != NULL && poly2 != NULL) { if (poly1->vertices >= 3 && poly2->vertices >= 3) { if (_satCheckGap(poly1, poly2, x1, y1, x2, y2) || _satCheckGap(poly2, poly1, x2, y2, x1, y1)) return false; else return true; } else { if (poly1->vertices < 3) jSetError(ERROR_INCORRECT_FORMAT, "JamPolygon 1 needs at least 3 vertices."); if (poly2->vertices < 3) jSetError(ERROR_INCORRECT_FORMAT, "JamPolygon 2 needs at least 3 vertices."); } } else { if (poly1 == NULL) jSetError(ERROR_NULL_POINTER, "JamPolygon 1 does not exist."); if (poly2 == NULL) jSetError(ERROR_NULL_POINTER, "JamPolygon 2 does not exist."); } return false; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// static bool _satToCircleCollisions(JamPolygon* p1, double r, double x1, double y1, double x2, double y2) { return false; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// static bool _satToRectangleCollisions(JamPolygon* p, double w, double h, double x1, double y1, double x2, double y2) { if (gRectPolyCache == NULL) { gRectPolyCache = jamPolygonCreate(4); if (gRectPolyCache == NULL) { jSetError(ERROR_ALLOC_FAILED, "Failed to create polygon cache."); return false; } } // We now know for certain the polygon cache exists gRectPolyCache->xVerts[0] = 0; gRectPolyCache->yVerts[0] = 0; gRectPolyCache->xVerts[1] = w; gRectPolyCache->yVerts[1] = 0; gRectPolyCache->xVerts[2] = w; gRectPolyCache->yVerts[2] = h; gRectPolyCache->xVerts[3] = 0; gRectPolyCache->yVerts[3] = h; return jamHitboxPolygonCollision(gRectPolyCache, p, x2, y2, x1, y1); } ////////////////////////////////////////////////// ////////////////////////////////////////////////// JamHitbox* jamHitboxCreate(JamHitboxType type, double radius, double width, double height, JamPolygon *polygon) { JamHitbox* hitbox = (JamHitbox*)malloc(sizeof(JamHitbox)); // Check if it worked of course if (hitbox != NULL) { hitbox->type = type; if (type == ht_Circle) { hitbox->radius = radius; } else if (type == ht_Rectangle) { hitbox->width = width; hitbox->height = height; } else if (type == ht_ConvexPolygon) { hitbox->polygon = polygon; } } else { jSetError(ERROR_ALLOC_FAILED, "Failed to allocate hitbox. (jamHitboxCreate)"); } return hitbox; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// bool jamHitboxCollision(JamHitbox *hitbox1, double x1, double y1, JamHitbox *hitbox2, double x2, double y2) { bool hit = false; // Double check it's there if (hitbox1 != NULL && hitbox2 != NULL) { if (hitbox1->type == ht_Circle && hitbox2->type == ht_Circle) { // Circle-to-circle hit = (pointDistance(x1, y1, x2, y2) < hitbox1->radius + hitbox2->radius); } else if (hitbox1->type == ht_Rectangle && hitbox2->type == ht_Rectangle) { // Rectangle-to-rectangle hit = (y1 + hitbox1->height > y2 && y1 < y2 + hitbox2->height && x1 + hitbox1->width > x2 && x1 < x2 + hitbox2->width); } else if (hitbox1->type == ht_Rectangle && hitbox2->type == ht_Circle) { // Rectangle-to-circle hit = _circRectColl(x2, y2, hitbox2->radius, x1, y1, hitbox1->width, hitbox1->height); } else if (hitbox1->type == ht_Circle && hitbox2->type == ht_Rectangle) { // Circle-to-rectangle hit = _circRectColl(x1, y1, hitbox1->radius, x2, y2, hitbox2->width, hitbox2->height); } else if (hitbox1->type == ht_ConvexPolygon && hitbox2->type == ht_ConvexPolygon) { // Poly-to-poly hit = jamHitboxPolygonCollision(hitbox1->polygon, hitbox2->polygon, x1, y1, x2, y2); } else if (hitbox1->type == ht_ConvexPolygon && hitbox2->type == ht_Rectangle) { // Poly-to-rectangle hit = _satToRectangleCollisions(hitbox1->polygon, hitbox2->width, hitbox2->height, x1, y1, x2, y2); } else if (hitbox1->type == ht_Rectangle && hitbox2->type == ht_ConvexPolygon) { // Rectangle-to-poly hit = _satToRectangleCollisions(hitbox2->polygon, hitbox1->width, hitbox2->height, x2, y2, x1, y1); } else if (hitbox1->type == ht_ConvexPolygon && hitbox2->type == ht_Circle) { // Poly-to-circle hit = _satToCircleCollisions(hitbox1->polygon, hitbox2->radius, x1, y1, x2, y2); } else if (hitbox1->type == ht_Circle && hitbox2->type == ht_ConvexPolygon) { // Circle-to-poly hit = _satToCircleCollisions(hitbox2->polygon, hitbox2->radius, x2, y2, x1, y1); } // TODO: Implement cirlce-to-poly collisions } else { if (hitbox1 == NULL) jSetError(ERROR_NULL_POINTER, "JamHitbox 1 does not exist. (jamHitboxCollision)"); if (hitbox2 == NULL) jSetError(ERROR_NULL_POINTER, "JamHitbox 2 does not exist. (jamHitboxCollision)"); } return hit; } ////////////////////////////////////////////////// ////////////////////////////////////////////////// void jamHitboxFree(JamHitbox *hitbox) { if (hitbox != NULL) { if (hitbox->type == ht_ConvexPolygon) jamPolygonFree(hitbox->polygon); free(hitbox); } if (gRectPolyCache != NULL) { jamPolygonFree(gRectPolyCache); gRectPolyCache = NULL; } } //////////////////////////////////////////////////
C
#include "stack.h" struct stack stack_init() { struct stack s; s.elem = malloc(2* sizeof(int)); s.capacity =2; s.size = 0; return s; } //扩容 static void expand(struct stack *s) { if(s->size < s->capacity) return; //尚未满员,不必扩容 s->elem = realloc(s->elem,(s->capacity<<=1)*sizeof(int)); } void stack_push(struct stack *s, int e) { expand(s); *(s->elem+s->size) = e; s->size++; } int stack_pop(struct stack *s) { s->size--; return *(s->elem + s->size); }
C
/* * ls.c * * Created on: 20 août 2008 * Author: drossier */ #include <stdio.h> #include <dirent.h> #include <stdlib.h> #include <string.h> #include <unistd.h> /* * Forking process for each dir... */ int main(int argc, char **argv) { DIR *stream; struct dirent *p_entry; char *dir; if (argc == 1) { dir = "."; } else if (argc == 2) { dir = argv[1]; } else { printf("Usage: ls [DIR]\n"); exit(1); } stream = opendir(dir); if (stream == NULL) exit(1); while ((p_entry = readdir(stream)) != NULL) { if ((argc > 1) && !strcmp(argv[1], "-l")) { if (p_entry->d_type) printf("d "); else printf("r "); printf("%dB\t", p_entry->d_size); } printf("%s\n", p_entry->d_name); } exit(0); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include "util.h" #include "generic_ipc.h" #define MAX_SEND_CNT 100 #define SEND_INTERVAL 1 //seconds #define IPC_MSG_MAX_LEN 255 static void client_hander (ipc_req_t *req_p, ipc_resp_t *resp_p) { pid_t pid; if (req_p->req_data) { pid = *(pid_t *)req_p->req_data; printf("##Server PID %d\n", pid); } pid = getpid(); resp_p->resp_data = calloc(1, sizeof(pid_t)); if (!resp_p->resp_data) { return; } memcpy(resp_p->resp_data, &pid, sizeof(pid_t)); resp_p->resp_data_size = sizeof(pid_t); return; } static void send_one_ipc_msg (char *ipc_msg) { ipc_req_t req; ipc_resp_t resp; uint32_t ipc_msg_size; int rc; ipc_msg_size = strlen(ipc_msg) + 1; printf("##client send ipc msg size %d, msg %s\n", ipc_msg_size, ipc_msg); req.req_type = IPC_PAK_REQ_DATA; req.req_data = ipc_msg; req.req_data_size = ipc_msg_size; rc = generic_ipc_request(&req, &resp); if (rc != 0) { printf("Fail to send ipc request."); return; } printf("##client get resp size %d, resp %s\n", resp.resp_data_size, (char *)resp.resp_data); if (resp.resp_data) { free(resp.resp_data); } return; } static void compose_ipc_msg (char *ipc_msg) { char timestamp[TIMESTAMP_MAX_LEN+1]; get_current_timestamp(timestamp); snprintf(ipc_msg, IPC_MSG_MAX_LEN+1, "##Client msg at %s##", timestamp); return; } static void test_send (void) { char ipc_msg[IPC_MSG_MAX_LEN+1]; uint32_t i; for (i = 0; i < MAX_SEND_CNT; i++) { compose_ipc_msg(ipc_msg); send_one_ipc_msg(ipc_msg); sleep(SEND_INTERVAL); } return; } int main (void) { int rc; rc = generic_ipc_init(IPC_OWNER_CLIENT, client_hander); if (rc != 0) { printf("Fail to init ipc.\n"); return -1; } test_send(); generic_ipc_clean(IPC_OWNER_CLIENT); return 0; }
C
#ifndef ESTRUCTURAS_H #define ESTRUCTURAS_H //CONSIDERACION: Se utilizaron estructuras usadas en el laboratorio anterior. /* * Descripcion: Estructura que almacena los elementos relacionados al forwarding tales como * su posicion, numero de instruccion, cual registro esta involucrado, y si posee multiple forward. * */ typedef struct forwardingDatos { int poseeHazzard; int posicion; int numInstruccion; int registroProblema; int multipleForward; }forward; /* * Descripcion: Dentro de esta estructura se almancenaran los elementos relevantes * de cada instruccion, tales como: * tipo = Que puede ser del grupo ADDI-SUBI(0) o LW-SW(1) * op = Que operacion del grupo es. * Rn = Indice del registro. * V_Rn = Valor temporal del registro. */ typedef struct elementosInstruccion { char *instruccion; int tipo; int op; int R1; int R2; int R3; int valor_R1; int valor_R2; int valor_R3; forward *datosForward; }instruccion; /* * Descripcion: Estructura que almacena una lista de instrucciones tipo string, estas son * ordanizadas por el indice de la estructura, el cual se modifica cada vez que se agrega * un nuevo elemento. */ typedef struct instruccionesArchivoArchivoLectura { char **datos; int indice; }instruccionesArchivo; /* * Descripcion: Dentro de esta estructura se almacenan todos los datos relacionados con * arreglos. Tal sea asi, que se conforma un arreglo por cada registro de este. */ typedef struct memoriaDatos { int **datos; }memoria; /* * Descripcion: Estructura que almacena una lista representativa de los datos almacenados * en los registros del programa. */ typedef struct registrosPrograma { int *datos; }registros; /* * Descripcion: Estructura que tiene un puntero para cada instruccion que se ejecutara dentro del pipeline */ typedef struct elementosPipeline { instruccion *IF; instruccion *ID; instruccion *EX; instruccion *MEM; instruccion *WB; }pipeline; /* * Descripcion: Estructura que almacena un puntero por cada instruccion que paso por los buffer intermedios. */ typedef struct bufferIntermedios { instruccion *ID_EX; instruccion *EX_MEM; instruccion *MEM_WB; }buffer; /* * Descripcion: Estructura que almacena el contenido de un error tipo hazard. */ typedef struct errorHazzard { int numeroInstruccion; int numeroCiclo; int tipoError; }error; /* * Descripcion: Estructura que almacena multiples errores. */ typedef struct reporteHazzard { error **listaError; int indiceError; }reporte; #endif /*ESTRUCTURAS_H*/
C
/* ** cmd_parsing.c for myirc in /home/ganesha/projets/Myirc/client_dir ** ** Made by Ambroise Coutarel ** Login <[email protected]> ** ** Started on Thu Apr 9 20:33:21 2015 Ambroise Coutarel ** Last update Sun Apr 12 13:41:15 2015 Ambroise Coutarel */ #include "irc_client.h" t_client_com g_commands_client[3]; int server_response(int fd) { int len; int timeout; char *resp; len = 0; timeout = 1; while (!len && ioctl(fd, FIONREAD, &len) >= 0) { if (timeout == 10) return (-1); usleep(3000); ++timeout; } if ((resp = malloc(sizeof(char) * (len + 1))) == NULL) { printf("Unable to malloc response\n"); return (-1); } len = read(fd, resp, len); resp[len] = '\0'; printf("%s", resp); free(resp); return (0); } void subinit(t_client_com *cmd, char *name, void (*func)(char **, int *, char *)) { cmd->command = strdup(name); cmd->func = func; } void send_to_serv(char *query, int *server_socket) { write((*server_socket), query, strlen(query)); } void init_commands() { subinit(&(g_commands_client[0]), "/server", &server); subinit(&(g_commands_client[1]), "/send_file", &send_file); subinit(&(g_commands_client[2]), "/accept_file", &accept_file); } void handle_cmds(char *query, int *server_socket, char *is_connected) { char **cmd; int v; v = 0; cmd = my_str_to_wordtab(query); while (v != CLIENT_CMD) { if (strcmp(cmd[0], g_commands_client[v].command) == 0) { if ((*server_socket) != -1 && (*is_connected) == 1) send_to_serv(query, server_socket); g_commands_client[v].func(&(cmd[1]), server_socket, is_connected); free_wtab(cmd); return ; } ++v; } if ((*server_socket) != -1 && (*is_connected) == 1) { send_to_serv(query, server_socket); server_response((*server_socket)); free_wtab(cmd); } }
C
#include <stdio.h> #include <limits.h> #include <float.h> #include <math.h> /* it is really important to select the appropriate format specifiers */ int main() { printf("####################### limits.h ########################\n"); printf("CHAR_BIT:\t%d\t%d\n", CHAR_BIT, 8); // 8 bits printf("CHAR_MAX:\t%d\t%.0f\n", CHAR_MAX, pow(2, CHAR_BIT) / 2 - 1); // 8 bits printf("CHAR_MIN:\t%d\t%.0f\n", CHAR_MIN, -1 * pow(2, CHAR_BIT) / 2); // 8 bits printf("INT_MAX:\t%d\n", INT_MAX); // 32 bits printf("INT_MIN:\t%d\n", INT_MIN); // 32 bits printf("LONG_MAX:\t%ld\n", LONG_MAX); // 32 bits (64 on my linux machine) printf("LONG_MIN:\t%ld\n", LONG_MIN); // 32 bits (64 on my linux machine) printf("SCHAR_MAX:\t%d\n", SCHAR_MAX); // 8 bits printf("SCHAR_MIN:\t%d\n", SCHAR_MIN); // 8 bits printf("SHRT_MAX:\t%d\n", SHRT_MAX); // 16 bits printf("SHRT_MIN:\t%d\n", SHRT_MIN); // 16 bits printf("UCHAR_MAX:\t%d\n", UCHAR_MAX); // 8 bits printf("UINT_MAX:\t%u\n", UINT_MAX); // 32 bits printf("ULONG_MAX:\t%lu\n", ULONG_MAX); // 32 bits printf("USHRT_MAX:\t%u\t%u\n", USHRT_MAX, (unsigned short int)pow(2, 16) - 1); // 16 bits printf("LLONG_MAX:\t%lld\t%lld\n", LLONG_MAX, (signed long long int)(pow(2, 64) / 2 - 1)); // 64 bits printf("LLONG_MIN:\t%lld\t%lld\n", LLONG_MIN, (signed long long int)(-1 * pow(2, 64) / 2)); // 64 bits printf("ULLONG_MAX:\t%llu\t%llu\n", ULLONG_MAX, (unsigned long long int)pow(2, 64)); // 64 bits printf("\n"); printf("####################### float.h ########################\n"); /* floating-point = ( S ) p x b**e S = sign p = precision b = base or radix e = e_min or e_max */ printf("FLT_RADIX:\t%d\n", FLT_RADIX); // base radix representation (b) printf("FLT_ROUNDS:\t%d\n", FLT_ROUNDS); // rounding mode (1 = nearest) printf("FLT_DIG:\t%d\n", FLT_DIG); // maximum number of decimal digits that can be represented without change after rounding printf("FLT_EPSILON:\t%5.e\n", FLT_EPSILON); // least significant digit representable (p) printf("FLT_MANT_DIG:\t%d\n", FLT_MANT_DIG); // number of digits in FLT_RADIX printf("FLT_MAX:\t%5.e\n", FLT_MAX); // maximum finite floating-point value printf("FLT_MIN:\t%5.e\n", FLT_MIN); // minimum floating-point values printf("FLT_MAX_EXP:\t%d\n", FLT_MAX_EXP); // maximum integer value for an exponent in base FLT_RADIX (e) printf("FLT_MIN_EXP:\t%d\n", FLT_MIN_EXP); // minimum integer value for an exponent in base FLT_RADIX (e) printf("DBL_DIG:\t%d\n", DBL_DIG); // see FLT_DIG printf("DBL_EPSILON:\t%5.e\n", DBL_EPSILON); // see FLT_EPSILON (p) printf("DBL_MANT_DIG:\t%d\n", DBL_MANT_DIG); // see FLT_MANT_DIG printf("DBL_MAX:\t%5.e\n", DBL_MAX); // see FLT_MAX printf("DBL_EXP_MAX:\t%d\n", DBL_MAX_EXP); // see FLT_MAX_EXP (e) printf("DBL_MIN:\t%5.e\n", DBL_MIN); // see FLT_MIN printf("DBL_MIN_EXP:\t%d\n", DBL_MIN_EXP); // see FLT_MIN_EXP (e) }
C
#include<stdio.h> int main(){ int days; //7 days = 1 week //30 days - 1 month //365 days - 1 year printf("Enter days:"); scanf("%d", &days); int year1 = days/365; int year2 = days%365; int month1 = days/30; int month2 = days%30; int week1 = days/7; int week2 = days%7; //i want to present the left days too. suppose there are 56 days user has given, for months 26 days more. So i wanna //show like 1 month 26 days printf("%d days is %d year(s) %d day(s)\n", days, year1, year2); printf("%d days is %d month(s) %d day(s)\n", days, month1, month2); printf("%d days is %d week(s) %d day(s)\n", days, week1, week2); }
C
#include "quaternion.h" #include <math.h> struct Quaternion convVecToQuat(struct Vector vec) { struct Quaternion quat = {0, vec.x, vec.y, vec.z}; return quat; } struct Quaternion quatForRot(struct Vector axis, float angle) { float halfAngle = angle / 2.0f; float sinHalfAngle = sinf(halfAngle); struct Quaternion quad = { cosf(halfAngle), axis.x * sinHalfAngle, axis.y * sinHalfAngle, axis.z * sinHalfAngle }; return quad; } struct Quaternion conjugate(struct Quaternion quat) { struct Quaternion ret = {quat.w, -quat.i, -quat.j, -quat.k}; return ret; } struct Quaternion hamiltonP(struct Quaternion lhs, struct Quaternion rhs) { struct Quaternion ret = { lhs.w * rhs.w - lhs.i * rhs.i - lhs.j * rhs.j - lhs.k * rhs.k, lhs.w * rhs.i + lhs.i * rhs.w + lhs.j * rhs.k - lhs.k * rhs.j, lhs.w * rhs.j - lhs.i * rhs.k + lhs.j * rhs.w + lhs.k * rhs.i, lhs.w * rhs.k + lhs.i * rhs.j - lhs.j * rhs.i + lhs.k * rhs.w }; return ret; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_unset.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: darodrig <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/27 14:08:38 by darodrig #+# #+# */ /* Updated: 2020/07/01 08:48:24 by darodrig ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int existe(t_sh *sh, const char *s) { int i; char *aux; char *saux; i = 0; while (sh->envp[i]) { aux = ft_strjoin(sh->envp[i], "="); saux = ft_strjoin(s, "="); if (ft_strncmp(saux, aux, ft_strlen(saux)) == 0) { free(aux); free(saux); return (i); } else { free(saux); free(aux); } i++; } return (-1); } void free_vars(t_sh *sh) { int i; i = array_counter(sh->envp); while (i > 0) { free(sh->envp[i - 1]); i--; } } void auxprint(char *str) { if (ft_strchr(str, '=')) { ft_putstr("unset: `"); ft_putstr(str); ft_putstr(": not a valid identifier\n"); } } void aux_loop(t_sh *sh, int pos) { int j; int size; char **new; j = 0; size = array_counter(sh->envp); new = malloc(sizeof(char*) * size); while (j < size - 1) { if (j >= pos) new[j] = ft_strdup(sh->envp[j + 1]); else new[j] = ft_strdup(sh->envp[j]); j++; } new[j] = NULL; free_vars(sh); free(sh->envp); sh->envp = new; } int ft_unset(t_sh *sh, t_comm *com) { int pos; int i; i = 0; while (com->params && com->params[++i]) { if ((pos = existe(sh, com->params[i])) != -1) aux_loop(sh, pos); else auxprint(com->params[i]); } return (0); }
C
bool isPowerOfThree(int n) { if(n<=0) return false; while((n%9) == 0)n/=9; if(n%3==0) n/=3; return !(n-1); }
C
#include "marla.h" const char* marla_getDefaultStatusLine(int statusCode) { const char* statusLine; switch(statusCode) { case 100: statusLine = "Continue"; break; case 101: statusLine = "Switching Protocols"; break; case 200: statusLine = "OK"; break; case 201: statusLine = "Created"; break; case 202: statusLine = "Accepted"; break; case 203: statusLine = "Non-Authoritative Information"; break; case 204: statusLine = "No Content"; break; case 205: statusLine = "Reset Content"; break; case 300: statusLine = "Multiple Choices"; break; case 301: statusLine = "Moved Permanently"; break; case 302: statusLine = "Found"; break; case 303: statusLine = "See Other"; break; case 305: statusLine = "Use Proxy"; break; case 307: statusLine = "Temporary Redirect"; break; case 400: statusLine = "Bad Request"; break; case 402: statusLine = "Payment Required"; break; case 403: statusLine = "Forbidden"; break; case 404: statusLine = "Not Found"; break; case 405: statusLine = "Method Not Allowed"; break; case 406: statusLine = "Not Acceptable"; break; case 408: statusLine = "Request Timeout"; break; case 409: statusLine = "Conflict"; break; case 410: statusLine = "Gone"; break; case 411: statusLine = "Length Required"; break; case 413: statusLine = "Payload Too Large"; break; case 414: statusLine = "URI Too Long"; break; case 415: statusLine = "Unsupported Media Type"; break; case 417: statusLine = "Expectation Failed"; break; case 426: statusLine = "Upgrade Required"; break; case 500: statusLine = "Internal Server Error"; break; case 501: statusLine = "Not Implemented"; break; case 502: statusLine = "Bad Gateway"; break; case 503: statusLine = "Service Unavailable"; break; case 504: statusLine = "Gateway Timeout"; break; case 505: statusLine = "HTTP Version Not Supported"; break; default: statusLine = "Unknown"; } return statusLine; }
C
/* * A D D _ P T R * * Demonstrate declaration and use of pointers. */ #include <stdio.h> int main(void) { int number1, number2, sum; /* declare variable names */ int *np1, *np2, *sp; /* declare pointers */ /* * Load pointers with addresses of the declared variables. */ np1 = &number1; np2 = &number2; sp = &sum; /* * Put values into memory locations pointed to by the pointers. */ *np1 = 5; *np2 = 7; *sp = *np1 + *np2; /* * Print out the addresses of the variables and their contents. */ printf("\nName\tAddress\tValue\n"); printf("----\t-------\t-----\n"); printf("%s\t%u\t%d\n", "number1", &number1, *np1); printf("%s\t%u\t%d\n", "number2", &number2, *np2); printf("%s\t%u\t%d\n", "sum", &sum, *sp); printf("%s\t%u\t%d\n", "*np1", &np1, np1); printf("%s\t%u\t%d\n", "*np2", &np2, np2); printf("%s\t%u\t%d\n", "*sp", &sp, sp); return 0; /* * Incidentally, the printf() statements show how to display the address * of a variable. They use the %u format specifier, which represents the * associated value as an unsigned integer. Note, however, that this * technique for displaying the address of a variable is valid only on a * 16-bit machine, such as an IBM PC. It failes in subtle ways on machines * with a different native word size. Also, the address is not an absolute * address; rather, it is an offset into the current data segment. An * explanation of "segmented architecture" lies outside the scope of this * book. -- from page 179. * * My results from this program were: * * Name Address Value * ---- ------- ----- * number1 6422092 5 * number2 6422088 7 * sum 6422084 12 * *np1 6422072 6422092 * *np2 6422064 6422088 * *sp 6422056 6422084 */ }
C
// // Created by zf on 2018/4/28. // 数组栈问题 数组大小固定 满了就无法压栈 ,出栈也不会释放空间 // 可以用realloc 重新分配空间但是麻烦 // realloc函数用于修改一个原先已经分配的内存块的大小, // 可以使一块内存的扩大或缩小。当起始空间的地址为空,即*ptr = NULL,则同malloc #ifndef C1_ARRAYSTACK_H #define C1_ARRAYSTACK_H #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdbool.h> #define MAX_SIZE 5 typedef struct arrStack{ int top; int arr[MAX_SIZE]; }*ArrSTACK; void create_arr_stack(ArrSTACK stack);/*创建数组栈*/ bool full_arr_stack(ArrSTACK stack);/*数组栈是否满*/ void push_arr_stack(ArrSTACK stack, int val); void pop_arr_stack(ArrSTACK stack, int *val); void traverse_arr_stack(ArrSTACK stack);/*遍历栈*/ #endif //C1_ARRAYSTACK_H
C
#include "max6675.h" #include "spi.h" /** * @brief max66675ģʼ * @param None * @retval None */ void max6675_init(void) { GPIO_InitTypeDef GPIO_InitStructure; RCC_APB2PeriphClockCmd(MAX6675_CS1_CLK, ENABLE); //PORTAʱʹ GPIO_InitStructure.GPIO_Pin = MAX6675_CS1_PIN; // PA4 T_CS GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP; // GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(MAX6675_CS1_PORT, &GPIO_InitStructure); GPIO_SetBits(MAX6675_CS1_PORT,MAX6675_CS1_PIN); // T_CS=1 spi1_init(); } /** * @brief max6675ģдһֽڵ * @param txDataҪ͵ * @retval յ */ uint8_t max6675_readWriteByte(uint8_t txData) { return spi1_readWriteByte(txData); } /** * @brief max6675ģȡõԭʼ * @param None * @retval ¶ȵԭʼ */ uint16_t max6675_readRawValue(void) { uint16_t tmp; GPIO_ResetBits(MAX6675_CS1_PORT,MAX6675_CS1_PIN); //enable max6675 tmp = max6675_readWriteByte(0XFF); //read MSB tmp <<= 8; tmp |= max6675_readWriteByte(0XFF); //read LSB GPIO_SetBits(MAX6675_CS1_PORT,MAX6675_CS1_PIN); //disable max6675 if (tmp & 4) { // thermocouple open tmp = 2000; //δ⵽ȵż } else { tmp = tmp >> 3; } return tmp; } /** * @brief max6675ģȡõԭʼ * @param None * @retval ¶ֵλ棩 */ float max6675_readTemperature(void) { return (max6675_readRawValue() * 1024.0 / 4096); }
C
#include <stdio.h> #include <stdlib.h> #define N 1000001 void selectionSort(char *); int main(){ char ch; char * vetor = (char *)malloc(sizeof(char)*N); int i = 0; while(scanf("%s", vetor) != EOF){ selectionSort(vetor); printf("%s\n", vetor); } return 0; } void selectionSort(char * vetor){ int i, j; int menor; char aux; for(i = 0; vetor[i] != '\0'; i++){ menor = i; for(j = i; vetor[j] != '\0'; j++){ if(vetor[j] < vetor[menor]){ menor = j; } } aux = vetor[i]; vetor[i] = vetor[menor]; vetor[menor] = aux; } }
C
//2. Upper Triangular Matrix #include <stdio.h> int main() { float a[3][3]; int i,j,k; for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%f",&a[i][j]); }} for(i=1;i<3;i++) { for(j=0;j<3;j++) { float pivot = - (a[i][j] / a[j][i]); for(k=0;k<3;k++) { a[i][k] = a[i][k] + (a[j][k] * pivot); } }} for(i=0;i<3;i++) { printf("\n"); for (j = 0;j<3;j++) printf("%f",a[i][j]); } printf("\n %f ",a[0][0] * a[1][1] * a[2][2]); return 0; }
C
/** * @file queue.c * @author Aviad Dudkevich * * @brief Implementation of a queue data structure. */ #include "queue.h" #include <string.h> #include <stdio.h> #include <assert.h> /** * @brief Initiate an queue. * @param elementSize - the size of the data in all the nodes. * @return a pinter to the queue. */ Queue* queueAlloc(size_t elementSize) { Queue* queue = (Queue*)malloc(sizeof(Queue)); if (queue == NULL) { return NULL; } queue->_head = NULL; queue->_tail = NULL; queue->_elementSize = elementSize; return queue; } /** * @brief free all memory the stack used. * @param queue - a pointer to pointer of the queue. */ void freeQueue(Queue** queue) { QueueNode* p1; QueueNode* p2; if (*queue != NULL) { p1= (*queue)->_head; while(p1) { p2= p1; p1= p1->_next; free(p2->_data); free(p2); } free(*queue); *queue = NULL; } } /** * @brief put new data un queue. * @param queue - a pointer to the queue. * @param data - a pointer to the data. * @param dataTypeFlag - an integer to represent the data type. */ void enqueue(Queue* queue, void *data, int dataTypeFlag) { //you should check allocation success QueueNode* node = (QueueNode*)malloc(sizeof(QueueNode)); if (node == NULL) { fprintf(stderr, "Memory error - enqueue filed.\n"); return; } node->_data = malloc(queue->_elementSize); if (node->_data == NULL) { fprintf(stderr, "Memory error - enqueue filed.\n"); return; } node->_dataTypeFlag = dataTypeFlag; memcpy(node->_data, data, queue->_elementSize); node->_next = NULL; if (queue->_head == NULL) { queue->_head = node; } else { queue->_tail->_next = node; } queue->_tail = node; } /** * @brief pop the data from the end of the queue. * @param queue - a pointer to the queue. * @param headData - - a pointer to save the data on. * @return integer represent the data type. */ int dequeue(Queue* queue, void *headData) { if(queue->_head == NULL) { fprintf(stderr, "The queue is empty\n"); return 0; } QueueNode *node = queue->_head; int dataFlagType = node->_dataTypeFlag; memcpy(headData, node->_data, queue->_elementSize); queue->_head = node->_next; free(node->_data); free(node); return dataFlagType; } /** * @brief check if stack is empty. * @param queue - a pointer to the queue. * @return true or false. */ int isEmptyQueue(Queue* queue) { return queue->_head == NULL; }
C
#include <stdlib.h> #include <time.h> #include <stdio.h> #include <unistd.h> #include "util.h" void Error(const char * error) { perror(error); exit(EXIT_FAILURE); } // Función de utilidad, para generar los tiempos usados por los aviones // Devuelve un número aleatorio comprendido entre min y max double randRange(double min, double max) { return min + (rand() / (double) RAND_MAX * (max - min + 1)); } // Función de utilidad para depuración. Emite por pantalla el mensaje // que se le pasa como parámetro, pero pone delante del mensaje un // timestamp, para poder ordenar la salida por si saliera desordenada // // Ejemplo de uso: // // log_debug("Avion en vuelo") // // Más ejemplos en el programa principal. void log_debug(char *msg){ struct timespec t; clock_gettime(_POSIX_MONOTONIC_CLOCK, &t); printf("[%ld.%09ld] %s", t.tv_sec, t.tv_nsec, msg); } // Función de utilidad para mostrar el array estado_pistas // precedido de un mensaje que recibe como parámetro. // // Ejemplo de uso: // // mostrar_estado_pistas("Antes de reservar pista", estado_pistas, MAX_PISTAS) // ... // mostrar_estado_pistas("Despues de reservar pista", estado_pistas, MAX_PISTAS) // void mostrar_estado_pistas(char * msg, int *estado_pistas, int num_pistas) { char buff[200]; sprintf(buff, "%s -> ESTADO PISTAS: [ ", msg); flockfile(stdout); log_debug(buff); for (int i=0; i<num_pistas;i++) { printf("%d ", estado_pistas[i]); } printf("]\n"); funlockfile(stdout); }
C
#pragma once #include "HashTable.h" #include <string.h> typedef struct SpellingSuggestion SpellingSuggestion; struct SpellingSuggestion { char* originalWord; LinkedList * suggestions; SpellingSuggestion* next; }; int wordSpellingChecker(HashTable* dictionaryTable); int isWordInDictionary(HashTable* dictionaryTable, char* word); LinkedList* addSpaceCheck(HashTable* dictionaryTable, char* word); LinkedList* replaceCharacterCheck(HashTable* dictionaryTable, char* word); LinkedList* deleteCharacterCheck(HashTable* dictionaryTable, char* word); LinkedList* addCharacterCheck(HashTable* dictionaryTable, char* word); LinkedList* switchAdjacentCharacterCheck(HashTable* dictionaryTable, char* word); LinkedList* getWordSuggestions(HashTable* dictionaryTable, char* word); int isWordInDictionary(HashTable* dictionaryTable, char* word) { if (word == NULL || search(dictionaryTable, word) == 0) return 0; else return 1; } LinkedList* addSpaceCheck(HashTable* dictionaryTable, char* word) { char checkword1[20]; char wordtemp2[20]; LinkedList* OfferList1 = /*(LinkedList*)*/malloc(sizeof(LinkedList)); OfferList1 = NULL; for (int i = 1; i < strlen(word); i++) { strcpy(checkword1, word); checkword1[i] = '\0'; if (isWordInDictionary(dictionaryTable, checkword1) == 1 ) { int startcopy = i; for (int j = 0; j < strlen(wordtemp2); j++)//copy the rest string to wordtemp2 { wordtemp2[j] = word[startcopy]; startcopy++; } if (isWordInDictionary(dictionaryTable, wordtemp2) == 1) {//search if the secnd word also appering the dict checkword1[i] = ' ';//plant sapce + end of string checkword1[++i] = '\0'; strcat(checkword1, wordtemp2); char* offerword1 = (char*)malloc(20 * sizeof(char));//add to the linklist a one string of the 2 words strcpy(offerword1, checkword1); OfferList1 = addToStart(OfferList1, offerword1); } } } return OfferList1; } char* strplace(char* word1,int location) { char wordtemp[20]; for (int i = 0; i < strlen(wordtemp); i++) { wordtemp[i] = word1[location]; } return wordtemp; } //check 2 LinkedList* replaceCharacterCheck(HashTable* dictionaryTable, char* word) { char checkword[20]; LinkedList* OfferList=/*(LinkedList*)*/malloc(sizeof(LinkedList)); OfferList = NULL; for (int i = 0; i < strlen(word); i++) { strcpy(checkword, word); for (int j = 'a'; j <= 'z'; j++) { checkword[i] = j; if (isWordInDictionary(dictionaryTable, checkword) == 1 && strcmp(checkword,word)!=0) { char* offerword = (char*)malloc(20 * sizeof(char)); strcpy(offerword, checkword); OfferList = addToStart(OfferList, offerword); } } } return OfferList; } void removeChar(char* s, char c) { int j, n = strlen(s); for (int i = j = 0; i < n; i++) if (s[i] != c) s[j++] = s[i]; s[j] = '\0'; } //check 3 LinkedList* deleteCharacterCheck(HashTable* dictionaryTable, char* word) { char checkword3[20]; LinkedList* OfferList3 = malloc(sizeof(LinkedList)); OfferList3 = NULL; for (int i = 0; i < strlen(word); i++) { /*int delocation = i + '0';*/ strcpy(checkword3, word); checkword3[i] = '3'; removeChar(checkword3, '3'); if (isWordInDictionary(dictionaryTable, checkword3) == 1 && strcmp(checkword3, word) != 0) { char* Offerword3 = (char*)malloc(20*sizeof(char)); strcpy(Offerword3, checkword3); OfferList3 = addToStart(OfferList3, Offerword3); } } return OfferList3; } char* CombainStr(char* str1, char label, char* str3) { char buffer[20]; char* temp; int len1 = strlen(str1); int len2 = strlen(str3); strcpy(buffer, str1); int k = len1 - 1; buffer[++k] = label; for (int i = 0; i < len2; i++) buffer[++k] = str3[i]; buffer[++k] = '\0'; temp = buffer; return temp; } LinkedList* addCharacterCheck(HashTable* dictionaryTable, char* word) { char checkword1[20]; char checkword2[20]; char temp[20]; LinkedList* OfferList = (LinkedList*)malloc(sizeof(LinkedList)); OfferList = NULL; for (int i = 0; i < strlen(word); i++) { int y = 0; for (int j = 0; j <= i; j++, y++) { checkword1[y] = word[j]; checkword1[y + 1] = '\0'; } for (int j = i + 1, index = 0; j <= strlen(word); j++) { checkword2[index] = word[j]; index++; } for (int j = 'a'; j <= 'z'; j++) { strcpy(temp, CombainStr(checkword1, j, checkword2)); if (isWordInDictionary(dictionaryTable, temp) == 1) { char* offerword = (char*)malloc(20 * sizeof(char)); strcpy(offerword, temp); OfferList = addToStart(OfferList, offerword); } } } return OfferList; } //check5 LinkedList* switchAdjacentCharacterCheck(HashTable* dictionaryTable, char* word) { char checkword5[20]; LinkedList* OfferList5 = /*(LinkedList*)*/malloc(sizeof(LinkedList)); OfferList5 = NULL; for (int i = 0; i < (strlen(word)-1); i++) { int j = i + 1; strcpy(checkword5, word); char first, secend; first = checkword5[i]; secend = checkword5[j]; checkword5[i] = secend;//swap checkword5[j] = first; if (isWordInDictionary(dictionaryTable, checkword5) == 1 && strcmp(checkword5, word) != 0) { char* offerword5 = (char*)malloc(20 * sizeof(char)); strcpy(offerword5, checkword5); OfferList5 = addToStart(OfferList5, offerword5); } } return OfferList5; } LinkedList* TailList(LinkedList* head) { if (head == NULL) return head; while (head->next != NULL) { head = head->next; } return head; } LinkedList* getWordSuggestions(HashTable* dictionaryTable, char* word) { LinkedList* SuggestionList = malloc(sizeof(LinkedList)); LinkedList* AdditionList; if (word == "" || word == NULL) { return SuggestionList; } SuggestionList = NULL; SuggestionList = addSpaceCheck(dictionaryTable, word); AdditionList = replaceCharacterCheck(dictionaryTable, word); SuggestionList= SortedMerge(SuggestionList,AdditionList ); //3 SuggestionList = SortedMerge(SuggestionList, deleteCharacterCheck(dictionaryTable, word)); //4 SuggestionList = SortedMerge(SuggestionList, addCharacterCheck(dictionaryTable, word)); //5 SuggestionList= SortedMerge(SuggestionList, switchAdjacentCharacterCheck(dictionaryTable, word)); LinkedList* dupList = SuggestionList; LinkedList* memoryDelList = NULL; int erase = 0; //loop to run on all the list to find any duplicate word while (dupList != NULL) { if (Search_index_in_list(dupList->next, dupList->data) > 0) { char* dupword = dupList->data; memoryDelList = addToStart(memoryDelList, dupword); erase = 1;//flag to mark delete neccery } dupList = dupList->next; } if (erase == 1) {//delete of list of words in memoery delete words while (memoryDelList!=NULL) { char* Wordel = memoryDelList->data; SuggestionList = DeleteElement(SuggestionList, Wordel); memoryDelList = memoryDelList->next; } } return SuggestionList; }
C
#include <stdio.h> #define MAX_NUM 100000 #define MIN_VAL -1000 int max(int a, int b); int maxCSum(int *arr, int n); int main() { int arr[MAX_NUM]; int N; scanf("%d", &N); for (int i = 0; i < N; i++) scanf("%d", &arr[i]); printf("%d\n", maxCSum(arr, N)); return 0; } int max(int a, int b) { return a > b ? a : b; } int maxCSum(int *arr, int n) { int dp[MAX_NUM + 1]; int ans = MIN_VAL; dp[0] = 0; for (int i = 1; i <= n; i++) dp[i] = max(arr[i - 1], arr[i - 1] + dp[i - 1]); for(int i = 1; i <= n; i++) ans = max(dp[i], ans); return ans; }
C
#include <stdio.h> int main() { int i, j; int x, y; scanf("%d %d", &x, &y); i=1; while(i <= y){ for(j=0;j<x;j++){ printf("%d",i); i++; if(j != x-1) printf(" "); } printf("\n"); } return 0; }
C
/*============================================================================= * Author: Marcos Dominguez <[email protected]> * Date: 2021/10/08 * Version: 0.0.1 *===========================================================================*/ /*=====[Inclusions of function dependencies]=================================*/ #include "app.h" #include <stdlib.h> #include "sapi.h" #include "../inc/port.h" #include "../inc/button.h" /*=====[Definition macros of private constants]==============================*/ #define MAX_TEMP_D_CELSIUS 500 #define TEMP_2_D_CELSIUS 20 #define TEMP_1_D_CELSIUS 10 #define TIME_TO_WAIT_FOR_CONV_IN_MS 1000 /*=====[Definition of private functions]==============================*/ /** * @brief Initialize the ADC configuration for this custom application * */ static void ADS1115_Init(void); /** * @brief Convert the raw data from the ADC to a temperature in Celsius * * @param counts The raw data from the ADC * @return uint16_t The temperature in Celsius */ static uint16_t ConutsToTemp(uint16_t counts); /** * @brief Convert temperature in Celsius to a raw data for the ADC * * @param temp Temperature in Celsius * @return uint16_t The raw data for the ADC */ static uint16_t TempToCounts(uint16_t temp); /** * @brief Set the New Set Treshold value * * @param new_setpoint The new setpoint value in Celsius */ static void SetNewSetTreshold(uint16_t new_setpoint); /*=====[Definitions of extern global variables]==============================*/ /*=====[Definitions of public global variables]==============================*/ /*=====[Definitions of private global variables]=============================*/ static ads111x_obj_t ads1115_0; //!< instance of ADS1115 static uint16_t temperature_setpoint = 240; //!< The default temperature setpoint in deci Celsius /*=====[Main function, program entry point after power on or reset]==========*/ int main(void) { boardInit(); FSMButtonInit(TEC1); //!< Initialize the button to decrease the setpoint FSMButtonInit(TEC2); //!< Initialize the button to increase the setpoint FSMButtonInit(TEC3); //!< Initialize the button to increase the setpoint FSMButtonInit(TEC4); //!< Initialize the button to increase the setpoint ADS1115_Init(); //!< Initialize the ADC delay_t wait_time; //!< Variable to wait for the conversion delayConfig(&wait_time, TIME_TO_WAIT_FOR_CONV_IN_MS); //!< Configure the delay uint16_t curret_temp; //!< Variable to store the current temperature while(TRUE) { if(delayRead(&wait_time)) { ADS111x_StartConversion(&ads1115_0); //!< Start the conversion } if(CheckFallState(TEC1)) { //Decrease temperature setpoint temperature_setpoint -= TEMP_1_D_CELSIUS; if(temperature_setpoint < 0) { temperature_setpoint = 0; } SetNewSetTreshold(temperature_setpoint); char str[40]; sprintf( str, "SetPoint: %i.\r\n", temperature_setpoint ); uartWriteString(UART_USB, str); sprintf( str, "Temperature: %i.\r\n", curret_temp ); uartWriteString(UART_USB, str); } if(CheckFallState(TEC2)) { //Increase temperature setpoint temperature_setpoint += TEMP_1_D_CELSIUS; if(temperature_setpoint > MAX_TEMP_D_CELSIUS) { temperature_setpoint = MAX_TEMP_D_CELSIUS; } SetNewSetTreshold(temperature_setpoint); char str[40]; sprintf( str, "SetPoint: %i.\r\n", temperature_setpoint ); uartWriteString(UART_USB, str); sprintf( str, "Temperature: %i.\r\n", curret_temp ); uartWriteString(UART_USB, str); } if(CheckFallState(TEC3)) { //Send the temperature to the UART /* routine to send the temperature by UART */ char str[40]; sprintf( str, "SetPoint: %i.\r\n", temperature_setpoint ); uartWriteString(UART_USB, str); } if(CheckFallState(TEC4)) { //Send the temperature to the UART /* routine to send the temperature by UART */ char str[40]; sprintf( str, "Temperature: %i.\r\n", curret_temp ); uartWriteString(UART_USB, str); } curret_temp = ConutsToTemp(ADS111x_Read(&ads1115_0)); if( curret_temp > temperature_setpoint + TEMP_2_D_CELSIUS) { //!< temperature is too high gpioWrite(LED2, ON); //!< Turn on the LED tha indicates that the temperature is too high } else { //!< temperature is not higher than setpoint gpioWrite(LED2, OFF); //!< Turn off the LED tha indicates that the temperature is too high } if(curret_temp < temperature_setpoint - TEMP_2_D_CELSIUS) { //!< temperature is lower than the setpoint gpioWrite(LED3, ON); //!< Turn on the LED tha indicates that the temperature is ok } else { //!< temperature is not lower than setpoint gpioWrite(LED3, OFF); //!< Turn off the LED tha indicates that the temperature is ok } if(!gpioRead(GPIO1)) { //!< alarm pin is set gpioWrite(LED1, ON); //!< turn on the cooling system } else { //!< alarm pin is not set gpioWrite(LED1, OFF); //!< turn off the cooling system } } return 0; } static void ADS1115_Init(void) { ads111x_i2c_t ads111x_port = PORT_Init(); ADS111x_Init(&ads1115_0, ADS111X_ADDR_0, ADS111X_PGA_4096, ADS1115, &ads111x_port); //!< Initialize the ADS1115 with address 0x48, PGA = 4096, and the ADS1115 as the device ADS111x_SetDataRate(&ads1115_0, ADS111X_DATA_RATE_16SPS); //!< Set the data rate to 16 samples per second ADS111x_SetMultiplexer(&ads1115_0, ADS111X_MUX_AN0_GND); //!< Select the Analog input to be AN0 ADS111x_SetMode(&ads1115_0, ADS111X_MODE_SINGLE); //!< Set the mode to single shot ADS111x_SetComparatorQueue(&ads1115_0, ADS111X_COMP_QUE_2_CONV); //!< Set the comparator queue to 2 conversions SetNewSetTreshold(temperature_setpoint); //!< Set the initial setpoint ADS111x_StartConversion(&ads1115_0); //!< First conversion } static uint16_t ConutsToTemp(uint16_t counts) { return (counts * MAX_TEMP_D_CELSIUS) / 0x7FFF; //!< Convert the raw data to a temperature in Celsius } static uint16_t TempToCounts(uint16_t temp) { return (temp * 0x7FFF) / MAX_TEMP_D_CELSIUS; //!< Convert the temperature in Celsius to a raw data for the ADC } static void SetNewSetTreshold(uint16_t new_setpoint) { uint16_t thesh_lo = TempToCounts(new_setpoint - TEMP_2_D_CELSIUS); //!< Set the low threshold to 2 degrees below the setpoint uint16_t thesh_hi = TempToCounts(new_setpoint + TEMP_2_D_CELSIUS) ; //!< Set the high threshold to 2 degrees above the setpoints ADS111x_SetThresholdLow(&ads1115_0, thesh_lo); ADS111x_SetThresholdHigh(&ads1115_0, thesh_hi); }
C
#include <stdio.h> int main(void) { int i, j, temp; int arr[10] = { 1,10,5,8,7,6,4,3,2,9 }; for (i = 0; i < 9; i++) { j = i; // ش Ұ Һ ũٸ, ٲش. , ε ҽѰ Ѵ. // Ǿ ִٸ while ʱ ĵ ȿ̴. while (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; j--; } } //־ ( ϳ Ǿ ) ð ⵵ O(N^2) ȴ. //δ >> ӵ ش. for (i = 0; i < 10; i++) printf("%d ", arr[i]); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> int32_t main(void) { int32_t *ptr = (int32_t *)calloc(10,sizeof(int32_t)); // int32_t *ptr = (int32_t *)aligned_alloc(sizeof(int32_t),10*sizeof(int32_t)); if (NULL == ptr){ perror("perror calloc()"); return -1; } ptr[0] = 1; // Dummy free(ptr); ptr=NULL; // Set NULL after free() /* Check the behavior of double free. */ free(ptr); ptr=NULL; // Set NULL after free() (void)printf("Done\n"); return 0; }
C
/* ** my_isnum.c for asm-corewar in /home/emad_n//ASM-Corewar/src/lib ** ** Made by navid emad ** Login <[email protected]> ** ** Started on Sun Feb 24 01:40:46 2013 navid emad ** Last update Sun Feb 24 16:58:59 2013 navid emad */ int my_isnum(char ch) { return ((ch >= '0' && ch <= '9') ? 1 : 0); } int my_isnum_str(char *str) { int i; i = (str[0] == '-'); while (str[i] != '\0') { if ('0' > str[i] || str[i] > '9') return (0); i += 1; } return (1); }
C
#include<stdio.h> int main() { int money1,money2; printf("Enter money gave to saurav = "); scanf("%d",&money1); printf("Enter money gave to sajal = "); scanf("%d",&money2); money1 += money2; money2 = money1 - money2; money1 -= money2; printf("Money on saurav = %d\nMoney on sajal = %d",money1,money2); return 0; }
C
#ifndef ARITHTYPE // define this to a number between 0 and 4 #define ARITHTYPE 4 #endif #if ARITHTYPE == 0 typedef signed char mysint; typedef unsigned char myuint; #elif ARITHTYPE == 1 typedef short mysint; typedef unsigned short myuint; #elif ARITHTYPE == 2 typedef int mysint; typedef unsigned int myuint; #elif ARITHTYPE == 3 typedef long mysint; typedef unsigned long myuint; #elif ARITHTYPE == 4 typedef long long mysint; typedef unsigned long long myuint; #else #error "Unknown ARITHTYPE" #endif /** Return the value of @x + @y using saturating unsigned addition. */ myuint sat_unsigned_add(myuint x, myuint y); /** Return the value of @x - @y using saturating unsigned subtraction. */ myuint sat_unsigned_sub(myuint x, myuint y); /** Return the value of @x + @y using saturating signed addition. */ mysint sat_signed_add(mysint x, mysint y); /** Return the value of @x - @y using saturating signed subtraction. */ mysint sat_signed_sub(mysint x, mysint y);
C
/* * Author: Sword Lord of The Lonely Peak * Date: 2020/05/18 * Program Name: Linked List Practice! */ /**************************************************************************************************************************************/ #include<stdlib.h> #include<stdio.h> typedef struct Node { int data; struct Node* next; }Node; struct Node* head; // Deleting a node at nth position void deleteNode(int position) { int i = 0; struct Node* temp1 = head; if(position==1) { head = temp1->next; //head now points to second node. free(temp1); return; } for(i = 0; i<(position-2); i++) { temp1 = temp1->next; } //temp1 points to (n-1)th node. struct Node* temp2 = temp1->next; //nth node temp1->next = temp2->next; free(temp2); } //Reverses the order of the node, such that: //15 10 40 45 becomes 45 40 10 15 Node* reverseNode() { struct Node* next; struct Node* prev = NULL; struct Node* current = head; while(current!=NULL) { next = current->next; current->next = prev; //*(current).next = prev; prev = current; current = next; } head = prev; return head; } void print() { struct Node* temp = head; while (temp != NULL){ printf ("%d -> ", temp->data); temp = temp->next; } printf("NULL\n"); } void printReverse() { struct Node* temp = head; while (temp != NULL){ printf ("%d <- ", temp->data); temp = temp->next; } printf("NULL\n"); } //Insert node at nth position in list. void insert (int data, int position) { struct Node* newNode = malloc(sizeof(struct Node)); newNode->data = data; newNode->next = NULL; if (position == 1) { newNode->next = head; head = newNode; return; } struct Node* previousNode = head; for (int i = 0; i < position - 2; i++) { previousNode = previousNode->next; } newNode->next = previousNode->next; previousNode->next = newNode; } //Creates the nodes for the list. Node*_getnode(int data) { struct Node* newNode = malloc(sizeof(struct Node*)); newNode -> data = data; newNode -> next = NULL; return newNode; } //Finds the length of the nodes (ie. the number of nodes in the list). int length() { int num = 0; struct Node* temp = head; while(temp != NULL) { num++; temp = temp->next; } printf("Number of nodes: %d\n", num); return num; } int main () { int position = 0; head = NULL; head = _getnode(3); head -> next = _getnode(5); head -> next -> next = _getnode(6); head -> next -> next -> next = _getnode(7); head -> next -> next -> next -> next = _getnode(10); head -> next -> next -> next -> next -> next = _getnode(15); insert(2,4); int count = length(); print(); printf("Enter a position to delete: "); scanf("%d", &position); if(position > count || count == 0) { printf("ERROR! Position not found!\n"); exit(0); } else { deleteNode(position); print(); head = reverseNode(); printf("Reversed order of the Linked List: \n"); printReverse(); count = length(); } } /**************************************************************************************************************************************/ #include <stdio.h> #include <stdlib.h> typedef struct myList { int info; struct myList *link; }Node; Node *_getnode(); int main() { Node *a = _getnode(); // First node Node *b = _getnode(); // Second node Node *c = _getnode(); // Third node a -> link = NULL; b -> link = NULL; c -> link = NULL; printf("a data = ?"); scanf("%d", &a->info); printf("b data = ?"); scanf("%d", &b->info); printf("c data = ?"); scanf("%d", &c->info); a -> link = b; // placing address of node b into link of node a (so that they become linked!). b -> link = c; while(a != NULL) { printf("%d -> ", a -> info); a = a -> link; } printf("NULL\n"); return 0; } Node *_getnode() { return((Node *)malloc(sizeof(Node))); } /**************************************************************************************************************************************/ #include <stdio.h> #include <stdlib.h> typedef struct myList { int info; struct myList *link; }Node; Node *_getnode(); int main() { Node *a = _getnode(); Node *t = a; a -> link = NULL; //First Node a -> link = _getnode(); //Second Node a -> link -> link = _getnode(); // Third node a -> link -> link -> link= NULL; // Fourth node printf("a data = ?"); scanf("%d", &a -> info); printf("b data = ?"); scanf("%d", &a -> link -> info); printf("c data = ?"); scanf("%d", &a -> link -> link -> info); //Prints the values of the linked list! while(a != NULL) { printf("%d -> ", a -> info); a = a -> link; } printf("NULL\n"); a = t; //Make sure to this before reprinting the linked list to make that a points at the first node and not the last node. while(a != NULL) { printf("%d -> ", a -> info); a = a -> link; } printf("NULL\n"); return 0; } Node *_getnode() { return((Node *)malloc(sizeof(Node))); } /**************************************************************************************************************************************/ #include <stdio.h> #include <stdlib.h> typedef struct myList { int info; struct myList *link; }Node; Node *_getnode(); int main() { Node *s = _getnode(); s -> link = NULL; Node *t = s; char c; int true = 1; while(true) //Creates x many nodes (user decides the amount). { printf("Please enter the data for s info : "); scanf("%d", &s -> info); printf("To add more node press Y else N : "); scanf(" %c", &c); if(c == 'n' || c == 'N') { s -> link = NULL; break; } s -> link = _getnode(); // create next node. s = s -> link; // make s equal to the next node. } s = t; //print the values of the linked list. while(s != NULL) { printf("%d -> ", s->info); s = s->link; } printf("NULL\n"); } Node *_getnode() { return((Node *)malloc(sizeof(Node))); //allocate memory for the node. } /**************************************************************************************************************************************/
C
#include <stdio.h> /* *This programe is demonstrated bell and so on */ int main ( void ) { printf("Hello world!\r"); // Herizontal tab printf("水平制表符\t"); printf("after herizontal tab\n"); printf("\a"); //vertical tab printf("垂直制表符\v"); printf("vertical tab\n"); /* *The text output:(where is the "Hello World!"?) * *水平制表符d! after herizontal tab *垂直制表符 * vertical tab */ return 0; }
C
/* hundscvt.f -- translated by f2c (version 19970219). */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "calpgm.h" int main(argc, argv) int argc; char *argv[]; { #define NFNAM 36 static int icv[4] = {1,2,4,0}; static char infil[NFNAM], outfil[NFNAM], work[82], fmt[5]; FILE *luin, *luout; char *finp, *fout, *pstr; int iqfmt, iq, nqn, ipj, i, k, wasb; char omega; if (argc >= 2){ finp = argv[1]; }else{ finp = infil; puts("ENTER CATALOG INPUT FILE NAME"); fgetstr(finp, NFNAM, stdin); } if (argc >= 3){ fout = argv[2]; }else{ fout = outfil; puts("ENTER CATALOG OUTPUT FILE NAME"); fgetstr(fout, NFNAM, stdin); } luin = fopen(finp,"r"); if (luin == NULL || fgetstr(work, 82, luin) < 55) { puts("bad input file"); exit (1); } rewind(luin); luout = fopen(fout,"w"); if (luout == NULL) { puts("bad output file"); exit (1); } memcpy(fmt,&work[51],4); fmt[4] = 0; if (fmt[2] == ' ') fmt[2] = 0; iqfmt = atoi(fmt); nqn = iqfmt % 10; iq = iqfmt / 100; ipj = 4; if (fmt[0] == '1'){ --nqn; ipj = 6; } if (nqn < 3) iq = 0; if (iq == 2 || iq == 13){ /* case b to a */ wasb = 1; fmt[1] += 6; fmt[2] -= icv[nqn-3]; }else if (iq == 8 || iq == 19){ /* case a to b */ wasb = 0; fmt[1] -= 6; fmt[2] += icv[nqn-3]; }else{ puts("bad quantum format"); exit(1); } while (fgetstr(work, 82, luin) > 70) { memcpy(&work[51], fmt, 4); for (i = 55; i < 70; i += 12) { /* check both states */ pstr = &work[i]; if (wasb) { if (strncmp(pstr, &pstr[ipj], 2)){ /* Omega = 3/2 */ pstr[0] = pstr[ipj]; pstr[1] = pstr[ipj+1]; omega = '2'; }else{ omega = '1'; } for (k = ipj - 1; k >= 2; --k) pstr[k+2] = pstr[k]; pstr[2] = ' '; pstr[3] = omega; }else{ omega = pstr[3]; for (k = 2; k < ipj; ++k) pstr[k] = pstr[k+2]; pstr[ipj] = pstr[0]; pstr[ipj+1] = pstr[1]; if (omega == '2') { /* N = J - 1/2 */ if (pstr[1] == '0') { if (pstr[0] == 'A') pstr[0] = '9'; else if (pstr[0] == '1') pstr[0] = ' '; else pstr[0] -= 1; pstr[1] = '9'; }else{ pstr[1] -= 1; } } } } fputs(work, luout); fputc('\n',luout); } fclose(luout); fclose(luin); return 0; } /* main */
C
#include <stdio.h> #include <stdlib.h> int encaixa(int a, int b){ int cont = 0; int auxA = a, auxB = b; int casas_dec; while(b!=0){ cont++; b = b/10; } casas_dec = pow(10,cont); if((auxA%casas_dec) == auxB) return 1; else return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_draw_line.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: rkamegne <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/21 14:52:56 by rkamegne #+# #+# */ /* Updated: 2019/01/28 15:55:14 by rkamegne ### ########.fr */ /* */ /* ************************************************************************** */ #include "fdf.h" void mlx_put_pixel_img(char *image_str, int x, int y, int color) { unsigned int pos; pos = (x + (WIDTH - 500) * y) * 4; if (pos <= (WIDTH - 500) * (HEIGHT - 200) * 4) { image_str[pos] = color & 0xFF; image_str[pos + 1] = (color >> 8) & 0xFF; image_str[pos + 2] = (color >> 16) & 0xFF; } } double percent(int start, int end, int current) { double placement; double distance; placement = current - start; distance = end - start; return ((distance == 0) ? 1.0 : (placement / distance)); } void ft_draw_l(char *image_str, t_proj start_pt, t_proj end_pt, t_draw draw) { int i; i = 1; while (i <= draw.dx) { draw.x += draw.xinc; draw.percentage = percent(start_pt.x, end_pt.x, draw.x); draw.color = ft_get_color(start_pt.color, end_pt.color, draw.percentage); draw.cumul += draw.dy; if (draw.cumul >= draw.dx) { draw.cumul -= draw.dx; draw.y += draw.yinc; } if (draw.x < WIDTH - 500 && draw.x > 0) { mlx_put_pixel_img(image_str, draw.x, draw.y, draw.color); } i++; } } void ft_draw_h(char *image_str, t_proj start_pt, t_proj end_pt, t_draw draw) { int i; i = 1; while (i <= draw.dy) { draw.y += draw.yinc; draw.percentage = percent(start_pt.y, end_pt.y, draw.y); draw.color = ft_get_color(start_pt.color, end_pt.color, draw.percentage); draw.cumul += draw.dx; if (draw.cumul >= draw.dy) { draw.cumul -= draw.dy; draw.x += draw.xinc; } if (draw.x < WIDTH - 500 && draw.x > 0) { mlx_put_pixel_img(image_str, draw.x, draw.y, draw.color); } i++; } } void ft_draw_line(char *image_str, t_proj start_pt, t_proj end_pt) { t_draw draw; draw.x = start_pt.x; draw.y = start_pt.y; draw.dy = end_pt.y - start_pt.y; draw.dx = end_pt.x - start_pt.x; draw.xinc = (draw.dx > 0) ? 1 : -1; draw.yinc = (draw.dy > 0) ? 1 : -1; if (draw.dx < 0) draw.dx = -draw.dx; if (draw.dy < 0) draw.dy = -draw.dy; if (draw.dx > draw.dy) { draw.cumul = draw.dx / 2; ft_draw_l(image_str, start_pt, end_pt, draw); } else { draw.cumul = draw.dy / 2; ft_draw_h(image_str, start_pt, end_pt, draw); } }
C
#include<avr/io.h> #include<util/delay.h> #include<compat/deprecated.h> #include<ilcd.h> #define s1_clr bit_is_clear(PIND,0) #define s2_clr bit_is_clear(PIND,1) #define s3_clr bit_is_clear(PIND,2) #define s4_clr bit_is_clear(PIND,3) #define s1_set bit_is_set(PIND,0) #define s2_set bit_is_set(PIND,1) #define s3_set bit_is_set(PIND,2) #define s4_set bit_is_set(PIND,3) #define fwd PORTC=5 #define right PORTC=6 #define left PORTC=9 #define stop PORTC=0 void stgt(int); void rgtturn(); void leftturn(); void zigzag(int,int); void lead(int,int); int x,y,dir,x1,y1; int main() { DDRD=0xF0; DDRC=0b11111111; DDRB=0x0F; int b,l; b=3; l=3; x1=1; y1=1; //zigzag(b-1,l-1); lead(1,2); lead(2,2); lead(3,3); //lead(2,1); //lead(1,1); stop; } void stgt(int a) { int i; for(i=1;i<=a;) { if(s1_clr && s2_clr && s3_clr && s4_clr) { i++; fwd; while(PIND==0); } if(s2_clr && s3_clr && s1_set && s4_set) { fwd; } if(s1_set && s2_set && s3_clr && s4_set) { right; } if(s1_set && s2_clr && s3_set && s4_set) { left; } } PORTC=0; } void rgtturn() { fwd; _delay_ms(1800); right; while(PIND!=7); right; while(PIND!=9); } void leftturn() { fwd; _delay_ms(1800); left; while(PIND!=14); left; while(PIND!=9); } void abtturn() { fwd; _delay_ms(1800); right; while(PIND!=7); right; while(PIND!=9); right; while(PIND!=7); right; while(PIND!=9); } /*void lcd(int a,int b,int c) { lcd_init(); lcd_goto(1,1); lcd_prints("X"); lcd_goto(9,1); lcd_prints("Y"); lcd_goto(13,1); lcd_prints("DIR"); lcd_goto(1,2); lcd_printi(a); lcd_goto(9,2); lcd_printi(b); lcd_goto(14,2); lcd_printi(c); }*/ void lead(int col,int row) { int a,b; a=col-x1; b=row-y1; if(a>0 && b>0) { stgt(b); rgtturn(); dir=2; stgt(a); leftturn(); dir=1; } else if(a<0 && b<0) { a=a*(-1); b=b*(-1); leftturn(); dir=4; stgt(a); leftturn(); dir=3; stgt(b); abtturn(); dir=1; } else if(a<0 && b==0) { a=a*(-1); leftturn(); dir=4; stgt(a); rgtturn(); dir=1; } else if(a<0 && b>0) { a=a*(-1); stgt(b); leftturn(); dir=4; stgt(a); rgtturn(); dir=1; } else if(a==0 && b<0) { b=b*(-1); abtturn(); dir=3; stgt(b); abtturn(); dir=1; } else if(a==0 && b>0) { stgt(b); } else if(a>0 && b<0) { b=b*(-1); rgtturn(); dir=2; stgt(a); leftturn(); dir=3; stgt(b); abtturn(); dir=1; } else if(a>0 && b==0) { rgtturn(); dir=2; stgt(a); leftturn(); dir=1; } x1=col; y1=row; } /*void zigzag(int r,int c) { int i; stgt(r); for(i=1;i<=c;i++) { if(i%2!=0) { rgtturn(); stgt(1); rgtturn(); stgt(r); } if(i%2==0) { leftturn(); stgt(1); leftturn(); stgt(r); } } if(c%2==0) { abtturn(); stgt(r); rgtturn(); stgt(c); rgtturn(); } if(c%2!=0) { rgtturn(); stgt(c); rgtturn(); } }*/
C
#include <msp430.h> #include "main.h" #include "hal_LCD.h" volatile unsigned char * S1buttonDebounce = &BAKMEM2_L; // S1 button debounce flag volatile unsigned char * S2buttonDebounce = &BAKMEM2_H; // S2 button debounce flag void Init_GPIO(void); /** * main.c */ int main(void) { Init_LCD(); Init_GPIO(); clearLCD(); WDTCTL = WDTPW | WDTHOLD; // stop watchdog timer PM5CTL0 &= ~LOCKLPM5; // Disable the GPIO power-on default high-impedance mode // to activate previously configured port settings int batteryStatus = 0; volatile unsigned int i = 0; int blinkCounter = 0; // Print Vorname Nachname 2x int textCounter = 0; // counter variable initialisieren um die while schleife 2x auszuführen while (textCounter < 2) { displayScrollText("ROUVEN BRAZEROL"); textCounter += 1; // counter inkrementieren } // Initialisation of switch 1 P1DIR &= ~BIT2; P1REN = BIT2; P1OUT = BIT2; // Initialisation of switch 2 P2DIR &= ~BIT6; P2REN = BIT6; P2OUT = BIT6; // Set Pins to output direction P1DIR |= BIT0; // Set P1.0 to output direction P4DIR |= BIT1; // Pins auf low setzen P1OUT &= ~BIT0; P4OUT &= ~BIT0; LCDM13 = BIT0; LCDM12 = BIT4; while (1) { P1OUT &= ~BIT0; P4OUT &= ~BIT0; if (!(P1IN & BIT2) && batteryStatus < 7) // request SW 1 { batteryStatus -= 1; P1OUT ^= 0x01; } if (!(P2IN & BIT6) && batteryStatus >= -1) // request SW 2 { batteryStatus += 1; P4OUT ^= BIT0; } switch(batteryStatus) { case -1: blinkCounter = 0; while(blinkCounter < 4) { volatile unsigned int i; // volatile to prevent optimization P1OUT ^= BIT0; // Toggle P1.0 using exclusive-OR i = 50000; // SW Delay do i--; while(i != 0); blinkCounter += 1; } batteryStatus += 1; break; case 0: LCDM13 &= ~BIT1; break; case 1: LCDM13 |= BIT1; LCDM12 &= ~BIT5; break; case 2: LCDM13 |= BIT1; LCDM12 |= BIT5; LCDM13 &= ~BIT2; break; case 3: LCDM13 |= BIT1; LCDM12 |= BIT5; LCDM13 |= BIT2; LCDM12 &= ~BIT6; break; case 4: LCDM13 |= BIT1; LCDM12 |= BIT5; LCDM13 |= BIT2; LCDM12 |= BIT6; LCDM13 &= ~BIT3; break; case 5: LCDM13 |= BIT1; LCDM12 |= BIT5; LCDM13 |= BIT2; LCDM12 |= BIT6; LCDM13 |= BIT3; LCDM12 &= ~ BIT7; break; case 6: LCDM13 |= BIT1; LCDM12 |= BIT5; LCDM13 |= BIT2; LCDM12 |= BIT6; LCDM13 |= BIT3; LCDM12 |= BIT7; break; case 7: LCDM13 |= BIT1; LCDM12 |= BIT5; LCDM13 |= BIT2; LCDM12 |= BIT6; LCDM13 |= BIT3; LCDM12 |= BIT7; blinkCounter = 0; while (blinkCounter < 2) { while(blinkCounter < 4) { volatile unsigned int i; // volatile to prevent optimization P4OUT ^= BIT0; // Toggle P1.0 using exclusive-OR i = 50000; // SW Delay do i--; while(i != 0); blinkCounter += 1; } } batteryStatus -= 1; break; default: LCDM13 &= ~BIT1; break; } i = 15000; // SW Delay do i--; while(i != 0); } // return 0; } void Init_GPIO() { // Set all GPIO pins to output low to prevent floating input and reduce power consumption GPIO_setOutputLowOnPin(GPIO_PORT_P1, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P2, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P3, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P4, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P5, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P6, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P7, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setOutputLowOnPin(GPIO_PORT_P8, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P1, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P2, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P3, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P4, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P5, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P6, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P7, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsOutputPin(GPIO_PORT_P8, GPIO_PIN0|GPIO_PIN1|GPIO_PIN2|GPIO_PIN3|GPIO_PIN4|GPIO_PIN5|GPIO_PIN6|GPIO_PIN7); GPIO_setAsInputPin(GPIO_PORT_P1, GPIO_PIN1); // Configure button S1 (P1.2) interrupt GPIO_selectInterruptEdge(GPIO_PORT_P1, GPIO_PIN2, GPIO_HIGH_TO_LOW_TRANSITION); GPIO_setAsInputPinWithPullUpResistor(GPIO_PORT_P1, GPIO_PIN2); GPIO_clearInterrupt(GPIO_PORT_P1, GPIO_PIN2); GPIO_enableInterrupt(GPIO_PORT_P1, GPIO_PIN2); // Configure button S2 (P2.6) interrupt GPIO_selectInterruptEdge(GPIO_PORT_P2, GPIO_PIN6, GPIO_HIGH_TO_LOW_TRANSITION); GPIO_setAsInputPinWithPullUpResistor(GPIO_PORT_P2, GPIO_PIN6); GPIO_clearInterrupt(GPIO_PORT_P2, GPIO_PIN6); GPIO_enableInterrupt(GPIO_PORT_P2, GPIO_PIN6); // Set P4.1 and P4.2 as Secondary Module Function Input, LFXT. GPIO_setAsPeripheralModuleFunctionInputPin( GPIO_PORT_P4, GPIO_PIN1 + GPIO_PIN2, GPIO_PRIMARY_MODULE_FUNCTION ); // Disable the GPIO power-on default high-impedance mode // to activate previously configured port settings PMM_unlockLPM5(); }
C
// Ҫǵ // һ, Կǵ. һַܴ, ת int ܳ int ıʾΧ int MyAtoi(const char* str) { int flag = 1; // int ret = 0; // ս if (str == NULL || *str == '\0') { return 0; } // 1. հַ(ո, , س, Ʊ, ֱƱ, ҳ...) while (isspace(*str)) { str++; } // 2. + - ŵ if (*str == '-') { flag = -1; str++; } if (*str == '+') { str++; } // 3. ַ while (*str != '\0') { if (isdigit(*str)) { // ַתֵĺIJ ret = ret * 10 + (*str - '0'); } else { return ret; } str++; } return ret * flag; }
C
#include<stdio.h> int main(void) { int input, on, sn; on = sn = 0; float s_sum, s_ave, o_sum, o_ave; printf("Please enter some numbers:\n"); scanf("%d", &input); while (input != 0) { if ((input % 2)) { sn++; s_sum += input; } else { on++; o_sum += input; } scanf("%d", &input); } s_ave = s_sum / sn; o_ave = o_sum / sn; printf("the on is %d.\n", on); printf("the sn is %d.\n", sn); printf("And the ave of the sn is %f.\n", s_ave); printf("And the ave of the on is %f", o_ave); return 0; }
C
void puth(unsigned int i); void puts(const char *a); void dac_init(void) { // no buffers required since we have an opamp //DAC->CR = DAC_CR_EN1 | DAC_CR_BOFF1 | DAC_CR_EN2 | DAC_CR_BOFF2; DAC->DHR12R1 = 0; DAC->DHR12R2 = 0; DAC->CR = DAC_CR_EN1 | DAC_CR_EN2; } void dac_set(int channel, uint32_t value) { if (channel == 0) { DAC->DHR12R1 = value; } else if (channel == 1) { DAC->DHR12R2 = value; } else { puts("Failed to set DAC: invalid channel value: "); puth(value); puts("\n"); } }
C
#include <stdio.h> int main() { int l, r ; while ( scanf("%d%d", &l, &r) , !(l == 0 && r == 0)) printf("%d\n", l + r); return 0; }
C
/* Víctor Manuel Cavero Gracia - DNI: 45355080T Iván Fernández Sánchez - DNI: 52902115E */ #include <stdlib.h> #include <stdio.h> #include <string.h> int my_system(int args, char* argc[]) { for(int i = 1; i < args; i++) { printf("Ejecutando comando: %s\n", argc[i]); system(argc[i]); printf("\n"); } return 0; } int main(int argc, char* argv[]) { if (argc < 2){ fprintf(stderr, "Usage: %s <command>\n", argv[0]); exit(1); } return my_system(argc, argv); }
C
/* a program that tests whether two words are anagrams */ #include <stdio.h> #include <ctype.h> #define TRUE 1 #define FALSE 0 /* 26 indexes are corresponding to 26 letters of the alphabet. */ void read_word(int counts[26]); int equal_array(int counts1[26], int counts2[26]); int main(void) { int first_alphabet_counter[26], second_alphabet_counter[26]; printf("Enter first word: "); read_word(first_alphabet_counter); printf("Enter second word: "); read_word(second_alphabet_counter); if (equal_array(first_alphabet_counter, second_alphabet_counter)) printf("they are anagrams.\n"); else printf("they are not anagrams.\n"); return 0; } void read_word(int counts[26]) { unsigned char now_char; int i; for (i = 0; ((now_char = getchar()) != '\n') && i < 20; i++) { /* if now_char is an alphabet, increase its corresponding counter by 1. */ if (isalpha(now_char)) { counts[tolower(now_char - 'a')] += 1; } } } int equal_array(int counts1[26], int counts2[26]) { int i; /* compare two arrays, whether they are identical or not. */ for (i = 0; i < 26; i++) { if (counts1[i] != counts2[i]) return FALSE; } return TRUE; }
C
#include "euler.h" /* * Find the best generator of primes g(n) = n^2+an+b where * |a| < 1000 and |b| < 1000. * * Clearly, b has to be at least 2, otherwise g(0) is not prime. * * Also, 1+a+b >= 2 (since g(1) is prime), so a >= 1-b. * * Also, g(b) is not prime, so the sequence can't be longer * than 1000, so we only have to consider primes up to * 2,001,000 (a^2+a^2+b). */ void eu027(char *ans) { const int MAXPRIME = 2001000; char *sieve = malloc(MAXPRIME); int max = 0; int max_ab; gensieve(sieve, MAXPRIME); for (int b = -999; b < 1000; b++) { for (int a = -999; a < 1000; a++) { int n = 0; while (n < b) { int f_n = n*n + a*n + b; if (f_n < 2 || f_n >= MAXPRIME || sieve[f_n]) { break; } n++; } /* * At this point, n is the minimum for which f_n is composite. * Subtracting 1 makes it the maximum for which f_n is prime. */ n--; if (n > max) { max = n; max_ab = a * b; } } } free(sieve); sprintf(ans, "%d", max_ab); }
C
/* * test_gcc.c * Copyright (C) 2015 jujian <[email protected]> * * Distributed under terms of the MIT license. */ #include <stdio.h> int main() { printf("a=%d, b=%d, c=%d", 1, 2, 3); return 0; }
C
#include <stdio.h> #include <stdint.h> #include <stdlib.h> #define SIZE 20 void Intercambiar_Arrays(uint8_t a[], uint8_t b[]); void main() { uint8_t A[SIZE]; uint8_t B[SIZE]; printf("Nombre 1: "); gets(A); printf("\nNombre 2: "); gets(B); Intercambiar_Arrays(A,B); } void Intercambiar_Arrays(uint8_t a[], uint8_t b[]) { uint8_t C[SIZE]; printf("\nNombre 1: %s",a); printf("\nNombre 2: %s",b); strcpy(C,a); strcpy(a,b); strcpy(b,C); printf("\nNombre 1: %s",a); printf("\nNombre 2: %s",b); }
C
#include<stdio.h> #include<stdlib.h> #include "../data_structures/heapSort.c" int lcm(int* ar, int m); int lcm(int* ar, int m) { int res = ar[0]; int a,b; for(int i=1; i<m; i++) { if(res>ar[i]) { b= res; a= ar[i]; } else { b = ar[i]; a = res; } int r=1; while(r>0) { r = b%a; b = a; a = r; } res = (ar[i]*res)/b; } return res; } void dms(int lcmm, int m, int* exec, int* deadline, int* period, int* arrival, int* ans){ int* rexec = (int*)(malloc(sizeof(int)*m)); int* index = (int*)(malloc(sizeof(int)*m)); for(int i=0; i<m; i++) { rexec[i] = exec[i]; } int* heapdead = (int*)(malloc(sizeof(int)*lcmm*m)); int* heapindex = (int*)(malloc(sizeof(int)*lcmm*m)); int** e = (int**)(malloc(sizeof(int)*m)); for(int i=0; i<m; i++) { e[i] = (int*)(malloc(sizeof(int)*lcmm)); } int value; int indexterm; int heapsize = 0; for(int i=0; i<lcmm; i++) { for(int j=0; j<m; j++) { e[j][i] = 0; if(arrival[j] == i) { minHeapPush(heapdead, heapindex, &heapsize, deadline[j], j ); arrival[j] += period[j]; rexec[j] = exec[j]; } } if(heapsize > 0) { minHeapPop(heapdead,heapindex,&value,&indexterm,&heapsize); ans[i] = indexterm+1; e[indexterm][i] = 1; rexec[indexterm]--; if(rexec[indexterm]>0) { minHeapPush(heapdead, heapindex, &heapsize, value, indexterm ); } } } }
C
#include <stdio.h> int main() { struct student { char name[30]; int rollno; float mark1, mark2, mark3, mark4, mark5; float avg; }; struct student s1; printf("enter the student's name :- "); scanf("%s", &s1.name); printf("enter the rollno of the student :- "); scanf("%d", &s1.rollno); printf("enter the marks of five subject of a student :- "); scanf("%f%f%f%f%f", &s1.mark1, &s1.mark2, &s1.mark3, &s1.mark4, &s1.mark5); s1.avg = (s1.mark1 + s1.mark2 + s1.mark3 + s1.mark4 + s1.mark5) / 5; printf("average of the student %f", s1.avg); return 0; }
C
/* * ===================================================================================== * * Filename: tcputil.c * * Description: * * Version: 1.0 * Created: 11/02/2013 07:17:02 AM * Revision: none * Compiler: gcc * * Author: YOUR NAME (), * Organization: * * ===================================================================================== */ #include "tcputil.h" void tcp_ntoh(tcphdr *header){ header->sourceport = ntohs(header->sourceport); header->destport = ntohs(header->destport); header->seqnum = ntohl(header->seqnum); header->ack_seq = ntohl(header->ack_seq); header->orf = ntohs(header->orf); header->adwindow = ntohs(header->adwindow); } void tcp_hton(tcphdr *header){ header->sourceport = htons(header->sourceport); header->destport = htons(header->destport); header->seqnum = (uint32_t)htonl(header->seqnum); header->ack_seq = (uint32_t)htonl(header->ack_seq); header->orf = (uint16_t)htons(header->orf); header->adwindow = (uint16_t)htons(header->adwindow); } //CONTAINS MALLOC tcphdr *tcp_mastercrafter(uint16_t srcport, uint16_t destport, uint32_t seqnum, uint32_t acknum, bool fin, bool syn, bool rst, bool psh, bool ack, uint16_t mywindow){ struct tcphdr *header = malloc(sizeof(struct tcphdr)); if (header == NULL) { printf("\tERROR : Malloc failed\n"); return NULL; } memset(header, 0, sizeof(struct tcphdr)); header->sourceport = srcport; header->destport = destport; header->seqnum = seqnum; header->ack_seq = acknum; HDRLEN_SET(header->orf); if(fin) FIN_SET(header->orf); if(syn) SYN_SET(header->orf); if(rst) RST_SET(header->orf); if(psh) PSH_SET(header->orf); if(ack) ACK_SET(header->orf); header->adwindow= mywindow; header->check = ZERO; return header; } int tcp_checksum(void *packet, uint16_t total_length) { uint32_t sum = 0; uint16_t odd_byte = 0; uint16_t *pseudo_itr = packet; int n = total_length; while (n > 1) { sum += *pseudo_itr++; n -= 2; } //odd bytes if (n == 1) { *(uint8_t *)(&odd_byte) = *(uint8_t*)pseudo_itr; sum += odd_byte; } //free(pseudo_hdr); sum = (sum >> 16) + (sum & 0xffff); sum += (sum >> 16); uint16_t res; res = ~sum; return res; } void tcp_print_packet_byte_ordered(tcphdr *header){ printf("\nNETWORK BYTE ORDERED TCP HEADER---------------\n"); printf("sourceport %u\n", ntohs(header->sourceport)); printf("destport %u\n", ntohs(header->destport)); printf("seqnum %lu\n", ntohl(header->seqnum)); printf("ack_seq %lu\n", ntohl(header->ack_seq)); printf("data offset: %d\n", ntohs(header->orf & 0xf000)>>12); printf("res: %d\n", (header->orf &0xFC0)>>6); printf("flags: \n"); printf(" URG? %d\n", (header->orf & 0x20)>>5); printf(" ACK? %d\n", (header->orf & 0x10)>>4); printf(" PSH? %d\n", (header->orf & 0x08)>>3); printf(" RST? %d\n", (header->orf & 0x04)>>2); printf(" SYN? %d\n", (header->orf & 0x02)>>1); printf(" FIN? %d\n", (header->orf & 0x01)); printf("adwindow: %u\n", ntohs(header->adwindow)); printf("check: %x\n", header->check); //printf("urgptr: %u\n",header->urgptr); printf("------------------------\n\n"); } void tcp_print_packet(tcphdr *header){ printf("\nTCP HEADER---------------\n"); printf("sourceport %u\n", header->sourceport); printf("destport %u\n", header->destport); printf("seqnum %lu\n", header->seqnum); printf("ack_seq %lu\n", header->ack_seq); printf("data offset: %d\n", (header->orf & 0xf000)>>12); printf("res: %d\n", (header->orf &0xFC0)>>6); printf("flags: \n"); printf(" URG? %d\n", (header->orf & 0x20)>>5); printf(" ACK? %d\n", (header->orf & 0x10)>>4); printf(" PSH? %d\n", (header->orf & 0x08)>>3); printf(" RST? %d\n", (header->orf & 0x04)>>2); printf(" SYN? %d\n", (header->orf & 0x02)>>1); printf(" FIN? %d\n", (header->orf & 0x01)); printf("adwindow: %u\n", header->adwindow); printf("check: %x\n", header->check); //printf("urgptr: %u\n",header->urgptr); printf("------------------------\n\n"); }
C
/* * RITHMOMACHIE - Created by Anderson5091 23/Avril/17. * - Fin de creation de prise par blocage 24/Avril/2017. * - Debut de creation de prise par arithmetique 27/Avril/2017. * ce module peremet de gerer l'ensemble de tous les prise possible * en prenant en compte qu'une case d'agression. */ #include "Prise.h" #include "Deplacement.h" #include "Moyeu.h" CASE* zone_en_danger[8][9]; CASE* zone_aneantie[8][9]; bool prise; int nomb_zone_en_danger=0,nomb_zone_aneantie=0, zone_actuel; bool Isset_prise(void){ return prise; } void Set_prise(void){ prise=TRUE; } void Reset_prise(void){ prise=FALSE; } void Reset_zone_en_danger(void) { int i, j; for(i=0;i<8;i++){ for(j=0;j<9;j++) zone_en_danger[i][j]=NULL; } nomb_zone_en_danger=0; zone_actuel=0; } void Reset_zone_aneantie(void) { int i,j; for(i=0;i<8;i++){ for(j=0;j<9;j++) zone_aneantie[i][j]=NULL; } nomb_zone_aneantie=0; } int Nomb_zone_en_danger(void) { return nomb_zone_en_danger; } int Nomb_zone_aneantie(void) { return nomb_zone_aneantie; } void Ajouter_zone_en_danger_cible(CASE* cs_en_danger) { zone_en_danger[nomb_zone_en_danger][0]=cs_en_danger;//on ajoute le cible dans la case zero de la zone nomb_zone_en_danger++; } void Ajouter_dans_zone_en_danger_agresseur(int zone,int num_agresseur, CASE* nouveau_agresseur){ zone_en_danger[zone][num_agresseur]=nouveau_agresseur; } void Ajouter_zone_aneantie(CASE* cs_aneantie){ zone_aneantie[nomb_zone_aneantie][0]=cs_aneantie; nomb_zone_aneantie++; } void Ajouter_dans_zone_aneantie_agresseur(int zone,int num_agresseur, CASE* nouveau_agresseur){ zone_aneantie[zone][num_agresseur]=nouveau_agresseur; } void R_Anneantie(CASE *case_agresseur, CASE *case_victime){ CASE* temp_case=case_victime; Deplacer_piece_vers_moyeu_plateau(case_victime->Piece,joueur_actuel->Id); case_victime->Piece=NULL; if(case_agresseur->Piece) Deplacer_piece_dans_tablier(case_agresseur,case_victime); else if(case_agresseur->Pyramide) Deplacer_pyramide_dans_tablier(case_agresseur,case_victime); } bool Verifier_prise(CASE *cible){ if(zone_en_danger[zone_actuel][0]==cible&&(zone_en_danger[zone_actuel][1]||zone_en_danger[zone_actuel][2]|| zone_en_danger[zone_actuel][3]||zone_en_danger[zone_actuel][4]||zone_en_danger[zone_actuel][5]|| zone_en_danger[zone_actuel][6]||zone_en_danger[zone_actuel][7]||zone_en_danger[zone_actuel][8])) return TRUE; else return FALSE; } bool Verifier_blocage_piece(CASE *cible, CASE* block) { P_COLOR _couleur_block, couleur_block; int i,j,l, c, nomb_d; bool Blocage=FALSE, Annuller_blocage=FALSE; CASE *_block[3]={NULL,NULL,NULL}; COORDTAB *liste_deplacement; COORDTAB position=cible->Position; if(cible->Piece->Type==Cercle){ COORDTAB liste_d[4]={{position.Ligne-1,position.Colonne-1},{position.Ligne-1,position.Colonne+1},{position.Ligne+1,position.Colonne-1},{position.Ligne+1,position.Colonne+1}}; nomb_d=1; liste_deplacement=malloc(4*sizeof(COORDTAB)); for(i=0;i<4;i++){liste_deplacement[i]=liste_d[i];printf("depl(%d,%d) ",liste_d[i].Ligne,liste_d[i].Colonne);}printf("\n cercle endanger\n"); } else if(cible->Piece->Type==Triangle){ COORDTAB liste_d[4]={{position.Ligne,position.Colonne+2},{position.Ligne,position.Colonne-2},{position.Ligne+2,position.Colonne},{position.Ligne-2,position.Colonne}}; nomb_d=2; liste_deplacement=malloc(4*sizeof(COORDTAB)); for(i=0;i<4;i++){liste_deplacement[i]=liste_d[i];printf("depl(%d,%d) ",liste_d[i].Ligne,liste_d[i].Colonne);} printf("triangle endanger\n"); } else if(cible->Piece->Type==Carre){ COORDTAB liste_d[4]={{position.Ligne,position.Colonne+3},{position.Ligne,position.Colonne-3},{position.Ligne+3,position.Colonne},{position.Ligne-3,position.Colonne}}; nomb_d=3; liste_deplacement=malloc(4*sizeof(COORDTAB)); for(i=0;i<4;i++){liste_deplacement[i]=liste_d[i];printf("depl(%d,%d) ",liste_d[i].Ligne,liste_d[i].Colonne);} printf("carre endanger\n"); } couleur_block=(block->Piece)?block->Piece->Color:block->Pyramide->Pieces[0]->Color; printf("verification blocage....\n"); for(i=0;i<4;i++){ if(Position_vers_adresse(liste_deplacement[i])){ printf("direction %d\n",i); Blocage=FALSE; l=liste_deplacement[i].Ligne-cible->Position.Ligne; c=liste_deplacement[i].Colonne-cible->Position.Colonne; printf("l:%d, c:%d\n\n",l,c); if(((l==0&&c>0)||(c==0&&l>0))||((l==0&&c<0)||(c==0&&l<0))) for(j=0;j<nomb_d;j++){ _block[j]=cible+(j+1)*l/nomb_d*8+(j+1)*c/nomb_d; printf("block%d: %d,%d ",j,_block[j]->Position.Ligne,_block[j]->Position.Colonne);} else{ _block[0]=Position_vers_adresse(liste_deplacement[i]);printf("block%d: %d,%d ",0,_block[0]->Position.Ligne,_block[0]->Position.Colonne);} printf("\n\n"); j=0; printf("verifier blocage sur....:\n "); while(!Blocage&&j<nomb_d){ printf("block:%d\n",j); if(_block[j]->Piece||_block[j]->Pyramide){ _couleur_block=(_block[j]->Piece)?_block[j]->Piece->Color:_block[j]->Pyramide->Pieces[0]->Color; if(couleur_block==_couleur_block){ Blocage=TRUE; printf("blocage\n"); } else{ Blocage=FALSE; printf("piece de meme couleur\n"); Annuller_blocage=TRUE; break; } }else{ j++; printf("suivant...\n"); } } if(j>=nomb_d){ Blocage=FALSE; Annuller_blocage=TRUE; printf("pas de piece dan cette direction\n"); } if(Blocage){ switch(cible->Piece->Type){ case Cercle: if(_block[j]->Piece){ if(_block[j]->Piece->Type==Cercle){ if(j+1==1){ Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); printf("cecle ajoute comme agresseur \n"); } } } else Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); break; case Triangle: if(_block[j]->Piece){ if(_block[j]->Piece->Type==Triangle){ if(j+1==2){ Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); printf("triangle(%d,%d) ajoute comme agresseur \n",_block[j]->Position.Ligne,_block[j]->Position.Colonne); } } } else Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); break; case Carre: if(_block[j]->Piece){ if(_block[j]->Piece->Type==Triangle){ if(j+1==2){ Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); printf("triangle ajoute comme agresseur \n"); } } else if(_block[j]->Piece->Type==Carre){ if(j+1==3){ Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); printf("carre ajoute comme agresseur \n"); } } } else Ajouter_dans_zone_en_danger_agresseur(zone_actuel,i+1,_block[j]); break; } } if(Annuller_blocage) break; } } free(liste_deplacement); if(Blocage) printf("blocage reussi....\n"); return Blocage; } bool Verifier_blocage_pyramide(CASE *cible,CASE* block) { P_COLOR _couleur_block, couleur_block; int i,j,l, c, nomb_d; bool Blocage=FALSE, Annuller_blocage=FALSE; CASE *_block[3]={NULL,NULL,NULL}; COORDTAB position=cible->Position; COORDTAB liste_glissement_pyramide[8]={{position.Ligne+3,position.Colonne},{position.Ligne-3,position.Colonne}, {position.Ligne,position.Colonne+3},{position.Ligne,position.Colonne-3}, {position.Ligne+3,position.Colonne+3},{position.Ligne+3,position.Colonne-3}, {position.Ligne-3,position.Colonne-3},{position.Ligne-3,position.Colonne+3}}; couleur_block=(block->Piece)?block->Piece->Color:block->Pyramide->Pieces[0]->Color; return Blocage; } void R_Prise(CASE* block) { int i, j, danger; CASE *cible=NULL; P_COLOR couleur_block=(block->Piece)?block->Piece->Color:block->Pyramide->Pieces[0]->Color; COORDTAB position=block->Position; COORDTAB zone_de_danger[8][3]={ {{position.Ligne,position.Colonne-1},{position.Ligne,position.Colonne-2},{position.Ligne,position.Colonne-3}}, {{position.Ligne,position.Colonne+1},{position.Ligne,position.Colonne+2},{position.Ligne,position.Colonne+3}}, {{position.Ligne-1,position.Colonne},{position.Ligne-2,position.Colonne},{position.Ligne-3,position.Colonne}}, {{position.Ligne+1,position.Colonne},{position.Ligne+2,position.Colonne},{position.Ligne+3,position.Colonne}}, {{position.Ligne-1,position.Colonne-1},{position.Ligne-2,position.Colonne-2},{position.Ligne-3,position.Colonne-3}}, {{position.Ligne-1,position.Colonne+1},{position.Ligne-2,position.Colonne+2},{position.Ligne-3,position.Colonne+3}}, {{position.Ligne+1,position.Colonne-1},{position.Ligne+2,position.Colonne-2},{position.Ligne+3,position.Colonne-3}}, {{position.Ligne+1,position.Colonne+1},{position.Ligne+2,position.Colonne+2},{position.Ligne+3,position.Colonne+3}}}; Reset_zone_en_danger(); Reset_zone_aneantie(); printf("recuperation des zone de danger\n"); for(i=0;i<8;i++){ bool cible_ami=FALSE; j=0; while(!cible&&j<3&&!cible_ami){ cible=Position_vers_adresse(zone_de_danger[i][j]); if(cible){ P_COLOR couleur_cible=(cible->Piece)?cible->Piece->Color: ((cible->Pyramide)?cible->Pyramide->Pieces[0]->Color:100); if(couleur_cible!=couleur_block) cible=cible; else{ cible_ami=TRUE; cible=NULL; } if(cible){ if(cible->Piece){ if(cible->Piece->Type==Cercle) { if(j<1) Ajouter_zone_en_danger_cible(cible); //else //pas de rencontre avec le cercle } else if(cible->Piece->Type==Triangle) { if(i<4&&j<2) Ajouter_zone_en_danger_cible(cible); //else //pas de rencontre avec le triangle } else if(cible->Piece->Type==Carre) { if(i<4&&j<3) Ajouter_zone_en_danger_cible(cible); //else //pas de rencontre avec le carre } } else if(cible->Pyramide){//dans tous les cas la rencontre avec le pyramide sera vrai Ajouter_zone_en_danger_cible(cible); } } //fin de verification de rencontre }//fin de verification cible adverse j++; //pochain cible dans la meme direction si on est encore dans la zone de danger et il n'y a pas encore de cible } //prochaine direction cible=NULL; }//fin de la recuperation des zones en danger printf("verification du blocage\n"); danger=Nomb_zone_en_danger(); for(i=0; i<danger; i++){//recuperation des autres blocs pour chaque zone de danger cible=zone_en_danger[i][0]; zone_actuel=i; if(cible->Piece){ if(Verifier_blocage_piece(cible, block)){ cible->Piece->Etat=P_Bloquer; if(Verifier_prise(cible)){ Ajouter_zone_aneantie(cible); for(j=1;j<5;j++){ if(zone_en_danger[i][j]){ Ajouter_dans_zone_aneantie_agresseur(i,j,zone_en_danger[i][j]); } } } } else if(Try_Out_arithmetique(cible, block)){ //R_Arithmetique(cible,block,i); } cible=NULL; } else{ if(cible->Pyramide->Compacite){ printf("pyramide compact\n"); if(Verifier_blocage_pyramide(cible,block)){ Ajouter_zone_aneantie(cible); } else{ printf("verification arithmetique pyramide\n"); // R_Arithmetique(cible,block,i); } cible=NULL; } else{//cible pyramide et compacite:faux , a revoirrrr int ref=0; bool blocage_piece_v=TRUE; cible->Piece=cible->Pyramide->Pieces[ref]; blocage_piece_v=Verifier_blocage_piece(cible,block); while(blocage_piece_v&&cible->Pyramide->Pieces[ref]){ //tant que le blocage reste vraie trouver une porte de sortie cible->Piece=cible->Pyramide->Pieces[ref]; blocage_piece_v=Verifier_blocage_piece(cible,block); ref++; } cible->Piece=NULL; if(blocage_piece_v){ Ajouter_zone_aneantie(cible); // } else{ //R_Arithmetique(cible,block,i); } cible=NULL; } } } //traitement des zone anneanties danger=Nomb_zone_aneantie(); cible=NULL; for(i=0; i<danger; i++) { cible=zone_aneantie[i][0]; //gere le cible actuel pour le moment on eface les pieces if(cible->Piece) { Set_prise(); } else if(cible->Pyramide) { j=0; while(cible->Pyramide->Pieces[j]) { Deplacer_piece_vers_moyeu_plateau(cible->Pyramide->Pieces[j],joueur_actuel->Id); cible->Pyramide->Pieces[j]=NULL; j++; } cible->Pyramide=NULL; } cible=NULL; } } /***************************************************************************/ bool Compte_est_bon(int cible, int nomb_1, int nomb_2) { float _cible, _nomb_1, _nomb_2; if((_cible==(_nomb_1+_nomb_2))||(_cible==(_nomb_1-_nomb_2))||(_cible==(_nomb_2-_nomb_1))) return TRUE; else if((_cible==_nomb_1*_nomb_2)||(_cible==(_nomb_1/_nomb_2))||(_cible==(_nomb_2/_nomb_1))) return TRUE; else if(_cible==(_nomb_1+_nomb_2)/2.0) return TRUE; else return FALSE; } bool Try_Out_arithmetique(CASE* cible,CASE* tire){ if(zone_en_danger[zone_actuel][0]==cible&&(zone_en_danger[zone_actuel][1]==tire||zone_en_danger[zone_actuel][2]==tire|| zone_en_danger[zone_actuel][3]==tire||zone_en_danger[zone_actuel][4]==tire||zone_en_danger[zone_actuel][5]==tire|| zone_en_danger[zone_actuel][6]==tire||zone_en_danger[zone_actuel][7]==tire||zone_en_danger[zone_actuel][8]==tire)) return TRUE; else return FALSE; } void R_Arithmetique(CASE* cible, CASE* tire, int ordre) { CASE* compte_agresseur; bool le_compte_est_bon=FALSE; int nomb_0, nomb_1, nomb_2, i, j, zone; P_TYPE type_tire=(tire->Piece)?tire->Piece->Type:tire->Pyramide->Pieces[0]->Type;// if(cible->Piece){ nomb_0=cible->Piece->Poids; nomb_1=(tire->Piece)?tire->Piece->Poids:tire->Pyramide->Poids; if(cible->Piece->Type!=type_tire&&nomb_0==nomb_1){ le_compte_est_bon=TRUE; zone=Nomb_zone_aneantie(); Ajouter_zone_aneantie(cible); Ajouter_dans_zone_aneantie_agresseur(zone,1,tire); } else{ j=1; while(!le_compte_est_bon&&zone_en_danger[ordre][j]){ if(zone_en_danger[ordre][j]!=tire){ nomb_2=(zone_en_danger[ordre][j]->Piece)?zone_en_danger[ordre][j]->Piece->Poids: zone_en_danger[ordre][j]->Pyramide->Poids; le_compte_est_bon=Compte_est_bon(nomb_0, nomb_1, nomb_2); } if(le_compte_est_bon){ compte_agresseur=zone_en_danger[ordre][j]; zone=Nomb_zone_aneantie(); Ajouter_zone_aneantie(cible); Ajouter_dans_zone_aneantie_agresseur(zone,1,tire); Ajouter_dans_zone_aneantie_agresseur(zone,2,compte_agresseur); } else j++; } } } else if(cible->Pyramide){ printf("Arith metique cible pyramide\n"); nomb_0=cible->Pyramide->Poids; nomb_1=(tire->Piece)?tire->Piece->Poids:tire->Pyramide->Poids; j=1; while(!le_compte_est_bon&&zone_en_danger[ordre][j]){ if(zone_en_danger[ordre][j]!=tire){ nomb_2=(zone_en_danger[ordre][j]->Piece)?zone_en_danger[ordre][j]->Piece->Poids: zone_en_danger[ordre][j]->Pyramide->Poids; le_compte_est_bon=Compte_est_bon(nomb_0, nomb_1, nomb_2); } if(le_compte_est_bon){ compte_agresseur=zone_en_danger[ordre][j]; zone=Nomb_zone_aneantie(); Ajouter_zone_aneantie(cible); Ajouter_dans_zone_aneantie_agresseur(zone,1,tire); Ajouter_dans_zone_aneantie_agresseur(zone,2,compte_agresseur); } else j++; } if(!le_compte_est_bon){ for(i=0; i<6; i++) { if(cible->Pyramide->Pieces[i]){ nomb_0=cible->Pyramide->Pieces[i]->Poids; if(type_tire!=cible->Pyramide->Pieces[i]->Type&&nomb_0==nomb_1){ le_compte_est_bon=TRUE; Deplacer_piece_vers_moyeu_plateau(cible->Pyramide->Pieces[i],joueur_actuel->Id); Retirer_piece_dans_pyramide(cible->Pyramide->Pieces[i], cible->Pyramide); Re_init_moyeu_boutons(&Moyeux[(joueur_actuel->Id==0)?1:0]); } while(!le_compte_est_bon&&zone_en_danger[ordre][j]){ if(zone_en_danger[ordre][j]!=tire){ nomb_2=(zone_en_danger[ordre][j]->Piece)?zone_en_danger[ordre][j]->Piece->Poids: zone_en_danger[ordre][j]->Pyramide->Poids; le_compte_est_bon=Compte_est_bon(nomb_0, nomb_1, nomb_2); } if(le_compte_est_bon){ Deplacer_piece_vers_moyeu_plateau(cible->Pyramide->Pieces[i],joueur_actuel->Id); Retirer_piece_dans_pyramide(cible->Pyramide->Pieces[i], cible->Pyramide); Re_init_moyeu_boutons(&Moyeux[(joueur_actuel->Id==0)?1:0]); } else j++; } } if(le_compte_est_bon) break; } } }//fin arithmetique cible type pyramide } bool fin_prise(void) { if(((!zone_aneantie[0][1]&&!zone_aneantie[0][2]&&!zone_aneantie[0][3]&&!zone_aneantie[0][4]&&!zone_aneantie[0][5]&&!zone_aneantie[0][6]&&!zone_aneantie[0][7]&&!zone_aneantie[0][8])&& (!zone_aneantie[1][1]&&!zone_aneantie[1][2]&&!zone_aneantie[1][3]&&!zone_aneantie[1][4]&&!zone_aneantie[1][5]&&!zone_aneantie[1][6]&&!zone_aneantie[1][7]&&!zone_aneantie[1][8])&& (!zone_aneantie[2][1]&&!zone_aneantie[2][2]&&!zone_aneantie[2][3]&&!zone_aneantie[2][4]&&!zone_aneantie[2][5]&&!zone_aneantie[2][6]&&!zone_aneantie[2][7]&&!zone_aneantie[2][8])&& (!zone_aneantie[3][1]&&!zone_aneantie[3][2]&&!zone_aneantie[3][3]&&!zone_aneantie[3][4]&&!zone_aneantie[3][5]&&!zone_aneantie[3][6]&&!zone_aneantie[3][7]&&!zone_aneantie[3][8])&& (!zone_aneantie[4][1]&&!zone_aneantie[4][2]&&!zone_aneantie[4][3]&&!zone_aneantie[4][4]&&!zone_aneantie[4][5]&&!zone_aneantie[4][6]&&!zone_aneantie[4][7]&&!zone_aneantie[4][8])&& (!zone_aneantie[5][1]&&!zone_aneantie[5][2]&&!zone_aneantie[5][3]&&!zone_aneantie[5][4]&&!zone_aneantie[5][5]&&!zone_aneantie[5][6]&&!zone_aneantie[5][7]&&!zone_aneantie[5][8])&& (!zone_aneantie[6][1]&&!zone_aneantie[6][2]&&!zone_aneantie[6][3]&&!zone_aneantie[6][4]&&!zone_aneantie[6][5]&&!zone_aneantie[6][6]&&!zone_aneantie[6][7]&&!zone_aneantie[6][8])&& (!zone_aneantie[7][1]&&!zone_aneantie[7][2]&&!zone_aneantie[7][3]&&!zone_aneantie[7][4]&&!zone_aneantie[7][5]&&!zone_aneantie[7][6]&&!zone_aneantie[7][7]&&!zone_aneantie[7][8]))|| (!zone_aneantie[0][0]&&!zone_aneantie[1][0]&&!zone_aneantie[2][0]&&!zone_aneantie[3][0]&&!zone_aneantie[4][0]&&!zone_aneantie[5][0]&&!zone_aneantie[6][0]&&!zone_aneantie[7][0])) return TRUE; else return FALSE; }
C
/* Inject DLL ini ke dalam proses. Pembacaan dan penulisan wilayah memory tertentu akan terjadi. Dalam kasus ini, nilai variabel global akan dimodifikasi. Sesuaikan alamat variabel global sebelum melakukan kompilasi!! Compile: [gcc] (x64) $ gcc -m64 -shared payload.c -o payload.dll (x86) $ gcc -m32 -shared payload.c -o payload.dll (msvc) $ cl /nologo /LD payload.c Inject: $ injector <PID> payload.dll */ #include <windows.h> #include <stdio.h> // Lokasi variabel global // Pastikan alamat ini sesuai #define ADDRESS 0x404010 BOOL WINAPI DllMain(HINSTANCE hinst, DWORD dwReason, LPVOID lpres) { int* global = NULL; switch (dwReason) { case DLL_PROCESS_ATTACH: global = (int*) ADDRESS; printf("\n\n"); printf("Nilai variabel global = %d\n", *global); // Read *global = 1337; // Write printf("Nilai variabel global = %d\n", *global); break; case DLL_PROCESS_DETACH: break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; } return 1; }
C
#include <stdio.h> #include <stdlib.h> #define MAX 50 #define ENCAD 10 int lePrecos(int arr[], float mat[][5]) { char tipo; int i=0; float p0, p1, p2, p3, p4; FILE *precos; precos = fopen("ENCADERNACAO.TXT", "r"); if (precos == NULL) { printf("\n\nERRO AO ABRIR ARQUIVO DE PRECOS DE ENCADERNACAO\n\n"); exit(-1); } while (fscanf(precos, " %c %f %f %f %f %f", &tipo, &p0, &p1, &p2, &p3, &p4) == 6 ) { arr[i] = tipo; mat[i][0] = p0; mat[i][1] = p1; mat[i][2] = p2; mat[i][3] = p3; mat[i][4] = p4; i++; } return i; fclose(precos); } void processaPedidos() { FILE *pedidos; pedidos = fopen("PEDIDOS.TXT", "r"); if (pedidos == NULL) { printf("\n\nERRO NA ABERTURA DO ARQUIVO DE PEDIDOS\n\n"); exit(-1); } } void main() { int quant, i, j, tiposEncad[ENCAD]; float precosEncad[MAX][5]; quant = lePrecos(tiposEncad, precosEncad); for (i = 0; i < quant; i++) { printf("\n%c ", tiposEncad[i]); for (j = 0; j < 5; j++) { printf("%10.2f ", precosEncad[i][j]); } } printf("\n\n"); }
C
#include<stdio.h> int fibonacci(int n); int main() { int n; printf("Enter n : "); scanf("%d", &n); printf("Fibonacci : %d",fibonacci(n)); return 0; } int fibonacci(int n) { int sum, prev, next; sum = 0; prev = 1; next = 1; if(n == 1) { return sum; } else if(n == 2) { return prev; } else { for (int i = 1; i < n-1;i++) { sum = sum + prev; prev = next; next = sum; } } return sum; }
C
#include "types.h" #include "stat.h" #include "user.h" int main(int argc, char *argv[]) { int fd; if(argc != 2){ printf(1, "Usage: filestat [filepath]\n"); exit(); } struct stat st; if((fd = open(argv[1], 0)) < 0){ printf(1, "cat: cannot open %s\n", argv[1]); exit(); } if(fstat(fd, &st) < 0){ printf(2, "filestat: cannot stat %s\n", argv[1]); close(fd); exit(); } switch (st.type) { case T_DIR: printf(1, "File type: %s\n", "Directory"); break; case T_FILE: printf(1, "File type: %s\n", "File"); break; case T_DEV: printf(1, "File type: %s\n", "Special device"); break; case T_CHECKED: printf(1, "File type: %s\n", "File with checksum feature"); break; } printf(1, "size: %d\n", st.size); printf(1, "checksum: %d\n", st.checksum); close(fd); exit(); }
C
#ifndef _STRING_FUNCTION_H #define _STRING_FUNCTION_H int Index(String s, String t, int pos){ // 如果在s的pos下标之后有t子串,返回第一个下标 String sub; InitString(sub); if(pos > 0){ int n = StrLength(s); int m = StrLength(t); int i = pos; while(i <= n - m + 1){ SubString(sub, s, i, m); if(StrCompare(sub, t) == 0){ return i; } ++i; } } return 0; } Status Replace(String &s, String t, String v){ // 在主串s中,用v替换t if(StrEmpty(t)){ return ERROR; } int i = 1; while(i){ i = Index(s, t, i); if(i){ StrDelete(s, i, StrLength(t)); Status k = StrInsert(s, i, v); if(!k){ return ERROR; } i += StrLength(v); } } return OK; } #endif
C
#include <stdio.h> void smile(int n) { while(n>=1){printf("smile!");n--;} printf("\n"); } int main(void) { int n; printf("input a number : "); scanf("%d",&n); while(n) { smile(n); n--; } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* redir.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mbarylak <[email protected] +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2023/02/09 16:46:58 by mbarylak #+# #+# */ /* Updated: 2023/04/24 20:36:42 by mbarylak ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" static void print_error(int type, char *data) { if (type == T_REDIR_OUT) printf("minishell: syntax error near unexpected token `>'\n"); else if (type == T_REDIR_IN) printf("minishell: syntax error near unexpected token `<'\n"); else if (type == T_APPEND_OUT) printf("minishell: syntax error near unexpected token `>>'\n"); else if (type == T_HEREDOC) printf("minishell: syntax error near unexpected token `<<'\n"); else if (type == T_PIPE) printf("minishell: syntax error near unexpected token `|'\n"); else if (type > T_HEREDOC || type == 0) printf("minishell: syntax error near unexpected token `newline'\n"); else if (type == -1) printf("minishell: *: ambiguous redirect\n"); else if (type == -2) printf("minishell: %s: Is a directory\n", data); else if (type == -3) printf("minishell: %s: No such file or directory\n", data); } int check_redir_list(t_redir *redir) { t_redir *aux; aux = redir; if (!aux) return (2); while (aux) { if (!aux->value) { print_error(aux->r_type, NULL); return (1); } else if (ft_strcmp(aux->value, "*") == 0) { print_error(-1, NULL); return (1); } else if (is_directory(aux->value)) { print_error(-2, aux->value); return (1); } aux = aux->next; } return (0); } void open_redir_list(t_redir *redir) { if (redir->r_type == T_REDIR_OUT) g_shell->fd[1] = open(redir->value, O_RDWR | O_CREAT | O_TRUNC, 00644); else if (redir->r_type == T_REDIR_IN) { g_shell->fd[0] = open(redir->value, O_RDONLY); if (g_shell->fd[0] == -1) print_error(-3, redir->value); } else if (redir->r_type == T_APPEND_OUT) g_shell->fd[1] = open(redir->value, O_APPEND | O_RDWR | O_CREAT, 00644); else if (redir->r_type == T_HEREDOC) heredoc(redir->value); } void close_redir(int fd0, int fd1) { close(fd0); close(fd1); if (g_shell->fd[0] != 0) { close(g_shell->fd[0]); g_shell->fd[0] = 0; } if (g_shell->fd[1] != 1) { close(g_shell->fd[1]); g_shell->fd[1] = 1; } } void redir(t_tree *tree) { t_redir *aux; int std_fd[2]; int check; aux = *tree->l_redir; check = check_redir_list(aux); if (!check) { std_fd[0] = dup(0); std_fd[1] = dup(1); while (aux) { open_redir_list(aux); aux = aux->next; } dup2(g_shell->fd[0], STDIN_FILENO); dup2(g_shell->fd[1], STDOUT_FILENO); execute(tree); dup2(std_fd[0], STDIN_FILENO); dup2(std_fd[1], STDOUT_FILENO); close_redir(std_fd[0], std_fd[1]); } else if (check == 2) execute(tree); }
C
#include "../inc/pathfinder.h" static void mx_recursion(t_path **list, char ***pathes, int i, int j, char *str) { char *tmp = mx_strdup(str); char **arr = mx_strsplit(pathes[i][j], ','); int k = 0; str = mx_strcat_del(tmp, mx_itoa(j), ","); while (arr[k] != NULL) { if (mx_strcmp(arr[k], "0") == 0) { str = mx_strcat_del(str, mx_itoa(i), ","); mx_del_strarr(&arr); mx_push_path(&(*list), NULL, str); return; } mx_recursion(list, pathes, i, mx_atoi(arr[k]), str); k++; } mx_del_strarr(&arr); mx_strdel(&str); } static t_path *mx_create_path_list(char ***pathes, int i, int j) { t_path *list = NULL; t_path *l = NULL; char **arr; int len; mx_recursion(&list, pathes, i, j, ""); l = list; while (l != NULL) { arr = mx_strsplit(l->route, ','); len = mx_arr_size(arr); l->path = mx_strcat_del(mx_strdup(arr[0]), mx_strdup(arr[len - 1]), ","); mx_del_strarr(&arr); l = l->next; } return list; } static t_path ***mx_create_list_matrix(int count) { t_path ***matrix = (t_path***)malloc(sizeof(t_path**) * count); int i; int j; for (i = 0; i < count; i++) matrix[i] = (t_path**)malloc(sizeof(t_path*) * count); for (i = 0; i < count; i++) for (j = 0; j < count; j++) { matrix[i][j] = NULL; } return matrix; } t_path ***mx_create_path_matrix(char ***pathes, int count) { t_path ***matrix = mx_create_list_matrix(count); int i; int j; for (i = 0; i < count; i++) { for (j = 0; j < count; j++) { if (j - i > 0) matrix[i][j] = mx_create_path_list(pathes, i, j); } } return matrix; }
C
#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/mman.h> // main fnc int main(void) { // data accessed from module2.c and module3.c extern int a[4096]; extern int b[32]; extern long* c; extern long* d; extern void* mainPtr; extern long* pointerToSharedMemory; extern int recursiveFnc(int i); extern void waitForUserInput(); // STEP 1 printf("---STEP 1---\n"); printf("%s%lx\n", "Address of main fnc: ",(void *) main); printf("%s%lx\n", "Address of uninitialized array: ",(void *) a); printf("%s%lx\n", "Address of initialized array: ",(void *) b); printf("%s%lx\n", "Address of user input fnc: ",(void *) waitForUserInput); printf("%s%lx\n", "Address of printf: ",(void *) printf); printf("%s%d\n", "PID: ",getpid()); waitForUserInput(); // STEP 2 printf("---STEP 2---\n"); c = malloc(125000); d = malloc(125000); printf("%s%lx\n", "Address of dynamically allocated data 1: ",(void *) c); printf("%s%lx\n", "Address of dynamically allocated data 2: ",(void *) d); waitForUserInput(); // STEP 3 printf("---STEP 3---\n"); recursiveFnc(12500); printf("%s%lx\n", "Address of main fnc: ",(void *) main); printf("%s%lx\n", "Address of uninitialized array: ",(void *) a); printf("%s%lx\n", "Address of initialized array: ",(void *) b); printf("%s%lx\n", "Address of user input fnc: ",(void *) waitForUserInput); printf("%s%lx\n", "Address of printf: ",(void *) printf); printf("%s%lx\n", "Address of dynamically allocated data 1: ",(void *) c); printf("%s%lx\n", "Address of dynamically allocated data 2: ",(void *) d); printf("%s%lx\n", "Address of recursive fnc: ",(void *) recursiveFnc); waitForUserInput(); // STEP 4 printf("---STEP 4---\n"); pointerToSharedMemory = mmap(NULL, 250000, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0); printf("%s%lx\n", "Address of start address: ",(void *) pointerToSharedMemory); waitForUserInput(); // STEP 5 printf("---STEP 5---\n"); pointerToSharedMemory[0] = 123; pointerToSharedMemory[1] = 456; pointerToSharedMemory[2] = 789; printf("%s%d\n", "data read: ",pointerToSharedMemory[0]); printf("%s%d\n", "data read: ",pointerToSharedMemory[1]); printf("%s%d\n", "data read: ",pointerToSharedMemory[2]); printf("%s%lx\n", "Adrs of data read from memory mapped region: ",(void *) pointerToSharedMemory[0]); printf("%s%lx\n", "Adrs of data read from memory mapped region: ",(void *) pointerToSharedMemory[1]); printf("%s%lx\n", "Adrs of data read from memory mapped region: ",(void *) pointerToSharedMemory[2]); waitForUserInput(); // STEP 6 printf("---STEP 6---\n"); mainPtr = (void *) (4096 * (((long unsigned int) main) / 4096)); for (int i = 0; i < 4096; i++) { // address printf("%lx -> %02x\n", (long unsigned int) (mainPtr + i), ((char *)(mainPtr))[i]); // corresponding content //printf("%02x\n", ((char *)(mainPtr))[i]); } waitForUserInput(); printf("end of program\n"); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> struct book{ int bookid; char title[20]; float price; }; int main(){ struct book b; FILE *fp; fp=fopen("f2.dat","wb"); printf("Enter bookid, title and price: "); scanf("%d",&b.bookid); fflush(stdin); gets(b.title); scanf("%f",&b.price); fwrite(&b,sizeof(b),1,fp); fclose(fp); return 0; }
C
#pragma warning(disable:4996) #include <stdio.h> #include <time.h> int main(void) { struct tm t1, t2, t3; time_t n1, n2, n3; t1.tm_year = 2020 - 1900; t1.tm_mon = 6 - 1; t1.tm_mday = 23; t1.tm_hour = 1; t1.tm_min = 12; t1.tm_sec = 50; t2.tm_year = 2020 - 1900; t2.tm_mon = 8 - 1; t2.tm_mday = 19; t2.tm_hour = 3; t2.tm_min = 35; t2.tm_sec = 22; n1 = mktime(&t1); n2 = mktime(&t2); n3 = n2 - n1; t3 = *gmtime(&n3); t3.tm_year -= 70; printf("ð 1: %4d-%02d-%02d %02d:%02d:%02d \n" , t1.tm_year + 1900, t1.tm_mon + 1, t1.tm_mday , t1.tm_hour, t1.tm_min, t1.tm_sec); printf("ð 2: %4d-%02d-%02d %02d:%02d:%02d \n" , t2.tm_year + 1900, t2.tm_mon + 1, t2.tm_mday , t2.tm_hour, t2.tm_min, t2.tm_sec); printf("¥: %4d-%02d-%02d %02d:%02d:%02d \n" , t3.tm_year, t3.tm_mon, t3.tm_mday , t3.tm_hour, t3.tm_min, t3.tm_sec); return 0; }