language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include"analyse.h" #include"misc.h" #include<unistd.h> #include<stdio.h> #include<stdlib.h> st_char analytics_table[256]; char print_table=1; unsigned char head; unsigned char sorted_table[256]; short table_size=0; void init_analytics_table(void){ for(unsigned short i = 0; i < 256; ++i){ analytics_table[i].count=0; analytics_table[i].seen=0; } } void analyse(void){ unsigned char buf; while(read(infile,&buf,1)==1){ ++analytics_table[buf].count; ++file_size; } while(table_size<256){ long long best=-1; unsigned char bchar; for(int i = 0; i < 256; ++i){ if((!analytics_table[i].seen)&&analytics_table[i].count>=best){ best=analytics_table[i].count; bchar=i; } } if(best==0){ break; }else{ analytics_table[bchar].seen=1; sorted_table[table_size++]=bchar; } } if(print_table){ printf("Table size: %d (0x%03x)\n", table_size, table_size); for(int i = 0; i < table_size; ++i) printf("%03d: %03d [0x%02x] (count: %12lld)\n", i, (int)sorted_table[i], (int)sorted_table[i],analytics_table[sorted_table[i]].count); } } void read_table(void){ unsigned char buf; if(read(infile,&buf,1)!=1){ printf("Error reading translation table size\n"); exit(-1); } table_size=buf; if(table_size==0) table_size=256; if(read(infile,&file_size,sizeof(file_size))!=sizeof(file_size)){ printf("Error reading archive file size\n"); exit(-1); } if(file_size==0){ printf("Expanded empty file.\n"); exit(0); } for(short i = 0; i < table_size; ++i){ if(read(infile,&sorted_table[i],1)!=1){ printf("Error reading translation table\n"); exit(-1); } } if(print_table){ printf("Table size: %d (0x%03x)\n", table_size, table_size); for(int i = 0; i < table_size; ++i) printf("%03d: %03d [0x%02x]\n", i, (int)sorted_table[i], (int)sorted_table[i]); } }
C
/* Author:Nikhil Kumar Arora,IT branch,IIIT Sonepat /* C program to check if a tree is height-balanced or not */ #include <stdio.h> #include <stdlib.h> #define bool int /*creating structure of node*/ struct node { int data; struct node* left; struct node* right; }; /* Returns the height of a binary tree */ int height(struct node* node); /* Returns true if binary tree with root as root is height-balanced */ bool isBalanced(struct node* root) { int lh; /* for height of left subtree */ int rh; /* for height of right subtree */ /* If tree is empty then return true */ if (root == NULL) return 1; /* Get the height of left and right sub trees */ lh = height(root->left); rh = height(root->right); if (abs(lh - rh) <= 1 && isBalanced(root->left) && isBalanced(root->right)) return 1; /* If we reach here then tree is not height-balanced */ return 0; } /* returns maximum of two integers */ int max(int a, int b) { return (a >= b) ? a : b; } int height(struct node* node) { /* base case tree is empty */ if (node == NULL) return 0; /* If tree is not empty then height = 1 + max of left height and right heights */ return 1 + max(height(node->left), height(node->right)); } struct node* newNode(int data) { struct node* node = (struct node*) malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->left->left = newNode(6); /*printf("1 "); printf(" \"); printf(" 2"); printf(" \"); printf(" 3"); printf(" \"); printf(" 4"); printf(" \"); printf(" 5"); printf(" \"); printf(" 6");*/ if (isBalanced(root)) printf("Tree is balanced"); else printf("Tree is not balanced"); getchar(); return 0; }
C
#include <ncurses.h> #include <unistd.h> #define DELAY 300000 int main(int argc, char *argv[]) { int x = 0, y = 0; int PLAYER = 5; initscr(); noecho(); curs_set(FALSE); while(1) { clear(); // Clear the screen of all previously-printed characters mvprintw(y, x, "%d", PLAYER); // Print our "ball" at the current xy position refresh(); usleep(DELAY); // Shorter delay between movements int dir = getch(); switch(dir) { case KEY_UP: y--; break; case KEY_DOWN: y++; break; case KEY_LEFT: x--; break; case KEY_RIGHT: x++; break; default: break; } } endwin(); }
C
/* 2)Napisati program na programskom jeziku C koji razvrstava đake osnovnih škola u željene srednje škole. U svakom redu datoteke skole.txt se nalaze informacije o srednjoj školi u sledećem formatu: broj slobodnih mesta (ceo broj), naziv skole (niz znakova, koji može sadržati blanko znake, od najviše 30 karaktera). Svakoj školi se dodeljuje redni broj koji odgovara rednom broju linije teksta u kojem se škola nalazi. Redni brojevi škola počinju od 0. U datoteci ima podataka o najviše 400 škola. U binarnoj datoteci zelje.pod svaki zapis sadrži: prijavni broj đaka (ceo broj), ime i prezime đaka (dužine tačno 30 karaktera), prosečnu ocenu (realan broj) i redni broj srednje škole koju đak želi da upiše. Prijavni brojevi đaka su jedinstveni. Program treba da učita podatke o školama i đacima, zatim da formira tekstualnu datoteku upisi.txt koja će za svakog đaka sadržati podatke o dodeljenoj srednjoj školi. Jedan red datoteke treba da ima sledeći format: prijavni broj đaka, me i prezime đaka, prosečna ocena, naziv škole. Ako nema mesta u školi koju je đak naveo kao želju, umesto upisane škole upisati NEUPISAN. Đaci sa višom prosečnom ocenom imaju veći prioritet pri raspoređivanju. Prednost prilikom upisa đaka sa istim prosekom imaju oni sa nižim prijavnim brojem. Voditi računa o ispravnoj upotrebi resursa. */ #include <stdio.h> #include <stdlib.h> typedef struct { int prijava; char ime[31]; double prosek; int skola; } Student; typedef struct elem { Student *s; struct elem *sled; } Elem; typedef struct { int mesta; char ime[31]; } School; int readSchools(FILE *in, School skole[400]) { School s; int i = 0; while (fscanf(in, "%d %[^\n]\n", &s.mesta, s.ime) != EOF) skole[i++] = s; return i; } void printSchools(School skole[], int n) { for (int i = 0; i < n; i++) { printf("%d %s\n", skole[i].mesta, skole[i].ime); } } Elem *readStudents(FILE *in) { Elem *lst = NULL, *novi, *tek, *pret; Student *s = malloc(sizeof(Student)); if (!s) exit(2); while (fread(s, sizeof(Student), 1, in) == 1) { //printf("%d %s %lf %d\n", s->prijava, s->ime, s->prosek, s->skola); tek = lst; pret = NULL; while (tek && tek->s->prosek > s->prosek) { pret = tek; tek = tek->sled; } if (tek && tek->s->prosek == s->prosek) { while (tek && tek->s->prosek == s->prosek && tek->s->prijava < s->prijava) { pret = tek; tek = tek->sled; } } novi = malloc(sizeof(Elem)); if (!novi) exit(2); novi->s = s; novi->sled = tek; if (!pret) lst = novi; else pret->sled = novi; s = malloc(sizeof(Student)); if (!s) exit(2); } return lst; } void printStudents(Elem *lst) { while (lst) { printf("%d %s %lf %d\n", lst->s->prijava, lst->s->ime, lst->s->prosek, lst->s->skola); lst = lst->sled; } } void deleteStudents(Elem *lst) { Elem *stari; while (lst) { stari = lst; lst = lst->sled; free(stari); } } void assignSchools(FILE *out, Elem *lst, School skole[]) { while (lst) { if (skole[lst->s->skola].mesta > 0) { fprintf(out, "%d %s %lf %s\n", lst->s->prijava, lst->s->ime, lst->s->prosek, skole[lst->s->skola].ime); skole[lst->s->skola].mesta--; } else fprintf(out, "%d %s %lf %s\n", lst->s->prijava, lst->s->ime, lst->s->prosek, "NEUPISAN"); lst = lst->sled; } } int main() { FILE *skole_ulaz = fopen("skole.txt", "r"); FILE *zelje = fopen("zelje.pod", "r"); FILE *upisi = fopen("upisi.txt", "w"); if (!skole_ulaz || !zelje || !upisi) exit(1); School skole[400]; int n; n = readSchools(skole_ulaz, skole); //printSchools(skole, n); Elem *lst = readStudents(zelje); //printStudents(lst); assignSchools(upisi, lst, skole); deleteStudents(lst); fclose(skole_ulaz); fclose(zelje); fclose(upisi); }
C
/* * Energinet Datalogger * Copyright (C) 2009 - 2012 LIAB ApS <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <signal.h> #include <syslog.h> #include "pidfile.h" int pidfile_pidwrite(const char *pidfile) { FILE *fp; if((fp = fopen(pidfile, "w")) == NULL) { syslog(LOG_ERR, "Error: could not open pidfile for writing: %s\n", strerror(errno)); return errno; } fprintf(fp, "%ld\n", (long) getpid()); fclose(fp); return 0; } int pidfile_create(const char *pidfile) { int ret; struct stat s; FILE *fp; int filepid; ret = stat(pidfile, &s); if(ret == 0){ /* file exits: open file */ if((fp = fopen(pidfile, "r")) == NULL) { syslog(LOG_ERR, "Error: could not open pidfile: %s\n", strerror(errno)); return -errno; } /* read pid */ ret = fscanf(fp, "%d[^\n]", &filepid); fclose(fp); if(ret !=1){ syslog(LOG_ERR, "Error: reading pidfile: %s\n", strerror(errno)); return -errno; } syslog(LOG_INFO,"pid in file is %d\n", filepid); if (kill (filepid, 0) == 0){ syslog(LOG_INFO,"pid is running... \n"); return 0; } } pidfile_pidwrite(pidfile); return 1; } int pidfile_close(const char *path) { if (unlink(path) != 0) return -1; return 0; }
C
#include<stdio.h> void main() { int r=0,i,j,k=0,c=-1,p=1,hs=5,a[5][5]={0}; //Է while(1) { for(i=0;i<hs;i++) // Ǵ { k++; c=c+p;// +1 a[r][c]=k; } hs--; if(hs==0) break; for(i=0;i<hs;i++)// Ǵ { k++; r=r+p; a[r][c]=k; } p=p*-1; } //ó // for(i=0;i<=4;i++) { for(j=0;j<=4;j++) { printf("%4d",a[i][j]); } printf("\n"); } }
C
#include "check_return_count_in_functions.h" #include <stdio.h> #include <string.h> /* strncmp */ static int brace_lvl = 0; /* balance of '{', '}' */ static int state = 0; static int state_last_warn = 0; /* reset balance counter when loading new file */ void check_return_count_in_functions_init(void) { brace_lvl = 0; state = 0; } void check_return_count_in_functions_new_token(struct source_file* s, struct token* toks, int tok_idx) { int i = tok_idx; if (brace_lvl >= 1) { if (toks[i].toktyp == KW_RETURN) { state += 1; } } else if (brace_lvl == 0) { state = 0; } if (state > MAX_RETURNS_PR_FUNC) { /* one warning pr. violation is sufficient */ if (state != state_last_warn) { state_last_warn = state; /* prettier names in the output: '3rd return statement in function' etc. */ const char* endings[] = { "th", "st", "nd", "rd" }; const char* ending = endings[0]; if ( (state < 10) || (state > 20)) { if (state % 10 == 1) ending = endings[1]; else if (state % 10 == 2) ending = endings[2]; else if (state % 10 == 3) ending = endings[3]; } fprintf(stdout, "[%s:%d] (style) %d%s return statement in function.\n", s->file_path, toks[i - 1].lineno, state, ending); } } if (toks[i].toktyp == OP_LBRACE) { brace_lvl += 1; } else if (toks[i].toktyp == OP_RBRACE) { brace_lvl -= 1; } if (brace_lvl < 0) { brace_lvl = 0; } }
C
#include<stdio.h> //3/4 Hola/s void main(){ int i,j; for(i=0;i<=3;i++){ for(j=1;j<=4;j++) printf("Hola "); printf("\n"); } }
C
/* Pointers on c - ch5, ex2 encrypt.c - read chars and prints them out encrypting alphas per algorithm given in ex author: nicolas miller <[email protected]> */ #include <stdio.h> int encrypt(int ch) { if(ch >= 'a' && ch <= 'z') return 'a' + ((ch - 'a') + 13) % 26; else return 'A' + ((ch - 'A') + 13) % 26; } int main(int argc, char* argv[]) { int ch; while((ch = getchar()) && ch != EOF) { if((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')) putchar(encrypt(ch)); else putchar(ch); } return 1; }
C
/* Example code for Think OS. Copyright 2014 Allen Downey License: GNU GPLv3 */ #include <stdio.h> #include <stdlib.h> int var1; int main () { int var2 = 5; void *p = malloc(128); <<<<<<< HEAD void *q = malloc(128); void *t = malloc(2); void *r = malloc(27); char *s = "Literal string"; ======= char *s = "Hello, World"; >>>>>>> eabcd612b48ede32a05df58f23fee9f78d330d85 printf ("Address of main is %p\n", main); printf ("Address of var1 is %p\n", &var1); printf ("Address of var2 is %p\n", &var2); <<<<<<< HEAD printf ("Address of p is %p\n", p); printf ("Address of s is %p\n", s); // t and r are 32 bytes apart printf ("Address of t is %p\n", t); printf ("Address of r is %p\n", r); ======= printf ("p points to %p\n", p); printf ("s points to %p\n", s); >>>>>>> eabcd612b48ede32a05df58f23fee9f78d330d85 return 0; }
C
#include <math.h> #include <stdio.h> #include <assert.h> #include <stdlib.h> #ifndef ICOSPHERE_H #define ICOSPHERE_H // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // points typedef struct { double x; double y; double z; } cartesian_point; typedef struct { double r; double theta; double phi; int index; } spherical_point; // point-conversion functions cartesian_point cartesian( spherical_point ); spherical_point spherical( cartesian_point ); // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // graph structures typedef struct { spherical_point pt; int neighbors[6]; } node; typedef struct { int size; node* nodes; } graph; // graph-building graph icosphere(int subdivisions); #endif
C
#ifdef PROFILE_ENABLE #include "prof.h" #include <stdio.h> #include <string.h> #include <omp.h> #include "time_.h" tick_t profile_time[n_profile] = {0}; int profile_count[n_profile] = {0}; void profile_print(FILE *log, tick_t wall_time) { #define X(a) #a, const char *name[] = { PROFILE_LIST NULL }; #undef X // ordered for loop through all threads #pragma omp parallel for ordered schedule(static, 1) for (int thread = 0; thread < omp_get_num_threads(); thread++) { #pragma omp ordered { // insertion sort for time int i_sorted[n_profile] = {0}; for (int i = 1; i < n_profile; i++) { int j; for (j = i; j > 0 && profile_time[i_sorted[j-1]] < profile_time[i]; j--) i_sorted[j] = i_sorted[j-1]; i_sorted[j] = i; } fprintf(log, "thread_%d/%d_______|_%% of all_|___total (s)_|___us per call_|___# calls\n", thread + 1, omp_get_num_threads()); for (int j = 0; j < n_profile; j++) { const int i = i_sorted[j]; if (profile_count[i] == 0) continue; fprintf(log, "%16s |%9.3f |%12.3f |%14.3f |%10d\n", name[i], 100.0 * profile_time[i] / wall_time, profile_time[i] * SEC_PER_TICK, US_PER_TICK * profile_time[i] / profile_count[i], profile_count[i]); } fprintf(log, "---------------------------------------------------------------------\n"); } } } void profile_clear(void) { #pragma omp parallel { memset(profile_time, 0, n_profile * sizeof(tick_t)); memset(profile_count, 0, n_profile * sizeof(int)); } } #endif
C
#ifndef _LISTAGENERICA_ #define _LISTAGENERICA_ 1 #include "nodoGenerico.h" #include <stdlib.h> struct listadoble { struct nodo* start = nullptr; struct nodo* end = nullptr; int size = 0; bool isEmpty() { return size == 0; } int getSize() { return size; } void addToEnd(void* pData) { struct nodo* newNode = (struct nodo*)malloc(sizeof(struct nodo)); newNode->data = pData; if (size==0) { start = newNode; end = newNode; } else { newNode->previous = end; end->next = newNode; end = newNode; } size++; } void addToBegining(void* pData) { struct nodo* newNode = (struct nodo*)malloc(sizeof(struct nodo)); newNode->data = pData; if (size==0) { start = newNode; end = newNode; } else { newNode->next = start; start->previous = newNode; start = newNode; } size++; } void* removeFirst() { void* result = nullptr; struct nodo* cursor = start; if (size>1) { start->next->previous = nullptr; start = start->next; cursor->next = nullptr; result = cursor->data; } else if (size==1) { start = nullptr; end = nullptr; result = cursor->data; } size--; return result; } }; #endif
C
#include "../headers/player.h" #include "../headers/globals.h" #include "../headers/map.h" #include "../headers/lights.h" #include <string.h> void drawPlayerName(Player *player); void animateIdle(Player *player, float y); float fontScale = 352.38; float playerHeight = levelHeight*0.7; float maxIdleAnimationY = levelHeight*0.1; void drawPlayer(Player *player){ glPushMatrix(); GLfloat diffuse_coeffs[] = {player->color[0], player->color[1], player->color[2], 1 }; glMaterialfv(GL_FRONT, GL_DIFFUSE, diffuse_coeffs); set_player_materials(); float x = (float)player->positionX; x = x * floorScaleX ; float y = (float)player->positionY; y = y * levelHeight + floorScaleY/2 + playerHeight/2; if (player->coordinateY == -100) player->coordinateY = y + ((float)rand() / (float)RAND_MAX) * maxIdleAnimationY; if (player->coordinateX == -100){ player->velocityX = playerHeight/25; player->velocityY = 0.0024 * 5; player->coordinateX = x; } if (player->state == 0){ animateIdle(player, y); } glTranslatef(player->coordinateX, player->coordinateY, 0); glColor3f( player->color[0], player->color[1], player->color[2]); glutSolidSphere( playerHeight / 2, 50, 50); glPopMatrix(); } void animateIdle(Player *player, float y){ float realY = player->coordinateY + player->velocityY; if (realY >= y + maxIdleAnimationY || realY <= y){ player->velocityY *= -1; } player->coordinateY = realY; } void drawPlayerName(Player *player){ glColor3f(player->color[0], player->color[1], player->color[2]); for (int i=0; i<strlen(player->name); i++){ glutStrokeCharacter(GLUT_STROKE_ROMAN, player->name[i]); } glTranslatef(fontScale, playerHeight/100, 0); } void drawPlayerNames(){ glPushMatrix(); glTranslatef(0, -1, 0); glScalef(1/fontScale, 1/fontScale, 1/fontScale); drawPlayerName(player1); drawPlayerName(player2); drawPlayerName(player3); drawPlayerName(player4); glTranslatef(2*fontScale, 0, 0); glPopMatrix(); } Player *createPlayer(GLfloat color[3], char name[10]){ Player *player; player = (Player *) malloc(sizeof(Player)); player->color[0] = color[0]; player->color[1] = color[1]; player->color[2] = color[2]; player->positionX = 0; player->positionY = 0; player->coordinateX = -100; player->coordinateY = -100; player->velocityX = 0; player->velocityY = 0.0024; player->state = 0; memcpy(player->name, name, sizeof(char)* 10); return player; }
C
#include<stdlib.h> #include<stdio.h> #include<string.h> #define PRIME 100003 //Binary Pattern Searching Rabin Karp with Hash Table struct node{ int data; struct node* link; }; void append(struct node** head, int data) { struct node* new_node = (struct node*)malloc(sizeof(struct node)); struct node* last_node = (*head); new_node->data = data; new_node->link = NULL; if((*head) == NULL) { (*head) = new_node; return; } while (last_node->link != NULL) { last_node = last_node->link; } last_node->link = new_node; } int confirm(char* text, char* pattern[], struct node* table[], int y, int start_index) { int len_pat = strlen(pattern[0]); int found = -1; int check = 0; struct node* temp = table[y]; while(table[y] != NULL) { for(int j =0; j<len_pat; j++) { if(text[start_index+j]!=pattern[(table[y]->data)][j]) break; else check++; } if(check==len_pat) { printf("Match Found - At %d index, pattern '%s' is found. \n",start_index,pattern[(table[y]->data)]); found++; } check = 0; table[y] = table[y]->link; } table[y] = temp; return found; } void stringMatch(char* text, char* pattern[], struct node* table[]) { int len_pat = strlen(pattern[0]); int len_text = strlen(text); int match = -1; int y = (text[0]-'0'); int pow = 2; for(int i = 1; i<len_pat; i++) { y = (2*y + (text[i]-'0'))%PRIME; pow *= 2; } if(table[y]!=NULL) { int found = confirm(text,pattern,table,y,0); if(found!=-1) match++; } for(int i =1; i<len_text-len_pat+1; i++) { y = (2*y + (text[i+len_pat-1]-'0') - (pow*(text[i-1]-'0')))%PRIME; if(y<0) y += PRIME; if(table[y]!=NULL) { int found = confirm(text,pattern,table,y,i); if(found!=-1) match++; } } if(match == -1) printf("No match found\n"); } int main() { struct node* table[1000000]; char* text = "111011101111011101111011101111000111011101111011101111011101111"; char* pattern[1000] = {"111011101111011101111011101111","011101111011101111011101111000"}; for(int i=0; i<2; i++) { int N = (pattern[i][0]-'0'); int len_pat = strlen(pattern[i]); for(int j = 1; j<len_pat; j++) { N = (2*N + (pattern[i][j]-'0'))%PRIME; } append(&table[N],i); } stringMatch(text,pattern,table); return 0; }
C
#include <stdio.h> int main(){ int a = 1; int b = 4; int c = 6; char string[10] = "hello"; printf("Value of a: %d ,", a); printf("address of its memory: %p\n",&a); //printf("Value of b: %d ,", b); //printf("address of its memory: %p\n",&b); //printf("Value of c: %d ,", c); //printf("address of its memory: %p\n",&c); printf("Value of string: %s ,", string); printf("address of its memory: %p\n",&string); foo(); return 0; } void foo(){ int i = 5; int j = 7; int *ia = &i; int k; printf("Size of int: %d\n", sizeof(int)); printf("Value of i: %d ,", i); printf("address of its memory: %p\n", &i); printf("address of previous: %p\n", ia-1); printf("address of next: %p\n", ia+1); printf("Located there: %d\n", *(ia+1)); for(k = 0; k<30;k++){ printf("Found something: %d\n", *(ia+k)); } //printf("Value of j: %d ,", j); //printf("address of its memory: %p\n", &j); }
C
/****************************************************************/ /* NUMBERHANDLER.C */ /****************************************************************/ /* This module supplies routines for number handling. */ /* It consists of the following function: */ /* - digits_n(): it computes the number of digits of a given */ /* integer. */ /****************************************************************/ /****************************************************************/ /* 1. Inclusion of header files. */ /****************************************************************/ #include "../h/const.h" /****************************************************************/ /* 2. Inclusion of declarations that are being imported. */ /****************************************************************/ /****************************************************************/ /* 3. Definitions of variables to be exported. */ /****************************************************************/ /****************************************************************/ /* 4. Definitions of variables strictly local to the module. */ /****************************************************************/ /****************************************************************/ /* 5. Definitions of functions to be exported. */ /****************************************************************/ /* The following function computes the number of digits of a given */ /* integer. */ digits_n(n) int n; /* integer whose number of */ /* digits is to be computed */ { int digits; for (digits = 1; (n = n / NUMBASE) != 0; digits++); return(digits); } /****************************************************************/ /* 6. Definitions of functions strictly local to the module. */ /****************************************************************/
C
#include "test.h" #include <stdio.h> #include <string.h> int test_num = 0; void DECLARE_NEW_TEST(char *description) { printf("\x1b[33m"); printf("-----------------------------------%s-----------------------------------\n", description); printf("\033[0m"); } int assert_equals_int(char *file_name, int line_num, char* description, int val1, int val2) { test_num++; if (val1 == val2){ printf("\033[0;32m"); printf("%s", description); printf(" pass # %d\n", test_num); } else { printf("\033[0;31m"); printf("%s", description); printf(" fail # %d %s:%d\n", test_num, file_name, line_num); printf("\033[0m"); return 1; } printf("\033[0m"); return 0; } int assert_not_equals_int(char *file_name, int line_num, char* description, int val1, int val2) { test_num++; if (val1 == val2){ printf("\033[0;31m"); printf("%s", description); printf(" fail # %d %s:%d\n", test_num, file_name, line_num); printf("\033[0m"); return 1; } else { printf("\033[0;32m"); printf("%s", description); printf(" pass # %d\n", test_num); } printf("\033[0m"); return 0; } int assert_equals_str(char *file_name, int line_num, char* description, void *val1, void* val2, size_t size) { test_num++; if (!memcmp(val1, val2, size)) { printf("\033[0;32m"); printf("%s", description); printf(" pass # %d\n", test_num); } else { printf("\033[0;31m"); printf("%s", description); printf(" fail # %d %s:%d\n", test_num, file_name, line_num); printf("\033[0m"); return 1; } printf("\033[0m"); return 0; } int assert_not_equals_str(char *file_name, int line_num, char* description, void *val1, void* val2, size_t size) { test_num++; if (!memcmp(val1, val2, size)) { printf("\033[0;31m"); printf("%s", description); printf(" fail # %d %s:%d\n", test_num, file_name, line_num); printf("\033[0m"); return 1; } else { printf("\033[0;32m"); printf("%s", description); printf(" pass # %d\n", test_num); } printf("\033[0m"); return 0; } int assert_null(char *file_name, int line_num, char* description, void *val1) { test_num++; if (val1 != NULL) { printf("\033[0;31m"); printf("%s", description); printf(" fail # %d %s:%d\n", test_num, file_name, line_num); printf("\033[0m"); return 1; } else { printf("\033[0;32m"); printf("%s", description); printf(" pass # %d\n", test_num); } printf("\033[0m"); return 0; } int assert_not_null(char *file_name, int line_num, char* description, void *val1) { test_num++; if (val1 == NULL) { printf("\033[0;31m"); printf("%s", description); printf(" fail # %d %s:%d\n", test_num, file_name, line_num); printf("\033[0m"); return 1; } else { printf("\033[0;32m"); printf("%s", description); printf(" pass # %d\n", test_num); } printf("\033[0m"); return 0; }
C
#include <stdio.h> #include <unistd.h> /* Used also for parapeter passing with getopt */ #include <ctype.h> #include <string.h> #include <stdlib.h> #include <pthread.h> #include <time.h> #include <sys/time.h> #include <math.h> #include "lib/functionList.h" #include "lib/globalVars.h" #include "src/readAdjacencyMatrix.c" #include "src/threadInit.c" #include "src/farmer.c" int main(int argc, char **argv) { int returnCode =0; char argument; int argSize = 0; int temp; if ((argument = getopt (argc, argv, "t:")) != -1) { if (argument == 't') { /* If the user has typed -t as argument name. */ if(argSize=strlen(optarg)) { /* If the user has typed a value for the argument t. */ for(temp=0;temp<argSize;temp++) { /* Check if the input is composed of digits. */ if (!isdigit(optarg[temp])) { /* Non digit character found. Invalid input. */ printf("The value for argument t is not non-negative digits.\n"); printf("Please type -t [NUMBER] to set\n"); printf("the desired number of threads.\n"); returnCode = 100; } } if(!returnCode) { /* No error has been encountered. The input is in correct format. */ if(numberThreads = atoi(optarg)) { /* Positive number of threads. All is well. */ printf("The desired number of threads is %d.\n", numberThreads); } else { /* Non-positive number of threads. Failure. */ printf("The number for argument t is not positive.\n"); printf("Please type -t [POSITIVE NUMBER] to set\n"); printf("the desired number of threads.\n"); returnCode = 101; } } } else { /* The user has not specified a value for the argument t. */ printf("You have not inserted a value for argument t.\n"); printf("Please type -t [NUMBER] to set\n"); printf("the desired number of threads.\n"); returnCode = 102; } } else { printf("You have typed an invalid argument.\n"); printf("Please use option -t to set\n"); printf("the desired number of threads.\n"); returnCode = 103; } } else { printf("Thread number not specified.\n"); printf("Please use option -t to set\n"); printf("the desired number of threads.\n"); returnCode = 104; } if(!returnCode) { /* No error has been encountered. The input data is correct.. */ if(returnCode=readAdjacencyMatrix()) return returnCode; if(returnCode=threadInit()) return returnCode; } return returnCode; /* Return the proper code. 0 for success, other for failure. */ }
C
#include <stdio.h> #include <string.h> typedef unsigned char *byte_pointer; void show_bytes(byte_pointer start,int len){ int i; for (i=0;i<len;i++){ //显示为保留前面2位的16进制数 printf("%.2x",start[i]); } printf("\n"); } void show_int(int x){ show_bytes((byte_pointer) &x,sizeof(int)); } void show_float(float x){ show_bytes((byte_pointer) &x, sizeof(float)); } void show_pointer(void *x){ show_bytes((byte_pointer) &x, sizeof(void *)); } void show_short(short x){ show_bytes((byte_pointer) &x, sizeof(short)); } void show_long(long x){ show_bytes((byte_pointer) &x, sizeof(long)); } void show_double(double x){ show_bytes((byte_pointer) &x, sizeof(double)); } int main(){ int ival = 12345; float fval = (float) ival; int *pval = &ival; show_int(ival); show_float(fval); show_pointer(pval); //我的测试 short s = 5555; long l = 1243454566734; double d = 12.234; show_short(s);//两个字节长 show_long(l); show_double(d); printf("%d", sizeof(short)); printf("%d", sizeof(int)); printf("%d", sizeof(long)); printf("%d", sizeof(float)); printf("%d", sizeof(double)); return 0; }
C
#include "../example1.h" #include <time.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wimplicit-function-declaration" void wait_for(double secs) { clock_t start_time = clock(); double sec_diff = 0; while(sec_diff < secs) { clock_t now_time = clock(); sec_diff = ((double) (now_time - start_time)) / CLOCKS_PER_SEC; } } void effect(struct razer_chroma *chroma) { struct razer_rgb col; col.g = 255; col.b = 0; col.r = 0; struct razer_pos pos0; struct razer_pos pos1; struct razer_pos pos2; struct razer_pos pos3; struct razer_pos pos4; struct razer_pos pos5; struct razer_pos pos6; struct razer_pos pos7; struct razer_pos pos8; struct razer_pos pos9; struct razer_pos logopos; int r,g,b,c; int ymod = 1; int xmod = 1; pos0.x = 10; pos0.y = 3; logopos.x = 20; logopos.y = 0; int cmod = 20; pos1 = pos0; pos2 = pos1; pos3 = pos2; pos4 = pos3; pos5 = pos4; pos6 = pos5; pos7 = pos6; pos8 = pos7; pos9 = pos8; while(1) { pos0.x += xmod; pos0.y += ymod; pos9 = pos8; pos8 = pos7; pos7 = pos6; pos6 = pos5; pos5 = pos4; pos4 = pos3; pos3 = pos2; pos2 = pos1; pos1 = pos0; if(pos0.x >= 28 || pos0.x < 1) pos0.x = 0; if(pos0.y >= 5 || pos0.y < 1) ymod *= -1; razer_clear_all(chroma->keys); razer_set_key_pos(chroma->keys,&pos0,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos1,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos2,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos3,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos4,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos5,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos6,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos7,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos8,&col); col.b += cmod; razer_set_key_pos(chroma->keys,&pos9,&col); col.b -= 9*cmod; razer_set_key_pos(chroma->keys,&logopos,&col); razer_update_keys(chroma,chroma->keys); wait_for(0.05); } } #pragma GCC diagnostic pop #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-parameter" int main(int argc,char *argv[]) { struct razer_chroma *chroma = razer_open(); if(!chroma) exit(1); razer_set_custom_mode(chroma); razer_clear_all(chroma->keys); razer_update_keys(chroma,chroma->keys); effect(chroma); razer_close(chroma); } #pragma GCC diagnostic pop
C
#include <stdio.h> #include <stdlib.h> int main(int argc, char* argv[]) { int nf = argc - 1; if (nf < 1) { printf("you need to provide some floating-point numbers as arguments!\n"); } double * fs = malloc(nf * sizeof(double)); for (int i=0; i<nf; i++) { fs[i] = atof(argv[i+1]; printf("fs[%d]=%f\n",i,fs[i]); } free(fs); printf("all done\n"); return 0; }
C
#ifndef FONCTIONS_H #define FONCTIONS_H #include "macros.h" #include <gtk/gtk.h> #include <string.h> #include <stdarg.h> typedef GtkWidget Widget; typedef gboolean boolean; //// Initialisation /////////////////////////////////////////////////////// #define initialiser(argc, argv) gtk_init(argc, argv) #define boucle_principale() gtk_main() //// DIMENSIONS /////////////////////////////////////////////////////////// typedef struct { int l; // largeur int L; // Longueur } Dimensions; //// FENETRE ////////////////////////////////////////////////////////////// /** Entrées : * titre : Le titre de la fenetre * icon : le chemin de l'icon * redimonsionable : indique si la fenetre peut etre redimonsionée * padding : espace entre le bord de la fenetre et son contenu * estPrincipale : ferme le programe * Description : * Cree une fenetre */ func_declare(Widget*, fenetre_creer, char *titre; char *icon; boolean redimonsinable; boolean estPrincipale; int padding; Dimensions dim;) #define fenetre_creer(...) func_link(fenetre_creer, __VA_ARGS__) func_head(Widget*, fenetre_creer) { // Valeurs par défault des pramètres char* param_default(titre, ""); char* param_default(icon, ""); boolean param_default(redimonsinable, TRUE); int param_default(padding, 10); boolean param_default(estPrincipale, FALSE); Dimensions dim; param_default(dim.l, 200); param_default(dim.L, 400); // Création de la fenetre GtkWidget *widget = gtk_window_new(GTK_WINDOW_TOPLEVEL); GtkWindow *win = GTK_WINDOW(widget); //// Titre gtk_window_set_title(win, titre); //// Icon if(strlen(icon) > 0) gtk_window_set_icon_from_file(win, icon, NULL); //// Dimensions gtk_window_set_default_size(win, dim.l, dim.L ); //// Redimonsionable gtk_window_set_resizable(win, redimonsinable); //// Fermer le programme lors de la femeture if(estPrincipale) gtk_signal_connect(GTK_OBJECT(widget), "destroy", G_CALLBACK(gtk_main_quit), NULL); //// padding gtk_container_set_border_width(GTK_CONTAINER(widget), padding); return widget; } #define fenetre_afficher(fen) gtk_widget_show_all(fen) //// Conteneur //////////////////////////////////////////////////////////// /** Description : * Ajoute le widget contenu dans le conteneur (fenetre, layout) */ #define conteneur_ajouter(conteneur, contenu) \ gtk_container_add(GTK_CONTAINER(conteneur), contenu) /** Conteneur horizontal **/ func_declare(Widget*, conteneur_h_creer, int espacement; boolean homogene;) #define conteneur_h_creer(...) func_link(conteneur_h_creer, __VA_ARGS__) func_head(Widget*, conteneur_h_creer) { int param_default(espacement, 5); boolean param_default(homogene, FALSE); return gtk_hbox_new(homogene, espacement); } /** Conteneur vertical **/ func_declare(Widget*, conteneur_v_creer, int espacement; boolean homogene;) #define conteneur_v_creer(...) func_link(conteneur_v_creer, __VA_ARGS__) func_head(Widget*, conteneur_v_creer) { int param_default(espacement, 5); boolean param_default(homogene, FALSE); return gtk_vbox_new(homogene, espacement); } //// BOUTON /////////////////////////////////////////////////////////////// /** Entrées : * texte : texte du bouton * icon : icon du bouton * callback : fonction appele lorsque le bouton est cliqué * data : parametere pour le callback * Description : * Cree un bouton */ func_declare(Widget*, bouton_creer, char *texte; char *icon; void (*callback)(Widget* widget, void* data); void* data;) #define bouton_creer(...) func_link(bouton_creer, __VA_ARGS__) func_head(Widget*, bouton_creer) { char* param_default(texte, ""); char* param_default(icon, ""); void* param_default(callback, NULL); void* param_default(data, NULL); Widget* bouton = gtk_button_new_with_label(texte); if(strlen(icon)) gtk_button_set_image(GTK_BUTTON(bouton), gtk_image_new_from_file(icon)); if(callback) g_signal_connect(GTK_OBJECT(bouton), "clicked", callback, data); return bouton; } //// CHECKBOX ///////////////////////////////////////////////////////////// /** Entrées : * text : texte à afficher * Description : * Cree une case a cocher avec le texte text */ Widget* checkbox_creer(char *text) { Widget *checkbox = gtk_check_button_new_with_label(text); return checkbox; } //// MENU ///////////////////////////////////////////////////////////////// /** Entrées : * nombreElements : le nombre d'éléments du menu * ... : les elements de type char* * Description : * Cree un menu déroulant */ Widget* menu_creer(int nombreElements, ...) { Widget *menu = gtk_combo_box_new_text(); va_list args; int i; va_start(args, nombreElements); for (i = 0; i < nombreElements; ++i) gtk_combo_box_append_text(GTK_COMBO_BOX(menu), va_arg(args, char*)); va_end(args); gtk_combo_box_set_active(GTK_COMBO_BOX(menu), 0); return menu; } #define menu_ajouter(menu, text) \ gtk_combo_box_append_text(GTK_COMBO_BOX(menu), text); #endif // FONCTIONS_H
C
#include "assert.h" void main() { int n = __VERIFIER_nondet_int(); int result = 0; __VERIFIER_assume(n >= 0); __VERIFIER_assume(LARGE_INT > n); for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { for(int k = 0; k < n; k++) { result++; } } } __VERIFIER_assert(result == n * n * n); }
C
#include<stdio.h> int main() { int i,key,low,high,mid,flag; int arr[]={10,15,25,35,63,98}; int n=sizeof(arr)/sizeof(arr[0]); printf("\n size of an array is=%d",n); printf("\n enter element you want to search:"); scanf("%d",&key); low=0; high=n-1; while(low<=high) { mid=(low+high)/2; if(key<arr[mid]) { high=mid-1; } else if(key>arr[mid]) { low=mid+1; } else if(key==arr[mid]) { printf("element fount at %d",mid); flag=1; break; } } if(flag!=1) { printf("element not found."); } }
C
/** * Note: The returned array must be malloced, assume caller calls free(). */ int comp(const void* a, const void* b) { return ((int*)b)[1] - ((int*)a)[1]; } int* rearrangeBarcodes(int* barcodes, int barcodesSize, int* returnSize){ /* cnts[i][1]是数字cnts[i][0]在barcodes中出现的次数 */ int cnts[10001][2] = {0}; for (int i = 0; i < 10001; i++) { cnts[i][0] = i; cnts[i][1] = 0; } for (int i = 0; i < barcodesSize; i++) { cnts[barcodes[i]][1]++; } /* 按出现次数大到小排序 */ qsort(cnts, 10001, sizeof(cnts[0]), comp); /* 按隔一个插一个的方式将数字隔开 */ int* ans = (int*)malloc(sizeof(int)*barcodesSize); int n = 0; for (int i = 0; i < 10001; i++) { if (cnts[i][1] == 0) { break; } for (int j = 0; j < cnts[i][1]; j++) { if (n >= barcodesSize) { n = 1; } ans[n] = cnts[i][0]; n += 2; } } *returnSize = barcodesSize; return ans; }
C
#include <arpa/inet.h> #include <errno.h> #include <netinet/in.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #pragma pack(1) char *format(char *name); typedef struct sockaddr SA; typedef struct { unsigned short transaction_id; unsigned short flags; unsigned short questions; unsigned short answers; unsigned short auths; unsigned short adds; } Header; typedef struct { char *name; unsigned short type; unsigned short class; } Query; /************************************************ *packet helper function * * ***********************************************/ /**/ // ./mydns cs.fiu.edu 202.12.27.33 int main(int argc, char **argv) { if (argc != 3) { printf("usage:%s hostname rootip\n", argv[0]); exit(EXIT_FAILURE); } char *hostname = argv[1]; char serverip[255]; strcpy(serverip, argv[2]); ssize_t retval = 0; int sockfd; retval = socket(AF_INET, SOCK_DGRAM, 0); if (retval == -1) { perror("create socket"); exit(EXIT_FAILURE); } sockfd = retval; struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(53); while (1) { printf("----------------------------\n"); printf("DNS server to query: %s\n", serverip); retval = inet_aton(serverip, &(servaddr.sin_addr)); if (retval == 0) { fprintf(stderr, "root ip is not valid\n"); exit(EXIT_FAILURE); } unsigned char req[512]; unsigned char resp[512]; int len = 0; Header a = {htons(23), 0, htons(1), 0, 0, 0}; Query q = {format(hostname), htons(1), htons(1)}; memcpy(req, &a, sizeof(Header)); len = len + sizeof(Header); memcpy(req + len, q.name, strlen(q.name) + 1); len = len + strlen(q.name) + 1; memcpy(req + len, &(q.type), 2); len += 2; memcpy(req + len, &(q.class), 2); len += 2; struct timeval tv; tv.tv_sec = 2; tv.tv_usec = 0; if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) { printf("socket option SO_RCVTIMEO not support\n"); exit(1); } while (1) { retval = sendto(sockfd, req, len, 0, (SA *)(&servaddr), sizeof(servaddr)); if (retval == 0) { perror("send to server failere"); exit(EXIT_FAILURE); } ssize_t len1 = sizeof(servaddr); retval = recvfrom(sockfd, resp, 512, 0, (SA *)(&servaddr), (socklen_t *)(&len1)); if (retval < 0) { if (errno == EWOULDBLOCK || errno == EAGAIN) continue; else { printf("recvfrom err:%d\n", errno); exit(1); } } break; } Header *h = (Header *)resp; int answer_count = ntohs(h->answers); int auth_count = ntohs(h->auths); int add_count = ntohs(h->adds); printf("Reply received. Content overview:\n"); printf("%02d Answers.\n", answer_count); printf("%02d Intermediate Name Servers.\n", auth_count); printf("%02d Additional Information Records.\n", add_count); printf("%d\n", len); printf("Answers Section:\n"); unsigned char *index = resp + len; unsigned char *temp = resp + len; for (int i = 0; i < answer_count; i++) { int count = 0; char name[255]; int is_offset = 0; int is_first = 1; while (1) { char c = *index; if (c == '\0') { name[count++] = '\0'; break; } if (c > 0 && c < 64) { index++; if (is_offset == 0) temp++; if (is_first == 0) name[count++] = '.'; is_first = 0; for (int i = 0; i < c; i++) { name[count++] = *index; index++; if (is_offset == 0) temp++; } } else { unsigned short offset = *((unsigned short *)index); offset = ntohs(offset) & 16383; if (is_offset == 0) temp = index + 2; index = resp + offset; is_offset = 1; } } temp = temp + 10; char *answerip = inet_ntoa(*((struct in_addr *)temp)); printf("Name:%s IP: %s\n", name, answerip); temp = temp + 4; index = temp; } printf("Authoritive Section:\n"); for (int i = 0; i < auth_count; i++) { int count = 0; char name[255]; char servername[255]; int is_first = 1; int is_offset = 0; while (1) { char c = *index; if (c == '\0') { name[count++] = '\0'; break; } if (c > 0 && c < 64) { index++; if (is_offset == 0) temp++; if (is_first != 1) name[count++] = '.'; is_first = 0; for (int i = 0; i < c; i++) { name[count++] = *index; index++; if (is_offset == 0) temp++; } } else { unsigned short offset = *((unsigned short *)index); offset = ntohs(offset) & 16383; if (is_offset == 0) temp = index + 2; index = resp + offset; is_offset = 1; } } if (is_offset == 0) { index++; temp++; } temp = temp + 10; index = temp; count = 0; is_first = 1; is_offset = 0; while (1) { char c = *index; if (c == '\0') { servername[count++] = '\0'; break; } if (c > 0 && c < 64) { index++; if (is_offset == 0) temp++; if (is_first != 1) servername[count++] = '.'; is_first = 0; for (int i = 0; i < c; i++) { servername[count++] = *index; index++; if (is_offset == 0) temp++; } } else { unsigned short offset = *((unsigned short *)index); offset = ntohs(offset) & 16383; if (is_offset == 0) temp = index + 2; index = resp + offset; is_offset = 1; } } printf("Name:%s Name Server: %s\n", name, servername); if (is_offset == 0) { index++; temp++; } index = temp; } printf("Additional Information Section:\n"); for (int i = 0; i < add_count; i++) { int count = 0; char name[255]; int is_first = 1; int is_offset = 0; while (1) { char c = *index; if (c == '\0') { name[count++] = '\0'; break; } if (c > 0 && c < 64) { index++; if (is_offset == 0) temp++; if (is_first == 0) name[count++] = '.'; is_first = 0; for (int i = 0; i < c; i++) { name[count++] = *index; index++; if (is_offset == 0) temp++; } } else { unsigned short offset = *((unsigned short *)index); offset = ntohs(offset) & 16383; if (is_offset == 0) temp = index + 2; index = resp + offset; is_offset = 1; } } if (is_offset == 0) { index++; temp++; } temp = temp + 8; unsigned short data_len = ntohs(*((unsigned short *)temp)); temp = temp + 2; printf("Name:%s", name); if (data_len != 4) { temp = temp + data_len; } else { char *answerip = inet_ntoa(*((struct in_addr *)temp)); printf(" IP: %s", answerip); temp = temp + 4; if (i == 0) strcpy(serverip, answerip); } index = temp; printf("\n"); } if (answer_count != 0) break; } return 0; } char *format(char *name) { char *format_name = malloc(strlen(name) + 2); strcpy(format_name + 1, name); format_name[0] = '.'; int len = strlen(name); char count = 0; for (int i = len; i >= 0; i--) { if (format_name[i] == '.') { format_name[i] = count; count = 0; } else { count++; } } return format_name; }
C
//01 #include<stdio.h> int main (void) { int cus_typ; float bill_amt; float charge; float discount = 0; printf("Customer Type : "); // input customer type scanf(" %d" , &cus_typ); printf("Bill Amount :RS. "); //Input Number of units scanf(" %f" , &bill_amt ); if(cus_typ == 1) { if(bill_amt <= 2500) { discount = bill_amt * 5.00 /100; } else if(bill_amt > 2500) { discount = bill_amt * 10.00 /100; } } else { if(bill_amt > 5000) { discount = bill_amt * 10 / 100; } else { discount = 0; } } printf("Discount Amount :Rs.%.2f\n" , discount); charge = bill_amt - discount; printf("Final Bill Amount :RS. %.2f \n", charge ); return 0; }
C
#include <stdio.h> int main(int argc, char const *argv[]) { // Test 1 // char phrase1[]="ordinateur\0"; // char phrase2[]="dur notaire\0"; // Test 2 char phrase1[]="ordinateur\0"; char phrase2[]="dur notaire\0"; int i,j; char courant1, courant2; int trouve; // Retourner vrai si chacun des caractères de phrase1 apparait // au moins une fois dans phrase2 i = 0; courant1 = phrase1[0]; trouve=1; while ((courant1!='\0')&&(trouve)) { // Vérifier si courant1 est dans phrase 2 j = 0; courant2 = phrase2[0]; trouve = 0; // caractère courant1 trouvé dans phrase2 while ((courant2!='\0')&(!trouve)) { trouve = (courant1 == courant2); printf("On compare %c ==? %c\n", courant1, courant2); if (!trouve) { j++; courant2 = phrase2[j]; } } // si le caractère courant1 appartient à la phrase2 // passer au caractère suivant if (!trouve) printf("%c n'est pas dans la phrase 2\n", courant1); if (trouve) { printf ("%c est dans la phrase 2\n", courant1); i++; courant1 = phrase1[i]; } } if (trouve) printf("Les caractères de phrase1 apparaissent au moins une fois dans phrase2\n"); if (!trouve) printf("Caractères de phrase1 qui n'apparaissent pas au moins dans phrase2\n"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* syntax_checker_utils.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: aclose <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/08/24 21:59:16 by aclose #+# #+# */ /* Updated: 2021/08/24 21:59:17 by aclose ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" void skip_blank_tokens(t_token **tokens) { while (*tokens && (*tokens)->type == T_BLANK) (*tokens) = (*tokens)->next; } t_bool token_contains_a_string(t_token *token) { t_token_type type; if (!token) return (FALSE); type = token->type; if (type == T_GENERAL || type == T_DQUOTE || type == T_SQUOTE) return (TRUE); return (FALSE); } t_bool line_contains_only_blanks(char *line) { while (*line) { if (*line != ' ' && *line != '\t') return (FALSE); line++; } return (TRUE); }
C
/* ************************************************************************** */ /* */ /* :::::::: */ /* parse_camera.c :+: :+: */ /* +:+ */ /* By: jsaariko <[email protected]> +#+ */ /* +#+ */ /* Created: 2020/06/21 17:57:23 by jsaariko #+# #+# */ /* Updated: 2020/06/21 17:59:03 by jsaariko ######## odam.nl */ /* */ /* ************************************************************************** */ #include "error.h" #include "parse.h" t_camera *get_camera(char *line) { size_t i; t_camera *cam; cam = (t_camera *)e_malloc(sizeof(t_camera)); if (cam == NULL) error_exit_errno(); i = 0; cam->pos = get_vec(line, &i); cam->orien = get_vec(line, &i); validate_orien(&cam->orien); cam->fov = get_int(line, &i); if (cam->fov <= 0 || cam->fov >= 180) error_exit_msg(C_INVALID_FOV, E_INVALID_FOV); if (line[i] != '\0') error_exit_msg(C_INVALID_CAM, E_INVALID_CAM); cam->next = NULL; return (cam); } t_camera *add_camera(char *line, t_camera *first_camera) { t_camera *new_cam; t_camera *cur; cur = first_camera; new_cam = get_camera(line); if (first_camera == NULL) first_camera = new_cam; else { while (cur->next != NULL) cur = cur->next; cur->next = new_cam; } return (first_camera); }
C
/* seq.c */ /* Sequences of types. */ #include <stdio.h> #include <stdlib.h> #include <stddef.h> #include <string.h> #include <ctype.h> /* Return the chartype of a char. */ int alpha(int c) { return isalpha(c) ; } int digit(int c) { return isdigit(c) ; } int punct(int c) { return ispunct(c) ; } int space(int c) { return isspace(c) ; } char type(char c) { char ret; if ( isalpha(c) ) ret = 'a' ; else if ( isdigit(c) ) ret = 'd' ; else if ( ispunct(c) ) ret = 'p' ; else if ( isspace(c) ) ret = 's' ; return ret; } typedef struct foo { char c; char (*myfuncptr)(char) ; /* Func pointer returning a char */ } a_foo ; /* Sequence function. */ /* Sequences of foos, each with their type. */ int main() { int a = alpha('h') ; printf("Result: %d \n", a ) ; char z = type('h') ; printf("Result: %c \n", z ) ; char q = type('5') ; printf("Result: %c \n", q ) ; char r = type('#') ; printf("Result: %c \n", r ) ; char t = type(' ') ; printf("Result: %c \n", t ) ; int b = alpha('5') ; printf("Result: %d \n", b ) ; int c = digit('5') ; printf("Result: %d \n", c ) ; int d = digit('a') ; printf("Result: %d \n", d ) ; int e = punct('*') ; printf("Result: %d \n", e ) ; int f = punct('8') ; printf("Result: %d \n", f ) ; int g = space(' ') ; printf("Result: %d \n", g ) ; int h = space('@') ; printf("Result: %d \n", h ) ; return 0; }
C
// HunterView.c ... HunterView ADT implementation #include <stdlib.h> #include <stdio.h> #include <assert.h> #include "Globals.h" #include "Game.h" #include "GameView.h" #include "HunterView.h" #include "Queue.h" #include "Queue.c" #include <string.h> // #include "Map.h" ... if you decide to use the Map ADT struct hunterView { GameView g; PlayerMessage *messages; }; // Creates a new HunterView to summarise the current state of the game HunterView newHunterView(char *pastPlays, PlayerMessage messages[]) { HunterView hunterView = malloc(sizeof(struct hunterView)); assert(hunterView!=NULL); hunterView->g = newGameView(pastPlays,messages); int rounds = giveMeTheRound(hunterView); hunterView->messages = malloc(sizeof(PlayerMessage)*rounds); int i; for (i=0;i<rounds;i++) { strncpy(hunterView->messages[i], messages[i], MESSAGE_SIZE); } return hunterView; } // Frees all memory previously allocated for the HunterView toBeDeleted void disposeHunterView(HunterView toBeDeleted) { disposeGameView(toBeDeleted->g); free(toBeDeleted->messages); free(toBeDeleted); } //// Functions to return simple information about the current state of the game // Get the current round int giveMeTheRound(HunterView currentView) { return getRound(currentView->g); } // Get the id of current player PlayerID whoAmI(HunterView currentView) { return getCurrentPlayer(currentView->g); } // Get the current score int giveMeTheScore(HunterView currentView) { return getScore(currentView->g); } // Get the current health points for a given player int howHealthyIs(HunterView currentView, PlayerID player) { return getHealth(currentView->g, player); } // Get the current location id of a given player LocationID whereIs(HunterView currentView, PlayerID player) { return getLocation(currentView->g, player); } //// Functions that return information about the history of the game // Fills the trail array with the location ids of the last 6 turns void giveMeTheTrail(HunterView currentView, PlayerID player, LocationID trail[TRAIL_SIZE]) { return getHistory(currentView->g, player, trail); } //// Functions that query the map to find information about connectivity // What are my possible next moves (locations) LocationID *whereCanIgo(HunterView currentView, int *numLocations, int road, int rail, int sea) { fprintf(stderr,"damPlayer:%d\n",getCurrentPlayer(currentView->g)); return whereCanTheyGo(currentView, numLocations, getCurrentPlayer(currentView->g), road, rail, sea); } // What are the specified player's next possible moves LocationID *whereCanTheyGo(HunterView currentView, int *numLocations, PlayerID player, int road, int rail, int sea) { int i, numValidLocations, index; LocationID forbidden; LocationID *validLocations; fprintf(stderr,"From:%d , player:%d\n",getLocation(currentView->g, player),player); LocationID *locations = connectedLocations(currentView->g, numLocations, getLocation(currentView->g, player), player, getRound(currentView->g), road, rail, sea); if(player == PLAYER_DRACULA){ forbidden = ST_JOSEPH_AND_ST_MARYS; } numValidLocations = 0; for(i = 0; i < (*numLocations); i++){ if(locations[i] != forbidden){ numValidLocations++; } } index = 0; validLocations = malloc(sizeof(LocationID) * numValidLocations); for(i = 0; i < numValidLocations; i++){ if(locations[i] != forbidden){ validLocations[index] = locations[i]; index++; } } free(locations); *numLocations = numValidLocations; return validLocations; } // find a path between two vertices using breadth-first traversal int findPath(HunterView h, LocationID src, LocationID dest, int *path, int road, int rail, int sea) { printf("finding path from %d to %d\n",src,dest); if(src==dest) { printf("trying to get to where you are\n"); path[1] = dest; return 1; } int tmp_city = src; // Temporary store of path_distance for calculations int tmp_distance = 0; int path_distance = 0; // Array of visited cities, if not visited 0, else 1 int visited[NUM_MAP_LOCATIONS] = {0}; // Stores index of the previous city, default value -1 int prev[NUM_MAP_LOCATIONS] = {[0 ... (NUM_MAP_LOCATIONS-1)] = -1}; Queue cityQ = newQueue(); QueueJoin(cityQ, src); // While Queue is not empty and the tmp_city is not the destination city (e.g. when path to destination city from src is found) while (QueueIsEmpty(cityQ) == 0 && tmp_city != dest) { tmp_city = QueueLeave(cityQ); int num_locs; int *locs = connectedLocations(h->g, &num_locs,tmp_city, whoAmI(h), giveMeTheRound(h),road,rail,sea); int i; for (i=0;i<num_locs;i++) { if (!visited[locs[i]]) { QueueJoin(cityQ, locs[i]); prev[locs[i]] = tmp_city; visited[locs[i]] = 1; } } if (tmp_city == dest) { prev[locs[i]] = tmp_city; // Calculating size of path int index = locs[i]; while (index != src) { index = prev[index]; path_distance++; } // Building path array, storing destination first tmp_distance = path_distance-1; path[tmp_distance] = dest; tmp_distance--; // Storing rest of array index = prev[dest]; while (tmp_distance >= 0) { path[tmp_distance] = index; index = prev[index]; tmp_distance--; } break; } } printf("path->"); int j; for(j=0;j<path_distance;j++) { printf("%d->",path[j]); } printf("x\n"); return path_distance; }
C
#include <stdio.h> #include <stdlib.h> struct list { int data; struct CircularLinkedList *next; }; struct CircularLinkedList *head=NULL; void insert(int value){ struct list *node, *i; node = (struct list*)malloc(sizeof(struct list)); node->data = value; node->next = NULL; if(head==NULL){ head = node; node->next = head; printf("\nNew node (%d), {head:%d, next:%d}, inserted at begining of linked list.\n",value, head, node->next); } else{ i = head; while(i->next != head){ i=i->next; } node->next = head; i->next = node; printf("\nNew node (%d), inserted at end\n",value); } } void printList(){ if(head == NULL){ printf("\nList Empty\n"); }else{ struct list *i; int j = 8; i=head; while(j){ printf("\n {address:%d,data:%d,next:%d}",i,i->data,i->next); i = i->next; j--; } } } int main() { insert(2); insert(4); insert(6); insert(8); printList(); return 0; }
C
#include<stdio.h> int main(void) { char ch; int count = 0; while((ch = getchar()) != '#') { count++; printf(" %c:%d %s", ch, ch, (count % 8 == 0) ? "\n" : ""); } printf("Bye.\n"); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> int main () { int number,playernumber,level,methode,attempts=0; srand(time(NULL)); system("cls"); printf("welcome to less or more game\n\n"); printf("plz chose if you want to play with the computer or with a friend\n"); printf("to play with the computer chose 1\n"); printf("to play with a friend chose 2\n"); scanf("%d",&methode); switch (methode) { case 1: printf("----you are now playing with the computer----\n\n"); printf("chose your level to play\n"); printf("level 1: the number will be from 0 to 100 \n"); printf("level 2: the number will be from 0 to 1000 \n"); printf("level 3: the number will be from 0 to 10000 \n"); printf("which level do you want?\n"); scanf("%d",&level); switch (level) { case 1: printf("you just selected level 1\n\n"); number = rand() % 100; do{ attempts++; printf("what is the number that the computer chosen ?\n"); scanf("%d",&playernumber); if (playernumber==number) { printf("bravo you won\n"); printf("you did it in %d attempts ",attempts); } else if (playernumber<number) { printf("it's more then that \n"); } else { printf("it's less then that \n"); } } while (playernumber!=number); break; case 2: printf("you just selected level 2\n\n"); number = rand() % 1000; do{ attempts++; printf("what is the number that the computer chosen ?\n"); scanf("%d",&playernumber); if (playernumber==number) { printf("bravo you won\n"); printf("you did it in %d attempts",attempts); } else if (playernumber<number) { printf("it's more then that \n"); } else { printf("it's less then that \n"); } } while (playernumber!=number); break; case 3: printf("you just selected level 3\n\n"); number = rand() % 10000; do{ attempts++; printf("what is the number that the computer chosen ?\n"); scanf("%d",&playernumber); if (playernumber==number) { printf("bravo you won\n"); printf("you did it in %d attempts",attempts); } else if (playernumber<number) { printf("it's more then that \n"); } else { printf("it's less then that \n"); } } while (playernumber!=number); break; default: printf("the level you selected is not available\n\n"); break; } break; case 2: printf("you just choosen to play with a friend\n\n"); printf("plz select your random number :"); scanf("%d",&number); system("cls"); printf("your friend just choosen a random number now guess it ?\n"); do{ attempts++; printf("what is the number that your friend chosen ?\n"); scanf("%d",&playernumber); if (playernumber==number) { printf("bravo you won\n"); printf("you did it in %d attempts",attempts); } else if (playernumber<number) { printf("it's more then that \n"); } else { printf("it's less then that \n"); } } while (playernumber!=number); break; default: break; } return 0; }
C
/* * SEQUENTIAL TCP SERVER * Distributed Programming I * Exercise2.3 Iterative File Transfer TCP Server * * File name: server1_main.c * Programmer: Victor Cappa * Date last modification: 15/05/2019 * */ #include <stdlib.h> #include <string.h> #include <inttypes.h> #include <sys/stat.h> #include <errno.h> #include <syslog.h> #include <unistd.h> #include <stdio.h> #include <bits/types/FILE.h> #include <sys/socket.h> #include <sys/select.h> #include <sys/wait.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <limits.h> #include "protocol.h" #define SERVERBUFLEN 4096 #define MAX_LEN_FILE_NAME 200 char *program_name; int get_request(int connected_socket, char* buffer, char* file_name) { ssize_t new_received; size_t to_read = SERVERBUFLEN; char* buf_cursor = buffer; struct timeval timer; fd_set socket_reading; int outcome = 0; /* get the request from the client */ while (1) { FD_ZERO(&socket_reading); FD_SET(connected_socket, &socket_reading); timer.tv_sec = 15; timer.tv_usec = 0; outcome = Select(FD_SETSIZE, &socket_reading, NULL, NULL, &timer); if (outcome <= 0) { /* timeout expired or error happened */ return -1; } else { new_received = recv(connected_socket, buf_cursor, to_read, 0); if (new_received <= 0) { return -1; } if(buf_cursor[new_received - 2] == '\r' && buf_cursor[new_received - 1] == '\n') { /* termination of reading request is reached */ break; } /* continue with the reading loop */ buf_cursor += new_received; to_read -= new_received; if(to_read <= 0) { /* request message is longer than SERVERBUFLEN bytes and thus is illegal */ printf("Waiting for a request from client but received an invalid request.\n"); return -1; } } } /* extrapolate the file name */ int count = 0; if(buffer[0] == 'G' && buffer[1] == 'E' && buffer[2] == 'T' && buffer[3] == ' ') { for(int i = 4; buffer[i] != '\r'; ++i) { file_name[count++] = buffer[i]; if (count == (MAX_LEN_FILE_NAME - 1)) break; } file_name[count] = '\0'; return count; } else { /* invalid request to server */ printf("Waiting for a request from client but received an invalid request.\n"); return -1; } } int get_file_timestamp (const char* file_name, uint32_t* timestamp, uint32_t* file_size) { struct stat my_stat; char file_path[100]; uint32_t tmp = 0, size = 0; if (getcwd(file_path, sizeof(file_path)) == NULL) { return -1; } if (strcat(file_path, "/") == NULL) { return -1; } if (strcat(file_path, file_name) == NULL) { return -1; } if(stat(file_path, &my_stat) == -1) { return -1; } tmp = (uint32_t) my_stat.st_mtime; *timestamp = tmp; size = (uint32_t) my_stat.st_size; *file_size = size; return 1; } int send_file(int connected_socket, char* buffer, FILE* fd_file, uint32_t timestamp_file, uint32_t file_size) { int outcome = 0; /* send heading of file transfer */ uint32_t n_characters_net = htonl(file_size); char* cursor = (char* ) &n_characters_net; buffer[0] = '+'; buffer[1] = 'O'; buffer[2] = 'K'; buffer[3] = '\r'; buffer[4] = '\n'; memcpy(&buffer[5], &cursor[0], 4); outcome = send_n(connected_socket, buffer, 9); if(outcome <= 0) { return -1; } int iterations = (int) (file_size / SERVERBUFLEN); for (int a = 0; a < iterations; ++a) { size_t eff_read = fread(buffer, sizeof(char), SERVERBUFLEN, fd_file); if (eff_read != SERVERBUFLEN) { /* error while reading the file on the file system */ return -1; } outcome = send_n(connected_socket, buffer, SERVERBUFLEN); if (outcome <= 0) { /* error while sending the file */ return -1; } } if ((file_size % SERVERBUFLEN) != 0) { size_t eff_read = fread(buffer, sizeof(char), file_size % SERVERBUFLEN, fd_file); if (eff_read != (file_size % SERVERBUFLEN)) { /* error while reading the file on the file system */ return -1; } outcome = send_n(connected_socket, buffer, file_size % SERVERBUFLEN); if (outcome <= 0) { /* error while sending the file */ return -1; } } /* send timestamp of last file modification */ uint32_t timestamp_file_net = htonl(timestamp_file); cursor = (char* ) &timestamp_file_net; memcpy(&buffer[0], &cursor[0], 4); outcome = send_n(connected_socket, buffer, 4); if (outcome <= 0) { /* error while sending the file */ return -1; } return 1; /* success in sending the file */ } /* returned -1 in case of error */ int send_error_message(int connected_socket) { const char error_message[] = "-ERR\r\n"; size_t error_message_len = 6; int outcome = send_n(connected_socket, (const char* )error_message, error_message_len); return outcome; } int service_server (int connected_socket) { /* serve the client on socket s */ char file_name[MAX_LEN_FILE_NAME + 1]; file_name[MAX_LEN_FILE_NAME] = '\0'; char buffer[SERVERBUFLEN + 1]; buffer[SERVERBUFLEN] = '\0'; uint32_t file_size = 0; int outcome = 0; while(1) { /* receive request from client */ int file_name_len = get_request(connected_socket, buffer, file_name); if(file_name_len < 0) { /* error while getting the request message or end or file requests from Client */ return -1; } /* check existence of the file in the working directory of the local file system */ printf("requested file: %s\n", file_name); FILE* my_file = fopen(file_name, "r"); if(my_file == NULL) { /* requested file does not exit on the server, send error message to client, end of service for the Client */ printf("requested file does not exist on the server\n"); send_error_message(connected_socket); return -1; } else { /* file does exist on the server, get last timestamp of file and its size, send file */ uint32_t timestamp; outcome = get_file_timestamp(file_name, &timestamp, &file_size); if (outcome < 0) { /* end of service for the Client */ printf("error while getting timestamp and size for file %s\n", file_name); fclose(my_file); return -1; } /* send request response to client (send file) */ outcome = send_file(connected_socket, buffer, my_file, htonl(timestamp), file_size); if (outcome < 0) { /* error while sending the file to the Client, end of service for the Client */ printf("error occurred while sending file to client\n"); fclose(my_file); return -1; /* exit and start listening (accept) for a new client */ } fclose(my_file); } printf("file transfer was successful.\n"); /* successful delivery of file to Client, continue waiting for a new request from the same Client */ } } int main(int argc, char *argv[]) { int passive_socket; /* passive socket */ uint16_t lport_n, lport_h; /* port used by server (net/host ord.) */ struct sockaddr_in saddr, caddr; /* server and client addresses */ program_name = argv[0]; if (argc != 2) { printf("Usage: %s <port number>\n", program_name); exit(1); } unsigned long tmp_port = strtoul(argv[1], NULL, 0); if ((tmp_port == ULONG_MAX) || (tmp_port < 1024) || (tmp_port > 65535)) { printf("Enter a valid port number - port numbers must be between 1024 and 65535\n"); exit(1); } lport_h = (uint16_t) tmp_port; lport_n = htons(lport_h); /* create the socket */ passive_socket = Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); /* bind the socket to any local IP address */ bzero(&saddr, sizeof(saddr)); saddr.sin_family = AF_INET; saddr.sin_port = lport_n; saddr.sin_addr.s_addr = INADDR_ANY; Bind(passive_socket, (struct sockaddr *) &saddr, sizeof(saddr)); /* listen */ int bk_log = 5; /* listen backlog */ Listen(passive_socket, bk_log); /* main server loop */ int s; /* current connected socket (SEQUENTIAL SERVER) */ socklen_t addr_len = sizeof(struct sockaddr_in); printf("Waiting for first Client connection...\n"); while (1) { /* accept next connection */ s = Accept(passive_socket, (struct sockaddr *) &caddr, &addr_len); if (s < 0) { /* start listening to a new connection */ continue; } printf("Accepted new connection on socket %d.\n", s); service_server(s); printf("End of service for the client on socket %d - closing the connection.\n", s); Close(s); } }
C
#include <stdio.h> #include <inttypes.h> #include <mraa/i2c.h> #include "lcd.h" void lcd_begin(){ lcd = mraa_i2c_init(0); _displayfunction |= LCD_2LINE; _numlines = 2; _currline = 0; sleep(1); command(LCD_FUNCTIONSET | _displayfunction); sleep(1); command(LCD_FUNCTIONSET | _displayfunction); _displaycontrol = LCD_DISPLAYON | LCD_CURSOROFF | LCD_BLINKOFF; display(); clear(); _displaymode = LCD_ENTRYLEFT | LCD_ENTRYSHIFTDECREMENT; command(LCD_ENTRYMODESET | _displaymode); setReg(REG_MODE1, 0); setReg(REG_OUTPUT, 0xFF); setReg(REG_MODE2, 0x20); setReg(REG_RED, (unsigned char) 255); setReg(REG_GREEN, (unsigned char) 255); setReg(REG_BLUE, (unsigned char) 255); } void i2c_send_bytes(unsigned char *dta, unsigned char len){ mraa_i2c_address(lcd, LCD_ADDRESS); int i; mraa_i2c_write(lcd, (uint8_t*) dta, (int) len); } void command(uint8_t value){ unsigned char dta[2] = {0x80, value}; i2c_send_bytes(dta, 2); } void display(){ _displaycontrol |= LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void noDisplay(){ _displaycontrol &= ~LCD_DISPLAYON; command(LCD_DISPLAYCONTROL | _displaycontrol); } void clear(){ command(LCD_CLEARDISPLAY); } void setReg(unsigned char addr, unsigned char dta){ mraa_i2c_address(lcd, RGB_ADDRESS); unsigned char toSend[2] = {addr, dta}; mraa_i2c_write(lcd, (uint8_t*)toSend, 2); } void lcd_end(){ noDisplay(); setReg(REG_RED, (unsigned char) 0); setReg(REG_GREEN, (unsigned char) 0); setReg(REG_BLUE, (unsigned char) 0); mraa_i2c_stop(lcd); } size_t lcd_write(char* str){ int i; unsigned char dta[2] = {0x40, 0}; for (i = 0; str[i] != '\0'; i++){ dta[1] = (unsigned char)str[i]; i2c_send_bytes(dta, 2); } return (size_t)i; } void setZero(){ unsigned char dta[2] = {0x80, 0x80}; i2c_send_bytes(dta, 2); }
C
#include <stdio.h> #include <string.h> #include <ev.h> #include <sys/epoll.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/inotify.h> #define EVENT_SIZE (sizeof (struct inotify_event) ) #define EVENT_BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) ) static int inotify_fd; static int watch_fd; static struct ev_loop * loop; static struct ev_io inotify_watcher; static struct ev_io cmdline_watcher; static char* dir = "/root/watchdir/"; static void inotify_cb (__attribute__((unused)) struct ev_loop *loop, ev_io *w, int revents) { if ((revents & EV_READ) && (w->fd == inotify_fd)) { int length, j = 0; char buffer[EVENT_BUF_LEN]; length = read(w->fd, buffer, EVENT_BUF_LEN); if (length < 0) return; while (j < length) { struct inotify_event *event = (struct inotify_event*)&buffer[j]; if (event->len) { if ( event->mask & IN_CLOSE_WRITE) { printf("inclose hahahaha %s, %d\n", event->name, event->len); } else if ( event->mask & IN_MOVED_TO) { printf("move to hahahaha %s, %d\n", event->name, event->len); } } j += EVENT_SIZE + event->len; } } } int main() { loop = ev_default_loop(0); if (loop == NULL) return -1; inotify_fd = inotify_init1(IN_NONBLOCK); if (inotify_fd < -1) return -1; watch_fd = inotify_add_watch(inotify_fd, dir, IN_CLOSE_WRITE | IN_MOVED_TO); if (watch_fd < 0) { close(inotify_fd); return -1; } ev_init(&inotify_watcher, inotify_cb); ev_io_set(&inotify_watcher, inotify_fd, EV_READ); ev_io_start(loop, &inotify_watcher); ev_run(loop, 0); return 0; }
C
// 16-12.c #include <sys/socket.h> #include <errno.h> #include <unistd.h> int initserver(int type, const struct sockaddr* addr, socklen_t alen, int qlen){ int fd, err = 0; if((fd = socket(addr->sa_family, type, 0)) < 0) return 1; if(bind(fd, addr, alen) < 0) goto errout; if(type == SOCK_STREAM || type == SOCK_DGRAM) { if(listen(fd, qlen) < 0) goto errout; } return fd; errout: err = errno; close(fd); errno = err; return -1; }
C
#include<stdio.h> int hcf(int, int, int); int main(void) { int n1, n2, i; printf("Enter two numbers: "); scanf("%d %d", &n1, &n2); printf("The HCF of %d and %d is:", n1, n2); hcf(n1, n2, i=n1>n2?n1-1:n2-1); return 0; } int hcf(int _1, int _2, int i) { if(i==0) // base condition { printf("%d", 1); return 0; } else { if(_1%i == 0 && _2%i == 0) { printf("%d", i); return 0; } else { --i; hcf(_1, _2, i); } } }
C
/* Crie um programa em C que permanece em um laço lendo URLs em sua entrada * padrão (uma por linha) e dispare um processo filho para fazer o download da * mesma a partir da internet Dica: utilize os programas wget ou curl para * efetuar do download. **/ #include <stdio.h> #include <stdlib.h> #include <unistd.h> int main(void){ char url[80]; pid_t pid; while(1){ scanf("%s", url); if((pid = fork()) < 0){ printf("Could not create child\n"); } else if(pid == 0){ char *args[] = {"curl", "-s", url, "-o", url}; execvp("curl", args); printf("downloaded %s\n", url); exit(0); } } return 0; }
C
#include <linux/kernel.h> // serve per il messaggio kernel info #include <linux/module.h> // serve per il modulo // le funzioni da implementare devono avere proprio le seguenti firme: // il SO le vede come punto d'ingresso e punto d'uscita // questa è una versione base: si possono utilizzare anche delle macro // libreria <linux/init.h> // si possono anche utilizzare altre interfacce da implementare // si possono modificare delle info riguardo al modulo del kernel, // andando a definire delle costanti // per creare un driver, il modulo del kernel deve creare una entry nella cartella /dev che rappresenta il dispositivo // e poi deve implementare la logica del driver // l'entry in dev si crea con il comando "mknod" int init_module(void){ printk(KERN_INFO "Hello world 1 "); return 0; } void cleanup_module(void){ printk(KERN_INFO "Hello world 1 "); }
C
# include <stdio.h> # include <math.h> float f (float x) { float y; if (x <= 3) { y = pow (x,2) - 3 * x + 9; } else { y = 1 / ( pow(x,3)+6); } return y; }
C
#include<stdio.h> #include<stdlib.h> int main (int argc, char *argv[]){ int i,id,idade[45],idsoma = 0 ,contadorid,contadoralt; float alt,altura[45],altsoma = 0,mediaid,mediaalt; for (i=0;i<=45;i++){ printf("Digite a idade do aluno"); scanf("%d",&id); printf("Digite a Altura do aluno"); scanf("%f",&alt); idade[i] = id; altura[i] = alt; } for (i=0;i<=45;i++){ if(altura[i] < 1.70); idsoma += idade[i]; contadoralt++; if(idade[i] > 20); altsoma += altura[45]; contadorid++; } mediaid = (idsoma/contadoralt); mediaalt = (altsoma/contadorid); printf("A media de altura dos alunos com menos de 1.70 e = %d \n",mediaid); printf("A media de idade dos alunos com mais de 20 anos = %d \n",mediaalt); }
C
/** * File : ../header/rbt_header.h * Author : Basava Prasad S J * Date : 20.07.2018 * Last Modified Date: 02.09.2018 * Last Modified By : Basava Prasad S J */ /** @brief : Header file to implement red-black tree */ /**Header guards*/ #ifndef RBT_HEADER_H #define RBT_HEADER_H /**Header files*/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> #include <stdio_ext.h> /**Macro definitions*/ #define SUCCESS 1 #define FAIL 0 #define STR_SIZE 100 /**Enum declaration*/ enum selection { /*to select operation to perform, traversal and color*/ Insertion = 1, Deletion, Display, Pre_order = 1, Post_order, In_order, Black = 0, Red }; /**Structure declaration for Tree node*/ struct node{ struct node *parent; /*to hold parent address*/ char color; /*color member*/ int data; /*data member*/ struct node *rchild; /*right child address*/ struct node *lchild; /*left child address*/ }; typedef struct node RBT_NODE; /**Function declarations*/ RBT_NODE *create_node (); RBT_NODE *insert_node (RBT_NODE *root); RBT_NODE *insert_color (RBT_NODE *newnode, RBT_NODE *root); /*RBT_NODE *delete_node (RBT_NODE *root);*/ RBT_NODE *rotate_right (RBT_NODE *grandparent, RBT_NODE *root); RBT_NODE *rotate_left (RBT_NODE *grandparent, RBT_NODE *root); RBT_NODE *rotate_right_left (RBT_NODE *parent_new, RBT_NODE *root); RBT_NODE *rotate_left_right (RBT_NODE *parent_new, RBT_NODE *root); void display_nodes (RBT_NODE *root); void inorder_traversal (RBT_NODE *root); void preorder_traversal (RBT_NODE *root); void postorder_traversal (RBT_NODE *root); /*int search_node (RBT_NODE *root);*/ int my_atoi (char *str); /**End of header guards*/ #endif
C
#include <stdio.h> /* #Take CRLF pairs and outputs LF only #Single LF chars are left alone #Single CR chars convert to LF */ int main(int argc, char **argv) { int c; int had_cr; had_cr = 0; while((c = getchar()) != -1) { if(c == '\r') { putchar('\n'); had_cr = 1; } else if(c == '\n' && had_cr == 1) had_cr = 0; else { had_cr = 0; putchar(c); } } return 0; }
C
int globalVar = 100; main(){ char middle_initial; printf("\n"); int num1 = 12, num2 = 15, numAns; float decimal1 = 1.2, decimal2 = 1.5, decimal_ans; printf("Integer Calculation %d\n\n", num2 / num1); printf("Float Calculation %f\n\n", decimal2 / decimal1); printf("Modulus %d\n\n",num2 % num1); printf("Without Parentheses %d\n\n", 3 + 6 * 10); printf("With Parentheses %d\n\n", (3 + 6) * 10); }
C
#include<stdio.h> int main() { int i,n; while(scanf("%d",&n)!=EOF) { for(i=1; i<=n; i++) { float c,f,C; scanf("%f%f",&c,&f); C=((5.0/9.0)*f)+c; printf("Case %d: %.2f\n",i,C); } } }
C
/** * +------------------------------+ * |˵:ǰ˽API 汾 | * |Ҫ, * |Լں湹һ * |ǰ˴. * +------------------------------+ * |ʹҪ:ڰ * |ǰ <vector> ʹ * |ռ STD * +------------------------------+ * |: ܽ * |[email protected] | * +------------------------------+ ******************/ #ifndef LOCAL_FUN_H_INCLUDED #define LOCAL_FUN_H_INCLUDED struct Person_info { int id; char* name; char sex; int age; char* id_card_num; char* mar_stu; char* edu_stu; char* photo_addr; //ù캯 Person_info() { id= 12; name = (char*)"nihao"; sex = 'D'; age = 34; } void print() { cout<<id<<" "<<name<<" "<<sex<<" "<<age<<endl; } }; struct Medical_info { int person_id; int medical_num; char dignose; char* place; int danger_level; char* danger_desc; char cure_meth; double in_panss; double out_panss; char* wtgo; Medical_info() { person_id = 12; medical_num = 2; dignose = 'S'; place = (char*)"zhoujinyu"; } void print() { cout<<person_id<<" "<<medical_num<<" "<<dignose<<" "<<place<<endl; } }; /** ú */ Person_info get_p() { Person_info p ; return p; } Medical_info get_m() { Medical_info m ; return m; } /** Ϣغ */ int create_person_info(Person_info person) { return 1; } bool update_person_info(int person_id,Person_info info) { return false; } Person_info get_person_by_id(int person_id) { Person_info p ; return p; } vector<Person_info> get_person_by_stu() { vector<Person_info> pl ; return pl; } /** סԺϢغ */ bool create_medical_info(int person_id,Medical_info info) { return false; } bool update_medical_info(int person_id,Medical_info info) { return false; } Medical_info get_medical_info(int person_id) { Medical_info m; return m; } vector<Medical_info> get_history_medical_info(int person_id) { vector<Medical_info> m; return m; } vector<Medical_info> get_period_medical_info(int person_id,char* start_date,char* end_date) { return get_history_medical_info(12); } #endif // LOCAL_FUN_H_INCLUDED
C
#include <stdio.h> #include <stdlib.h> void rotateLeft(int * array, int count) { int temp; printf("Swapping %d @%d and %d @ %d\n",array[0],0,array[count-1],count); char pause; pause = getchar(); temp = array[0]; array[0]=array[count-1]; array[count-1]=temp; if (count!=2) rotateLeft(array,count-1); } int main() { int count=5; int array[]={5,6,7,8,9}; rotateLeft(array,count); for(int i=0; i<count; i++) { printf(" %d ",array[i]); } printf("\n"); return 0; }
C
/* Link: https://open.kattis.com/problems/quadrant */ #include <stdio.h> int main() { int x,y,q = 1; scanf("%d %d", &x, &y); if(x>0) { if(y<0){ q=4; } } else { if(y<0){ q=3; } else q=2; } printf("%d", q); }
C
#include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <getopt.h> #include <netdb.h> #include <netinet/in.h> #include <netinet/ip.h> #include <sys/socket.h> #include <sys/types.h> #include "modulo.h" #define mem_block_size 4 struct Server { char ip[255]; int port; }; uint64_t total = 1; int recogn(char* buff, uint32_t* pos, struct Server* to) { char* temp = buff; uint32_t offset = 0; for (int j = 0; j < 3; j++) for (int i = 0; i < 4; i++) { if ((*(temp + offset) >= '0') && (*(temp + offset) <= '9')) { offset++; continue; } if (*(temp + offset) == '.') { offset++; break; } return 1; } for (int i = 0; i < 4; i++) { if ((*(temp + offset) >= '0') && (*(temp + offset) <= '9')) { offset++; continue; } if (*(temp + offset) == ':') break; return 1; } memcpy(&to->ip, temp, offset); to->ip[offset] = '\0'; offset++; temp += offset; *pos += offset; offset = 0; while ((*(temp + offset) >= '0') && (*(temp + offset) <= '9')) offset++; if ((*(temp + offset) != '\n') && (*(temp + offset) != ' ')) return 1; temp[offset] = '\0'; to->port = atoi(temp); *pos += offset; return 0; } bool ConvertStringToUI64(const char *str, uint64_t *val) { char *end = NULL; unsigned long long i = strtoull(str, &end, 10); if (errno == ERANGE) { fprintf(stderr, "Out of uint64_t range: %s\n", str); return false; } if (errno != 0) return false; *val = i; return true; } int main(int argc, char **argv) { uint64_t k = -1; uint64_t mod = -1; char servers[255] = {'\0'}; while (true) { int current_optind = optind ? optind : 1; static struct option options[] = {{"k", required_argument, 0, 0}, {"mod", required_argument, 0, 0}, {"servers", required_argument, 0, 0}, {0, 0, 0, 0}}; int option_index = 0; int c = getopt_long(argc, argv, "", options, &option_index); if (c == -1) break; switch (c) { case 0: { switch (option_index) { case 0: ConvertStringToUI64(optarg, &k); if(k == 0) k = -1; break; case 1: ConvertStringToUI64(optarg, &mod); if(mod == 0) mod = -1; break; case 2: memcpy(servers, optarg, strlen(optarg)); break; default: printf("Index %d is out of options\n", option_index); } } break; case '?': printf("Arguments error\n"); break; default: fprintf(stderr, "getopt returned character code 0%o?\n", c); } } if (k == -1 || mod == -1 || !strlen(servers)) { fprintf(stderr, "Using: %s --k 1000 --mod 5 --servers /path/to/file\n", argv[0]); return 1; } FILE* f = fopen(servers, "r"); if (!f) { printf("server file error!\n"); return 1; } struct Server *to = malloc(sizeof(struct Server) * mem_block_size); uint32_t pos = 0; char buff[24]; uint32_t mem_serv_counter = 1; uint32_t servers_num = 0; while (!feof(f) || (servers_num > k)) { if (servers_num == (mem_block_size*mem_serv_counter)) { mem_serv_counter++; to = (struct Server *) realloc(to, mem_block_size*mem_serv_counter*sizeof(struct Server)); } fseek(f, pos, SEEK_SET); if (fread(&buff, 1, 24, f) == 0) { printf("rw file error!\n"); fclose(f); return 1; } if (recogn(buff, &pos, to + servers_num)) { fclose(f); printf("file format error!\n"); return 1; } pos++; servers_num++; } fclose(f); to = (struct Server *) realloc(to, servers_num*sizeof(struct Server)); for (int i = 0; i < servers_num; i++) { struct hostent *hostname = gethostbyname(to[i].ip); if (hostname == NULL) { fprintf(stderr, "gethostbyname failed with %s\n", to[i].ip); exit(1); } struct sockaddr_in server; server.sin_family = AF_INET; server.sin_port = htons(to[i].port); server.sin_addr.s_addr = *((unsigned long *)hostname->h_addr); int sck = socket(AF_INET, SOCK_STREAM, 0); if (sck < 0) { fprintf(stderr, "Socket creation failed!\n"); exit(1); } if (connect(sck, (struct sockaddr *)&server, sizeof(server)) < 0) { fprintf(stderr, "Connection failed\n"); exit(1); } uint64_t begin = i*k / servers_num + 1; uint64_t end = (i == (servers_num - 1)) ? k + 1 : (i+1)*k/servers_num + 1; memcpy(buff, &begin, sizeof(uint64_t)); memcpy(buff + sizeof(uint64_t), &end, sizeof(uint64_t)); memcpy(buff + 2 * sizeof(uint64_t), &mod, sizeof(uint64_t)); if (send(sck, buff, 3 * sizeof(uint64_t), 0) < 0) { fprintf(stderr, "Send failed\n"); exit(1); } uint64_t answer = 0; if (recv(sck, (char*)&answer, sizeof(answer), 0) < 0) { fprintf(stderr, "Recieve failed\n"); exit(1); } total = MultModulo(total, answer, mod); close(sck); } printf("answer: %lu\n", total); free(to); return 0; }
C
/* problem link = "https://www.hackerrank.com/challenges/richie-rich/problem"*/ ----------------------------------------------------CODE--------------------------------------------------- #include <assert.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int main() { int n,count; scanf("%d %d\n", &n, &count); char arr[n+1]; int i, j; scanf("%[^\n]%%c",arr); int present_count =0; int k = n - 1; int diff = 0; for (i = 0; i < n/2; i++) { if(arr[i]!=arr[k--]) diff++; // to know how many diff elements are present in the string for making it a palindrome } k = n-1; if(diff>count)// if diff elements are more than the given no of operations to make it palindrome printf("-1\n");//then it isn't possible to make it one else { for (i = 0; i < n/2; i++)//iterate till half of the array (ignore the mid ele) { if(arr[i]==arr[k])//case 1 : both ele are same { if(arr[i]!='9')//and they both are not 9 if(count-2 >= diff) { arr[i] = '9'; arr[k] = '9'; count -= 2; } } else if ((arr[i] != arr[k]) && ((arr[i]=='9') || (arr[k] == '9'))) //one ele is same and one of them is 9 { if (arr[i] == '9') { if (count - 1 >= diff -1) //diff - 1 because these are the diff elements { arr[k] = '9'; count --; diff--;//one pair of diff ele is done making palindrome } } else if(arr[k] == '9') if (count - 1 >= diff - 1) { arr[i] = '9'; count --; diff--; } } else if ((arr[i] != arr[k]))//both ele are not same { if (count - 2 >= diff - 1) //if we have the req count to make both the ele 9 { arr[i] = '9'; arr[k] = '9'; count -= 2; diff--; } else if (count - 1 >= diff - 1) //if we have only one count to make it palindrome { if(arr[i] > arr[k]) //we decide the max ele out of the both to make both the ele same arr[k] = arr[i]; else arr[i] = arr[k]; count--; diff--; } } k--;//for iterating backwards }//for loop end if((n % 2 )== 1)//if middle ele is present { if(count>0)// if we have more count to perform operations arr[n/2] = '9'; //make the mid ele 9 } printf("%s\n",arr); } }
C
#include<stdio.h> typedef int (*fptrOperation)(int,int); int add(int num1,int num2){ return num1+num2; } int sub(int num1,int num2){ return num1-num2; } int compute(fptrOperation operation,int num1,int num2){ return operation(num1,num2); } void main(){ printf("%d\n",compute(add,5,6)); printf("%d\n",compute(sub,5,6)); }
C
/* Print prime numbers program André Barros de Medeiros 29/08/17 */ #include <stdio.h> int main() { int num; int d; int r; while (num=num) { for (d=1; d<num; d=d+1) { num = num + 1; num % d = r; if (r=0) printf("nao\n"); else printf("sim\n"); } } return 0; }
C
/* * License: Public Domain */ #include "pmm.h" #define unlikely(x) __builtin_expect((x),0) #define likely(x) __builtin_expect((x),1) uint32_t* pmm_memory_bitmap = (uint32_t *)0x38400; uint32_t pmm_total_blocks = 0; uint32_t used_blocks = 0; extern uint32_t totalRAM; void * memset(void * ptr, int value, unsigned num); uint32_t pmm_used_blocks() { return used_blocks; } void pmm_init(){ pmm_total_blocks = totalRAM / 4; used_blocks = pmm_total_blocks; display_put_character(0, 0, 'Z', 0x0F); //unsigned t = (pmm_total_blocks+0) / 32; unsigned t = (pmm_total_blocks+8) / 8; char buf[10]; itoa(t, 10, buf); display_place_string(0, 2, buf, 3); //for(unsigned i = 0; i < t; i++) // pmm_memory_bitmap[i] = 0xFFFFFFFF; memset(pmm_memory_bitmap, 0xFF, 131072); display_put_character(0, 0, 'Y', 0x0F); } unsigned pmm_free_blocks(){ return pmm_total_blocks - used_blocks; } int pmm_first_free(){ for (uint32_t i = 0; i < (pmm_total_blocks/32); i++)// Search for memory map one uint32_t at a time for (int j = 0; j < 32; j++) {// For each bit in the uint32_t... int bit = 1 << j; if (!(pmm_memory_bitmap[i] & bit)) return (i * 4 * 8) + j; } return -1; } void pmm_set_bit_in_bitmap(int bit) { pmm_memory_bitmap[bit / 32] |= (1 << (bit % 32)); } void pmm_unset_bit_in_bitmap(int bit) { pmm_memory_bitmap[bit / 32] &= ~(1 << (bit % 32)); } int pmm_is_bit_set(int bit) { return pmm_memory_bitmap[bit / 32] & (1 << (bit % 32)); } void* pmm_allocate_block() { if (unlikely(used_blocks >= pmm_total_blocks)){ return (void *)0; } int block = pmm_first_free(); if (unlikely(block == -1)) return 0; // Out of memory, return NULL pointer pmm_set_bit_in_bitmap(block); used_blocks++; return (void*)(block * 4096); } int pmm_first_free_s(unsigned size) { if (size == 0) return -1; if (size == 1) return pmm_first_free(); for (uint32_t i = 64; i < (pmm_total_blocks / 32); i++)// skip first 8mb if (pmm_memory_bitmap[i] != 0xFFFFFFFF) for (int j = 0; j<32; j++) { // test each bit in the dword int bit = 1 << j; if (!(pmm_memory_bitmap[i] & bit)) { int startingBit = i * 32; startingBit += bit; // get the free bit in the dword at index i uint32_t free = 0; // loop through each bit to see if its enough space for (uint32_t count = 0; count <= size; count++) { if (!pmm_is_bit_set(startingBit + count)) free++; // this bit is clear (free frame) if (free == size) return i * 4 * 8 + j; //free count==size needed; return index } } } return -1; } void * pmm_allocate_blocks(unsigned blockCount) { if (unlikely(used_blocks >= pmm_total_blocks)){ return (void *)0; } unsigned freeBlocks = pmm_total_blocks - used_blocks; if(unlikely(freeBlocks < blockCount)){ return 0; } int frame = pmm_first_free_s(blockCount); if (frame == -1) return 0; for (uint32_t i = 0; i < blockCount; i++) pmm_set_bit_in_bitmap(frame + i); uint32_t addr = frame * 4096; used_blocks += blockCount; return (void*)addr; } void pmm_free_block(void * address) { int block = (unsigned)address / 4096; pmm_unset_bit_in_bitmap(block); if(likely(used_blocks != 0)) used_blocks--; } void pmm_free_region(uint32_t base, unsigned size) { int cur_block = base / 4096; int blocks = (size+4095) / 4096; for (; blocks > 0; blocks--, cur_block++) { int bitWasSet = pmm_is_bit_set(cur_block); if (bitWasSet){ pmm_unset_bit_in_bitmap(cur_block); used_blocks--; } } } void pmm_allocate_region(uint32_t base, unsigned size) { int cur_block = base / 4096; int blocks = (size+4095) / 4096; for (; blocks > 0; blocks--, cur_block++) { int bitWasSet = pmm_is_bit_set(cur_block); if (!bitWasSet){ pmm_set_bit_in_bitmap(cur_block); used_blocks++; } } }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int calcula(float valor){ float resultado; if (valor >=0 && valor <=5){ resultado = (160*M_PI*(pow(valor,3)))/3; } if(valor>5 && valor<=9){ resultado = ((160*M_PI*(pow(5,3))/3))+(4000*M_PI*(valor-5)); } if(valor<0 || valor>9){ resultado = 0; printf("\n\nDigite um valor entre 0 e 9"); } return resultado; } int main() { float C; float n; printf("Escreva o valor do nivel em metros : "); scanf("%f", &n); C = calcula(n); printf("\n\nO valor resultado da função com o nível em %.2f metros eh: %.4f\n\n", n, C); return 0; }
C
#include <stdio.h> int main(void) { int i,j; printf("Enter i = "); scanf("%d",&i); printf("Enter j = "); scanf("%d",&j); j += i; printf("%d %d\n",i,j); j -= i; printf("%d %d\n",i,j); j *= i; printf("%d %d\n",i,j); j /= i; printf("%d %d\n",i,j); return 0; }
C
#include "hash_tables.h" /** * hash_table_set - function that adds an element to hash table * @ht: hash table to add * @key: key * @value: value * Return: 1 on success otherwise 0. */ int hash_table_set(hash_table_t *ht, const char *key, const char *value) { unsigned long int idx; hash_node_t *new; hash_node_t *tempo; if (key == NULL || value == NULL || ht == NULL) return (0); idx = key_index((const unsigned char *)key, ht->size); new = ht->array[idx]; while (tempo) { if (strcmp(tempo->key, key) == 0) { free(tempo->value); tempo->value = strdup(value); return (1); } new = new->next; } new = malloc(sizeof(hash_node_t)); if (new == NULL) return (NULL); new->key = strdup(key); if (new->key == NULL) { free(new); return (NULL); } new->value = strdup(value); if (new->value == NULL) { free(new->key); free(new); return (NULL); } new->next = ht->array[idx]; ht->array[idx] = new; return (1); }
C
#include <stdio.h> #include <time.h> #include <unistd.h> #include <limits.h> #define MAX 400000000 long int binsearch(long int x, long int v[], long int n) { long int low, high, mid; low = 0; high = n - 1; while (low <=high){ mid = (low + high) / 2; if (x < v[mid]) high = mid - 1; else if (x > v[mid]) low = mid + 1; else return mid; } return -1; } long int binsearch2(long int x, long int v[], long int n) { long int low, high, mid; low = 0; high = n - 1; while (low <= high){ mid = (low + high) / 2; if (x < v[mid]) high = mid -1; else low = mid + 1; } if (v[mid] == x) return mid; else return -1; } int main() { long val = 1000000; time_t start, end; long v[val]; long int count; for (long int i=0; i<val-1; i++){ v[i] = i; } count = MAX; printf("Benchmarking binsearh with two conditions. Cycle iterations = %ld \n", count); start = time(NULL); while(count--) binsearch(9, v, val); end = time(NULL); printf("%f\n", difftime(end, start)); count = MAX; printf("Benchmarking binsearh with one conditions. Cycle iterations = %ld \n", count); start = time(NULL); while(count--) binsearch2(9, v, val); end = time(NULL); printf("%f\n", difftime(end, start)); }
C
#include<stdio.h> //libreria E/S int N3; int N1; int N2; int precio; int main() {//Inicio printf("seleccione una opcin:\n1 = Ventas del dia\n2 = men de venta\n"); scanf("%d", &N3); switch(N3){ case 1: printf("\nGANANCIA DE:500"); break; case 2: printf("La tiendita de Doa Yolis\n"); printf("Pepsi $10= 1\nSabritas $12= 2\nCarlos V $7= 3\nMaruchan $6= 4\nJarrito $9= 5\nGalletas Emperador $9= 6\nBarritas Marinela $8= 7\nMazapan $2= 8\nCigarros sueltos c/u $4= 9\nFrutsi $6= 10\n"); printf("Escriba el Nmero correspondiente al producto: \n"); scanf("%d", &N1); printf("Cuntos deseas?:\n"); scanf("%d", &N2); switch(N1){ case 1: N1=10; precio=N1*N2; printf("Pepsi:\n"); printf("Usted debe pagar: $%d", precio); break; case 2:N1=12; precio=N1*N2; printf("Sabritas:\nUsted debe pagar: $%d", precio); break; case 3:N1=7; precio=N1*N2; printf("Carlos V:\nUsted debe pagar: $%d", precio); break; case 4:N1=6; precio=N1*N2; printf("Maruchan:\nUsted debe pagar: $%d", precio); break; case 5:N1=9; precio=N1*N2; printf("Jarrito:\nUsted debe pagar: $%d", precio); break; case 6:N1=9; precio=N1*N2; printf("Galletas Emperador:\nUsted debe pagar: $%d", precio); break; case 7:N1=8; precio=N1*N2; printf("Barritas Marinela:\nUsted debe pagar: $%d", precio); break; case 8:N1=2; precio=N1*N2; printf("Mazapan:\nUsted debe pagar: $%d", precio); break; case 9:N1=4; precio=N1*N2; printf("Cigarro(s):\nUsted debe pagar: $%d", precio); break; case 10:N1=6; precio=N1*N2; printf("Frutsi:\nUsted debe pagar: $%d", precio); break; default: printf("No existe este articulo"); } break; } }//final
C
#pragma once #define NORTH 0 #define SOUTH 1 #define EAST 2 #define WEST 3 #define DIRECTIONS 4 ref class MazeCell { private: bool isVisited; array<bool>^ isPassable; // can you move in the given direction from this cell. public: MazeCell(); bool getIsVisited() { return isVisited;} void setIsVisited(bool b) { isVisited = b; } array<bool>^ getIsPassable() { return isPassable; } bool getIsPassable(int direction) { return isPassable[direction]; } void setIsPassable(int direction, bool value) { isPassable[direction] = value; } };
C
#include <R.h> #include <math.h> #include "nrutilR.h" #define TINY 1.0e-20; // A small number void ludcmp(double **a, int dim, int *indx, double *d){ // Given a matrix a[1..dim][1..dim], this routine replaces it by the LU decomposition of a rowwise permutation of itself. // a and dim are input. // a is output, arranged as in equation (2.3.14); // indx[1..dim] is an output vector that records the row permutation effected by the partial pivoting // d is output as +-1 depending on whether the number of row interchanges was even or odd, respectively. // This routine is used in compination with lubksb to solve linear equations or invert a matrix. int i, imax, j, k; double big, dum, sum, temp; double *vv; // vv stores the implicit scaling of each row. vv=dvector(1,dim); *d=1.0; // no row interchanges yet for (i=1;i<=dim;i++){ // Loop over rows to get the implicit scaling information. big=0.0; for (j=1;j<=dim;j++) if ((temp=fabs(a[i][j]))> big) big=temp; if (big==0.0) warning("Singular matrix in routine LUDCMP"); // no nonzero largest element. vv[i]=1.0/big; // save the scaling } /////////////// This is the loop over columns of Crout's method. for (j=1;j<=dim;j++){ for (i=1;i<j;i++){ // This is equation (2.3.12) except for i=j!!!!!!!!!!!!!! sum=a[i][j]; for (k=1;k<i;k++) sum-=a[i][k]*a[k][j]; a[i][j]=sum; } big=0.0; // Initialize for the search for largest pivot element for (i=j;i<=dim;i++){ // This is i=j of equation (2.3.12) and i=j+1...N of eq (2.3.13) sum=a[i][j]; for (k=1;k<j;k++) sum-=a[i][k]*a[k][j]; a[i][j]=sum; if ( (dum=vv[i]*fabs(sum)) >= big){ // Is the figure of merit for the pivot better than the best so far? big=dum; imax=i; } } if (j!= imax){ // Do we need to interchange rows? for(k=1;k<=dim;k++){ // Yes, do so... dum=a[imax][k]; a[imax][k]=a[j][k]; a[j][k]=dum; } *d= -(*d); // and change the parity of d vv[imax]=vv[j]; // Also interchange the scale factor. } indx[j]=imax; if (a[j][j] == 0.0) a[j][j]=TINY; // If the pivot element is zero the matrix is singular if (j!= dim){ // Now finally, divide by the pivot element. dum=1.0/(a[j][j]); for (i=j+1;i<=dim;i++) a[i][j] *= dum; } } free_dvector(vv,1,dim); } void lubksb(double **a, int dim, int *indx, double *b){ // Solve the set of 'dim' linear equations AX=B. Here a[1..dim][1..dim] is input, not as the matrix A but rather as its LU decomposition, determined by the routine ludcmp. // indx[1..dim] is input as the permutation vector returned by ludcomp. // b[1..dim] is input as the right-hand side vector B, and returns with the solution vector X. // a, dim, and indx are NOT modified by this routine and can be left in place for successive calls with different right-hand side b. int i,ii=0,ip,j; double sum; for (i=1;i<=dim;i++){ // When ii is set to a positive value, it will become the index of the first nonvanishing element of b. ip=indx[i]; sum=b[ip]; b[ip]=b[i]; if (ii) for (j=ii;j<=i-1;j++) sum -= a[i][j]*b[j]; else if (sum) ii=i; b[i]=sum; } for (i=dim;i>=1;i--){ sum=b[i]; for (j=i+1;j<=dim;j++) sum-= a[i][j]*b[j]; b[i]=sum/a[i][i]; } }
C
/* * one_time_init.c * * Implementing a simplified version of pthread_once. * */ #include <stdio.h> #include <pthread.h> typedef struct one_time_s { int is_initialized; int foobar; pthread_mutex_t mtx; } one_time_t; static one_time_t control = {.is_initialized = 0, .mtx = PTHREAD_MUTEX_INITIALIZER}; void one_time_init(one_time_t *control, void (*init)(void)) { pthread_mutex_lock(&control->mtx); if (!control->is_initialized) { init(); control->is_initialized = 1; } pthread_mutex_unlock(&control->mtx); } static void test_function() { printf("Running\n"); } int main() { one_time_init(&control, test_function); one_time_init(&control, test_function); }
C
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <string.h> #include "tree.h" void errorMes(int e, int line); uint32_t getU32(FILE * f, int offset); float price(FILE * f); char* word(FILE * f); void getChild(FILE * f, int child); void find(char * search_word, FILE * f); void printNotFound(char * word); void print(FILE * f); #define LEFT_CHILD 0 #define RIGHT_CHILD 4 #define COUNT 8 #define PRICE 12 #define WORD 16 int main(int argc, char * argv[]){ if(argc < 3) errorMes(1, __LINE__); FILE * file = fopen(argv[1], "r"); if(!file) errorMes(2, __LINE__); char fileType[5]; fileType[4] = 0; fread(&fileType, 1, 4, file); if(strcmp(fileType, "BTRE")) errorMes(3, __LINE__); /* uint32_t lc = getU32(file, LEFT_CHILD); uint32_t rc = getU32(file, RIGHT_CHILD); uint32_t count = getU32(file, COUNT); float p = price(file); char * w = word(file); printf("lc: %u\t rc: %u\t count: %u\t price: %.2f\t word: %s\n", lc, rc, count, p, w); getChild(file, LEFT_CHILD); lc = getU32(file, LEFT_CHILD); rc = getU32(file, RIGHT_CHILD); count = getU32(file, COUNT); p = price(file); w = word(file); printf("lc: %u\t rc: %u\t count: %u\t price: %.2f\t word: %s\n", lc, rc, count, p, w); getChild(file, RIGHT_CHILD); lc = getU32(file, LEFT_CHILD); rc = getU32(file, RIGHT_CHILD); count = getU32(file, COUNT); p = price(file); w = word(file); printf("lc: %u\t rc: %u\t count: %u\t price: %.2f\t word: %s\n", lc, rc, count, p, w); */ int i; for(i = 2; i < argc; i++){ find(argv[i], file); fseek(file, 4, SEEK_SET); } //free(w); return 0; } void find(char * search_word, FILE * f){ int x = strcmp(search_word, word(f)); uint32_t offset = -1; if(x == 0){ print(f); return; } else if(x > 0){ offset = RIGHT_CHILD; } else{ offset = LEFT_CHILD; } if(!getU32(f, offset)){ printNotFound(search_word); } else{ getChild(f, offset); find(search_word, f); } } void errorMes(int e, int line){ if(e == 1) printf("When running this program please use the format:\nLookup1 <data_file> <keyword> [<keyword> ...]\n"); else if(e == 2) printf("File not found\n"); else if(e == 3) printf("Data file is not a binary search tree\n"); else{ if(e == 4) printf("fseek failed to find array data location\n"); if(e == 5) printf("fread failed to read struct data\n"); if(e == 6) printf("getline failed to read the word\n"); printf("Error at line %d", line); } exit(e); } void print(FILE * f){ printf("%s: %u at $%.2f\n", word(f), getU32(f, COUNT), price(f)); } void printNotFound(char * word){ printf("%s not found\n", word); } uint32_t getU32(FILE * f, int offset){ int err = fseek(f, offset, SEEK_CUR); if(err) errorMes(4, __LINE__); uint32_t retVal; err = fread(&retVal, sizeof(uint32_t), 1, f); if(!err) errorMes(5, __LINE__); fseek(f, -offset - sizeof(uint32_t), SEEK_CUR); return retVal; } float price(FILE * f){ int err = fseek(f, PRICE, SEEK_CUR); if(err) errorMes(4, __LINE__); float price; err = fread(&price, sizeof(float), 1, f); if(!err) errorMes(5, __LINE__); fseek(f, -PRICE - sizeof(float), SEEK_CUR); return price; } char* word(FILE * f){ int err = fseek(f, WORD, SEEK_CUR); if(err) errorMes(4, __LINE__); char * word = malloc(8); size_t size = 0; err = getdelim(&word, &size, (char)0, f); //printf("getdelim: %ld\n", ftell(f)); if(!err) errorMes(6, __LINE__); fseek(f, -WORD - err, SEEK_CUR); //printf("prince: %d\t size: %d\t getdelim2: %ld\n",PRICE, err, ftell(f)); return word; } void getChild(FILE * f, int child){ //size_t start = (size_t)f; //printf("child: %d\t cur pos: %ld\n", child, ftell(f)); uint32_t offset = getU32(f, child); //if(offset == 0) fseek(f, (long)offset, SEEK_SET); }
C
/* * * Write a program to display the following stars pattern. * *** ***** ******* ********* *********** * any number of lines ;) * * created by Ahmed_Elkhodary */ # include <stdio.h> # include <math.h> void print_shape(int n) { int i , j, k, p, m; int dot_num, star_num; p = n; m = 0; for(i = 1 ; i <= n ; i++, p-- ) { for(j = p-1 ; j >=1 ; j-- ) { printf(" "); } for(k = 1 ; k <= i+m ; k++) { printf("*"); } m++; printf("\n"); } } int main (void) { int num_line; printf("Enter number of lines: "); scanf ("%d",&num_line); print_shape(num_line); scanf("%d"); return 0 ; }
C
/* * cfgfile.c: * * Copyright (c) 2003 DecisionSoft Ltd. * */ #include <stdio.h> #include <string.h> #include <errno.h> #include <stdlib.h> #include "../include/stringmap.h" #include "../include/iftop.h" #include "../include/options.h" #include "../include/cfgfile.h" #define CONFIG_TYPE_STRING 0 #define CONFIG_TYPE_BOOL 1 #define CONFIG_TYPE_INT 2 #define MAX_CONFIG_LINE 2048 char *config_directives[] = { "interface", "dns-resolution", "port-resolution", "filter-code", "show-bars", "promiscuous", "hide-source", "hide-destination", "use-bytes", "sort", "line-display", "show-totals", "log-scale", "max-bandwidth", "net-filter", "net-filter6", "link-local", "port-display", NULL }; stringmap config; extern options_t options; int is_cfgdirective_valid(const char *s) { int t; for (t = 0; config_directives[t] != NULL; t++) if (strcmp(s, config_directives[t]) == 0) return 1; return 0; } int config_init() { config = stringmap_new(); return config != NULL; } /* read_config_file: * Read a configuration file consisting of key: value tuples, returning a * stringmap of the results. Prints errors to stderr, rather than using * syslog, since this file is called at program startup. Returns 1 on success * or 0 on failure. */ int read_config_file(const char *f, int whinge) { int ret = 0; FILE *fp; char *line; int i = 1; line = xmalloc(MAX_CONFIG_LINE); fp = fopen(f, "rt"); if (!fp) { if (whinge) fprintf(stderr, "%s: %s\n", f, strerror(errno)); goto fail; } while (fgets(line, MAX_CONFIG_LINE, fp)) { char *key, *value, *r; for (r = line + strlen(line) - 1; r > line && *r == '\n'; *(r--) = 0); /* Get continuation lines. Ugly. */ while (*(line + strlen(line) - 1) == '\\') { if (!fgets(line + strlen(line) - 1, MAX_CONFIG_LINE - strlen(line), fp)) break; for (r = line + strlen(line) - 1; r > line && *r == '\n'; *(r--) = 0); } /* Strip comment. */ key = strpbrk(line, "#\n"); if (key) *key = 0; /* foo : bar baz quux * key^ ^value */ key = line + strspn(line, " \t"); value = strchr(line, ':'); if (value) { /* foo : bar baz quux * key^ ^r ^value */ ++value; r = key + strcspn(key, " \t:"); if (r != key) { item *I; *r = 0; /* foo\0: bar baz quux * key^ ^value ^r */ value += strspn(value, " \t"); r = value + strlen(value) - 1; while (strchr(" \t", *r) && r > value) --r; *(r + 1) = 0; /* (Removed check for zero length value.) */ /* Check that this is a valid key. */ if (!is_cfgdirective_valid(key)) fprintf(stderr, "%s:%d: warning: unknown directive \"%s\"\n", f, i, key); else if ((I = stringmap_insert(config, key, item_ptr(xstrdup(value))))) /* Don't warn of repeated directives, because they * may have been specified via the command line * Previous option takes precedence. */ fprintf(stderr, "%s:%d: warning: repeated directive \"%s\"\n", f, i, key); } } memset(line, 0, MAX_CONFIG_LINE); /* security paranoia */ ++i; } ret = 1; fail: if (fp) fclose(fp); if (line) xfree(line); return ret; } int config_get_int(const char *directive, int *value) { stringmap S; char *s, *t; if (!value) return -1; S = stringmap_find(config, directive); if (!S) return 0; s = (char *) S->d.v; if (!*s) return -1; errno = 0; *value = strtol(s, &t, 10); if (*t) return -1; return errno == ERANGE ? -1 : 1; } /* config_get_float: * Get an integer value from a config string. Returns 1 on success, -1 on * failure, or 0 if no value was found. */ int config_get_float(const char *directive, float *value) { stringmap S; item *I; char *s, *t; if (!value) return -1; if (!(S = stringmap_find(config, directive))) return 0; s = (char *) S->d.v; if (!*s) return -1; errno = 0; *value = strtod(s, &t); if (*t) return -1; return errno == ERANGE ? -1 : 1; } /* config_get_string; * Get a string value from the config file. Returns NULL if it is not * present. */ char *config_get_string(const char *directive) { stringmap S; S = stringmap_find(config, directive); if (S) return (char *) S->d.v; else return NULL; } /* config_get_bool: * Get a boolean value from the config file. Returns false if not present. */ int config_get_bool(const char *directive) { char *s; s = config_get_string(directive); if (s && (strcmp(s, "yes") == 0 || strcmp(s, "true") == 0)) return 1; else return 0; } /* config_get_enum: * Get an enumeration value from the config file. Returns false if not * present or an invalid value is found. */ int config_get_enum(const char *directive, config_enumeration_type *enumeration, int *value) { char *s; config_enumeration_type *t; s = config_get_string(directive); if (s) { for (t = enumeration; t->name; t++) { if (strcmp(s, t->name) == 0) { *value = t->value; return 1; } } fprintf(stderr, "Invalid enumeration value \"%s\" for directive \"%s\"\n", s, directive); } return 0; } /* config_set_string; Sets a value in the config, possibly overriding * an existing value */ void config_set_string(const char *directive, const char *s) { stringmap S; S = stringmap_find(config, directive); if (S) { xfree(S->d.v); S->d = item_ptr(xstrdup(s)); } else { stringmap_insert(config, directive, item_ptr(xstrdup(s))); } } int read_config(char *file, int whinge_on_error) { void *o; return read_config_file(file, whinge_on_error); }
C
#define F_CPU 8000000UL #include <avr/io.h> #include <util/delay.h> void usart_init(); void lcd_cmd(char x); void lcd_data(char x); void lcd_string(char *); void lcd_init(); char rx(); char arr[] = "20002C6F5437"; char arr2[]; int i; int main(void) { DDRA = 0x0F; DDRB = 0xFF; usart_init(); lcd_init(); //lcd_string("hello"); while(1) { rx() ; } } void usart_init() { UCSRB=UCSRB|1<<RXEN; UCSRC=UCSRC|1<<URSEL|1<<UCSZ0|1<<UCSZ1; UBRRL=0x33; } char rx() { //while((UCSRA&(1<<RXC))==0){} for( i=0; i<=11; i++) { while((UCSRA&(1<<RXC))==0){} arr2[i] = UDR ; }arr2[i] = '\0'; if(strcmp(arr,arr2)==0) { PORTA |= 0x01; lcd_string("WELCOME"); lcd_cmd(0xc0); lcd_string("SHIKHAR SINGH"); lcd_cmd(0x80); } else { PORTA &= ~(1<<0); lcd_cmd(0x01); } } void lcd_init() { lcd_cmd(0x38); lcd_cmd(0x0e); lcd_cmd(0x06); //lcd_cmd(0x80); } void lcd_cmd(char x) { PORTB = x; PORTA=PORTA&~(1<<1); PORTA=PORTA&~(1<<2); PORTA=PORTA|(1<<3); _delay_ms(1); PORTA=PORTA&~(1<<3); _delay_ms(1); } void lcd_data(char x) { PORTB = x; PORTA=PORTA|(1<<1); PORTA=PORTA&~(1<<2); PORTA=PORTA|(1<<3); _delay_ms(1); PORTA=PORTA&~(1<<3); _delay_ms(1); } void lcd_string(char *x) { while(*x) { lcd_data(*x); _delay_ms(50); x++; } }
C
#include <stdlib.h> #include <stdio.h> #include <math.h> #include <pthread.h> #include <assert.h> #include <string.h> #include "march.h" void hello(void) { printf("Hello, world!\n"); } float norm(struct Vec3 vec) { return sqrt(vec.x*vec.x + vec.y*vec.y + vec.z*vec.z); } struct Vec3 unit_vec(struct Vec3 vec) { return scalar_mult(vec, 1.0f/norm(vec)); } struct Vec3 scalar_mult(struct Vec3 vec, float scalar) { struct Vec3 vect; vect.x = vec.x * scalar; vect.y = vec.y * scalar; vect.z = vec.z * scalar; return vect; } struct Vec3 vec_add(struct Vec3 u, struct Vec3 v) { struct Vec3 vect; vect.x = u.x + v.x; vect.y = u.y + v.y; vect.z = u.z + v.z; return vect; } struct Vec3 get_ray_point(struct Ray ray, float distance) { return vec_add(ray.origin, scalar_mult(unit_vec(ray.direction), distance)); } float sphere_SDF(struct Sphere sp, struct Vec3 point) { float x = sp.origin.x - point.x; float y = sp.origin.y - point.y; float z = sp.origin.z - point.z; return sqrt(x*x + y*y + z*z) - sp.r; } struct MarchVolume* march_create(void) { struct MarchVolume *mv = malloc(sizeof(struct MarchVolume)); memset(mv, 0xCC, sizeof(struct MarchVolume)); *mv = (struct MarchVolume) {(struct Vec3) {0.0f, 0.0f, 0.0f}, 0, NULL, 0, NULL, NULL, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0, 0, 0.0f, 0.0f, 0.0f, 0.0f}; return mv; } int march_destroy(struct MarchVolume *mv) { if (!mv) return -1; if (mv->volumes) free(mv->volumes); if (mv->matrix) free(mv->matrix); free(mv); return 0; } int march_init(struct MarchVolume *mv, struct Cloud *volumes, int n_vols, float resolution, int PROJECTION, Evaluator eval, int mat_cell_bytes) { mv->volumes = volumes; mv->resolution = resolution; mv->n_vols = n_vols; mv->evaluate = eval; float r_max = 0.0f; struct Vec3 point; for (int i = 0; i < n_vols; i++) { point = volumes[i].volume.origin; if (point.x < mv->x_min) mv->x_min = point.x; if (point.x > mv->x_max) mv->x_max = point.x; if (point.y < mv->y_min) mv->y_min = point.y; if (point.y > mv->y_max) mv->y_max = point.y; if (point.z < mv->z_min) mv->z_min = point.z; if (point.z > mv->z_max) mv->z_max = point.z; if (volumes[i].volume.r > r_max) r_max = volumes[i].volume.r; } mv->x_max += r_max; mv->x_min -= r_max; mv->y_max += r_max; mv->y_min -= r_max; mv->z_max += r_max; mv->z_min -= r_max; float vol_width = 0.0f, vol_height = 0.0f; switch (PROJECTION) { case XY: vol_width = mv->x_max - mv->x_min; vol_height = mv->y_max - mv->y_min; mv->proj_direction = (struct Vec3){0.0f, 0.0f, -1.0f}; mv->w_img_plane = mv->z_max; mv->w_depth_bound = mv->z_min; break; case YZ: break; case ZX: break; } mv->matrix_u = (int)(vol_width / resolution); mv->matrix_v = (int)(vol_height / resolution); mv->u_cell_width = vol_width / mv->matrix_u; mv->v_cell_height = vol_height / mv->matrix_v; if (mv->matrix) free(mv->matrix); mv->matrix = malloc(mat_cell_bytes * mv->matrix_u * mv->matrix_v); if (!mv->matrix) return -1; return 0; } int run_march(struct MarchVolume *mv) { if (!mv || !mv->volumes || !mv->matrix) return -1; if (!USE_THREADING) { // Run in main thread struct Subregion full; full.mv = mv; full.u0 = 0; full.v0 = 0; full.u1 = mv->matrix_u; full.v1 = mv->matrix_v; march_subvolume((void*)&full); return 0; } // Require NUM_THREADS to be a multiple of 2 for easy workload division assert(NUM_THREADS % 2 == 0); pthread_t pool[NUM_THREADS]; // Find an intermediate divisor of NUM_THREADS to calculate grid meshing // We assert that NUM_THREADS is even above so NUM_THREADS % 2 is // guaranteed to produce a valid arrangement int cols = (int)sqrt(NUM_THREADS); for (; cols > 2; cols--) { if (NUM_THREADS % cols == 0) break; } int rows = NUM_THREADS / cols; fprintf(stderr, "Rows: %d, Cols: %d", rows, cols); // Compute the corners of the subregions and launch threads struct Subregion chunks[NUM_THREADS]; for (int v = 0; v < rows; v++) { for (int u = 0; u < cols; u++) { struct Subregion *region = &chunks[u + cols*v]; region->mv = mv; region->u0 = u * (mv->matrix_u/cols); region->v0 = v * (mv->matrix_v/rows); if (u == cols - 1) region->u1 = mv->matrix_u; else region->u1 = region->u0 + mv->matrix_u / cols; if (v == rows - 1) region->v1 = mv->matrix_v; else region->v1 = region->v0 + mv->matrix_v / rows; int result_code = pthread_create(&pool[u + cols*v], NULL, march_subvolume, (void*)region); assert(!result_code); } } // Wait for threads to finish for (int i = 0; i < NUM_THREADS; i++) { int result_code = pthread_join(pool[i], NULL); assert(!result_code); } return 0; } void* march_subvolume(void *args) { struct Subregion *region = (struct Subregion*)args; struct MarchVolume *mv = region->mv; struct Ray cast; cast.direction = mv->proj_direction; // Generalize: cast.origin.z = mv->w_img_plane; float u_min = mv->x_min; float v_min = mv->y_min; for (int u = region->u0; u < region->u1; u++) { for (int v = region->v0; v < region->v1; v++) { cast.origin.x = u_min + u*mv->u_cell_width; cast.origin.y = v_min + v*mv->v_cell_height; march_ray(cast, mv, u, v); } } return NULL; } void march_ray(struct Ray cast, struct MarchVolume *mv, int u, int v) { float depth = 0.0f; float max_depth = fabs(mv->w_img_plane - mv->w_depth_bound); while (depth < max_depth) { depth += mv->resolution; mv->evaluate(mv, get_ray_point(cast, depth), u, v); } } void test_volumes(struct MarchVolume *mv, struct Vec3 point, int u, int v) { float sdf = 0.0f; for (int i = 0; i < mv->n_vols; i++) { sdf = sphere_SDF(mv->volumes[i].volume, point); if (sdf < 0.0f) { ((float*)mv->matrix)[u + v * mv->matrix_u] += mv->volumes[i].density; } } }
C
#include <math.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <assert.h> #include <limits.h> #include <stdbool.h> int main(){ int n; int t; scanf("%d %d",&n,&t); int width[n+5]; for(int i = 0; i < n; i++){ scanf("%d",&width[i]); } for(int a = 0; a < t; a++){ int i; int j; int min=5; // min=width[i];//printf("%d a\n",min); scanf("%d %d",&i,&j); for(int k=i;k<=j;k++){ if(width[k]<min){min=width[k];} } printf("%d\n",min); } return 0; }
C
//工作队列使用说明 内核线程处理工作队列 1>>定义个数据结构 static struct work_struct work; 2>>初始化工作队列 INIT_WORK(&work,work_handler); 3>>进行工作队列调度 schedule_work(&work);//放入队列并唤醒线程 >>源码讲解 static inline bool schedule_work(struct work_struct *work) { //放入系统提供的默认队列中 return queue_work(system_wq, work); } static inline bool queue_work(struct workqueue_struct *wq, struct work_struct *work) { return queue_work_on(WORK_CPU_UNBOUND, wq, work); } bool queue_work_on(int cpu, struct workqueue_struct *wq, struct work_struct *work) { bool ret = false; unsigned long flags; local_irq_save(flags);//关中断 //WORK_STRUCT_PENDING_BIT = 0, /* work item is pending execution */ test_and_set_bit(int nr, long* addr) 将*addr 的第n位设置成1,并返回原来这一位的值 if (!test_and_set_bit(WORK_STRUCT_PENDING_BIT, work_data_bits(work))) { __queue_work(cpu, wq, work); ret = true; } local_irq_restore(flags);//开中断 return ret; } EXPORT_SYMBOL(queue_work_on); struct work_struct { atomic_long_t data; struct list_head entry; work_func_t func; #ifdef CONFIG_LOCKDEP struct lockdep_map lockdep_map; #endif }; //系统的工作队列如何创建的 是否可以这样理解 work_pool结构体 管理对应的线程 static int __init init_workqueues(void) { /* initialize CPU pools */ for_each_possible_cpu(cpu) { struct worker_pool *pool; i = 0; /* 对每一个CPU都创建2个worker_pool结构体,它是含有ID的 */ /* 一个worker_pool对应普通优先级的work,第2个对应高优先级的work */ for_each_cpu_worker_pool(pool, cpu) { BUG_ON(init_worker_pool(pool)); pool->cpu = cpu; cpumask_copy(pool->attrs->cpumask, cpumask_of(cpu)); pool->attrs->nice = std_nice[i++]; pool->node = cpu_to_node(cpu); /* alloc pool ID */ mutex_lock(&wq_pool_mutex); BUG_ON(worker_pool_assign_id(pool)); mutex_unlock(&wq_pool_mutex); } } /* create the initial worker */ /* 对每一个CPU的每一个worker_pool,创建一个worker */ /* 每一个worker对应一个内核线程 */ for_each_online_cpu(cpu) { struct worker_pool *pool; //对于每一个pool创建内核线程 for_each_cpu_worker_pool(pool, cpu) { pool->flags &= ~POOL_DISASSOCIATED; BUG_ON(!create_worker(pool));//创建内核线程 } } //workqueue_struct *system_wq; //system_wq = $1 = (struct workqueue_struct *) 0xffff8ddbff80d800 /* alloc_workqueue() 申请一个workqueue_struct(system_wq)让系统使用 schedule_work(&work);-->>queue_work(system_wq, work); 但是一个问题?worker_pool和workqueue_struct如何关联起来的? init_workqueues system_wq = alloc_workqueue("events", 0, 0);//次函数会做关联操作 __alloc_workqueue_key wq = kzalloc(sizeof(*wq) + tbl_size, GFP_KERNEL); // 分配workqueue_struct alloc_and_link_pwqs(wq) // 跟worker_poll建立联系 */ system_wq = alloc_workqueue("events", 0, 0); system_highpri_wq = alloc_workqueue("events_highpri", WQ_HIGHPRI, 0); system_long_wq = alloc_workqueue("events_long", 0, 0); system_unbound_wq = alloc_workqueue("events_unbound", WQ_UNBOUND, WQ_UNBOUND_MAX_ACTIVE); system_freezable_wq = alloc_workqueue("events_freezable", WQ_FREEZABLE, 0); system_power_efficient_wq = alloc_workqueue("events_power_efficient", WQ_POWER_EFFICIENT, 0); system_freezable_power_efficient_wq = alloc_workqueue("events_freezable_power_efficient", WQ_FREEZABLE | WQ_POWER_EFFICIENT, 0); } static struct worker *create_worker(struct worker_pool *pool) { struct worker *worker = NULL; int id = -1; char id_buf[16]; /* ID is needed to determine kthread name */ id = ida_simple_get(&pool->worker_ida, 0, 0, GFP_KERNEL); worker = alloc_worker(pool->node); worker->pool = pool; worker->id = id; if (pool->cpu >= 0) snprintf(id_buf, sizeof(id_buf), "%d:%d%s", pool->cpu, id, pool->attrs->nice < 0 ? "H" : ""); else snprintf(id_buf, sizeof(id_buf), "u%d:%d", pool->id, id); //创建的内核线程 worker->task = kthread_create_on_node(worker_thread, worker, pool->node, "kworker/%s", id_buf); set_user_nice(worker->task, pool->attrs->nice); kthread_bind_mask(worker->task, pool->attrs->cpumask); /* successful, attach the worker to the pool */ worker_attach_to_pool(worker, pool); /* start the newly created worker */ spin_lock_irq(&pool->lock); worker->pool->nr_workers++; worker_enter_idle(worker); wake_up_process(worker->task); spin_unlock_irq(&pool->lock); return worker; return NULL; } //内核线程死循环在worker_thread 等待work任务 static int worker_thread(void *__worker) { struct worker *worker = __worker; struct worker_pool *pool = worker->pool; /* tell the scheduler that this is a workqueue worker */ worker->task->flags |= PF_WQ_WORKER; woke_up: spin_lock_irq(&pool->lock); /* am I supposed to die? */ if (unlikely(worker->flags & WORKER_DIE)) { spin_unlock_irq(&pool->lock); WARN_ON_ONCE(!list_empty(&worker->entry)); worker->task->flags &= ~PF_WQ_WORKER; set_task_comm(worker->task, "kworker/dying"); ida_simple_remove(&pool->worker_ida, worker->id); worker_detach_from_pool(worker, pool); kfree(worker); return 0; } worker_leave_idle(worker); recheck: /* no more worker necessary? */ if (!need_more_worker(pool)) goto sleep; /* do we need to manage? */ if (unlikely(!may_start_working(pool)) && manage_workers(worker)) goto recheck; /* * ->scheduled list can only be filled while a worker is * preparing to process a work or actually processing it. * Make sure nobody diddled with it while I was sleeping. */ WARN_ON_ONCE(!list_empty(&worker->scheduled)); /* * Finish PREP stage. We're guaranteed to have at least one idle * worker or that someone else has already assumed the manager * role. This is where @worker starts participating in concurrency * management if applicable and concurrency management is restored * after being rebound. See rebind_workers() for details. */ worker_clr_flags(worker, WORKER_PREP | WORKER_REBOUND); do { struct work_struct *work = list_first_entry(&pool->worklist, struct work_struct, entry); pool->watchdog_ts = jiffies; if (likely(!(*work_data_bits(work) & WORK_STRUCT_LINKED))) { /* optimization path, not strictly necessary */ process_one_work(worker, work); if (unlikely(!list_empty(&worker->scheduled))) process_scheduled_works(worker); } else { move_linked_works(work, &worker->scheduled, NULL); process_scheduled_works(worker); } } while (keep_working(pool)); worker_set_flags(worker, WORKER_PREP); sleep: /* * pool->lock is held and there's no work to process and no need to * manage, sleep. Workers are woken up only while holding * pool->lock or from local cpu, so setting the current state * before releasing pool->lock is enough to prevent losing any * event. */ worker_enter_idle(worker); __set_current_state(TASK_INTERRUPTIBLE); spin_unlock_irq(&pool->lock); schedule(); goto woke_up; }
C
/* Problem Statement : Write a program which creates three diffrent processess internally as process2, process3, process4. */ #include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> int main(int argc,char *argv[]) { int iRet = 0; int status = 0; int pid = 0; if((iRet=fork())==0) { if((iRet=fork())==0) { printf("Process-2 is created....\n"); execl("./Process2","",NULL); } } else { if((iRet=fork())==0) { printf("Process-3 is created....\n"); execl("./Process3","",NULL); } else { if((iRet=fork())==0) { printf("Process-4 is created....\n"); execl("./Process4","",NULL); } else { while((pid=wait(&status))>0); } } } exit(0); }
C
//program to print sum upto given number using recursion. #include <stdio.h> int sum(int n); int main(){ int n; int x; printf("Enter a number\n"); scanf("%d",&n); x = sum(n); printf("Sum upto %d no. is %d",n,x); return 0; } int sum(int n){ if (n != 0) return n + sum(n-1); }
C
#include <sys/types.h> #include <fcntl.h> #include <unistd.h> #include <errno.h> #include <stdlib.h> #include <stdio.h> #include <string.h> /* modules */ #include "loopback.h" #include "xmpp.h" #define err_exit(str) { \ perror(str); \ exit(errno); \ } #define PPPOAT_DESCR "PPPoAT" #define PPPOAT_VERSION "dev" #define STD_LOG_PATH "/var/log/pppoat.log" #define STD_PPPD_PATH "/usr/sbin/pppd" #define ARG_MODULE 1 #define ARG_LOG_PATH 2 struct module { char *name; int (*func)(int, char **, int, int); }; struct module mod_tbl[] = { #ifdef MOD_LOOP {"loop", &mod_loop}, #endif #ifdef MOD_XMPP {"xmpp", &mod_xmpp}, #endif {"", NULL}, }; int quiet = 0; char *prog_name; static void help(char *name) { printf(PPPOAT_DESCR " version " PPPOAT_VERSION "\n" "Usage: %s [options] [<local_ip>:<remote_ip>] [-- [module's options]]\n" "\n" "Options:\n" " -h, --help\tprint this text and exit\n" " -l, --list\tprint list of available modules and exit\n" " -L <path>\tspecify file for logging\n" " -m <module>\tchoose module\n" " -q, --quiet\tdon't print anything to stdout\n", name); exit(0); } static void list_mod() { int i = 0; while (mod_tbl[i].func) { printf("%s\n", mod_tbl[i].name); i++; } exit(0); } static int is_mod(char *name) { int i = 0; while (mod_tbl[i].func) { if (!strcmp(name, mod_tbl[i].name)) return i; i++; } return -1; } static int redirect_logs(char *path) { int fd; if (!path) goto out; fd = open(path, O_WRONLY | O_CREAT | O_APPEND, 0664); if (fd < 0 || dup2(fd, 2) < 0) goto out_fd; close(fd); return 0; out_fd: if (fd > 0) close(fd); out: fprintf(stderr, "%s: can't open log file %s\n", prog_name, path); fprintf(stderr, "%s: logging will continue to stderr.\n", prog_name); return -1; } int main(int argc, char **argv) { /* pipe descriptors */ int pd_rd[2], pd_wr[2]; pid_t pid; char *pppd = STD_PPPD_PATH; char *log_path = STD_LOG_PATH; char *ip = NULL; char *mod_name = NULL; int mod_idx; int i; int need_arg = 0; int mod_argc = 0; char **mod_argv = NULL; prog_name = argv[0]; /* parsing arguments */ if (argc < 2) help(argv[0]); for (i = 1; i < argc; i++) { if (need_arg) { switch (need_arg) { case ARG_MODULE: mod_name = argv[i]; break; case ARG_LOG_PATH: log_path = argv[i]; break; default: fprintf(stderr, "there is internal problem with parsing arguments\n"); return 1; } need_arg = 0; continue; } if (argv[i][0] != '-') { /* <local_ip>:<remote_ip> */ ip = argv[i]; continue; } if (!strcmp("-h", argv[i]) || !strcmp("--help", argv[i])) /* print help and exit */ help(argv[0]); if (!strcmp("-l", argv[i]) || !strcmp("--list", argv[i])) /* print list of available modules and exit */ list_mod(); if (!strcmp("-L", argv[i])) { /* specify file for logging */ need_arg = ARG_LOG_PATH; continue; } if (!strcmp("-m", argv[i])) { /* choose module */ need_arg = ARG_MODULE; continue; } if (!strcmp("-q", argv[i]) || !strcmp("--quiet", argv[i])) { /* quiet mode */ quiet = 1; continue; } if (!strcmp("--", argv[i])) { /* TODO: set pointer to i+1, the rest options are for pppd */ mod_argv = argv + i; mod_argc = argc - i; break; } /* unrecognized options may be addressed for the module */ } if (need_arg) { fprintf(stderr, "incomplete arguments, see %s --help\n", argv[0]); return 2; } /* check whether required arguments are set */ if (!mod_name) { fprintf(stderr, "you must choose a module, see %s --help\n", argv[0]); return 2; } /* redirect logs to a file */ redirect_logs(log_path); /* check whether module name is correct */ if ((mod_idx = is_mod(mod_name)) < 0) { fprintf(stderr, "there isn't such a module: %s\n", mod_name); return 2; } /* create pipes for communication with pppd */ if (pipe(pd_rd) < 0) err_exit("pipe"); if (pipe(pd_wr) < 0) err_exit("pipe"); /* exec pppd */ if ((pid = fork()) < 0) err_exit("fork"); if (!pid) { if (dup2(pd_rd[1], 1) < 0) err_exit("dup2"); if (dup2(pd_wr[0], 0) < 0) err_exit("dup2"); close(pd_rd[0]); close(pd_rd[1]); close(pd_wr[0]); close(pd_wr[1]); execl(pppd, pppd, "nodetach", "noauth", "notty", "passive", ip, NULL); err_exit("execl"); } close(pd_rd[1]); close(pd_wr[0]); /* run appropriate module's function */ return mod_tbl[mod_idx].func(mod_argc, mod_argv, pd_rd[0], pd_wr[1]); }
C
char buffer[100]; #include <stdio.h> #include <string.h> void main() { char *f = buffer; char *g = buffer; printf("%8.8x\n", f); f=(char*)memset(f,0x0a,12); printf("%8.8x\n", f); if (f == g) { int k = 12; while (k--) printf("%2.2x", *f++); } }
C
#include <stdio.h> #include <stdlib.h> #define p 3.14 double calc_circle(double radius); int main(void) { double radius; double ans; printf("radius:"); scanf("%lf",&radius); ans = calc_circle(radius); printf("Area = %f\n",ans); exit(EXIT_SUCCESS); } double calc_circle(double radius) { double ans; ans = radius * radius * p; return ans; }
C
// File: mypthread_t.h // List all group member's name: Jonathan Konopka, Anthony Siu // username of iLab: // iLab Server: #ifndef MYTHREAD_T_H #define MYTHREAD_T_H #define _GNU_SOURCE /* To use Linux pthread Library in Benchmark, you have to comment the USE_MYTHREAD macro */ #define USE_MYTHREAD 1 /* include lib header files that you need here: */ #include <unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <ucontext.h> #include <sys/time.h> #include <signal.h> typedef uint mypthread_t; typedef struct threadControlBlock { /* add important states in a thread control block */ // thread Id int id; // thread status int status; // 0 = running, 1 = ready, 2 = blocked, 3 = scheduled // thread context struct ucontext_t *context; // thread stack // thread priority // And more ... void *output; int elapsed; //indicates how many time quantum has expired since the time thread was scheduled int p_level; void * retval; } tcb; /* mutex struct definition */ typedef struct mypthread_mutex_t { /* add something here */ // YOUR CODE HERE int id; int locked; // 0 = unlocked, 1 = locked } mypthread_mutex_t; //Linked List struct node { struct threadControlBlock *tcb; struct node *next; }; //insert link at the first location struct node* insertNode(struct node *list, struct threadControlBlock *inputtcb) { //create a link struct node *link = (struct node*) malloc(sizeof(struct node)); link->tcb = inputtcb; link->next = NULL; int inputquantum = inputtcb->elapsed; struct node *temp = list; struct node *prev = NULL; while (temp != NULL) { if (inputquantum <= temp->tcb->elapsed) { link->next = temp; prev->next = link; break; } prev = temp; temp = temp->next; } if (temp == NULL) { prev->next = link; } return list; } //is list empty int isEmpty(struct node *list) { return (list == NULL); } //delete first item struct threadControlBlock* deleteFirst(struct node *list) { //save reference to first link struct node *firstNode = list; //mark next to first link as first list = list->next; if (isEmpty(list)) { free(list); } //return the deleted link return firstNode->tcb; } /* Function Declarations: */ /* create a new thread */ int mypthread_create(mypthread_t * thread, pthread_attr_t * attr, void *(*function)(void*), void * arg); /* give CPU pocession to other user level threads voluntarily */ int mypthread_yield(); /* terminate a thread */ void mypthread_exit(void *value_ptr); /* wait for thread termination */ int mypthread_join(mypthread_t thread, void **value_ptr); /* initial the mutex lock */ int mypthread_mutex_init(mypthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr); /* aquire the mutex lock */ int mypthread_mutex_lock(mypthread_mutex_t *mutex); /* release the mutex lock */ int mypthread_mutex_unlock(mypthread_mutex_t *mutex); /* destroy the mutex */ int mypthread_mutex_destroy(mypthread_mutex_t *mutex); /* helper for runqueque */ void thread_runner(void *(*function)(void*), void *arg); #ifdef USE_MYTHREAD #define pthread_t mypthread_t #define pthread_mutex_t mypthread_mutex_t #define pthread_create mypthread_create #define pthread_exit mypthread_exit #define pthread_join mypthread_join #define pthread_mutex_init mypthread_mutex_init #define pthread_mutex_lock mypthread_mutex_lock #define pthread_mutex_unlock mypthread_mutex_unlock #define pthread_mutex_destroy mypthread_mutex_destroy #endif #endif
C
#include <stdio.h> void sum_odd(int n); void main() { int n; printf("Enter n: "); scanf("%d",&n); sum_odd(n); } void sum_odd(int n){ int sum=0; for(int i=0;i<n;i++){ printf("%d",2*i); if(i!=n-1) printf(" + "); sum += i*2; } printf(" = %d",sum); }
C
struct Room { char* description; char* requirement; struct Item* items; struct Room* north; struct Room* south; struct Room* east; struct Room* west; struct Room* up; struct Room* down; }; /* construct a room using malloc rooms are initialized with a null Item (item(NULL, NULL, NULL);) */ struct Room * room(char* description, char* requirement); //For each room, free its items, the room itself, and nullify the pointer. void freeRooms(struct Room* rooms[8]); /* print a visual representation of a room. The visual representation uses if statements to print doors and stairs corresponding to if a room has (a) neighboring room(s). room -> non-null room */ void roomToString(struct Room * room);
C
#include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <poll.h> #include <sys/types.h> #include "packet.h" // do initial setup for socket int setup(int* channel, int num_channels){ ////////////////////// SETTING UP SERVER SIDE ///////////////////////////////// // Create a TCP Socket for server int svr_socket = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(svr_socket < 0) error("Error while creating server socket\n"); // constructing address structure for server struct sockaddr_in svr_address, clt_address; memset (&svr_address, 0, sizeof(svr_address)); svr_address.sin_family = AF_INET; svr_address.sin_port = htons(SERVER_PORT); svr_address.sin_addr.s_addr = htonl(INADDR_ANY); // binding the server socket to the server address int temp = bind(svr_socket, (struct sockaddr*) &svr_address, sizeof(svr_address)); if (temp < 0) error("Error while binding\n"); temp = listen(svr_socket, num_channels); if (temp < 0) error("Error while listening\n"); //////////////////////////// ACCEPTING CLIENT SOCKETS ////////////////////////////// // Accept client channels int clt_length = sizeof(clt_address); for(int i=0;i<num_channels;i++){ channel[i] = accept(svr_socket, (struct sockaddr*) &clt_address, &clt_length); if(clt_length < 0) error("Error while accepting client\n"); } return svr_socket; } int recieve(int channel, FILE* fp, PACKET* recieved){ int recvsize; recvsize = recv(channel, recieved, sizeof(PACKET), 0); if(recvsize == -1) error("Error while recieving packet through channel\n"); if(recieved->ifData == 0) error("Error: DATA packet expected, recieved an ACK packet\n"); return recvsize; } void create_packet(PACKET* sent, int seq, int channel){ sent->size = 0; sent->seq = seq; sent->ifLast = 0; sent->ifData = 0; sent->channel = channel; } int main (){ int num_channels = 2; int channel[num_channels]; int svr_socket = setup(channel, num_channels); // initialize packets and buffer to handle out of order packets PACKET sent, recieved; int expectedSeq = 0; PACKET buffer[BUFFER_SIZE]; for(int i=0;i<BUFFER_SIZE;i++) buffer[i].seq = -1; // select, read and send to clients FILE* fp = fopen("output.txt", "w"); fd_set read_channels, temp_channels; int fd_max = channel[num_channels-1]; FD_ZERO(&read_channels); FD_ZERO(&temp_channels); for(int i=0;i<num_channels;i++) FD_SET(channel[i], &read_channels); while(1){ // if channel is ready to read, read data packeta and send ack or drop the packet temp_channels = read_channels; if(select(fd_max+1, &temp_channels, NULL, NULL, NULL)==-1) error("Error while selecting client channel\n"); int i; for(i=0;i<num_channels;i++){ if(FD_ISSET(channel[i],&temp_channels)){ if(recieve(channel[i], fp, &recieved)==0) break; printf("RCVD PKT: Seq. No. %d of size %d bytes from channel %d\n", recieved.seq, recieved.size,i); if(rand()%100>=PACKET_DROP_RATE){ create_packet(&sent, recieved.seq, i); // if it is the expected packet or there is still space left in buffer, send ack if(expectedSeq == recieved.seq || buffer[(recieved.seq/PACKET_SIZE) % BUFFER_SIZE].seq == -1){ if(send(channel[i], &sent, sizeof(sent),0) != sizeof(sent)) error("Error while sending packet\n"); printf("SENT ACK: for PKT with Seq. No. %d from channel %d\n", recieved.seq, i); } // if it is the expected packet, write this packet and the buffered packets in order // else if buffer still has space, buffer the packet if(expectedSeq == recieved.seq){ fwrite(recieved.data, sizeof(char), recieved.size, fp); expectedSeq += recieved.size; while(buffer[(expectedSeq/PACKET_SIZE) % BUFFER_SIZE].seq == expectedSeq){ int val = (expectedSeq/PACKET_SIZE) % BUFFER_SIZE; fwrite(buffer[val].data, sizeof(char), buffer[val].size, fp); expectedSeq += buffer[val].size ; buffer[val].seq = -1; } } else if(buffer[(recieved.seq/PACKET_SIZE) % BUFFER_SIZE].seq == -1){ buffer[(recieved.seq/PACKET_SIZE) % BUFFER_SIZE] = recieved; } } } } if(i!=num_channels) break; } for(int i=0;i<num_channels;i++) close(channel[i]); close(svr_socket); fclose(fp); }
C
#include <stdio.h> int main() { int d, c; int count = 0; scanf("%d", &d); for (int i = 0; i < 5; i++) { scanf("%d", &c); if (d == c)count++; } printf("%d", count); return 0; } ​
C
#include "data_store.h" #include "stream_parse.h" int stream_input_parse(stream_buffer *sb, char *path); int main(int argc, char **argv) { //step1: 解析参数,参数应该包括需要读取的文件名或者一个网络地址 char *path, *word; int len, ret; //step2: 对象初始化,初始化stream buffer和data store stream_buffer *sb; data_store *ds; data_store_object *set; for (int i=1 ; i<argc ; i++) { path = argv[i]; sb = stream_buffer_create(WF_SB_CAPACITY); if (!sb) { puts("memory error!"); continue; } #ifdef DATA_STORE_LIST ds = data_store_create(); if (!ds) { puts("memory error!\n"); continue; } #endif #ifdef DATA_STORE_ARRAY ds = data_store_create(WF_ARRAY_CAPACITY); if (!ds) { puts("memory error!\n"); continue; } #endif set = data_store_object_array_creat(WF_WORD_PRINT_NUMBER); if (!set) { puts("memory error!\n"); return 1; } word = (char *)calloc(1, sizeof(char)*WORD_SIZE); if (!word) { puts("memory error!\n"); return 1; } //step3: stream input流程处理,包括将处理好的word存进stream buffer ret = stream_input_parse(sb, path); if (ret == ENOMEM) { puts("memory error\n"); continue; } if (ret == WF_SB_FULL) { puts("stream_buffer full\n"); continue; } //step4: 依次将stream buffer中的word存进data store中 while (1) { ret = stream_buffer_get_word(sb, word); if (ret == WORD_GET_FAIL) break; ret = data_store_insert_count(ds, word); if (ret == WF_WORD_INSERT_FAIL) { printf("word:%s insert failed\n",word); continue; } } //step5: 对data store进行排序,然后获取个数最多的10个word,打印 ret = data_store_sort(ds); if (ret) puts("data store is empty\n"); data_store_get_max_count (ds, set, WF_WORD_PRINT_NUMBER); data_store_print_max_count (set, path); data_store_object_array_destroy(set, WF_WORD_PRINT_NUMBER); stream_buffer_destroy (sb); data_store_destroy (ds); free(word); } return 0; //备注:有空可以考虑一下,为什么对数据进行多份存储,以及为什么对框架进行这种划分? /*多份存储便于根据数据类型选择执行效率更高的存储方式,这样的框架划分,将程序处理过程模块化,便于编程和排错*/ }
C
#include <stdio.h> #define MAXLINE 1000 /* 入力の最大行数 */ int getline_(char line[], int maxline); void reverse(char to[], char from[], int len); int main() { int len; /* 現在行の長さ */ char line[MAXLINE]; /* 現在の入力行 */ char reverse_line[MAXLINE];/* 格納されている最長行 */ while ((len = getline_(line, MAXLINE)) > 0) { reverse(reverse_line, line, len); printf("%s", reverse_line); } if (len == -1) printf("最大字数を超えています"); return 0; } int getline_(char s[], int lim) { int c, i; for (i = 0; (c = getchar()) != EOF && c != '\n'; ++i) if(i >= lim) return -1; else s[i] = c; if (c == '\n') { s[i] = c; ++i; } s[i] = '\0'; return i; } void reverse(char to[], char from[], int len) { int i; for(i = 0; i < MAXLINE; ++i) to[i] = '\0'; for (i = 0; i < len; ++i) to[i] = from[len - i - 1]; } //演習1-19 文字列sを逆に並べる関数reverse(s)を書け。さらに、この関数を使って、入力を一時に一行ずつ逆転するプログラムを書け。 // (日本語非対応)
C
#include <stdio.h> int main(void) { int a; printf("Enter a"); scanf("%d", &a); if (a >= 90) { a=4; } else if (a < 90) { a=3; } else if (a < 80) { a=2; } else if (a < 70) { a=1; } else { a=0; } switch (a) { case 4: printf("Excellent"); break; case 3: printf("Good"); break; case 2: printf("Average"); break; case 1: printf("Poor"); break; case 0: printf("Failing"); break; default: printf("no"); break; } return 0; }
C
class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { if(matrix.size()==0){ return 0; } vector<int> tmp(matrix[0].size(),-1); vector<vector<int>> result(matrix.size(),tmp); int longest=-1; for(int i=0;i<matrix.size();++i){ for(int j=0;j<matrix[i].size();++j){ int var=recursive(matrix,result,i,j); if(longest<var){ longest=var; } } } return longest; } int recursive(vector<vector<int>>& matrix, vector<vector<int>>&result, int row, int col){ if(result[row][col]!=-1){ return result[row][col]; } int left,right,up,down; if(row==0 or matrix[row-1][col]<=matrix[row][col]){ up=0; }else{ up=recursive(matrix,result,row-1,col); } if(row==matrix.size()-1 or matrix[row+1][col]<=matrix[row][col]){ down=0; }else{ down=recursive(matrix,result,row+1,col); } if(col==0 or matrix[row][col-1]<=matrix[row][col]){ left=0; }else{ left=recursive(matrix,result,row,col-1); } if(col==matrix[0].size()-1 or matrix[row][col+1]<=matrix[row][col]){ right=0; }else{ right=recursive(matrix,result,row,col+1); } return result[row][col]=max(up,down,left,right)+1; } int max(int a,int b,int c,int d){ if(a>b){ return max(a,c,d); }else{ return max(b,c,d); } } int max(int a,int b,int c){ if(a>b){ if(a>c){ return a; }else{ return c; } }else{ if(b>c){ return b; }else{ return c; } } } };
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include "../ran.h" #include "../mymath.h" #include "../structure.h" #include "../Kernels.h" /*===============================================*/ /*O(MAXPOPS*numalleles + NUMINDS*LINES) */ void GetNumFromPop (int *NumAFromPop, int *Geno, int *Z, int loc, int numalleles,struct IND *Individual) { /*Fill in the number of each allele from each pop */ int ind, line, pop, allele; /* int genpos; */ int allelevalue; int popvalue; /* O(MAXPOPS*numalleles) */ for (pop = 0; pop < MAXPOPS; pop++) { for (allele = 0; allele < numalleles; allele++) { NumAFromPop[NumAFromPopPos (pop, allele)] = 0; } } /* O(NUMINDS*LINES) */ if (PFROMPOPFLAGONLY) { /*this option uses only individuals with POPFLAG=1 to update P*/ for (ind = 0; ind < NUMINDS; ind++) { if (Individual[ind].PopFlag == 1) { /*individual must have popflag turned on*/ for (line = 0; line < LINES; line++) { popvalue = Z[ZPos (ind, line, loc)]; allelevalue = Geno[GenPos (ind, line, loc)]; if ((allelevalue != MISSING) && (popvalue != UNASSIGNED)) { NumAFromPop[NumAFromPopPos (popvalue, allelevalue)]++; } } } } } else { /*standard update--use everybody to update P */ for (ind = 0; ind < NUMINDS; ind++) { for (line = 0; line < LINES; line++) { popvalue = Z[ZPos (ind, line, loc)]; allelevalue = Geno[GenPos (ind, line, loc)]; if ((allelevalue != MISSING) && (popvalue != UNASSIGNED)) { NumAFromPop[NumAFromPopPos (popvalue, allelevalue)]++; } } } } } void GetNumFromPops (int *NumAFromPops, int *Geno, int *Z, int *NumAlleles, struct IND *Individual) { int loc; int ind, line, pop, allele; int allelevalue; int popvalue; int numalleles; int offset; for (loc = 0; loc < NUMLOCI; loc++) { numalleles = NumAlleles[loc]; offset = loc*MAXPOPS*MAXALLELES; /*Fill in the number of each allele from each pop */ /* int genpos; */ /* O(MAXPOPS*numalleles) */ for (pop = 0; pop < MAXPOPS; pop++) { for (allele = 0; allele < numalleles; allele++) { NumAFromPops[NumAFromPopPos (pop, allele)+offset] = 0; } } /* O(NUMINDS*LINES) */ for (ind = 0; ind < NUMINDS; ind++) { if (!PFROMPOPFLAGONLY || Individual[ind].PopFlag == 1) { /*individual must have popflag turned on*/ for (line = 0; line < LINES; line++) { popvalue = Z[ZPos (ind, line, loc)]; allelevalue = Geno[GenPos (ind, line, loc)]; if ((allelevalue != MISSING) && (popvalue != UNASSIGNED)) { NumAFromPops[NumAFromPopPos (popvalue, allelevalue) + offset]++; } } } } } } /*------------------------------------------*/ /* * O(NUMLOCI*(MAXPOPS* (max_loc NumAlleles[loc]) + NUMINDS*LINES)) => * O(NUMLOCI*(MAXPOPS*MAXALLELES + NUMINDS*LINES)) */ void UpdateP (float *P, float *Epsilon, float *Fst, int *NumAlleles, int *Geno, int *Z, float *lambda, struct IND *Individual, float * randomArr) /*Simulate new allele frequencies from Dirichlet distribution */ { int loc, pop, allele; float *Parameters; /*[MAXALLS] **Parameters of posterior on P */ /*int *NumAFromPop; [>[MAXPOPS][MAXALLS] **number of each allele from each pop <]*/ int *NumAFromPops;/*[NUMLOCI][MAXPOPS][MAXALLS] **number of each allele from each pop at each loc */ int popsoffset; RndDiscState randState[1]; Parameters = calloc(MAXALLELES, sizeof (float)); /*NumAFromPop = calloc(MAXPOPS * MAXALLELES, sizeof (int));*/ NumAFromPops = calloc(NUMLOCI*MAXPOPS * MAXALLELES, sizeof (int)); if ((Parameters == NULL) || (NumAFromPops == NULL)) { printf ("WARNING: unable to allocate array space in UpdateP\n"); Kill (); } /*initialize the NumAFromPops array*/ GetNumFromPops (NumAFromPops,Geno, Z, NumAlleles, Individual); /* O(NUMLOCI*(MAXPOPS* (max_loc NumAlleles[loc]) + NUMINDS*LINES)) */ initRndDiscState(randState,randomArr,MAXALLELES*MAXRANDOM); for (loc = 0; loc < NUMLOCI; loc++) { popsoffset = loc*MAXPOPS*MAXALLELES; /*count number of each allele from each pop */ /*O(MAXPOPS*NumAlleles[loc] + NUMINDS*LINES) */ /* * Testing: */ /*GetNumFromPop (NumAFromPop, Geno, Z, loc, NumAlleles[loc], Individual); for (pop = 0; pop < MAXPOPS; pop++) { for (allele = 0; allele < NumAlleles[loc]; allele++) { if (NumAFromPops[NumAFromPopPos (pop, allele)+popsoffset] != NumAFromPop[NumAFromPopPos (pop, allele)]) { printf("NUMAFROMPOPS NOT CORRECT!!!!\n\n\n\n\n\n\n\n\n\n\n\n\n"); } } }*/ /* O(MAXPOPS*NumAlleles[loc])*/ for (pop = 0; pop < MAXPOPS; pop++) { rndDiscStateReset(randState,popsoffset*MAXRANDOM+pop*MAXALLELES*MAXRANDOM); for (allele = 0; allele < NumAlleles[loc]; allele++) { if (FREQSCORR) { Parameters[allele] = Epsilon[EpsPos (loc, allele)] *(1.0- Fst[pop])/Fst[pop] + NumAFromPops[NumAFromPopPos (pop, allele)+popsoffset]; } else { Parameters[allele] = lambda[pop] + NumAFromPops[NumAFromPopPos (pop, allele)+popsoffset]; } } /*return a value of P simulated from the posterior Di(Parameters) */ /*O(NumAlleles[loc]) */ LogRDirichletDisc (Parameters, NumAlleles[loc], P + PPos (loc, pop, 0), randState); /*need to worry about underflow in UpdateEpsilon due to allele frequencies being set to zero---hence previously used the following hack, however now pass LogP instead for (allele=0;allele<NumAlleles[loc];allele++) if (P[PPos(loc,pop,allele)]<1E-20) { P[PPos(loc,pop,allele)]=1E-20; for (pop=0; pop<MAXPOPS; pop++) { printf(" loc =%d pop= %d fst=%f ",loc,pop,Fst[pop]); for (allele=0;allele<NumAlleles[loc];allele++) printf (" Epsilon= %.5E P= %.5E Parameters= %.5E Num= %d", Epsilon[EpsPos(loc,allele)],P[PPos(loc,pop,allele)], Parameters[allele],NumAFromPop[NumAFromPopPos (pop, allele)]); printf("\n"); } } */ } } free (Parameters); free (NumAFromPops); } void UpdatePCL (CLDict *clDict,float *P, float *Epsilon, float *Fst, int *NumAlleles, int *Geno, int *Z, float *lambda, struct IND *Individual, float * randomArr) /*Simulate new allele frequencies from Dirichlet distribution */ { /*int *NumAFromPops;*/ size_t global[2]; /* for error handling in kernel */ int error[2]; /*NumAFromPops = calloc(NUMLOCI*MAXPOPS * MAXALLELES, sizeof (int));*/ error[0] = 0; error[1] = 0; global[0] = fmin(MAXDIM,NUMINDS); global[1] = fmin(MAXDIM,NUMLOCI); /* if (ONLYONEDIM){ */ /* global[0] = 1; */ /* global[1] = 1; */ /* } */ /* * GetNumFromPops writes */ /* =================================================== */ /* already up to date on gpu */ /* Clear buffer */ /*writeBuffer(clDict,NumAFromPops,sizeof(int)* NUMLOCI*MAXPOPS*MAXALLELES, NUMAFROMPOPSCL,"NumAFromPops");*/ /*writeBuffer(clDict,error,sizeof(int)*2,ERRORCL,"error");*/ /* =================================================== */ /* * UpdateP writes */ /* =================================================== */ /*writeBuffer(clDict,randomArr, sizeof(float) * NUMLOCI*MAXALLELES*MAXPOPS*MAXRANDOM,RANDCL,"randomArr");*/ /* =================================================== */ runKernel(clDict,GetNumFromPopsKernel,2,global,"GetNumFromPops"); global[0] = fmin(MAXDIM,NUMLOCI); global[1] = fmin(MAXDIM,MAXPOPS); /* if (ONLYONEDIM){ */ /* global[0] = 1; */ /* global[1] = 1; */ /* } */ runKernel(clDict,UpdatePKernel,2,global,"UpdateP"); /*readBuffer(clDict,error,sizeof(int)*2,ERRORCL,"Error"); [> some error handling <] if (error[0] != KERNEL_SUCCESS ) { printf("UpdateP Error in Kernel:\n"); PrintKernelError(error[0]); printf("%d\n",error[1]); ReleaseCLDict(clDict); exit(EXIT_FAILURE); }*/ /*free (NumAFromPops);*/ }
C
#include <stdio.h> #include <stdlib.h> #define NumberOfNodes 22 #define NilValue -1 /*Τροποποιείση του τύπου ListElementType ώστε να αποθηκευεί τον ΑΜ και τον Βαθμό του μαθητή και αναλογες αλλαγές στις συναρτήσεις InitializeStoragePool,ReleaseNode,Insert,TraverseLinked για να περνάμε και τα δυο δεδομένα.*/ typedef struct{ int AM; float grade; } ListElementType; typedef int ListPointer; typedef struct { ListElementType Data; ListPointer Next; } NodeType; typedef enum { FALSE, TRUE } boolean; void InitializeStoragePool(NodeType Node[], ListPointer *FreePtr); void CreateLList(ListPointer *List); boolean EmptyLList(ListPointer List); boolean FullLList(ListPointer FreePtr); void GetNode(ListPointer *P, ListPointer *FreePtr, NodeType Node[]); void ReleaseNode(NodeType Node[NumberOfNodes], ListPointer P, ListPointer *FreePtr); void Insert(ListPointer *List, NodeType Node[],ListPointer *FreePtr, ListPointer PredPtr, ListElementType Item); void Delete(ListPointer *List, NodeType Node[], ListPointer *FreePtr, ListPointer PredPtr); void TraverseLinked(ListPointer List, NodeType Node[]); int main() { int number_of_students,i,j; ListPointer AList; NodeType Node[NumberOfNodes]; ListPointer FreePtr,PredPtr; ListElementType Item; /*Δημιουεγεία κενής ΣΛ.(Ερώτημα i)*/ InitializeStoragePool(Node, &FreePtr); CreateLList(&AList); /*Διάβασμα πλήθους μαθητών και έλεγχος εγκυρότητας.(Ερώτημα ii)*/ do{ printf("DWSE ARI8MO MA8ITWN:"); scanf("%d",&number_of_students); if(number_of_students < 0 || number_of_students >20) printf("MH EPITREPTOS ARI8MOS.PROSPA8ISTE KSANA.\n"); }while(number_of_students < 0 || number_of_students >20); /*Διάβασμα στοιχείων μαθητών και εμφάνιση ΣΛ με την συνάρτηση TraverseLinked.(Ερώτημα iii)*/ for(i=0; i < number_of_students; i++) { printf("DWSE ARI8MO MHTRWOU GIA EISAGWGH STH LISTA: "); scanf("%d",&Item.AM); printf("DWSE BA8MO GIA EISAGWGH STH LISTA: "); scanf("%f",&Item.grade); printf("DWSE TH 8ESH META THN OPOIA 8A GINEI H EISAGWGH STOIXEIOU: "); scanf("%d",&PredPtr); printf("\n"); printf("Plithos stoixeiwn sth lista %d\n",i+1); Insert(&AList,Node,&FreePtr,PredPtr,Item); TraverseLinked(AList,Node); } /*Διαγραφή ενος μαθητή και εμφάνιση της ΣΛ.(Ερώτημα iv)*/ printf("DWSE TH 8ESH TOY PROHGOUMENOY STOIXEIOY GIA DIAGRAFI: "); scanf("%d",&PredPtr); printf("\n"); Delete(&AList,Node,&FreePtr,PredPtr); printf("Plithos stoixeiwn sth lista %d\n",i-1); TraverseLinked(AList,Node); /*Διάβασμα στοιχείων δυο νέων μαθητών και εμφάνιση ΣΛ.(Ερώτημα v)*/ for(j=0; j < 2; j++) { printf("DWSE ARI8MO MHTRWOU GIA EISAGWGH STH LISTA: "); scanf("%d",&Item.AM); printf("DWSE BA8MO GIA EISAGWGH STH LISTA: "); scanf("%f",&Item.grade); printf("DWSE TH 8ESH META THN OPOIA 8A GINEI H EISAGWGH STOIXEIOU: "); scanf("%d",&PredPtr); printf("\n"); printf("Plithos stoixeiwn sth lista %d\n",i+j); Insert(&AList,Node,&FreePtr,PredPtr,Item); TraverseLinked(AList,Node); } return 0; } void InitializeStoragePool(NodeType Node[], ListPointer *FreePtr) { int i; for (i=0; i<NumberOfNodes-1;i++) { Node[i].Next=i+1; Node[i].Data.AM=-1; Node[i].Data.grade=-1; } Node[NumberOfNodes-1].Next=NilValue; Node[NumberOfNodes-1].Data.AM=NilValue; Node[NumberOfNodes-1].Data.grade=NilValue; *FreePtr=0; } void CreateLList(ListPointer *List) { *List=NilValue; } boolean EmptyLList(ListPointer List) { return (List==NilValue); } boolean FullLList(ListPointer FreePtr) { return (FreePtr == NilValue); } void GetNode(ListPointer *P, ListPointer *FreePtr, NodeType Node[]) { *P = *FreePtr; if (!FullLList(*FreePtr)) *FreePtr =Node[*FreePtr].Next; } void ReleaseNode(NodeType Node[], ListPointer P, ListPointer *FreePtr) { Node[P].Next =*FreePtr; Node[P].Data.AM = -1; Node[P].Data.grade = -1; *FreePtr =P; } void Insert(ListPointer *List, NodeType Node[],ListPointer *FreePtr, ListPointer PredPtr, ListElementType Item) { ListPointer TempPtr; GetNode(&TempPtr,FreePtr,Node); if (!FullLList(TempPtr)) { if (PredPtr==NilValue) { Node[TempPtr].Data.AM = Item.AM; Node[TempPtr].Data.grade = Item.grade; Node[TempPtr].Next =*List; *List =TempPtr; } else { Node[TempPtr].Data.AM =Item.AM; Node[TempPtr].Data.grade=Item.grade; Node[TempPtr].Next =Node[PredPtr].Next; Node[PredPtr].Next =TempPtr; } } else printf("Full List ...\n"); } void Delete(ListPointer *List, NodeType Node[], ListPointer *FreePtr, ListPointer PredPtr) { ListPointer TempPtr ; if (!EmptyLList(*List)) if (PredPtr == NilValue) { TempPtr =*List; *List =Node[TempPtr].Next; ReleaseNode(Node,TempPtr,FreePtr); } else { TempPtr =Node[PredPtr].Next; Node[PredPtr].Next =Node[TempPtr].Next; ReleaseNode(Node,TempPtr,FreePtr); } else printf("Empty List ...\n"); } void TraverseLinked(ListPointer List, NodeType Node[]) { ListPointer CurrPtr; if (!EmptyLList(List)) { CurrPtr =List; while (CurrPtr != NilValue) { printf("[%d: (%d,%.1f) ->%d] ",CurrPtr,Node[CurrPtr].Data.AM,Node[CurrPtr].Data.grade, Node[CurrPtr].Next); CurrPtr=Node[CurrPtr].Next; } printf("\n"); } else printf("Empty List ...\n"); }
C
#include <stdio.h> void imprimir(int arreglo[], int tamaño){ for (int i=0; i<tamaño; i++){ printf("%d", arreglo[i]); } } void qs(int arreglo[], int inicio, int tamaño){ int cero= inicio, fin = tamaño; int ref, aux, dd; dd= (cero + fin)/2; ref = arreglo[dd]; cero = inicio; fin = tamaño; do{ while(cero <tamaño && arreglo [cero] <ref){ cero++; } while(fin> inicio && ref<arreglo[fin]){ fin--; } if (cero <= fin){ aux = arreglo[fin]; arreglo [fin]= arreglo[cero]; arreglo[cero] = aux; fin--; cero++; } }while (cero<= fin); if (inicio<fin){ qs (arreglo, inicio, fin); } if (tamaño>cero){ qs (arreglo, cero, tamaño); } } int main (){ int tamaño; printf ("Cuántos valores tiene tu arreglo: \n "); scanf ("%d", &tamaño); int arreglo[tamaño]; printf ("Dame los valores: \n "); for (int i=0; i<tamaño; i++){ int valor; scanf ("%d", &valor); arreglo[i]= valor; } qs (arreglo, 0, tamaño-1); printf("El orden de tus valores es: \n "); imprimir (arreglo, tamaño); printf("\n"); return 0; }
C
//Returns n-grams for characters as well as words in a character array separated by newline //Usage : char_ngram(<character array>,<integer n>) or word_ngram(<character array>,<integer n>) //Dependencies : stdlib.h, stdio.h, string.h char* char_ngram(char* s, int n) { char *ngram = (char*)calloc(100000,sizeof(char)); char temp[n+1]; for(int i=0;i<strlen(s);i++) { strcpy(temp,""); for(int j=0;j<n;j++) temp[j] = s[i+j]; strcat(ngram,temp); ngram[strlen(ngram)] = '\n'; } return ngram; } char* word_ngram(char*s, int n) { char *ngram = (char*)calloc(100000,sizeof(char)); char *words = (char*)calloc(100000,sizeof(char)); int beg = 0; s[strlen(s)] = ' '; for(int i=0;i<strlen(s);i++) { if (s[i]==' ') { for(int j = 0;j<10000;j++) words[j] = '\0'; int pos = 0; for(int j=beg;j<i;j++) words[pos++] = s[j]; int ctr = 0; beg = i+1; words[pos++] = ' '; for(int j = i+1;j<strlen(s);j++) { if(ctr==(n-1)) break; if (s[j]==' ') ctr++; words[pos++] = s[j]; } strcat(ngram,words); ngram[strlen(ngram)] = '\n'; } } s[strlen(s)] = '\0'; return ngram; }
C
#include <stdio.h> int main(){ int t, lesser = 0, greater , n = 10, prev, this, i, j; scanf("%d", &t); printf("Lumberjacks:\n"); for( i = 0; i < t; ++i ){ lesser = greater = 0; n = 10; for( j = 0; j < n; ++j){ if( j ) prev = this; scanf("%d", &this); if( j ){ if( prev < this ) lesser++; if( prev > this ) greater++; } } if( ( lesser && !greater ) || ( greater && !lesser ) ) printf("Ordered\n"); else printf("Unordered\n"); } return 0; }
C
#include "bitBuffer.h" #include "bitsUtils.h" #include "stdio.h" void testFullBytes(); void testBitsAlternados(); void testFullBytesTakenHalf(); void testFullBytesTaken3(); void testManyBytesTaken3(); void testFullBytesTaken5(); void testDeath(); void testWriteShort(); int main() { // testFullBytes(); // testFullBytesTakenHalf(); // testFullBytesTaken3(); // testManyBytesTaken3(); // testFullBytesTaken5(); // testBitsAlternados(); // testDeath(); testWriteShort(); return 0; } void testFullBytes() { bitBuffer b = bB_new(5); unsigned char pattern = 0xF0; for (int i = 0; i < 5; ++i) { bB_write(&pattern, 8, &b); } printBuffer(&b); bB_free(&b); } void testFullBytesTaken5() { bitBuffer b = bB_new(6); //1010.1111 unsigned char alt = 0xAF; unsigned char altt[2]; altt[0] = alt; printf("Byte Alt: "); printBitsInByte(altt[0]); printf("\n"); //0110.0110 unsigned char pattern = 0x66; printf("WR0\n"); bB_write(altt, 5, &b); for (int i = 0; i < 5; ++i) { printf("WR%d\n", i+1); bB_write(&pattern, 8, &b); } printBuffer(&b); bB_free(&b); } void testFullBytesTaken3() { bitBuffer b = bB_new(6); //1010.0000 unsigned char alt = 0xA0; unsigned char altt[2]; altt[0] = alt; printf("Byte Alt: "); printBitsInByte(altt[0]); printf("\n"); //1001.1001 unsigned char pattern = 0x99; printf("WR0\n"); bB_write(altt, 3, &b); for (int i = 0; i < 5; ++i) { printf("WR%d\n", i+1); bB_write(&pattern, 8, &b); } printBuffer(&b); bB_free(&b); } void testManyBytesTaken3() { bitBuffer b = bB_new(6); //1010.0000 unsigned char alt = 0xA0; unsigned char altt[2]; altt[0] = alt; printf("Byte Alt: "); printBitsInByte(altt[0]); printf("\n"); //1001.1001 unsigned char pattern[3] = {0x99, 0x99, 0x99}; printf("WR0\n"); bB_write(altt, 3, &b); printf("WR1\n"); bB_write(pattern, 24, &b); printf("WR2\n"); bB_write(pattern, 16, &b); printBuffer(&b); bB_free(&b); } void testFullBytesTakenHalf() { bitBuffer b = bB_new(6); //1010.1111 unsigned char alt = 0xAF; unsigned char altt[2]; altt[0] = alt; printf("Byte Alt: "); printBitsInByte(altt[0]); printf("\n"); //0110.1001 unsigned char pattern = 0x69; bB_write(altt, 4, &b); for (int i = 0; i < 5; ++i) { bB_write(&pattern, 8, &b); } printBuffer(&b); bB_free(&b); } void testBitsAlternados() { bitBuffer b = bB_new(5); // 1001.0010 0100.1001 0010.0100 1001.0010 unsigned char bits3[4] = {0x92, 0x49, 0x24, 0x92}; // 1001.0010 01 bB_write(bits3, 10, &b); //0010.0(000) unsigned char bits3_2[2] = {0x20, 0x00}; bB_write(bits3_2, 5, &b); //1001.0010 0100.1(111) unsigned char bits3_3[2] = {0x92, 0x4F}; bB_write(bits3_3, 13, &b); printBuffer(&b); bB_free(&b); } void testDeath() { // 1000.0100 0010.0001 0000.1000 0100.0010 0001.0000 1000.0100 0011.111s bitBuffer b = bB_new(7); // 1000.0(111) unsigned char bits1[1] = {0x87}; bB_write(bits1, 5, &b); //1000.0100 0010.0001 0000.1(111) unsigned char bits2[3] = {0x84, 0x21, 0x0F}; bB_write(bits2, 21, &b); //0000.1000 0100.0010 0001.0000 1111.1(000) unsigned char bits3[4] = {0x08, 0x42, 0x10, 0xF8}; bB_write(bits3, 29, &b); printBuffer(&b); bB_free(&b); } void testWriteShort() { bitBuffer b; // Escribimos cosas que empiezan con 1 b = bB_new(5); // 101(0.000) bB_write_short((unsigned short) 5, 3, &b); printBuffer(&b); // 1011.01(00) bB_write_short((unsigned short) 5, 3, &b); printBuffer(&b); // 1011.0111 001(0.000) bB_write_short((unsigned short) 25, 5, &b); printBuffer(&b); // 1011.0111 0011.0000 0000.0000 001(0.0000) bB_write_short((unsigned short) 0x8001, 16, &b); printBuffer(&b); // 1011.0111 0011.0000 0000.0000 0011.1111 1111.111(0) // 0000.1111 1111.1111 bB_write_short((unsigned short) 0x0FFF, 12, &b); printBuffer(&b); bB_free(&b); // Escribimos cosas que empiezan con 0 b = bB_new(5); // 0001.11(00) bB_write_short((unsigned short) 7, 6, &b); printBuffer(&b); // 0001.1100 0111.1(000) bB_write_short((unsigned short) 15, 7, &b); printBuffer(&b); // 0001.1100 0111.1000 0000.0000 0000.1(000) bB_write_short((unsigned short) 1, 16, &b); printBuffer(&b); // 0001.1100 0111.1000 0000.0000 0000.1000 1000.0001 bB_write_short((unsigned short) 0x81, 11, &b); printBuffer(&b); }
C
#include<stdio.h> #include<string.h> int i,j,k,l,m,n=0,o,p,nv,z=0,t,x=0; char str[10],temp[20],temp2[20],temp3[20]; struct prod { char lhs[10],rhs[10][10]; int n; }pro[10]; void findter() { for(k=0;k<n;k++) { if(temp[i]==pro[k].lhs[0]) { for(t=0;t<pro[k].n;t++) { for(l=0;l<20;l++) temp2[l]='\0'; for(l=i+1;l<strlen(temp);l++) temp2[l-i-1]=temp[l]; for(l=i;l<20;l++) temp[l]='\0'; for(l=0;l<strlen(pro[k].rhs[t]);l++) temp[i+l]=pro[k].rhs[t][l]; strcat(temp,temp2); if(str[i]==temp[i]) return; else if(str[i]!=temp[i] && temp[i]>=65 && temp[i]<=90) break; } break; } } if(temp[i]>=65 && temp[i]<=90) findter(); } int main() { FILE *f; // clrscr(); for(i=0;i<10;i++) pro[i].n=0; f=fopen("in.txt","r"); while(!feof(f)) { fscanf(f,"%s",pro[n].lhs); if(n>0) { if( strcmp(pro[n].lhs,pro[n-1].lhs) == 0 ) { pro[n].lhs[0]='\0'; fscanf(f,"%s",pro[n-1].rhs[pro[n-1].n]); pro[n-1].n++; continue; } } fscanf(f,"%s",pro[n].rhs[pro[n].n]); pro[n].n++; n++; } n--; printf("\n\nTHE GRAMMAR IS AS FOLLOWS\n\n"); for(i=0;i<n;i++) for(j=0;j<pro[i].n;j++) printf("%s -> %s\n",pro[i].lhs,pro[i].rhs[j]); while(1) { for(l=0;l<10;l++) str[0]=NULL; printf("\n\nENTER ANY STRING ( 0 for EXIT ) : "); scanf("%s",str); if(str[0]=='0') break; for(j=0;j<pro[0].n;j++) { for(l=0;l<20;l++) temp[l]=NULL; strcpy(temp,pro[0].rhs[j]); m=0; for(i=0;i<strlen(str);i++) { if(str[i]==temp[i]) m++; else if(str[i]!=temp[i] && temp[i]>=65 && temp[i]<=90) { findter(); if(str[i]==temp[i]) m++; } else if( str[i]!=temp[i] && (temp[i]<65 || temp[i]>90) ) break; } if(m==strlen(str) && strlen(str)==strlen(temp)) { printf("\n\nTHE STRING can be PARSED !!!"); break; } } if(j==pro[0].n) printf("\n\nTHE STRING can NOT be PARSED !!!"); } // cin.ignore(numeric_limits<streamsize>::max(), '\n'); }
C
#include <math.h> #include <stdio.h> #include <time.h> typedef int bool; #define FALSE 0 #define TRUE 1 #define N 10000000 //returns whether num is prime bool isPrime(long num) { long limit = sqrt(num); for(long i=2; i<=limit; i++) { if(num % i == 0) { return FALSE; } } return TRUE; } int main(void) { int pCount = 1; long nextCand = 3; struct timespec start, end; clock_gettime(CLOCK_REALTIME, &start); while(nextCand < N) { if(isPrime(nextCand)) { pCount++; } nextCand += 2; } clock_gettime(CLOCK_REALTIME, &end); double time_spent = (end.tv_sec - start.tv_sec) + (end.tv_nsec - start.tv_nsec) / 1000000000.0f; printf("Time tasken: %f seconds\n", time_spent); printf("%d primes found.\n", pCount); }
C
#include <stdio.h> void triInsertion(int tab[],int nb); int arr[]={12,11,13,8,7,5,6,9,10}; int main(int argc, char** argv){ printf("Hello world\n"); int nb=sizeof(arr)/sizeof(arr[0]); for(int i=0;i<nb;i++){ printf("the %d element is %d\n",i,arr[i]); } triInsertion(arr,nb); printf("**********************************\n"); for(int i=0;i<nb;i++){ printf("the %d element is %d\n",i,arr[i]); } } void triInsertion(int tab[],int nb){ int pos=1; int i; for(i=0;i<nb-1;i++){ int temp=tab[i+1]; int j; for(j=i;j>=0;j--){ if(tab[j]>temp){ tab[j+1]=tab[j]; } else{ break; } } tab[j+1]=temp; } }
C
#include <stdio.h> int main() { int x; int i,a; printf("Enter any no.\n"); scanf("%d",&x); for(i=2;i<=9;i++) { while(x%i==0) { printf("%d\t",i); x=x/i; } } return 0; }
C
/* Из родительского процесса создается дочерний. Дочерний пишет свой pid и pid родителя в txt файл и генерирует 10 Мб чего-нибудь. Родительский ожидает окончания дочернего и выводит сколько он ждал */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> #include <time.h> #include <stdlib.h> int main() { FILE *lab_1;/* объявляем указатель на структуру File*/ (lab_1 = fopen("fl.txt", "wt"));/*открываем файл "fl.txt" для записи*/ pid_t pid; /* объявляем переменнтую типа pid_t, которая показывает идентификатор процесса*/ int *status=NULL;/*задаем статус равным NULL, т.к. информация о статусе завершения дочернего процесса для нас не имеет значения*/ switch(pid=fork()) {/* порождаем дочерний процесс с помощью функции fork */ case 0: { /*для дочернего процесса*/ fprintf(lab_1, " Pid of child: %d\nPid of parent: %d\n\n", getpid(), getppid());/*зааписываем в файл идентификатор дочернего и родительского процессов*/ int TenMbyte = 1024*1024*10; int i=0; for( i; i < TenMbyte; i++){ fprintf(lab_1, "A"); /*цикл будет записывать в файл букву 'A' пока их не наберется на 10 мегабайт*/ } return 0; } case -1: { perror("Fork failed"); return -1; } default:{/*для родительского процесса*/ struct timespec start, end;//объявляем структуры для хранения определенного времени clock_gettime (CLOCK_REALTIME, &start);//записываем в start текущее время в секундах(до начала дочернего процесса) waitpid(pid, status, 0);/*родительский процесс начнет ожидание завершения дочернего*/ clock_gettime (CLOCK_REALTIME, &end);//записываем в end текущее время в секундах(после завершения дочернего процесса) long double WaitingTime=0.0;//объявляем переменную в которую запишем время ожидания WaitingTime=(1000000000*(end.tv_sec - start.tv_sec)+(end.tv_nsec - start.tv_nsec));// считаем разницу в наносекундах как длительность ожидания родительским процессом дочернего printf("I was waiting for %Lf nanoseconds\n",WaitingTime);// выводим время ожидания return 0; } fclose(lab_1);/*закрываем файл*/ } }
C
#include <stdlib.h> #include <stdio.h> #include <assert.h> #define BUFFER_LENGTH 10 #define NDEBUG int main (int argc, char * argv[]) { //Arguments for source and destination files assert(argc > 2); //Open file pointers for files FILE * fps = fopen(argv[1], "rb"); FILE * fpd = fopen(argv[2], "wb"); //Set p buffer char * buffer; buffer = malloc(sizeof(char) * BUFFER_LENGTH); //Keep track of characters read int readChars; //Read input when there are characters to be read while(readChars = fread(buffer,1,BUFFER_LENGTH,fps)) { //Write the same ouput when there input is read successfully fwrite(buffer,1,readChars,fpd); } fclose(fps); fclose(fpd); return 0; }
C
#include "tm_stm32f4_ds18b20.h" uint8_t TM_DS18B20_Start(uint8_t *ROM) { if (!TM_DS18B20_Is(ROM)) { return 0; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Start temperature conversion TM_OneWire_WriteByte(TM_DS18B20_CMD_CONVERTTEMP); return 1; } void TM_DS18B20_StartAll(void) { //Reset pulse TM_OneWire_Reset(); //Skip rom TM_OneWire_WriteByte(TM_ONEWIRE_CMD_SKIPROM); //Start conversion on all connected devices TM_OneWire_WriteByte(TM_DS18B20_CMD_CONVERTTEMP); } uint8_t TM_DS18B20_Read(uint8_t *ROM, float *destination) { uint16_t temperature; uint8_t resolution; int8_t digit, minus = 0; float decimal; if (!TM_DS18B20_Is(ROM)) { return 0; } //Check if line is released, if it is, then conversion is complete if (!TM_OneWire_ReadBit()) { return 0; //Conversion is not finished yet } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Read scratchpad command by onewire protocol TM_OneWire_WriteByte(TM_ONEWIRE_CMD_RSCRATCHPAD); //First two bytes of scratchpad are temperature values temperature = TM_OneWire_ReadByte() | (TM_OneWire_ReadByte() << 8); //Reset line TM_OneWire_Reset(); if (((temperature >> 15)) == 1) { //Two's complement, temperature is negative temperature = ~temperature + 1; minus = 1; } //Get sensor resolution resolution = TM_DS18B20_GetResolution(ROM); //Store temperature integer digits and decimal digits digit = temperature >> 4; digit |= ((temperature >> 8) & 0x7) << 4; //Store decimal digits switch (resolution) { case 9: { decimal = (temperature >> 3) & 0x01; decimal *= (float)TM_DS18B20_DECIMAL_STEPS_9BIT; } break; case 10: { decimal = (temperature >> 2) & 0x03; decimal *= (float)TM_DS18B20_DECIMAL_STEPS_10BIT; } break; case 11: { decimal = (temperature >> 1) & 0x07; decimal *= (float)TM_DS18B20_DECIMAL_STEPS_11BIT; } break; case 12: { decimal = temperature & 0x0F; decimal *= (float)TM_DS18B20_DECIMAL_STEPS_12BIT; } break; default: { decimal = 0xFF; digit = 0; } } decimal = digit + decimal; if (minus) { decimal = 0 - decimal; } *destination = decimal; return 1; } uint8_t TM_DS18B20_GetResolution(uint8_t *ROM) { uint8_t conf; if (!TM_DS18B20_Is(ROM)) { return 0; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Read scratchpad command by onewire protocol TM_OneWire_WriteByte(TM_ONEWIRE_CMD_RSCRATCHPAD); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); //5th byte of scratchpad is configuration register conf = TM_OneWire_ReadByte(); return ((conf & 0x60) >> 5) + 9; } uint8_t TM_DS18B20_SetResolution(uint8_t *ROM, TM_DS18B20_Resolution_t resolution) { uint8_t th, tl, conf; if (!TM_DS18B20_Is(ROM)) { return 0; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Read scratchpad command by onewire protocol TM_OneWire_WriteByte(TM_ONEWIRE_CMD_RSCRATCHPAD); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); th = TM_OneWire_ReadByte(); tl = TM_OneWire_ReadByte(); conf = TM_OneWire_ReadByte(); if (resolution == TM_DS18B20_Resolution_9bits) { conf &= ~(1 << TM_DS18B20_RESOLUTION_R1); conf &= ~(1 << TM_DS18B20_RESOLUTION_R0); } else if (resolution == TM_DS18B20_Resolution_10bits) { conf &= ~(1 << TM_DS18B20_RESOLUTION_R1); conf |= 1 << TM_DS18B20_RESOLUTION_R0; } else if (resolution == TM_DS18B20_Resolution_11bits) { conf |= 1 << TM_DS18B20_RESOLUTION_R1; conf &= ~(1 << TM_DS18B20_RESOLUTION_R0); } else if (resolution == TM_DS18B20_Resolution_12bits) { conf |= 1 << TM_DS18B20_RESOLUTION_R1; conf |= 1 << TM_DS18B20_RESOLUTION_R0; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Write scratchpad command by onewire protocol, only th, tl and conf register can be written TM_OneWire_WriteByte(TM_ONEWIRE_CMD_WSCRATCHPAD); //Write bytes TM_OneWire_WriteByte(th); TM_OneWire_WriteByte(tl); TM_OneWire_WriteByte(conf); //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Copy scratchpad to EEPROM of DS18B20 TM_OneWire_WriteByte(TM_ONEWIRE_CMD_CPYSCRATCHPAD); return 1; } uint8_t TM_DS18B20_Is(uint8_t *ROM) { //Checks if first byte is equal to DS18B20's family code (0x28) if (*ROM == TM_DS18B20_FAMILY_CODE) { return 1; } return 0; } uint8_t TM_DS18B20_SetAlarmLowTemperature(uint8_t *ROM, int8_t temp) { uint8_t tl, th, conf; if (!TM_DS18B20_Is(ROM)) { return 0; } if (temp > 125) { temp = 125; } if (temp < -55) { temp = -55; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Read scratchpad command by onewire protocol TM_OneWire_WriteByte(TM_ONEWIRE_CMD_RSCRATCHPAD); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); th = TM_OneWire_ReadByte(); tl = TM_OneWire_ReadByte(); conf = TM_OneWire_ReadByte(); tl = (uint8_t)temp; //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Write scratchpad command by onewire protocol, only th, tl and conf register can be written TM_OneWire_WriteByte(TM_ONEWIRE_CMD_WSCRATCHPAD); //Write bytes TM_OneWire_WriteByte(th); TM_OneWire_WriteByte(tl); TM_OneWire_WriteByte(conf); //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Copy scratchpad to EEPROM of DS18B20 TM_OneWire_WriteByte(TM_ONEWIRE_CMD_CPYSCRATCHPAD); return 1; } uint8_t TM_DS18B20_SetAlarmHighTemperature(uint8_t *ROM, int8_t temp) { uint8_t tl, th, conf; if (!TM_DS18B20_Is(ROM)) { return 0; } if (temp > 125) { temp = 125; } if (temp < -55) { temp = -55; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Read scratchpad command by onewire protocol TM_OneWire_WriteByte(TM_ONEWIRE_CMD_RSCRATCHPAD); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); th = TM_OneWire_ReadByte(); tl = TM_OneWire_ReadByte(); conf = TM_OneWire_ReadByte(); th = (uint8_t)temp; //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Write scratchpad command by onewire protocol, only th, tl and conf register can be written TM_OneWire_WriteByte(TM_ONEWIRE_CMD_WSCRATCHPAD); //Write bytes TM_OneWire_WriteByte(th); TM_OneWire_WriteByte(tl); TM_OneWire_WriteByte(conf); //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Copy scratchpad to EEPROM of DS18B20 TM_OneWire_WriteByte(TM_ONEWIRE_CMD_CPYSCRATCHPAD); return 1; } uint8_t TM_DS18B20_DisableAlarmTemperature(uint8_t *ROM) { uint8_t tl, th, conf; if (!TM_DS18B20_Is(ROM)) { return 0; } //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Read scratchpad command by onewire protocol TM_OneWire_WriteByte(TM_ONEWIRE_CMD_RSCRATCHPAD); TM_OneWire_ReadByte(); TM_OneWire_ReadByte(); th = TM_OneWire_ReadByte(); tl = TM_OneWire_ReadByte(); conf = TM_OneWire_ReadByte(); th = 125; tl = (uint8_t)-55; //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Write scratchpad command by onewire protocol, only th, tl and conf register can be written TM_OneWire_WriteByte(TM_ONEWIRE_CMD_WSCRATCHPAD); //Write bytes TM_OneWire_WriteByte(th); TM_OneWire_WriteByte(tl); TM_OneWire_WriteByte(conf); //Reset line TM_OneWire_Reset(); //Select ROM number TM_OneWire_SelectWithPointer(ROM); //Copy scratchpad to EEPROM of DS18B20 TM_OneWire_WriteByte(TM_ONEWIRE_CMD_CPYSCRATCHPAD); return 1; } uint8_t TM_DS18B20_AlarmSearch(void) { return TM_OneWire_Search(TM_DS18B20_CMD_ALARMSEARCH); } uint8_t TM_DS18B20_AllDone(void) { return TM_OneWire_ReadBit(); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> #define N 11 typedef struct NoFuncionario{ char nome[20]; int numid; char depart[30]; float salario; struct NoFuncionario *prox; } NoFuncionario, *Funcionario; void inicializa (Funcionario *l); _Bool consulta (Funcionario *l, NoFuncionario *x); _Bool insere (Funcionario *l, NoFuncionario *x); void retira (Funcionario *l, int x); void ordemcod (Funcionario *l, int i, int x); void ordemnome (Funcionario *l, int x); int contarfuncio (Funcionario *l); int main() { Funcionario VetListas[N]; char entrada; inicializa (VetListas); scanf ("%c", &entrada); while (entrada != 'e'){ if (entrada == 'c'){ NoFuncionario ConsFunc; scanf ("%d", &ConsFunc.numid); if (consulta (VetListas, &ConsFunc)){ printf ("%s\n", ConsFunc.nome); printf ("%d\n", ConsFunc.numid); printf ("%s\n", ConsFunc.depart); printf ("%.2f\n", ConsFunc.salario); } } if (entrada == 'i'){ int i, QtFunc; scanf ("%d", &QtFunc); for (i=0; i!=QtFunc; i++){ NoFuncionario NovoFunc; scanf ("%s", NovoFunc.nome); scanf ("%d", &NovoFunc.numid); scanf ("%s", NovoFunc.depart); if (strcmp(NovoFunc.depart , "adm")==0) strcpy(NovoFunc.depart, "administrativo"); if (strcmp(NovoFunc.depart , "ped")==0) strcpy(NovoFunc.depart, "pesquisa-e-desenvolvimento"); if (strcmp(NovoFunc.depart , "prod")==0) strcpy(NovoFunc.depart, "producao"); scanf ("%f", &NovoFunc.salario); insere(VetListas, &NovoFunc); } } if (entrada == 'r'){ int x; scanf ("%d", &x); retira (VetListas, x); } if (entrada == 'l'){ NoFuncionario *p; int ind, cont=0; scanf ("%d", &ind); for (p=VetListas[ind]; p!=NULL; p=p->prox, cont++); ordemcod (VetListas, ind, cont); } if (entrada == 'o'){ int QtFunc = contarfuncio (VetListas); ordemnome (VetListas, QtFunc); } scanf ("%c", &entrada); } return 0; } void inicializa (Funcionario *l){ int i; for (i=0; i<N; i++) l[i]= NULL; } _Bool consulta (Funcionario *l, NoFuncionario *x){ NoFuncionario *p; int i = x->numid % N; for (p=l[i]; (p!=NULL)&&(p->numid!=x->numid); p=p->prox); if (p==NULL) return false; strcpy(x->nome, p->nome); strcpy(x->depart, p->depart); x->salario = p->salario; return true; } _Bool insere (Funcionario *l, NoFuncionario *x){ NoFuncionario *p; int i = x->numid % N; if ((consulta(l,x))||(!(p=(NoFuncionario*)malloc(sizeof(NoFuncionario))))) return false; strcpy(p->nome, x->nome); p->numid = x->numid; strcpy(p->depart, x->depart); p->salario = x->salario; p->prox = l[i]; l[i] = p; return true; } void retira (Funcionario *l, int x){ NoFuncionario *p, *q; int i = x%N; for (p=l[i], q=NULL;(p) && (p->numid != x); q=p, p=p->prox); if (p){ if (!q) l[i] = p->prox; else q->prox = p->prox; free (p); } } void ordemcod (Funcionario *l, int i, int x){ NoFuncionario *p; int chave, n, j=0, VetIds[x]; for (p=l[i]; p!=NULL; p=p->prox){ VetIds[j]= p->numid; j++; } for (j=1; j<x; j++){ chave = VetIds[j]; n = j-1; while ((n>=0) && (chave < VetIds[n])){ VetIds[n+1] = VetIds[n]; n--; } VetIds[n+1]=chave; } for (j=0; j<x; j++) printf ("%d\n", VetIds[j]); } void ordemnome (Funcionario *l, int x){ NoFuncionario *p; char ord, VetNomes[x][20], chave[20]; int i, a=0; for (i=0; i < N; i++) for (p=l[i]; p!=NULL; p=p->prox){ strcpy (VetNomes[a], p->nome); a++; } for (i=1; i<x; i++){ strcpy (chave, VetNomes[i]); a = i-1; while ((a>=0) && (strcmp (VetNomes[a], chave)>0)){ strcpy (VetNomes[a+1], VetNomes[a]); a--; } strcpy (VetNomes[a+1], chave); } scanf ("\n%c", &ord); if (ord == 'c'){ for (i=0; i < x; i++) printf ("%s\n", VetNomes[i]); } if (ord == 'd'){ for (i=x-1; i >= 0 ; i--) printf ("%s\n", VetNomes[i]); } } int contarfuncio (Funcionario *l){ NoFuncionario *p; int i, cont=0; for (i=0; i < N; i++) for (p=l[i]; p!=NULL; p=p->prox, cont++); return cont; }