language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include<stdio.h> #include<stdlib.h> main(){ int i, j, aux, *vet,*vetaux, a=0; vet=(int*)malloc(100*sizeof(int)); vetaux=(int*)malloc(100*sizeof(int)); for(i=0;i<100;i++){ scanf("%d",&vet[i]); vetaux[i]=vet[i]; } for(i=0;i<99;i++) for(j=99;j>i;j--){ if(vetaux[j-1]>vetaux[j]){ aux=vetaux[j-j]; vetaux[j-1]=vetaux[j]; vetaux[j]=aux; } } for(i=0;i<100;i++){ if(vetaux[0]==vetaux[i]) a++; } for(i=0;i<100;i++){ printf("%d ",vet[i]); } printf("O menor numero e: %d\n", vetaux[0]); printf("Ele se repete: %d vezes\n",a); free(vet); free(vetaux); }
C
#include <stdlib.h> #include <string.h> /* for memcpy() */ #include "AStructBase.h" #include "AList.h" static void* AListCreate(AList* self, int numArgs, va_list args); static void AListClear(AList* self, AValueFree freeValue); static void AListDestroy(AList* self, AValueFree freeValue); static AListNode* AListAppend(AList* self, void* value); static void* AListLast(AList* self); static void* AListPopLast(AList* self); static AListNode* AListPrepend(AList* self, void* value); static void* AListFirst(AList* self); static void* AListPopFirst(AList* self); static AListNode* AListInsert(AList* self, AListNode* prev, void* value); static AListNode* AListInsertAt(AList* self, size_t pos, void* value); static void* AListValueAt(AList* self, size_t pos); static void* AListReplaceAt(AList* self, size_t pos, void* value); static void* AListRemove(AList* self, AListNode* node); static void* AListRemoveAt(AList* self, size_t pos); static AList* AListCopy(AList* self, AValueFunc copyValue); static AList* AListSplitReal(AList* self, AListNode* node); static AList* AListSplit(AList* self, AListNode* node); static AList* AListSplitAt(AList* self, size_t pos); static void AListJoin(AList* first, AList* second); const AList AListProto = { AListCreate, AListClear, AListDestroy, AListAppend, AListLast, AListPopLast, AListPrepend, AListFirst, AListPopFirst, AListInsert, AListInsertAt, AListValueAt, AListReplaceAt, AListRemove, AListRemoveAt, AListCopy, AListSplit, AListSplitAt, AListJoin }; /* * Create a new list */ static void* AListCreate(AList* self, int numArgs, va_list args) { self->head = self->tail = NULL; self->size = 0; return self; } /** * @fn void (*AList::clear)(AList* self, AValueFree freeValue) * @param self The list * @param freeValue Callback function to free the value pointer * * Clear the list by removing all the nodes and their values * using freeValue to free the values (if it's not NULL). */ static void AListClear(AList* self, AValueFree freeValue) { AListNode* node = self->head; while (node != NULL) { AListNode* temp = node; node = node->next; if (freeValue != NULL) { freeValue(temp->value); } free(temp); } self->head = self->tail = NULL; self->size = 0; } /** * @fn void (*AList::destroy)(AList* self, AValueFree freeValue) * @param self The list * @param freeValue Callback function to free the value pointer * * @link AList::clear() Clear@endlink the list and free all * of its storage. Any access to a destroyed list is forbidden. */ static void AListDestroy(AList* self, AValueFree freeValue) { if (self != NULL) { AListClear(self, freeValue); free(self); } } /** * @fn AListNode* (*AList::append)(AList* self, void* value) * @param self The list * @param value The value * @return Pointer to the new node or NULL on error. */ static AListNode* AListAppend(AList* self, void* value) { AListNode* node = malloc(sizeof *node); if (node != NULL) { node->value = value; node->next = NULL; if (self->tail == NULL) /* first node */ { self->head = self->tail = node; node->prev = NULL; } else { self->tail->next = node; node->prev = self->tail; self->tail = node; } self->size++; } return node; } /** * @fn void* (*AList::last)(AList* self) * @param self The list * @return The value of the last node or NULL on error */ static void* AListLast(AList* self) { AListNode* tail = self->tail; return tail != NULL ? tail->value : NULL; } /** * @fn void* (*AList::popLast)(AList* self) * @param self The list * @return The value of the last node or NULL on error * * Remove the last node from the list and return its value. */ static void* AListPopLast(AList* self) { AListNode* tail = self->tail; return tail != NULL ? AListRemove(self, tail) : NULL; } /** * @fn AListNode* (*AList::prepend)(AList* self, void* value) * @param self The list * @param value The value * @return Pointer to the new node or NULL on error. */ static AListNode* AListPrepend(AList* self, void* value) { AListNode* node = malloc(sizeof *node); if (node != NULL) { node->value = value; node->prev = NULL; if (self->head == NULL) /* first node */ { self->head = self->tail = node; node->next = NULL; } else { self->head->prev = node; node->next = self->head; self->head = node; } self->size++; } return node; } /** * @fn void* (*AList::first)(AList* self) * @param self The list * @return The value of the first node or NULL on error. */ static void* AListFirst(AList* self) { AListNode* head = self->head; return head != NULL ? head->value : NULL; } /** * @fn void* (*AList::popFirst)(AList* self) * @param self The list * @return The value of the first node or NULL on error * * Remove the first node from the list and return its value. */ static void* AListPopFirst(AList* self) { AListNode* head = self->head; return head != NULL ? AListRemove(self, head) : NULL; } /** * @fn AListNode* (*AList::insert)(AList* self, AListNode* prev, void* value) * @param self The list * @param prev The node to insert after * @param value The value * @return Pointer to the new node or NULL on error * * Insert a value to a new node which will be after prev. */ static AListNode* AListInsert(AList* self, AListNode* prev, void* value) { AListNode* node; if (prev == self->tail) { return AListAppend(self, value); } node = malloc(sizeof *node); if (node != NULL && prev != NULL) { node->value = value; node->next = prev->next; node->next->prev = node; node->prev = prev; prev->next = node; self->size++; return node; } return NULL; } /** * @fn AListNode* (*AList::insertAt)(AList* self, size_t pos, void* value) * @param self The list * @param pos Position index * @param value The value * @return Pointer to the new node or NULL on error * * Insert a value to a new node which will be placed at a zero-based position in the list. */ static AListNode* AListInsertAt(AList* self, size_t pos, void* value) { AListNode* node; size_t i; /* invalid positions */ if (pos < 0 || pos > self->size) { return NULL; } if (pos == 0) /* first */ { return AListPrepend(self, value); } else if (pos == self->size) /* last */ { return AListAppend(self, value); } /* iterate from the nearest end */ if (pos < self->size / 2) { for (node = self->head, i = 0; i < pos; i++) /* from head */ { node = node->next; } } else { for (node = self->tail, i = self->size - 1; i > pos; i--) /* from tail */ { node = node->prev; } } return AListInsert(self, node->prev, value); } /** * @fn void* (*AList::valueAt)(AList* self, size_t pos) * @param self The list * @param pos Position index * @return The value of the node at the zero-based position or NULL on error */ static void* AListValueAt(AList* self, size_t pos) { AListNode* node; size_t i; /* invalid positions */ if (pos < 0 || pos >= self->size) { return NULL; } /* iterate from the nearest end */ if (pos < self->size / 2) { for (node = self->head, i = 0; i < pos; i++) /* from head */ { node = node->next; } } else { for (node = self->tail, i = self->size - 1; i > pos; i--) /* from tail */ { node = node->prev; } } return node->value; } /** * @fn void* (*AList::replaceAt)(AList* self, size_t pos, void* value) * @param self The list * @param pos Position index * @param value The new value * @return The original value or NULL on error * * Replace the value at a zero-based position in the list with a new value and return the original one. */ static void* AListReplaceAt(AList* self, size_t pos, void* value) { AListNode* node; size_t i; void* oldValue; /* invalid positions */ if (pos < 0 || pos >= self->size) { return NULL; } /* iterate from the nearest end */ if (pos < self->size / 2) { for (node = self->head, i = 0; i < pos; i++) /* from head */ { node = node->next; } } else { for (node = self->tail, i = self->size - 1; i > pos; i--) /* from tail */ { node = node->prev; } } oldValue = node->value; node->value = value; return oldValue; } /** * @fn void* (*AList::remove)(AList* self, AListNode* node) * @param self The list * @param node The node to remove * @return The value in the node or NULL on error * * Remove the node from the list and return its value. */ static void* AListRemove(AList* self, AListNode* node) { void* value = NULL; /* empty list or invalid node */ if (self->head == NULL || self->tail == NULL || node == NULL) { return NULL; } if (node == self->head && node == self->tail) /* the only node in the list */ { self->head = self->tail = NULL; } else if (node == self->head) /* first node */ { self->head = self->head->next; self->head->prev = NULL; } else if (node == self->tail) /* last node */ { self->tail = self->tail->prev; self->tail->next = NULL; } else /* middle node */ { node->prev->next = node->next; node->next->prev = node->prev; } value = node->value; free(node); self->size--; return value; } /** * @fn void* (*AList::removeAt)(AList* self, size_t pos) * @param self The list * @param pos Position index * @return The value at the position or NULL on error * * Remove the node at a zero-based position and return its value. */ static void* AListRemoveAt(AList* self, size_t pos) { AListNode* node; size_t i; /* iterate from the nearest end */ if (pos < self->size / 2) { for (node = self->head, i = 0; i < pos; i++) /* from head */ { node = node->next; } } else { for (node = self->tail, i = self->size - 1; i > pos; i--) /* from tail */ { node = node->prev; } } return AListRemove(self, node); } /** * @fn AList* (*AList::copy)(AList* self, AValueFunc copyValue) * @param self The list * @param copyValue Callback function that returns a pointer to a copy of the value * @return A new copy of the list or NULL on error * * Create a new copy of the list and all of its values (if copyValue isn't NULL) * and return the new list. */ static AList* AListCopy(AList* self, AValueFunc copyValue) { AListNode* node = self->head; AList* newList = AStruct->ANew(AList); if (newList != NULL) { while (node != NULL) { newList->append(newList, copyValue != NULL ? copyValue(node->value) : node->value); node = node->next; } newList->size = self->size; } return newList; } /* * Split the list 'self' by node 'node' and return the second list * (which will include the node). Don't change the sizes of the lists. */ static AList* AListSplitReal(AList* self, AListNode* node) { AList* newList = AStruct->ANew(AList); if (newList != NULL) { if (node == self->head) /* first node */ { newList->head = node; newList->tail = self->tail; self->head = self->tail = NULL; /* first list is empty now */ } else { newList->head = node; newList->tail = self->tail; self->tail = node->prev; self->tail->next = NULL; newList->head->prev = NULL; } } return newList; } /** * @fn AList* (*AList::split)(AList* self, AListNode* node) * @param self The list * @param node The node to split by * @return The second list * * Split the list by the node. This will trim the list to contain * everything up to (but not including) the node and create a second * list which will contain everything from (and including) the node * up to the end of the original list. */ static AList* AListSplit(AList* self, AListNode* node) { AListNode* iter; size_t size; AList* newList = AListSplitReal(self, node); if (newList != NULL) { /* get the size of the second list */ for (iter = newList->head, size = 0; iter != NULL; iter = iter->next) { size++; } newList->size = size; self->size -= size; } return newList; } /** * @fn AList* (*AList::splitAt)(AList* self, size_t pos) * @param self The list * @param pos Position index * @return The second list * * Split the list by a zero-based position. This will trim the list * to contain everything up to (but not including) the node at the * position and create a second list which will contain everything * from (and including) the node at the position up to the end of * the original list. */ static AList* AListSplitAt(AList* self, size_t pos) { AList* newList; AListNode* node; size_t i; /* iterate from the nearest end */ if (pos < self->size / 2) { for (node = self->head, i = 0; i < pos; i++) /* from head */ { node = node->next; } } else { for (node = self->tail, i = self->size - 1; i > pos; i--) /* from tail */ { node = node->prev; } } newList = AListSplitReal(self, node); if (newList != NULL) { newList->size = self->size - pos; self->size -= newList->size; } return newList; } /** * @fn void (*AList::join)(AList* first, AList* second) * @param first The first list * @param second The second list * * Join the first list with the second list. The second list * will be destroyed afterwards. */ static void AListJoin(AList* first, AList* second) { first->tail->next = second->head; second->head->prev = first->tail; first->tail = second->tail; first->size += second->size; free(second); }
C
#include "URL.h" #include "Global.h" #include <ctype.h> #include <string.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/socket.h> /**** This file contains functions relating to both domain/host names and ****/ /**** IP Addresses. Hence the chosen name of the file may be a bit mis- ****/ /**** leading. Alternative suggestions are welcome. ****/ char *ExtractDomainName(char *FullName) { char *tempptr; tempptr=strchr(FullName,'.'); if (!tempptr) return(""); tempptr++; return(tempptr); } /* This is a simple function to decide if a string is an IP address as */ /* opposed to a host/domain name. */ int IsAddress(char *Str) { int len,count; len=strlen(Str); if (len <1) return(FALSE); for (count=0; count < len; count++) if ((! isdigit(Str[count])) && (Str[count] !='.')) return(FALSE); return(TRUE); } char *IPtoStr(unsigned long Address) { struct sockaddr_in sa; sa.sin_addr.s_addr=Address; return(inet_ntoa(sa.sin_addr)); } unsigned long StrtoIP(char *Str) { struct sockaddr_in sa; if (inet_aton(Str,&sa.sin_addr)) return(sa.sin_addr.s_addr); return(0); } /* In some other DNS servers fully qualified domain names are written */ /* backwards, in keeping with the 'black magick' feel of DNS. This makes it */ /* simple to calculate if somehost.somedomain.com matches *.somedomain.com, */ /* or *.*.com etc. I've chosen to use a function that does a backwards */ /* strcmp instead. This function then checks if www.foobar.com is in the */ /* domain foobar.com. This function will return true if you compare */ /* www.foobar.com against itself, or against .foobar.com, otherwise false. */ int DomainNameCompare(char *CompareThis, char *CompareAgainstThis) { int len1, count, len2; if ((CompareThis==NULL) || (CompareAgainstThis==NULL)) return(FALSE); len1 = strlen(CompareAgainstThis); len2 = strlen(CompareThis); if ((len1==0) || (len2==0)) return(FALSE); if (len2 < len1) return(FALSE); for (count=1; count <=len1; count++) { if (tolower(CompareThis[len2-count]) != tolower(CompareAgainstThis[len1-count])) break; } /* we didn't find any difference but we must now check that we are either */ /* comparing identical names, or ones that are the same up to a domain '.' */ if ((count > len1) && ((len1==len2) || (CompareThis[len2-count]=='.'))) { return(TRUE); } return(FALSE); } int AddressCompare(unsigned long CompareThis, unsigned long CompareAgainstThis) { int count; unsigned long mask, result, SubNetMask=0; /* first if they are equal then there you go !*/ if (CompareThis==CompareAgainstThis) return(TRUE); /*This only works for subnets of the types 255.0.0.0, 255.255.0.0 and */ /* 255.255.255.0 and 255.255.255.255 (which is pointless) */ mask =255; for (count=0; count <4; count++) { result=CompareAgainstThis & mask; if (result) SubNetMask=SubNetMask | mask; mask=mask << 8; } if ((CompareThis & SubNetMask) == CompareAgainstThis) return(TRUE); return(FALSE); }
C
#include <stdio.h> #define swap(a, b) tempr=(a); (a)=(b); (b)=tempr void fft(double data[], unsigned long nn, int isign); main() { int i; int isign = 1; unsigned long nn = 8; double data[16]={0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7}; for(i=0; i<2*nn; i++) printf("%f\n", data[i]); fft(data, nn, isign); printf("hello\n"); for(i=0; i<2*nn; i++) printf("%f\n", data[i]); } /* nn must be integer power of 2 */ void fft(double data[], unsigned long nn, int isign) { /* nn number of elements in array data */ unsigned long n; unsigned long i, j; unsigned long mmax; unsigned long m; unsigned long istep; double wtemp, wr, wpr, wpi, wi, theta; double tempr; /* temporary variable in swap macro */ double tempi; n = nn << 1; /* left bit shift (multiply by 2) */ j=0; for(i=0; i<n; i+=2){ if(j>i){ swap(data[j], data[i]); swap(data[j+1], data[i+1]); } m = n >> 1; while(m>=2 && j>m){ j -= m; m >>= 1; } j += m; } }
C
// ************************* Introduction ************************* // This is the program to compute the Harborth constant g(G) by brute force, that accompanies our article: "On the Harborth constant of C_3 ⊕ C_3n". // G is a finite abelian group. // The Harborth constant g(G) is the smallest integer k such that each set over G whith size at least k, has a subset of size e=exp(G) that sums to 0. The Harborth constant g(G) corresponds to e= exp(G). // There is no interface but you only have to change this source code to get results for the Harborth constant for the different finite abelian groups. // This program is valid for any finite abelian group. With the hardware at our disposal it is possible to compute the Harborth constant for finite abelian groups of order up to about 45. // The main limiting factor is memory. // In order to increase the size of accessible groups,currently, we are working on a another version, more efficient based on data compression. // The group intervenes only in this step [Initialization]. // The subsets of G are represented by a bitmap. #include <stdio.h> #include <stdlib.h> #include <inttypes.h> #include <malloc.h> #include <time.h> typedef long long unsigned u64; typedef unsigned char u8; // ************************* The user manual ************************* // [Initialization]: in this step you have to change the parameters of: MODULO1, MODULO2, MODULO3 and MODULO4, according to the finite abelian group of which you are looking for its Harborth constant. // Examples: For The group C_3 ⊕ C_12, you have to enter the following parameters: //[Initialization]. #define RANG 2 #define MODULO1 3 #define MODULO2 12 #if (RANG>=3) #define MODULO3 0 #endif #if (RANG==4) #define MODULO4 0 #endif #if (RANG==2) #define CARDINAL (MODULO1*MODULO2) #define EXPOSANT MODULO2 #endif #if (RANG==3) #define CARDINAL (MODULO1*MODULO2*MODULO3) #define EXPOSANT MODULO3 #endif #if(RANG==4) #define CARDINAL (MODULO1*MODULO2*MODULO3*MODULO4) #define EXPOSANT MODULO4 #endif // ************************* Functions ************************* // In this step you have no change to do. // Let's first look at the caclulation of w ---> x // We consider a Pascal's triangle whose first column a(i,0)=1, // The diagonal a(i,i)=2^i (powers of 2) and whose other values are defined by the Pascal's triangle relation. // a(i,j)=a(i-1,j)+a(i-1,j-1). // Example : // O // 0 1 // 0 1 2 // 0 1 3 4 // 0 1 4 7 8 ... // Let w be a bitmap, for example w=1100. The value x will be given by browsing this triangle. // The starting point is the position (-1,-1) // We browse w from the left to the right. // When we meet 1, we move diagonally down right. // When we meet 0, we move vertically down. // The result is x which is the sum of all the summits encountered values. // Example : w=1100 //----------------- // // O // \ 1 : Move diagonally down right // 0 1 // \ 1 : Move diagonally down right // 0 1 2 // | 0 : Move vertically down // 0 1 3 4 // | 0 : Move vertically down // 0 1 4 7 8 // The result : the cumulation 0 + 1 + 2 + 3 + 4 = 10 // The function numsubset: return the number of the subset of a set of n elements. // The subsets of G are represented by a bitmap. u64 numsubset(u64 w,int n) { int i,j; // The index of Pascal's triangle. u64 a; // Modified Pascal's triangle value. u64 p; // Pascal's triangle value. u64 x; // Cumulative of all the summits. //[Initialization]. i=-1; j=-1; p=0; a=0; x=0; while (n>0) { // According to the value of the number switch (w&1) { case 0: ++i; // Move vertically down a=2*a-p; // Update of the modified Pascal coefficient p=(p*i)/(i-j); // Update of Pascal coefficient break; case 1: if (j==-1) p=1; else p=(p*(i-j))/(j+1); // p(i-1,j) in terms of p(i-1,j-1) a=2*a+p; // Update of a ++i; ++j; // Diagonally down right if (i==j) p=1; else p=(p*i)/(i-j); // update of p(i,j) in terms of p(i-1,j) break; } // shift w to position the next number w>>=1; // cumulative value of the summit x+=a; --n; } return x; } // The function subsetnum: return the subset of a given number u64 subsetnum(u64 x,int i) // The parameter i serves as a current line { int j; // current column u64 a; // modifies Pascal's coefficient a(n,j) u64 p; // Pascal's coefficient u64 w; // result (a bitmap) // [Initialization] w=0; p=1; a=0; j=0; // The search for column j such that a(i,j) <= "x" < a(i,j+1) // The Initialization of a(i,j) while (a+p<=x) { a+=p; j++; p=(p*(i-j+1))/j; } p=(p*j)/i; a=(a+p)/2; --j; x-=a; --i; while ( (j>=0) && (j<i) ) { // The algorithm stops when we arrive on one of the sides. // The side j=0, in this case we complete with zéros // The side i=j, we complete with 1 if (x>=a) // Can we subtract a(i-1,j) { p=(p*(i-j))/i; a=(a+p)/2; // Update of a --i; // At the top only } else { w|=(1ll<<i); // remember that the number is 1 a=(a-(p*(i-j))/i)/2; // Update of a p=(p*j)/i; // Update of p --i; // At the top --j; // At the left } x-=a; // Substracting what we could } // Fill last characters whith 0 or 1. if (j!=-1) { w|=(1ll<<(i+1))-1ll; } return w; } // The function binome: return {n\choose p} u64 binome(int n, int p) { u64 r=1; int i; for (i=1;i<=p;i++,n--) { r=(r*n)/i; } return r; } #if (RANG==2) // The group law C_f + C_e // e is MODULO=EXPONENT of the group // ------------------------ unsigned add(unsigned x,unsigned y) { unsigned u,v; u=x%MODULO1; v=x/MODULO1; x=y%MODULO1; y=y/MODULO1; u+=x; if (u>=MODULO1) u-=MODULO1; v+=y; if (v>=MODULO2) v-=MODULO2; return u+MODULO1*v; } // Display void affiche(unsigned x) { printf("(%d,%d)",x%MODULO1,x/MODULO1); } // Opposite unsigned opp(unsigned x) { unsigned u,v; u=(x%MODULO1); if (u!=0) u=MODULO1-u; v=(x/MODULO1); if (v!=0) v=MODULO2-v; return u+MODULO1*v; } #endif #if (RANG==3) unsigned add(unsigned x, unsigned y) { unsigned u,v,a,b; u=x%MODULO1; x/=MODULO1; a=y%MODULO1; y/=MODULO1; v=x%MODULO2; x/=MODULO2; b=y%MODULO2; y/=MODULO2; u+=a; if (u>=MODULO1) u-=MODULO1; v+=b; if (v>=MODULO2) v-=MODULO2; x+=y; if (x>=MODULO3) x-=MODULO3; return (v+x*MODULO2)*MODULO1+u; } unsigned opp(unsigned x) { unsigned u,v; u=x%MODULO1; x/=MODULO1; v=x%MODULO2; x/=MODULO2; if (u!=0) u=MODULO1-u; if (v!=0) v=MODULO2-v; if (x!=0) x=MODULO3-x; return (v+x*MODULO2)*MODULO1+u; } void affiche(unsigned x) { unsigned u,v; u=x%MODULO1; x/=MODULO1; v=x%MODULO2; x/=MODULO2; printf("(%u,%u,%u)",u,v,x); } #endif #if (RANG==4) unsigned add(unsigned x, unsigned y) { unsigned u,v,w,a,b,c; u=x%MODULO1; x/=MODULO1; v=x%MODULO2; x/=MODULO2; w=x%MODULO3; x/=MODULO3; a=y%MODULO1; y/=MODULO1; b=y%MODULO2; y/=MODULO2; c=y%MODULO3; y/=MODULO3; u+=a; v+=b; w+=c; x+=y; if (u>=MODULO1) u-=MODULO1; if (v>=MODULO2) v-=MODULO2; if (w>=MODULO3) v-=MODULO3; if (x>=MODULO4) x-=MODULO4; return (((x*MODULO3+w)*MODULO2+v)*MODULO1+u); } unsigned opp(unsigned x) { unsigned u,v,w; u=x%MODULO1; x/=MODULO1; v=x%MODULO2; x/=MODULO2; w=x%MODULO3; x/=MODULO3; if(u!=0) u=MODULO1-u; if(v!=0)v=MODULO2-v; if (w!=0) w=MODULO3-w; if (x!=0) x=MODULO4-x; return (((x*MODULO3+w)*MODULO2+v)*MODULO1+u); } #endif //Calculate the opposite of the elements of a subset given by a bitmap. u64 completeoppsum(u64 w) { u64 m; unsigned i,s; s=0; for (m=1,i=0;m<=(1ll<<CARDINAL);m<<=1,i++) { if ((m&w)!=0) { s=add(s,i); } } s=opp(s); m=1ll<<s; // if ((m&w)==0ll) { return m|w; } return 0ll; } // Calculate the sum of elements of a subset given by its bitmap w. unsigned sum(u64 w) { u64 m; unsigned s,i; for (s=0,i=0,m=1;m<(1ll<<CARDINAL);i++,m<<=1) { if ((m&w)!=0) s=add(s,i); } return s; } // The function w64: return the binary weight of x int w64(u64 x) { x=(x&0x5555555555555555ll)+((x>>1)&0x5555555555555555ll); x=(x&0x3333333333333333ll)+((x>>2)&0x3333333333333333ll); x=(x&0x0f0f0f0f0f0f0f0fll)+((x>>4)&0x0f0f0f0f0f0f0f0fll); x=(x&0x00ff00ff00ff00ffll)+((x>>8)&0x00ff00ff00ff00ffll); x=(x&0x0000ffff0000ffffll)+((x>>16)&0x0000ffff0000ffffll); return (x&0x00000000ffffffff)+((x>>32)&0x00000000ffffffffll); } // The function include: add an element in a set. void include(u64 x, u64*S) { ((u8*)S)[x>>3]|=(1<<(x&7)); } // x is it in S? int isin(u64 x, u64*S) { return (((u8*)S)[x>>3]>>(x&7))&1; } // The function: clear_set: Makes the set S of cardinal n empty void clear_set(u64*S,u64 n) { u64 w=(n+63)>>6; u64 i; for(i=0;i<w;i++) S[i]=0; } u64 cardinal(u64*S,u64 n) { u64 w=(n+63)>>6; u64 c=0; u64 i; for (i=0;i<w;i++) c+=w64(S[i]); return c; } void affiche_set(u64*S,u64 n) { u64 w=(n+63)>>6; u64 i; for (i=0;i<w;i++) { printf("%llx",S[i]); } printf("\n"); } u64 *setA,*setB; // Binomial coefficient table. u64 b[CARDINAL]; u64 c[CARDINAL]; // b[n,p]= b[n*(n+1)/2 + p] u64 bb[(CARDINAL+2)*(CARDINAL+1)/2]; u64 cc[(CARDINAL+2)*(CARDINAL+1)/2]; // Initialization of tables bb and cc void initbbcc() { int i,j,k; for (i=0;i<=CARDINAL;i++) { k=i*(i+1)/2; bb[k]=1; for (j=1;j<i;j++) { bb[k+j]=bb[k-i+j]+bb[k-i+j-1]; } bb[k+i]=1; } for (i=0;i<=CARDINAL;i++) { k=i*(i+1)/2; cc[k]=1; for (j=1;j<i;j++) { cc[k+j]=cc[k-i+j]+cc[k-i+j-1]; } cc[k+i]=cc[k+i-1]+1; } } // return the subset of a given number using the precalculated tables u64 subsetnum1(u64 x,int i) // the i parameter indicates the current line { int j; // the current column u64 a; // modified Pascal's Coefficient a(n,j) u64 p; // Pascal's triangle Coefficient u64 w; // result bitmap int k; // initialization w=0; p=1; a=0; j=0; // lookup for the column j such that a(i,j) <= "x" < a(i,j+1) // et initialisation de a(i,j) k=i*(i+1)/2; while (a+p<=x) { a+=p; j++; p=bb[k+j]; } --j; k-=i; --i; a=cc[k+j]; x-=a; // nominale lookup while ( (j>=0) && (j<i) ) { // the algorithm stops whenever a side is reached // let be the side j=0, then we complete with zeros // let be the side i=j, then we complete with ones if (x>=a) // can we substruct a(i-1,j) { k-=i; --i; // to the top only a=cc[k+j]; } else { w|=(1ll<<i); // memorize that the number is 1 k-=i; --i; // to the top --j; // to the left a=cc[k+j]; } x-=a; // we substruct with what we could } // filling the last characters with 0 or 1 if (j!=-1) { w|=(1ll<<(i+1))-1ll; } return w; } // return the number of a subsets using the precalculated tables u64 numsubset1(u64 w,int n) { int i,j,k; // index of the course of the triangle u64 a; // pascal's triangle values u64 x; // cumul of all browsed summits // initialization i=-1; j=-1; a=0; x=0; k=0; while (n>0) { // depends on the value of the number i++; // move down anyways k+=i; switch (w&1) { case 0: // ++i; // move just down break; case 1: //++i; ++j; // Move diagonally down right break; } // chift w to position the next number w>>=1; // cumulative value of the summit if (j==-1) a=0; else a=cc[k/*i*(i+1)/2*/+j]; x+=a; // --n; // lookup counter } return x; } // calculate the list of next elements of a given number // return the number of elements in the list // the indexes are affected to *s int suivants(u64 x,u64*s,int i) { int l; // result int j; // the current column u64 a; // the modified pascal's triangle Coefficients a(n,j) u64 p; // pascal's triangle Coefficients int k; u64 c; // initialization p=1; a=0; j=0; l=0; // lookup for j column j such as a(i,j) <= "x" < a(i,j+1) // and initialization of a(i,j) k=i*(i+1)/2; while (a+p<=x) { a+=p; j++; p=bb[k+j]; } --j; k-=i; --i; a=cc[k+j]; c=+x; x-=a; // nominal lookup while ( (j>=0) && (j<i) ) { // the algorithm stops whenever one side is reached // let be the side j=0, then we complete with zeros // let be the side i=j, then we complete with ones if (x>=a) // can we substract a(i-1,j) {// number 0, must memorize the next element c=s[l++]=c+bb[k+j+1]; k-=i; --i; // just at top a=cc[k+j]; } else {// number 1, no next element, just memorize // the value to be incremented c+=bb[k+j+1]; k-=i; --i; // at the top --j; // at the left a=cc[k+j]; } x-=a; // We substract what we could } if (j==-1)// If we stop at j==-1, il means that the bitmap ends with 0, and we have to add all the next elements. { while (i>=0) { c=s[l++]=c+1; i--; } } return l; } // Fill the set number k in set1 from date of set2. u64 brol(u64*set1,u64*set2,int k) { u64 ii,pp,w,n; printf("p=%d b[p]=%llu\n",k,b[k]); fflush(stdout); clear_set(set1,b[k]); for (ii=0;ii<b[k-1];ii++) { if (isin(ii,set2)!=0) { w=subsetnum1(c[k-2]+ii,CARDINAL); for (pp=1;pp<(1ll<<CARDINAL);pp<<=1) { if ((pp&w)==0) { n=numsubset1(w|pp,CARDINAL); include(n-c[k-1],set1); } } } } pp=cardinal(set1,b[k]); printf("%llu %llu %llu\n",pp, b[k], b[k]-pp); fflush(stdout); return b[k]-pp; } // The procedure to obtain the successors u64 brol1(u64*set1,u64*set2,int k) { u64 ii,pp; u64 s[CARDINAL]; int l,i; printf("p=%d b[p]=%llu\n",k,b[k]); fflush(stdout); clear_set(set1,b[k]); for (ii=0;ii<b[k-1];ii++) { if (isin(ii,set2)!=0) { l=suivants(c[k-2]+ii,s,CARDINAL); for (i=0;i<l;i++) { include(s[i]-c[k-1],set1); } } } pp=cardinal(set1,b[k]); printf("%llu %llu %llu\n",pp, b[k], b[k]-pp); fflush(stdout); return b[k]-pp; } // The function verif: verifying that the sum of the elements of a subset is zero. // //------------------------------------------------------------------ void verif(u64 w) { int s,i; s=0; u64 m; for (i=0,m=1;m<(1ll<<CARDINAL);m<<=1,i++) { if ((w&m)!=0) s=add(s,i); } if (s!=0) printf("!!! "); fflush(stdout); } // ************************* The algorithme description ************************* // Let : G a finit abelian group ; // N : The cardinal of G ; // E : The exponent of G ; // g : Harboth’s constant. //— The starting point: We consider all subsets of E elements (we have N choose E subsets of E elements). //— We mark all of them whose sum’s zero. //— Thus we obtain all N choose E subsets of E elements whose sum’s zero. //— We browse all subsets of E elements. When one subset is marked, we mark //all its successors immidiate for inclusion those how are obtained by adding any element. // Thus we obtain all subsets of E + 1 elements which have a zero sum subset of E //elements. //— We repeat recursively with the subsets of E+1 elements marked until all the susets would be marked with a given cardinal. //_ This cardinal represent the Harborth constant g(G). //— We note that just before reaching this constant, the subset no marked have no zero sum subset of E elements, so we can have ideas for the lower bound. //— The subsets of G are represent by a bitmap. int main() { clock_t h; double dh; u64 no,m,ii,jj; u64 w; int n,p; printf("Hello somme nulle!\n"); setA=malloc(3500000000); setB=malloc(3500000000); printf("setA size = %lu\n", malloc_usable_size(setA)); printf("setB size = %lu\n", malloc_usable_size(setB)); initbbcc(); int k; // binominal coefficients table initialization n=CARDINAL; for(p=0;p<CARDINAL;p++) b[p]=binome(n,p); // calculate the cumulates c[0]=b[0]; for(p=1;p<CARDINAL;p++) c[p]=c[p-1]+b[p]; for (p=0;p<=2*EXPOSANT+1;p++) { printf("binome(%d,%d)=%llu cumuls=%llu\n",CARDINAL,p,b[p],c[p]); } no=c[EXPOSANT-2]; m=c[EXPOSANT-1]; printf("%llu ... %llu\n",no,m); // initialization for k=EXPONENT clear_set(setA,b[EXPOSANT]); jj=0; // browse of all sets of EXPONENT-1 elements for (ii=0;ii<b[EXPOSANT-1];ii++) { w=subsetnum1(ii+c[EXPOSANT-2],CARDINAL); w=completeoppsum(w); if (w!=0) jj++; if(w!=0) { include(numsubset1(w,CARDINAL)-c[EXPOSANT-1],setA); } } printf("%llu %llu %llu %llu\n",b[EXPOSANT-1],m-no,jj,cardinal(setA,b[EXPOSANT])); fflush(stdout); u64*s1,*s2,*st; s1=setB; s2=setA; u64 cs; k=EXPOSANT+1; do { cs=brol1(s1,s2,k); st=s1; s1=s2; s2=st; /* Listing of elements of interesting cases, in fact just before reaching this constant, the subset no marked have no zero sum subset of E elements, so we can have ideas for the lower bound. if (k==10) { u64 ii; printf("sous-ensembles sans somme nulle:\n"); for (ii=0;ii<b[k];ii++) { if (isin(ii,st)==0) { int l; u64 w; w=subsetnum1(ii+c[k-1],CARDINAL); for (l=0;l<CARDINAL;l++) { if (((1ll<<l)&w)!=0) { affiche(l); printf(" "); } } printf("\n"); fflush(stdout); } } } */ k++; } while ((cs!=0)&&(k<CARDINAL-1)); h=clock(); dh=((double)h)/CLOCKS_PER_SEC; printf("temps passé = %lf\n",dh); return 0; }
C
#include<stdio.h> #include<pthread.h> #define NUM_HILOS 4 void *hola(void *arg){ printf("hola mundo\n"); printf("soy el hillo %lu \n", pthread_self()); } int main(){ int i; pthread_t tid[NUM_HILOS]; for (i = 0; i<NUM_HILOS; i++) pthread_create(&tid[i], NULL, hola, NULL); for (i=0; i<NUM_HILOS; i++) pthread_join(tid[i], NULL); return 0; }
C
/* * File: main.c * Author: Armands Skolmeisters * */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <sys/time.h> #include <string.h> #include <signal.h> #include "../common/Defs.h" #include "Server.h" int game_state; int listener; struct Player players[MAX_PLAYER_COUNT]; char send_buffer[MAX_MESSAGE_SIZE]; int do_move; int main(int argc, char** argv) { pthread_t thread_timer; pthread_t thread_listener; struct sigaction new_action, old_action; new_action.sa_handler = end_game_time_limit; sigaction (SIGALRM, NULL, &old_action); if (old_action.sa_handler != SIG_IGN) sigaction (SIGALRM, &new_action, NULL); parse_config(); shuffle_ids(); clear_players(); pthread_create (&thread_timer, NULL, (void *) &timer_thread_function, NULL); pthread_create (&thread_listener, NULL, (void *) &listener_thread_function, NULL); game_state = STATE_INITIAL; do_move = 0; while(1) { if (do_move == 1 && game_state == STATE_GAME) { do_move = 0; move_all(); //send_messages(); } } return(EXIT_SUCCESS); } void timer_thread_function() { struct timespec ts; int milisec = 1000 / game_config.snake_speed; ts.tv_sec = 0; ts.tv_nsec = milisec * 1000000L; infof("Timer thread working"); while (1) { while (game_state == STATE_GAME) { //infof("do move"); do_move = 1; nanosleep(&ts, (struct timespec *)NULL); } printf("Iztīra spēli"); clear_game(); while (game_state == STATE_INITIAL) { } start_game(); send_messages(); } } void clear_players() { int i; for (i = 0; i < MAX_PLAYER_COUNT; i++) { players[i].id = '\0'; players[i].username[0] = '\0'; players[i].state = 0; players[i].points = 0; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_strjoin.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: csimon <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2016/11/15 20:34:25 by csimon #+# #+# */ /* Updated: 2016/11/15 20:34:26 by csimon ### ########.fr */ /* */ /* ************************************************************************** */ #include <string.h> #include <stdlib.h> static size_t ft_strlen(const char *s) { size_t index; char *str; str = (char*)s; index = 0; while (str[index]) index++; return (index); } char *ft_strjoin(char const *s1, char const *s2) { char *str; unsigned int index; size_t len; index = 0; if (!s1 || !s2) return (NULL); len = (ft_strlen(s1) + ft_strlen(s2)); str = (char*)malloc(sizeof(char) * (len + 1)); if (!str) return (NULL); while (s1[index] != '\0') { str[index] = s1[index]; index++; } len = 0; while (s2[len] != '\0') { str[index] = s2[len]; len++; index++; } str[index] = '\0'; return (str); }
C
#include <stdio.h> #include <stdlib.h> #define G 9.81 int main() { float vel_iniziale, theta; float x = 0, y = 0; float vx, vy; float tempo = 0.1; printf("Inserisci velocità iniziale e angolo in radianti"); scanf("%f", &vel_iniziale); scanf("%f", &theta); vx = cos(theta)*vel_iniziale; vy = sin(theta)*vel_iniziale; do{ printf("x: %f, y: %f\n",x,y); x = vx*tempo; y = vy*tempo - 0.5*G*tempo*tempo; tempo = tempo + 0.1; }while (y > 0); return 0; }
C
/* ---------------------------------------------------------------------------- * ûԶģʵ * --------------------------------------------------------------------------*/ #include "TWord.h" #include "string.h" //-------------õGB2312׼λתΪԶֵ------------------ //˺ûԶģزܵõģ //0xffffʾδҵ unsigned short TWord_Word2UserID(unsigned short Word,//ǰֱ>=128 const char *pLUT, //ֶӦԶַ unsigned short Count)//ԶַС { unsigned short Left = 0; //߽ unsigned short Center = Count >> 1;//мλ unsigned short CurPos; //ǰλ unsigned short Condition; //ǰֵ do{ Center >>= 1; //λ CurPos = Center + Left; Condition = *((unsigned short*)pLUT + CurPos);//õ //ǷڷΧ if(Word > Condition)Left = CurPos; //ں else if(Word == Condition) return CurPos;//ҵ //else ǰ棬 }while(Center); //ûҵʱ,Ҳλ! if((Condition > Word) && (Word == *((unsigned short*)pLUT + CurPos - 1))) return CurPos; //ûҵʱ,Ҳλ! if((Condition < Word) && (Word == *((unsigned short*)pLUT + CurPos + 1))) return CurPos; //Ҳûˣ return 0xffff; } //--------------------õ16X16ıһлģ-------------------------- //ֱͨ˺һֵGB2312ͼε void TWord_GetLineBuf_GB2312(char *pString, //ַ unsigned char w, //п unsigned char *pLine)//л,>=w * 32 { char Code; unsigned short Word; unsigned short WordCount = TWord_GetGB2312LUTSize();//ԶַС for(unsigned char i = 0; i < w; i++){ Code = *pString++; if(Code < 0x80){//ASCII //ַֿ֧ʱʾո #ifndef TWORD_ASC_EN_CTRL if(Code < 32) Code = 32; #endif memcpy(pLine,TWord_pGetAsciiModule(Code),16); pLine += 16; } else{//ȫַ Word = (unsigned short)Code << 8 + *pString++; Word = TWord_Word2UserID(Word,TWord_GB2312LUT,WordCount); if(Word < 0xffff){ //ҵ memcpy(pLine,TWord_pGetWordModule(Word),32); pLine += 16; } else{//δҵʱΪո memcpy(pLine,TWord_pGetAsciiModule(32),16); pLine += 16; memcpy(pLine,TWord_pGetAsciiModule(32),16); pLine += 16; } } } }
C
/* **统计输入文本的行数 */ #include<stdio.h> void main(){ int c, nl; nl = 0; while((c = getchar()) != EOF) if(c == '\n') ++nl; printf("输入文本的行数是: %d\n",nl); }
C
#include "tab.h" void InitTab(int *tab, int size){ srand(time(NULL)); int i; for (i=0;i<size;i++){ tab[i]= rand()%10; } return; } void PrintTab(int * tab, int size){ int i; for(i=0; i<size; i++){ printf("%d ", tab[i]); } return; } int Sum_Tab(int *tab, int size){ int S=0; int i; for(i=0; i<size; i++){ S+=tab[i]; } return S; } int MinSum_Tab(int *min, int *tab, int size){ int S=0; int i; int min2=10; for(i=0; i<size; i++){ S+=tab[i]; if(min2>tab[i]){ min2=tab[i]; } } *min=min2; return S; }
C
#include <stdio.h> /* Program to demonstrate function definition: num1. with arguments num2. with multiple return type */ void foo(int num1, int num2, int *largest_num, int *smallest_num) { if (num1 > num2) { *largest_num = num1; *smallest_num = num2; } else { *largest_num = num2; *smallest_num = num1; } } int main() { int great, small, x, y; printf("Enter two numbers: \n"); scanf("%d%d", &x, &y); //3 ,4 foo(x, y, &great, &small); //mixed call - call by val + call vy ref printf("\nThe greater number is %d and the" "smaller number is %d", great, small); return 0; }
C
#include <stdio.h> #include <stdbool.h> #include <string.h> bool is_palindrome(char str[]){ char reverse[20]={0}; char length = strlen(str); for(int i=0; i<length; i++){ reverse[i] = str[length-1-i]; } if(strcmp(str, reverse) == 0){ return true; } else{ return false; } } int main(){ char str[20] = {0}; scanf("%s", str); if(is_palindrome(str)){ printf("true"); } else{ printf("false"); } }
C
#include <stdio.h> #include <stdlib.h> #include <time.h> void transpose(int *dst, int *src, int n) { for (long i = 0; i < n; i++) for (long j = 0; j < n; j++) dst[j * n + i] = src[i * n + j]; } void transpose2(int *dst, int *src, int n) { for (long i = 0; i < n; i += 8) { for (long j = 0; j < n; j += 8) { for (long Xi = i; Xi + i < n && Xi < i + 8; Xi++) { for(long Xj = j; Xj + j < n && Xj < j + 8; Xj++) { dst[(j + Xj)*n + i + Xi] = src[(i + Xi)*n + j + Xj]; } } } } } int main() { int n = 10000; int *m1 = malloc(n * n * 4); int *m2 = malloc(n * n * 4); clock_t t = clock(); transpose(m2, m1, n); t = clock() - t; printf("Unoptimized transpose: %fs\n",((double)t) / CLOCKS_PER_SEC); t = clock(); transpose2(m2, m1, n); t = clock() - t; printf("Optimized transpose: %fs\n",((double)t) / CLOCKS_PER_SEC); return 0; }
C
#include "../SPBPriorityQueue.h" #include "unit_test_util.h" #include <stdbool.h> #define ASSERT(condition) ASSERT_TRUE(condition) static bool listElementsEqualsNotSame3(SPListElement firstElement, SPListElement secondElement, SPListElement third); static bool listElementsEqualsNotSame(SPListElement firstElement, SPListElement secondElement); static bool successfulEnqueue(SPBPQueue queue, int index, double value); static bool successfulEnqueueElement(SPBPQueue queue, SPListElement newElement); static bool fullEnqueue(SPBPQueue queue, int index, double value); static bool successfulDequeue(SPBPQueue queue); static bool emptyDequeue(SPBPQueue queue); static bool emptyQueue(SPBPQueue queue); static bool queueState(SPBPQueue queue, int expectedSize, int minElementIndex, double minValue, int maxElementIndex, double maxValue); static bool peekAndDequeueEquals(SPBPQueue queue1, SPBPQueue queue2, int index, double value); static bool peekEquals(SPBPQueue queue, SPListElement element); static bool peekLastEquals(SPBPQueue queue, SPListElement element); static bool testQueueCreate() { ASSERT_NULL(spBPQueueCreate(0)); ASSERT_NULL(spBPQueueCreate(-2)); SPBPQueue queue = spBPQueueCreate(1); ASSERT_NOT_NULL(queue); ASSERT_SAME(spBPQueueGetMaxSize(queue), 1); spBPQueueDestroy(queue); return true; } static bool testSingletonQueue() { SPBPQueue queue = spBPQueueCreate(1); ASSERT_NOT_NULL(queue); ASSERT(emptyQueue(queue)); ASSERT(successfulEnqueue(queue, 2, 10.0)); ASSERT(queueState(queue, 1, 2, 10.0, 2, 10.0)); ASSERT(fullEnqueue(queue, 2, 11.0)); ASSERT(queueState(queue, 1, 2, 10.0, 2, 10.0)); ASSERT(fullEnqueue(queue, 3, 10.0)); ASSERT(queueState(queue, 1, 2, 10.0, 2, 10.0)); ASSERT(fullEnqueue(queue, 2, 10.0)); ASSERT(queueState(queue, 1, 2, 10.0, 2, 10.0)); ASSERT(successfulEnqueue(queue, 1, 10.0)); ASSERT(queueState(queue, 1, 1, 10.0, 1, 10.0)); ASSERT(successfulEnqueue(queue, 1, 9.999)); ASSERT(queueState(queue, 1, 1, 9.999, 1, 9.999)); ASSERT(fullEnqueue(queue, 1, 9.999)); ASSERT(queueState(queue, 1, 1, 9.999, 1, 9.999)); ASSERT(successfulDequeue(queue)); ASSERT(emptyQueue(queue)); ASSERT(successfulEnqueue(queue, 1, 10.0)); ASSERT(queueState(queue, 1, 1, 10.0, 1, 10.0)); spBPQueueClear(queue); ASSERT(emptyQueue(queue)); spBPQueueDestroy(queue); return true; } static bool testMultipleQueueOperations() { SPBPQueue queue = spBPQueueCreate(3); ASSERT_NOT_NULL(queue); ASSERT(emptyQueue(queue)); ASSERT(successfulEnqueue(queue, 2, 10.0)); // e1 ASSERT(queueState(queue, 1, 2, 10.0, 2, 10.0)); ASSERT(successfulEnqueue(queue, 1, 10.0)); // e2 ASSERT(queueState(queue, 2, 1, 10.0, 2, 10.0)); ASSERT(successfulDequeue(queue)); ASSERT(queueState(queue, 1, 2, 10.0, 2, 10.0)); ASSERT(successfulDequeue(queue)); ASSERT(emptyQueue(queue)); ASSERT(successfulEnqueue(queue, 2, 1.0)); // e1 ASSERT(queueState(queue, 1, 2, 1.0, 2, 1.0)); // Expected e1 ASSERT(successfulEnqueue(queue, 1, 2.0)); // e2 ASSERT(queueState(queue, 2, 2, 1.0, 1, 2.0)); // Expected e1->e2 ASSERT(successfulEnqueue(queue, 3, 0.5)); // e3 ASSERT(queueState(queue, 3, 3, 0.5, 1, 2.0)); // Expected e3->e1->e2 ASSERT(successfulEnqueue(queue, 4, 1.23)); // e4 ASSERT(queueState(queue, 3, 3, 0.5, 4, 1.23)); // Expected e3->e1->e4 ASSERT(fullEnqueue(queue, 5, 1.23)); ASSERT(queueState(queue, 3, 3, 0.5, 4, 1.23)); // Expected e3->e1->e4 ASSERT(successfulDequeue(queue)); ASSERT(queueState(queue, 2, 2, 1.0, 4, 1.23)); // Expected e1->e4 ASSERT(successfulEnqueue(queue, 5, 1.23)); // e2 ASSERT(queueState(queue, 3, 2, 1.0, 5, 1.23)); // Expected e1->e4->e2 ASSERT(fullEnqueue(queue, 3, 3.0)); ASSERT(queueState(queue, 3, 2, 1.0, 5, 1.23)); // Expected e1->e4->e2 ASSERT(successfulEnqueue(queue, 1, 1.2)); // e3 ASSERT(queueState(queue, 3, 2, 1.0, 4, 1.23)); // Expected e1->e3->e4 ASSERT(fullEnqueue(queue, 10, 1.23)); ASSERT(queueState(queue, 3, 2, 1.0, 4, 1.23)); // Expected e1->e3->e4 ASSERT(successfulEnqueue(queue, 1, 1.1)); // e2 ASSERT(queueState(queue, 3, 2, 1.0, 1, 1.2)); // Expected e1->e2->e3 ASSERT(successfulDequeue(queue)); ASSERT(queueState(queue, 2, 1, 1.1, 1, 1.2)); // Expected e2->e3 ASSERT(successfulDequeue(queue)); ASSERT(queueState(queue, 1, 1, 1.2, 1, 1.2)); // Expected e3 spBPQueueClear(queue); ASSERT(emptyQueue(queue)); spBPQueueDestroy(queue); return true; } static bool testDequeue() { ASSERT_SAME(spBPQueueDequeue(NULL), SP_BPQUEUE_INVALID_ARGUMENT); SPBPQueue queue = spBPQueueCreate(4); ASSERT(successfulEnqueue(queue, 2, 10.0)); // e1 ASSERT(successfulEnqueue(queue, 5, 2.0)); // e2 ASSERT(successfulDequeue(queue)); ASSERT(successfulDequeue(queue)); ASSERT(emptyDequeue(queue)); ASSERT(emptyDequeue(queue)); spBPQueueDestroy(queue); return true; } static bool testCopy() { ASSERT_NULL(spBPQueueCopy(NULL)); SPBPQueue queue = spBPQueueCreate(3); SPBPQueue copy = spBPQueueCopy(queue); ASSERT_SAME(spBPQueueGetMaxSize(queue), spBPQueueGetMaxSize(copy)); ASSERT_SAME(spBPQueueSize(queue), spBPQueueSize(copy)); ASSERT(successfulEnqueue(queue, 1, 2)); // e1 ASSERT(successfulEnqueue(queue, 2, 3)); // e2 ASSERT(successfulEnqueue(queue, 3, 4)); // e3 SPBPQueue copy2 = spBPQueueCopy(queue); ASSERT_SAME(spBPQueueSize(queue), 3); ASSERT_SAME(spBPQueueSize(copy), 0); ASSERT_SAME(spBPQueueSize(copy2), 3); ASSERT(peekAndDequeueEquals(queue, copy2, 1, 2)); ASSERT(peekAndDequeueEquals(queue, copy2, 2, 3)); ASSERT(peekAndDequeueEquals(queue, copy2, 3, 4)); ASSERT(emptyQueue(queue)); ASSERT(emptyQueue(copy2)); ASSERT_SAME(spBPQueueSize(queue), 0); ASSERT_SAME(spBPQueueSize(copy2), 0); ASSERT(successfulEnqueue(queue, 2, 3)); ASSERT(successfulEnqueue(queue, 3, 4)); SPBPQueue copy3 = spBPQueueCopy(queue); ASSERT_SAME(spBPQueueSize(copy3), 2); ASSERT(peekAndDequeueEquals(queue, copy3, 2, 3)); ASSERT(peekAndDequeueEquals(queue, copy3, 3, 4)); ASSERT(emptyQueue(queue)); ASSERT(emptyQueue(copy3)); spBPQueueDestroy(queue); spBPQueueDestroy(copy); spBPQueueDestroy(copy2); spBPQueueDestroy(copy3); return true; } static bool testEnqueue() { SPBPQueue queue = spBPQueueCreate(4); ASSERT_NOT_NULL(queue); ASSERT_SAME(spBPQueueEnqueue(NULL, NULL), SP_BPQUEUE_INVALID_ARGUMENT); SPListElement e = spListElementCreate(2, 10.0); ASSERT_SAME(spBPQueueEnqueue(NULL, e), SP_BPQUEUE_INVALID_ARGUMENT); spListElementDestroy(e); ASSERT_SAME(spBPQueueEnqueue(queue, NULL), SP_BPQUEUE_INVALID_ARGUMENT); ASSERT(successfulEnqueue(queue, 2, 10.0)); // e1 ASSERT(successfulEnqueue(queue, 5, 1.0)); // e3 ASSERT(successfulEnqueue(queue, 5, 2.0)); // e2 ASSERT(successfulEnqueue(queue, 3, 2.1)); // e4 // The state of the queue should be e3->e2->e4->e1 ASSERT(successfulEnqueue(queue, 7, 2.05)); // e5 // The state of the queue should be e3->e2->e5->e4 // Check a few not inserting scenarios ASSERT(fullEnqueue(queue, 100, 20.0)); ASSERT(fullEnqueue(queue, 0, 15.0)); ASSERT(fullEnqueue(queue, 7, 2.2)); // The state of the queue should be e3->e2->e5->e4 ASSERT(successfulEnqueue(queue, 6, 0.5)); // e1 // The state of the queue should be e1->e3->e2->e5 ASSERT(fullEnqueue(queue, 3, 2.06)); ASSERT(successfulEnqueue(queue, 6, 2.05)); // e4 // The state of the queue should be e1->e3->e2->e4 ASSERT(successfulEnqueue(queue, 5, 1.0)); // Insert same instance SPListElement e1 = spListElementCreate(6, 0.5); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT(successfulEnqueueElement(queue, e1)); spListElementDestroy(e1); ASSERT(fullEnqueue(queue, 5, 1.0)); ASSERT(successfulEnqueue(queue, 6, 0.5)); ASSERT(fullEnqueue(queue, 6, 0.5)); spBPQueueDestroy(queue); return true; } static bool testQueueDestroy() { spBPQueueDestroy(NULL); return true; } static bool testClear() { spBPQueueClear(NULL); SPBPQueue queue = spBPQueueCreate(3); ASSERT(emptyQueue(queue)); ASSERT(successfulEnqueue(queue, 1, 1.0)); // e1 ASSERT(successfulEnqueue(queue, 2, 2.0)); // e2 ASSERT_SAME(spBPQueueSize(queue), 2); spBPQueueClear(queue); ASSERT(emptyQueue(queue)); ASSERT_SAME(spBPQueueGetMaxSize(queue), 3); ASSERT(successfulEnqueue(queue, 2, 2.0)); ASSERT(successfulEnqueue(queue, 1, 1.0)); ASSERT_SAME(spBPQueueSize(queue), 2); spBPQueueClear(queue); ASSERT(emptyQueue(queue)); ASSERT_SAME(spBPQueueGetMaxSize(queue), 3); spBPQueueDestroy(queue); return true; } static bool testPeek() { ASSERT_NULL(spBPQueuePeek(NULL)); SPBPQueue queue = spBPQueueCreate(4); ASSERT_NULL(spBPQueuePeek(queue)); SPListElement e1 = spListElementCreate(1, 2.0); SPListElement e2 = spListElementCreate(2, 3.0); SPListElement e3 = spListElementCreate(2, 1.0); SPListElement e4 = spListElementCreate(2, 4.0); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT(peekEquals(queue, e1)); ASSERT(successfulEnqueueElement(queue, e2)); ASSERT(peekEquals(queue, e1)); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT(peekEquals(queue, e3)); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT(peekEquals(queue, e3)); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT(peekEquals(queue, e3)); ASSERT(fullEnqueue(queue, 1, 2.0)); ASSERT(peekEquals(queue, e3)); ASSERT(fullEnqueue(queue, 2, 4.0)); ASSERT(peekEquals(queue, e3)); spBPQueueDestroy(queue); spListElementDestroy(e1); spListElementDestroy(e2); spListElementDestroy(e3); spListElementDestroy(e4); return true; } static bool testPeekLast() { ASSERT_NULL(spBPQueuePeekLast(NULL)); SPBPQueue queue = spBPQueueCreate(3); ASSERT_NULL(spBPQueuePeekLast(queue)); SPListElement e1 = spListElementCreate(2, 2.0); SPListElement e2 = spListElementCreate(1, 2.0); SPListElement e3 = spListElementCreate(0, 2.01); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT(peekLastEquals(queue, e1)); ASSERT(successfulEnqueueElement(queue, e2)); ASSERT(peekLastEquals(queue, e1)); ASSERT(successfulEnqueueElement(queue, e2)); ASSERT(peekLastEquals(queue, e1)); ASSERT(successfulEnqueueElement(queue, e2)); ASSERT(peekLastEquals(queue, e2)); ASSERT(successfulDequeue(queue)); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT(peekLastEquals(queue, e3)); spBPQueueDestroy(queue); spListElementDestroy(e1); spListElementDestroy(e2); spListElementDestroy(e3); return true; } static bool testMinValue() { ASSERT_SAME(spBPQueueMinValue(NULL), -1); SPBPQueue queue = spBPQueueCreate(3); ASSERT_SAME(spBPQueueMinValue(queue), -1); SPListElement e1 = spListElementCreate(2, 2.0); SPListElement e2 = spListElementCreate(1, 2.1); SPListElement e3 = spListElementCreate(3, 1.99); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_SAME(spBPQueueMinValue(queue), 2.0); ASSERT(successfulEnqueueElement(queue, e2)); ASSERT_SAME(spBPQueueMinValue(queue), 2.0); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT_SAME(spBPQueueMinValue(queue), 1.99); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_SAME(spBPQueueMinValue(queue), 1.99); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT_SAME(spBPQueueMinValue(queue), 1.99); spBPQueueDestroy(queue); spListElementDestroy(e1); spListElementDestroy(e2); spListElementDestroy(e3); return true; } static bool testMaxValue() { ASSERT_SAME(spBPQueueMaxValue(NULL), -1); SPBPQueue queue = spBPQueueCreate(3); ASSERT_SAME(spBPQueueMaxValue(queue), -1); SPListElement e1 = spListElementCreate(2, 2.0); SPListElement e2 = spListElementCreate(1, 2.1); SPListElement e3 = spListElementCreate(3, 1.99); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_SAME(spBPQueueMaxValue(queue), 2.0); ASSERT(successfulEnqueueElement(queue, e2)); ASSERT_SAME(spBPQueueMaxValue(queue), 2.1); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT_SAME(spBPQueueMaxValue(queue), 2.1); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_SAME(spBPQueueMaxValue(queue), 2.0); ASSERT(successfulEnqueueElement(queue, e3)); ASSERT_SAME(spBPQueueMaxValue(queue), 2.0); spBPQueueDestroy(queue); spListElementDestroy(e1); spListElementDestroy(e2); spListElementDestroy(e3); return true; } static bool testEmpty() { SPBPQueue queue = spBPQueueCreate(2); ASSERT_TRUE(spBPQueueIsEmpty(queue)); SPListElement e1 = spListElementCreate(2, 2.0); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_FALSE(spBPQueueIsEmpty(queue)); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_FALSE(spBPQueueIsEmpty(queue)); ASSERT(successfulDequeue(queue)); ASSERT_FALSE(spBPQueueIsEmpty(queue)); ASSERT(successfulDequeue(queue)); ASSERT_TRUE(spBPQueueIsEmpty(queue)); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_FALSE(spBPQueueIsEmpty(queue)); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_FALSE(spBPQueueIsEmpty(queue)); spBPQueueClear(queue); ASSERT_TRUE(spBPQueueIsEmpty(queue)); spBPQueueDestroy(queue); spListElementDestroy(e1); return true; } static bool testFull() { SPBPQueue queue = spBPQueueCreate(2); ASSERT_FALSE(spBPQueueIsFull(queue)); SPListElement e1 = spListElementCreate(2, 2.0); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_FALSE(spBPQueueIsFull(queue)); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_TRUE(spBPQueueIsFull(queue)); ASSERT(fullEnqueue(queue, 2, 2.0)); ASSERT_TRUE(spBPQueueIsFull(queue)); ASSERT(successfulDequeue(queue)); ASSERT_FALSE(spBPQueueIsFull(queue)); ASSERT(successfulEnqueueElement(queue, e1)); ASSERT_TRUE(spBPQueueIsFull(queue)); spBPQueueDestroy(queue); spListElementDestroy(e1); return true; } static bool testElementCopy() { SPBPQueue queue = spBPQueueCreate(2); SPListElement element = spListElementCreate(2, 3); ASSERT(successfulEnqueueElement(queue, element)); spListElementSetValue(element, 1); ASSERT_SAME(spBPQueueMinValue(queue), 3); spListElementSetValue(element, 3); SPListElement peekElement = spBPQueuePeek(queue); ASSERT(listElementsEqualsNotSame(element, peekElement)); spBPQueueDestroy(queue); spListElementDestroy(element); spListElementDestroy(peekElement); return true; } /*** Helper assertion methods ***/ static bool peekEquals(SPBPQueue queue, SPListElement element) { SPListElement peekElement = spBPQueuePeek(queue); ASSERT(listElementsEqualsNotSame(peekElement, element)); spListElementDestroy(peekElement); return true; } static bool peekLastEquals(SPBPQueue queue, SPListElement element) { SPListElement peekElement = spBPQueuePeekLast(queue); ASSERT(listElementsEqualsNotSame(peekElement, element)); spListElementDestroy(peekElement); return true; } static bool peekAndDequeueEquals(SPBPQueue queue1, SPBPQueue queue2, int index, double value) { SPListElement e1 = spBPQueuePeek(queue1); spBPQueueDequeue(queue1); SPListElement e2 = spBPQueuePeek(queue2); spBPQueueDequeue(queue2); SPListElement e3 = spListElementCreate(index, value); ASSERT(listElementsEqualsNotSame3(e1, e2, e3)); spListElementDestroy(e1); spListElementDestroy(e2); spListElementDestroy(e3); return true; } static bool emptyDequeue(SPBPQueue queue) { ASSERT_TRUE(spBPQueueIsEmpty(queue)); ASSERT_SAME(spBPQueueDequeue(queue), SP_BPQUEUE_EMPTY); ASSERT_TRUE(spBPQueueIsEmpty(queue)); return true; } static bool successfulDequeue(SPBPQueue queue) { ASSERT_FALSE(spBPQueueIsEmpty(queue)); int size = spBPQueueSize(queue); ASSERT_SAME(spBPQueueDequeue(queue), SP_BPQUEUE_SUCCESS); ASSERT_SAME(spBPQueueSize(queue), size - 1); return true; } static bool emptyQueue(SPBPQueue queue) { ASSERT_TRUE(spBPQueueIsEmpty(queue)); ASSERT(emptyDequeue(queue)); // Assert basic properties ASSERT_NULL(spBPQueuePeek(queue)); ASSERT_NULL(spBPQueuePeekLast(queue)); ASSERT_SAME(spBPQueueMinValue(queue), -1); ASSERT_SAME(spBPQueueMaxValue(queue), -1); return true; } static bool queueState(SPBPQueue queue, int expectedSize, int minElementIndex, double minValue, int maxElementIndex, double maxValue) { SPListElement expectedMinElement = spListElementCreate(minElementIndex, minValue); SPListElement expectedMaxElement = spListElementCreate(maxElementIndex, maxValue); ASSERT_SAME(spBPQueueSize(queue), expectedSize); SPListElement peekElement = spBPQueuePeek(queue); SPListElement peekLastElement = spBPQueuePeekLast(queue); ASSERT(listElementsEqualsNotSame(peekElement, expectedMinElement)); ASSERT(listElementsEqualsNotSame(peekLastElement, expectedMaxElement)); ASSERT_SAME(spBPQueueMinValue(queue), spListElementGetValue(expectedMinElement)); ASSERT_SAME(spBPQueueMaxValue(queue), spListElementGetValue(expectedMaxElement)); if (expectedSize == spBPQueueGetMaxSize(queue)) { ASSERT_TRUE(spBPQueueIsFull(queue)); } spListElementDestroy(expectedMinElement); spListElementDestroy(expectedMaxElement); spListElementDestroy(peekElement); spListElementDestroy(peekLastElement); return true; } static bool listElementsEqualsNotSame(SPListElement firstElement, SPListElement secondElement) { ASSERT_NOT_SAME(firstElement, secondElement); ASSERT_SAME(spListElementCompare(firstElement, secondElement), 0); return true; } static bool listElementsEqualsNotSame3(SPListElement firstElement, SPListElement secondElement, SPListElement thirdElement) { ASSERT(listElementsEqualsNotSame(firstElement, secondElement)); ASSERT(listElementsEqualsNotSame(firstElement, thirdElement)); ASSERT(listElementsEqualsNotSame(secondElement, thirdElement)); return true; } static bool successfulEnqueue(SPBPQueue queue, int index, double value) { SPListElement newElement = spListElementCreate(index, value); ASSERT(successfulEnqueueElement(queue, newElement)); spListElementDestroy(newElement); return true; } static bool successfulEnqueueElement(SPBPQueue queue, SPListElement newElement) { if (spBPQueueIsFull(queue)) { ASSERT_SAME(spBPQueueEnqueue(queue, newElement), SP_BPQUEUE_SUCCESS); ASSERT_TRUE(spBPQueueIsFull(queue)); } else { int size = spBPQueueSize(queue); ASSERT_SAME(spBPQueueEnqueue(queue, newElement), SP_BPQUEUE_SUCCESS); ASSERT_SAME(spBPQueueSize(queue), size + 1); } return true; } static bool fullEnqueue(SPBPQueue queue, int index, double value) { ASSERT_TRUE(spBPQueueIsFull(queue)); SPListElement e = spListElementCreate(index, value); ASSERT_SAME(spBPQueueEnqueue(queue, e), SP_BPQUEUE_FULL); ASSERT_TRUE(spBPQueueIsFull(queue)); spListElementDestroy(e); return true; } int main() { printf("Running SPBOQueueTest.. \n"); RUN_TEST(testQueueCreate); RUN_TEST(testCopy); RUN_TEST(testQueueDestroy); RUN_TEST(testClear); RUN_TEST(testEnqueue); RUN_TEST(testDequeue); RUN_TEST(testPeek); RUN_TEST(testPeekLast); RUN_TEST(testMinValue); RUN_TEST(testMaxValue); RUN_TEST(testEmpty); RUN_TEST(testFull); RUN_TEST(testMultipleQueueOperations); RUN_TEST(testSingletonQueue); RUN_TEST(testElementCopy); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include"dLinkList.h" //һҵڵṹ typedef struct _teacher { TDLinkListNode node; int age; }teacher; //Գ void main() { teacher t1,t2,t3,t4; DLinkList *list = NULL; TDLinkListNode *tlist = NULL; teacher *pt = NULL; int length; int i = 0; t1.age = 10; t2.age = 20; t3.age = 30; t4.age = 40; //һ˫ list = DLinkList_Create(); //ڵIJ DLinkList_Insert(list,(TDLinkListNode *)&t1,0); DLinkList_Insert(list,(TDLinkListNode *)&t2,1); DLinkList_Insert(list,(TDLinkListNode *)&t3,2); DLinkList_Insert(list,(TDLinkListNode *)&t4,3); ////ڵ,Ȼȡ˫ij length = DLinkList_Length(list); for (i = 0; i<length; i++ ) { pt = (teacher *)DLinkList_Get(list,i); printf("%d ",pt->age); } //ڵɾһɾһڵ㣩 DLinkList_Delete(list,0); //ڵɾٴɾĵһڵ㣩 tlist = DLinkList_Get(list,0); DLinkList_DeleteNode(list,tlist); printf("\n"); for (i = 0; i<2; i++ ) { pt = (teacher *)DLinkList_Get(list,i); printf("%d ",pt->age); } //˫αеһϵв tlist = DLinkList_Reset(list); //α겢αĵǰλõָ tlist = DLinkList_Current(list); //ǰαλòαĵǰλõָ tlist = DLinkList_Next(list); //αƲαһλõָ tlist = DLinkList_Pre(list); //ʹصʼ״̬ DLinkList_Clear(list); // DLinkList_Destroy(list); system("pause"); }
C
#include <stdio.h> #include <string.h> int main(void) { char buffer[256]; printf("Enter your name and press <Enter>:\n"); //gets( buffer ); fgets( buffer, 256, stdin ); printf("\nYour name has %d characters and spaces!\n", strlen( buffer )); return 0; }
C
#include "list.h" void push_heap(t_list *head, t_list **heap, int block) { int i; int k; t_list *tmp; heap[0] = (void *)0; heap[1] = (void *)0; i = 0; while (head) { if (i / 2) i %= 2; k = block; while (k-- && head) { tmp = head->next; head->next = heap[i]; heap[i] = head; head = tmp; } i++; } } t_list *merge_list(t_list **heap, int block) { t_list *head; t_list *champ; int k[2]; int max; head = (void *)0; while (heap[0] || heap[1]) { k[0] = block; k[1] = block; while ((k[0] || k[1]) && (heap[0] || heap[1])) { if (heap[0] && k[0]) { if (heap[1] && k[1]) { if (order(heap[0], heap[1])) { max = 0; } else { max = 1; } } else { max = 0; } } else if (heap[1] && k[1]) { max = 1; } else { return (head); } champ = heap[max]->next; heap[max]->next = head; head = heap[max]; heap[max] = champ; k[max]--; } } return (head); } t_list *vm_sort_merge(t_list *head, int len) { t_list *heap[2]; int block; block = 1; while(block < len) { push_heap(head, heap, block); head = merge_list(heap, block); block *= 2; } return (head); }
C
/* ** calc.c for wolf ** ** Made by marc brout ** Login <[email protected]> ** ** Started on Fri Dec 18 18:56:11 2015 marc brout ** Last update Fri Dec 25 00:57:53 2015 marc brout */ #include "wolf.h" void basic_to_sec(t_param *arg, int x) { arg->calc.xf = arg->calc.d; arg->calc.yf = arg->wm.ydep[x]; arg->calc.vecx = arg->calc.xf * arg->wm.costab[(int)arg->lvl[arg->curlvl].plangle] - arg->calc.yf * arg->wm.sintab[(int)arg->lvl[arg->curlvl].plangle]; arg->calc.vecy = arg->calc.xf * arg->wm.sintab[(int)arg->lvl[arg->curlvl].plangle] + arg->calc.yf * arg->wm.costab[(int)arg->lvl[arg->curlvl].plangle]; } void get_len(t_param *arg) { arg->calc.k = 0; arg->calc.xf = arg->lvl[arg->curlvl].playerx + arg->calc.vecx * arg->calc.k; arg->calc.yf = arg->lvl[arg->curlvl].playery + arg->calc.vecy * arg->calc.k; while (!arg->lvl[arg->curlvl].map[(int)arg->calc.yf][(int)arg->calc.xf]) { arg->calc.k += 0.005; arg->calc.xf = arg->lvl[arg->curlvl].playerx + arg->calc.vecx * arg->calc.k; arg->calc.x = 1; if (arg->lvl[arg->curlvl].map[(int)arg->calc.yf][(int)arg->calc.xf]) return ; arg->calc.yf = arg->lvl[arg->curlvl].playery + arg->calc.vecy * arg->calc.k; arg->calc.x = 0; if (arg->lvl[arg->curlvl].map[(int)arg->calc.yf][(int)arg->calc.xf]) return ; if ((int)arg->calc.xf <= 0 || (int)arg->calc.xf >= arg->lvl[arg->curlvl].width || (int)arg->calc.yf <= 0 || (int)arg->calc.yf >= arg->lvl[arg->curlvl].height) return ; } } void project_k(t_param *arg, t_lvl *lvl, int x) { int y; t_color *pixels; int total; pixels = arg->pix->pixels; total = (HEIGHT / 2) + HEIGHT / (2 * arg->calc.k) + lvl->yangle; y = (HEIGHT / 2) - HEIGHT / (2 * arg->calc.k) - 1 + lvl->yangle; y = (y >= 0) ? y : -1; if (lvl->map[(int)arg->calc.yf][(int)arg->calc.xf] == 3) while (++y < total && y < HEIGHT) pixels[x + y * WIDTH].full = GREEN; else if (lvl->map[(int)arg->calc.yf][(int)arg->calc.xf] == 4) while (++y < total && y < HEIGHT) pixels[x + y * WIDTH].full = RED; else { wall_north_east(arg, x, y, total); wall_north_west(arg, x, y, total); wall_south_west(arg, x, y, total); wall_south_east(arg, x, y, total); } } void calc_walls(t_param *arg) { int x; x = -1; while (++x < WIDTH) { basic_to_sec(arg, x); get_len(arg); project_k(arg, &arg->lvl[arg->curlvl], x); } }
C
#include <stdlib.h> #include <stdio.h> #include "iterator.h" iterator_Z * iterator_Z_create(float * array) { iterator_Z * iterator = malloc(sizeof(iterator_Z)); iterator->array = array; iterator_Z_rewind(iterator); return iterator; } void iterator_Z_destroy(iterator_Z * iterator) { free(iterator); } iterator_Z * iterator_Z_rewind(iterator_Z * iterator) { iterator->x = 0; iterator->y = 0; iterator->flag_up = 1; iterator->flag_exception = 1; return iterator; } iterator_Z * iterator_Z_next(iterator_Z * iterator) { if(iterator->flag_up) { if(iterator->flag_exception) { if(iterator->x == 7) { iterator->y += 1; } else { iterator->x += 1; } iterator->flag_exception = 0; iterator->flag_up = 0; } else { iterator->x += 1; iterator->y -= 1; if(iterator->y == 0 || iterator->x == 7) { iterator->flag_exception = 1; } } } else { if(iterator->flag_exception) { if(iterator->y == 7) { iterator->x += 1; } else { iterator->y += 1; } iterator->flag_up = 1; iterator->flag_exception = 0; } else { iterator->y += 1; iterator->x -= 1; if(iterator->x == 0 || iterator->y == 7) { iterator->flag_exception = 1; } } } return iterator; }
C
#include "main.h" #define FLOORFILE "metal2.ppm" #define BODYFILE "r2.ppm" extern GLuint floortex, bodytex; EYE eye; MONSTER me = { 0.05, 0.02, 0.20, 0.20, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00, 0.00 }; int main(int argc, char *argv[]) { glutInit(&argc,argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(800,800); glutInitWindowPosition(80,60); glutCreateWindow("First Program Today"); glutDisplayFunc(display); glutKeyboardFunc(keyboard); glutSpecialFunc(specialkeyboard); glutIdleFunc(dostuff); init(argv[1]); glutMainLoop(); } void init(char *fname) { glClearColor(0.0, 0.0, 0.0, 1.0); glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); glEnable(GL_DEPTH_TEST); glEnable(GL_TEXTURE_2D); eye.x = 0.0; eye.y = 0.0; eye.z = 2.0; eye.facing.theta = DEG2RAD(270.0); eye.facing.phi = 0.0; setdirection(&eye.facing); eye.velocity.theta = DEG2RAD(270.0); eye.velocity.phi = 0.0; setdirection(&eye.velocity); srand48(getpid()); initme(); floortex = readppm(FLOORFILE,1); bodytex = readppm(BODYFILE,1); } void display() { GLfloat xzlen; glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(60.0, 4.0/3.0, 0.001, 5000.0); gluLookAt(eye.x, eye.y + HGT, eye.z, eye.x+eye.facing.x, eye.y + HGT + eye.facing.y, eye.z+eye.facing.z, 0.0, 1.0, 0.0); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); drawfloor(); drawme(); glPopMatrix(); glutSwapBuffers(); } void dostuff() { GLfloat tx,ty,tz; if(eye.speed > 0){ eye.speed *= FRICTION; tx = eye.x + eye.speed * eye.velocity.x; ty = eye.y + eye.speed * eye.velocity.y; tz = eye.z + eye.speed * eye.velocity.z; eye.x = tx; eye.y = ty; eye.z = tz; } glutPostRedisplay(); }
C
#include <stdio.h> int main(void) { char c; while((c = getch()) != EOF) { printf("%c\n", c); } printf("END\n"); return 0; }
C
// RUN: %layout_check %s struct A { int i; struct B { int x, y; } b; int j; } ent1 = { .j = 1, .b.x = 2, 3 // b.y };
C
#include "System_init.h" /*رע⣺flag Ը ޷ֱ*/ extern u8 flag; /********************/ int main(void) { system_init(); //ϵͳʼ temp_data11 = 80; for(;;) { /* ˵ upright_Adjust ܣֱơ 3 1P 2I 3D ˺ֱĺPPIDеı DPID΢ֱֲIֲ */ /* ˵ speed_control ܣƺ 3 1ڲɼҪġžͿԣ 2ٶȿƲԸ40С10 3תٶȿƲ޸ģ40С10 */ if(1 == flag) { upright_Adjust(400.0,0.0,25.0); //9.5 /*رע⣺flag Ը ޷ֱ*/ flag = 0; } } }
C
#include <stddef.h> extern void hostcall_containing_block_on(int); extern void hostcall_containing_yielding_block_on(int); extern int hostcall_async_containing_yielding_block_on(int, int); int main(void) { hostcall_containing_block_on(1312); return 0; } int yielding() { hostcall_containing_yielding_block_on(0); hostcall_containing_yielding_block_on(1); hostcall_containing_yielding_block_on(2); hostcall_containing_yielding_block_on(3); int six = hostcall_async_containing_yielding_block_on(3, 6); hostcall_async_containing_yielding_block_on(3, six); return 0; } int manual_future() { await_manual_future(); return 0; }
C
#include "rand.h" float rand_from(int min, int max) { int range = max - min; int div = RAND_MAX / range; return min + ((float) rand() / div); }
C
typedef struct node { int x; int y; struct node *prev; } Node; Node *getNode(int x, int y) { Node *n = (Node*)malloc(sizeof(Node)); n->x = x; n->y = y; n->prev = NULL; return n; } typedef struct stack { Node *top; } Stack; Stack *getStack() { Stack *s = (Stack*)malloc(sizeof(Stack)); s->top = NULL; return s; } void pushStack(Stack *s, int x, int y) { Node *n = getNode(x, y); n->prev = s->top; s->top = n; } Node *popStack(Stack *s) { Node *n = s->top; s->top = s->top->prev; return n; } bool isEmpty(Stack *s) { if(!s->top) return true; else return false; } int numIslands(char** grid, int gridRowSize, int gridColSize) { int counter = 0; for(int i = 0; i < gridRowSize; i++) { for(int j = 0; j < gridColSize; j++) { if(grid[i][j] == '1') { counter++; Stack *s = getStack(); pushStack(s, i, j); while(!isEmpty(s)) { Node *n = popStack(s); int x = n->x; int y = n->y; grid[x][y] = 'a'; //test up if( (x - 1) >= 0 && grid[x - 1][y] == '1') pushStack(s, x - 1, y); //test left if( (y - 1) >= 0 && grid[x][y - 1] == '1') pushStack(s, x, y - 1); //test right if( (y + 1) < gridColSize && grid[x][y + 1] == '1') pushStack(s, x, y + 1); //test down if( (x + 1) < gridRowSize && grid[x + 1][y] == '1') pushStack(s, x + 1, y); } free(s); } } } return counter; }
C
// Test various lexer edge cases int strcmp(char*, char*); int main() { char*/*strange comment*/a = "he\ l\ lo///*"\ ; if(strcmp(a, "hel lo///*")) return 1; /\ / this is a comment int b = 3; "*/"; // /* /* // */ /* /* */ b = 4; /* b = 5; */ if(b != 4) return 2; return 0; }\
C
#include "common.h" #define TEST_NUM 456 typedef struct { UINT32 a; }Acc; typedef struct _MeiMei { UINT32 b; UINT8 c; Acc Song; }MeiMei; void CommonMacroTest(void) { MeiMei stJiangMin; MeiMei* pstMin = NULL; const Acc* pSong = &stJiangMin.Song; pSong = pSong; stJiangMin.Song.a = TEST_NUM; printf("MB_OFFSET(MeiMei, b) = %ld\n", MB_OFFSET(MeiMei, b)); printf("MB_OFFSET(MeiMei, c) = %ld\n", MB_OFFSET(MeiMei, c)); printf("MB_OFFSET(MeiMei, Song) = %ld\n\n\n", MB_OFFSET(MeiMei, Song)); pstMin = CONTAINER_OF(pSong, MeiMei, Song); printf("pstMin->Song.a = %d\n", pstMin->Song.a); printf("&stJiangMin = 0x%lx\n", (UINT)&stJiangMin); printf("CONTAINER_OF(pSong, MeiMei, Song) = 0x%lx\n", (UINT)CONTAINER_OF(pSong, MeiMei, Song)); assert(0 == MB_OFFSET(MeiMei, b)); assert(4 == MB_OFFSET(MeiMei, c)); assert(8 == MB_OFFSET(MeiMei, Song)); assert(pstMin->Song.a == stJiangMin.Song.a); }
C
#include <stdio.h> #include <pthread.h> #include <stdlib.h> typedef struct arguments{ int i; int j; } numbers; void *function(void *arg){ numbers *value=(numbers *)arg; printf("i: %d, j: %d\n",value->i, value->j); } int main(){ printf("Hello from main\n"); /*int a=3; int *b=(int *)malloc(sizeof(int)); *b=2; pthread_t tid1, tid2; pthread_create(&tid2, NULL, function, (void *)b); pthread_create(&tid1, NULL, function, (void *)&a);*/ pthread_t tid1; numbers *args=(numbers *)malloc(sizeof(numbers)); args->i=1; args->j=2; pthread_create(&tid1, NULL, function, (void *)args); pthread_join(tid1, NULL); //pthread_join(tid2, NULL); /* pthread_create(//function to create a thread pthread_t *thread,//thread id const pthread_attr_t *attr,//attributes of the thread void *(*start_routine) (void *),//function void *arg);//arguments of the function function(); */ return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* environ_dup.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: oyagci <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/04/11 16:58:49 by oyagci #+# #+# */ /* Updated: 2017/04/19 14:05:55 by oyagci ### ########.fr */ /* */ /* ************************************************************************** */ #include <environ/environ.h> t_environ_var *environ_dup_var(t_environ_var *original) { t_environ_var *dup; dup = ft_memalloc(sizeof(t_environ_var)); dup->name = ft_strdup(original->name); dup->value = ft_strdup(original->value); return (dup); } t_list *environ_dup(void) { t_list *environ; t_list *dup; t_list *elem; t_environ_var *var; dup = NULL; environ = environ_get(); while (environ) { var = environ_dup_var(environ->content); elem = ft_lstnew(NULL, 0); elem->content = var; ft_lstpush(&dup, elem); environ = environ->next; } return (dup); }
C
#include "lerEgravarImagem.h" void ler_imagem(FILE *img, PIXEL ***Matriz, int *altura, int *largura, int *MAX, char *formato, BITMAPFILEHEADER *cab1, BITMAPINFOHEADER *cab2) { int i, j; //int MAX; fscanf(img, "%c%c", &formato[0], &formato[1]); //Lê o formato da imagem formato[2] = '\0'; //Insere no último índice o caractere especial delimitador do final da string if(strcmp(formato, "P6") != 0 && strcmp(formato, "BM") != 0){//verifica se o formato é válido(PPM ou BMP) fprintf(stderr, "O FORMATO DA IMAGEM NÃO É VÁLIDO\n"); ferror(img); } if(strcmp(formato, "P6") == 0){ //testa se o formato é PPM binário fscanf(img, "%d %d %d", largura, altura, MAX); //Lê o cabeçalho da imagem fgetc(img); *Matriz = (PIXEL **) malloc( (*largura) * sizeof(PIXEL *)); //Aloca dinamicamente a largura da imagem for(i=0; i<*largura; i++){ //Percorre as colunas (*Matriz)[i] = (PIXEL *) malloc( (*altura) * sizeof(PIXEL) ); //Aloca dinamicamente a altura da imagem for(j=0; j<*altura; j++){ //Percorre as linhas fscanf(img, "%c%c%c", &(*Matriz)[i][j].rgbRed, &(*Matriz)[i][j].rgbGreen, &(*Matriz)[i][j].rgbBlue); //Lê as cores por pixel } } } if(strcmp(formato, "BM") == 0){ //Verifica se o formato é BMP rewind(img); //Aponta para o início do arquivo /*Lê todos os atributos do cabeçalho 1*/ fread(&cab1->bfType, sizeof(cab1->bfType)-1, 1,img); fread(&cab1->bfSize, sizeof(cab1->bfSize), 1,img); fread(&cab1->bfReserved1, sizeof(cab1->bfReserved1), 1,img); fread(&cab1->bfReserved2, sizeof(cab1->bfReserved2), 1,img); fread(&cab1->bfOffBits, sizeof(cab1->bfOffBits), 1,img); /*Lê todos os atributos do cabeçalho 2*/ fread(&cab2->biSize, sizeof(cab2->biSize), 1,img); fread(&cab2->biWidth, sizeof(cab2->biWidth), 1,img); fread(&cab2->biHeight, sizeof(cab2->biHeight), 1,img); fread(&cab2->MbiPlanes, sizeof(cab2->MbiPlanes), 1,img); fread(&cab2->biBitCount, sizeof(cab2->biBitCount), 1,img); fread(&cab2->biCompression, sizeof(cab2->biCompression), 1,img); fread(&cab2->biSizeImage, sizeof(cab2->biSizeImage), 1,img); fread(&cab2->biXPelsPerMeter, sizeof(cab2->biXPelsPerMeter), 1,img); fread(&cab2->biYPelsPerMeter, sizeof(cab2->biYPelsPerMeter), 1,img); fread(&cab2->biClrUsed, sizeof(cab2->biClrUsed), 1,img); fread(&cab2->biClrImportant, sizeof(cab2->biClrImportant), 1,img); int trash; *Matriz = (PIXEL **) malloc( cab2->biHeight * sizeof(PIXEL *) ); //Aloca dinamicamente a altura da imagem for(i=0; i<cab2->biHeight; i++){ //Percorre as linhas (*Matriz)[i] = (PIXEL *) malloc( cab2->biWidth * sizeof(PIXEL) ); //Aloca dinamicamente as colunas for(j=0; j<cab2->biWidth; j++){ //Percorre as colunas fscanf(img, "%c%c%c", &(*Matriz)[i][j].rgbRed, &(*Matriz)[i][j].rgbGreen, &(*Matriz)[i][j].rgbBlue); //Lê as cores por pixel } } } } void gravar_imagem(FILE *img, PIXEL **Matriz, char *formato, int largura, int altura, int MAX, BITMAPFILEHEADER cab1, BITMAPINFOHEADER cab2) { int i, j; if(strcmp(formato, "P6") != 0 && strcmp(formato, "BM") != 0){ //Verifica se o formato é válido fprintf(stderr, "O FORMATO DA IMAGEM NÃO É VÁLIDO\n"); ferror(img); } if(strcmp(formato, "P6") == 0){ //Verifica se o formato é PPM binário fprintf(img, "%s\n%d %d\n%d\n", formato, largura, altura, MAX); //imprime o cabeçalho no arquivo "img" for(i=0; i<largura; i++){ //Percorre as colunas for(j=0; j<altura; j++){ //Percorre as linha fprintf(img, "%c%c%c", Matriz[i][j].rgbRed, Matriz[i][j].rgbGreen, Matriz[i][j].rgbBlue); //Imprime as cores/pixel no arquivo "img" } } } if(strcmp(formato, "BM") == 0){ //Verifica se o formato é BMP rewind(img); //Aponta para o início do arquivo /*Lê todos os atributos do cabeçalho 1*/ fwrite(&cab1.bfType, sizeof(cab1.bfType)-1, 1,img); fwrite(&cab1.bfSize, sizeof(cab1.bfSize), 1,img); fwrite(&cab1.bfReserved1, sizeof(cab1.bfReserved1), 1,img); fwrite(&cab1.bfReserved2, sizeof(cab1.bfReserved2), 1,img); fwrite(&cab1.bfOffBits, sizeof(cab1.bfOffBits), 1,img); /*Lê todos os atributos do cabeçalho 2*/ fwrite(&cab2.biSize, sizeof(cab2.biSize), 1,img); fwrite(&cab2.biWidth, sizeof(cab2.biWidth), 1,img); fwrite(&cab2.biHeight, sizeof(cab2.biHeight), 1,img); fwrite(&cab2.MbiPlanes, sizeof(cab2.MbiPlanes), 1,img); fwrite(&cab2.biBitCount, sizeof(cab2.biBitCount), 1,img); fwrite(&cab2.biCompression, sizeof(cab2.biCompression), 1,img); fwrite(&cab2.biSizeImage, sizeof(cab2.biSizeImage), 1,img); fwrite(&cab2.biXPelsPerMeter, sizeof(cab2.biXPelsPerMeter), 1,img); fwrite(&cab2.biYPelsPerMeter, sizeof(cab2.biYPelsPerMeter), 1,img); fwrite(&cab2.biClrUsed, sizeof(cab2.biClrUsed), 1,img); fwrite(&cab2.biClrImportant, sizeof(cab2.biClrImportant), 1,img); int trash; for(i=0; i<cab2.biHeight; i++){ //Percorre as linhas for(j=0; j<cab2.biWidth; j++){ //Percorre as colunas fprintf(img, "%c%c%c", Matriz[i][j].rgbRed, Matriz[i][j].rgbGreen, Matriz[i][j].rgbBlue); //Imprime as cores/pixel no arquivo "img" } } } }
C
/* ** my_display_default.c for my_display_default in /home/antonin.rapini/UnixSystemProgrammation/PSU_2016_my_ls/src/display ** ** Made by Antonin Rapini ** Login <[email protected]> ** ** Started on Tue Nov 29 22:29:12 2016 Antonin Rapini ** Last update Fri Dec 2 21:02:57 2016 Antonin Rapini */ #include <stdlib.h> #include <sys/stat.h> #include "my_list.h" #include "my_options.h" #include "my_fileinfos.h" #include "utils.h" #include "sources.h" void my_display_default(t_options *options, t_list *list) { t_list *start; start = list; while (list != NULL) { if (options->show_hidden || (list->fileinfos->name[0] != '.' || options->show_self)) { my_putstr(list->fileinfos->name); if (list->fileinfos->typespecifier != '\0') my_putchar(list->fileinfos->typespecifier); my_putchar('\n'); } list = list->next; } if (options->recursive && !options->show_self) my_display_recursive(options, start); }
C
/***************************************************************************** * This file is part of Mikrocode library. * * * * Mikrocode project is free software; you can redistribute it and/or * * modify it under the terms of the GNU Lesser General Public * * License as published by the Free Software Foundation; either * * version 2.1 of the License, or (at your option) any later version. * * * * Mikrocode 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 * * Lesser General Public License for more details. * * * * You should have received a copy of the GNU Lesser General Public * * License along with Mikrocode; if not, write to the Free Software * * Foundation, Inc., 51 Franklin Street, Fifth Floor, * * Boston, MA 02110-1301 USA * * * * Copyright (C) 2009-2014 Cyril Hrubis <[email protected]> * * * *****************************************************************************/ #ifndef __STRING_H__ #define __STRING_H__ #include <stdint.h> void str_write(void (*write)(char), char *str); /* * Converts uint8_t into ASCII string. buf must be at least 4 chars wide. */ void str_uint8_t(char *buf, uint8_t val); /* * Converts uint16_t into ASCII string, buf must be at least 6 chars wide. */ void str_uint16_t(char *buf, uint16_t val); /* * Converts uint32_t into ASCII string, buf must be at least 11 chars wide. */ void str_uint32_t(char *buf, uint32_t val); #endif /* __STRING_H__ */
C
/* ** EPITECH PROJECT, 2019 ** my_params_to_list ** File description: ** my_params_to_list */ #include "include/mylist.h" #include <stdlib.h> linked_list_t *my_params_to_list(int ac, char *const *av) { linked_list_t *transition = NULL; linked_list_t *list = malloc(sizeof(*transition)); int count = 0; while (count < ac) { transition = malloc(sizeof(*transition)); transition->data = av[count]; list = transition; transition->next = list; count++; } return list; } int main(int ac, char *av[]) { my_params_to_list(ac,av); return 0; }
C
/* -*- indent-tabs-mode:T; c-basic-offset:8; tab-width:8; -*- vi: set ts=8: * $Id: fast_matrix.c,v 1.1 2004/09/12 03:40:39 poine Exp $ * * Optimized matrix math library. This is messy for speed, not * for readability. * * (c) 2003 Trammell Hudson <[email protected]> * ************* * * This file is part of the autopilot onboard code package. * * Autopilot is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Autopilot 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 Autopilot; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <mat/fast_matrix.h> #include <stdint.h> static inline int is_zero( const double * dp ) { const uint32_t * ip = (uint32_t*) dp; return ip[0] == 0 && ip[1] == 0; } /* * mulNxMxP will perform the following operations: * * OUT = A * B * OUT += A * B * OUT -= A * B * OUT = A * B' * OUT += A * B' * OUT -= A * B' */ void multNxMxP( void * OUT_ptr, const void * A_ptr, const void * B_ptr, int n, int m, int p, int add, int transpose_B ) { int i; int j; int k; double * OUT = OUT_ptr; const double * A = A_ptr; const double * B = B_ptr; for( i=0 ; i<n ; i++ ) { const double * A_i = A + i * m; double * O_i = OUT + i * p; for( j=0 ; j<p ; j++ ) { double s = 0; double * O_i_j = O_i + j; for( k=0 ; k<m ; k++ ) { const double * a = A_i + k; const double * b; #ifdef NO_FPU if( is_zero( a ) ) continue; #endif if( transpose_B ) b = B + j * m + k; else b = B + k * p + j; #ifdef NO_FPU if( is_zero( b ) ) continue; #endif s += *a * *b; } if( add == 0 ) *O_i_j = s; else if( add > 0 ) *O_i_j += s; else *O_i_j -= s; } } }
C
#include <stdio.h> char* getSubstr(char* str, int a,int b){ int arrayLen = (b-a +1) + 1; //we need space for b+1-a chars and 1 space for NULL //allocate space char* substr = (char*)malloc(sizeof(char)*arrayLen); int i,j=0; //copy elements for(i=a-1;i<b;i++){ //j will point to position in substring array and i will point to position in main array. substr[j] = str[i]; j++;//forward j } //terminate the string substr[j] = '\0'; return substr; } int main(void) { char str[] = "billgates"; printf("%s",getSubstr(str,3,6)); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parse_quote.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: toh <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/06/15 14:01:55 by seomoon #+# #+# */ /* Updated: 2021/06/22 16:26:56 by toh ### ########.fr */ /* */ /* ************************************************************************** */ #include "minishell.h" int check_remain_character(t_cmd *curr, char *command) { int i; int len; char *remain_str; i = 0; if (command[i] == 0 || is_space(command[i])) { curr->index++; return (i); } len = get_command_len(command); remain_str = malloc(sizeof(char) * (len + 1)); if (!remain_str) exit_shell(); while (i < len) { remain_str[i] = command[i]; i++; } remain_str[i] = '\0'; curr->argv[curr->index] = ft_strjoin_free_s1(&(curr->argv[curr->index]), remain_str); free(remain_str); curr->index++; return (i); } static int push_arg_quote(t_cmd *curr, char *command, char quote) { int i; int j; int len; len = 0; while (command[len] && command[len] != quote) len++; curr->argv[curr->index] = malloc(sizeof(char) * (len + 1)); if (!curr->argv[curr->index]) exit_shell(); i = 0; j = 0; while (command[i] && command[i] != quote) { if (command[i] == ESCAPE) i++; curr->argv[curr->index][j] = command[i]; j++; i++; } curr->argv[curr->index][j] = '\0'; return (i); } int handle_single_quote(t_cmd *curr, char *command) { int i; command++; i = 0; while (command[i] && command[i] != S_QUOTE) i += push_arg_quote(curr, command, S_QUOTE); if (command[i] != S_QUOTE) return (handle_parse_error(S_QUOTE)); if (i == 0) curr->argv[curr->index] = ft_strdup(""); return (i + 2); } int handle_double_quote(t_cmd *curr, char *command) { int i; command++; i = 0; while (command[i] && command[i] != D_QUOTE) { if (is_symbol(command[i])) i += handle_symbol(curr, command + i); else i += push_arg_quote(curr, command + i, D_QUOTE); } if (command[i] != D_QUOTE) return (handle_parse_error(D_QUOTE)); if (i == 0) curr->argv[curr->index] = ft_strdup(""); return (i + 2); } int handle_quote(t_cmd *curr, char *command, int i) { int result; result = 0; if (command[i] == S_QUOTE) { result = handle_single_quote(curr, command + i); if (result < 0) { curr->index++; return (result); } } else if (command[i] == D_QUOTE) { result = handle_double_quote(curr, command + i); if (result < 0) { curr->index++; return (result); } } result += check_remain_character(curr, command + i + result); return (result); }
C
/* * 二叉搜索树模块的接口 */ #define TREE_TYPE int //树的值类型 /* * 动态分配数组 */ void createBinaryTree(); /* * 向树添加一个新值,参数是需要被添加的值,它必须原先并不在树中 */ void insert( TREE_TYPE value); /* * 查找一个特定的值,这个值作为第一个参数传递个函数 */ TREE_TYPE *find( TREE_TYPE value); /* * 执行树的前序遍历,它的参数是一个回调函数指针,他所指向的函数将在树中处理 * 每个节点被调用,节点的值作为参数传递给这个函数 */ //void pre_order_traverse( void(*callback)(TREE_TYPE value) ); void pre_order_traverse(int root); int treeSize();
C
#include "DandDCharacter.h" #include <stdio.h> #include <malloc.h> #include <string.h> //Prototypes int rollAvg(); void GenerateCharacter(Character * pCharacter); void DisplayCharacter(Character * pCharacter); void SaveCharacter(Character * pCharacter); void LoadCharacter(Character * pCharacter, char * fileName); int DisplayMenu(); int rollAvg() { //Adds together the top 3 rolls of the dice int firstRoll = RollD6(); int secondRoll = RollD6(); int thirdRoll = RollD6(); int fourthRoll = RollD6(); int one=0,two=0,three=0,final=0; int rolls[4] = {firstRoll, secondRoll, thirdRoll, fourthRoll}; int i; for(i=0; i<4; i++) { if(rolls[i] > one) { three= two; two= one; one= rolls[i]; } else if(rolls[i] > two) { three = two; two = rolls[i]; } else if(rolls[i] > three) { three = rolls[i]; } } final = one + two + three; return final; } void GenerateCharacter(Character * pCharacter) { //Generates a new character int choice; //Menu item for ancestry printf("\nSelect an ancestry from this list:\n"); printf("0) human\n"); printf("1) elf\n"); printf("2) halfling\n"); printf("3) dwarf\n"); printf("4) half_elf\n"); printf("5) half_orc\n"); do{ scanf("%d", &choice); switch(choice){ case 0: pCharacter->ancestry = human; break; case 1: pCharacter->ancestry = elf; break; case 2: pCharacter->ancestry = halfling; break; case 3: pCharacter->ancestry = dwarf; break; case 4: pCharacter->ancestry = half_elf; break; case 5: pCharacter->ancestry = half_orc; break; default: printf("Please enter a selection between 0-5\n"); break; } }while(choice<0 || choice>5); //Decides character and player names printf("Please Enter Your Character's Name (no spaces): "); scanf("%s", pCharacter->charname); printf("Please Enter Your Name (no spaces): "); scanf("%s", pCharacter->playername); //Have to set seed for rollAvg to work properly SetSeed(-1); pCharacter->strength = rollAvg(); pCharacter->dexterity = rollAvg(); pCharacter->constitution = rollAvg(); pCharacter->intelligence = rollAvg(); pCharacter->wisdom = rollAvg(); pCharacter->charisma = rollAvg(); } void DisplayCharacter(Character * pCharacter) { //Displays the character the way JimR had it. static char *ancestry[60] = {"human", "elf", "halfling", "dwarf", "half_elf", "half_orc"}; printf("\n*************************\n"); printf("* %s *\n", pCharacter->charname); printf("* By %s *\n", pCharacter->playername); printf("-------------------------\n"); printf("* Strength: %d *\n", pCharacter->strength); printf("* Dexterity: %d *\n", pCharacter->dexterity); printf("* Constitution: %d *\n", pCharacter->constitution); printf("* Intelligence: %d *\n", pCharacter->intelligence); printf("* Wisdom: %d *\n", pCharacter->wisdom); printf("* Charisma: %d *\n", pCharacter->charisma); printf("* Ancestry: %s *\n", ancestry[pCharacter->ancestry]); printf("*************************\n\n\n"); } void SaveCharacter(Character * pCharacter) { //Declare my variables for the files FILE * rpgFile = NULL; char fileType[] = ".character"; char fileName[256]; static char *ancestry[60] = {"human", "elf", "halfling", "dwarf", "half_elf", "half_orc"}; //Retreives the file name printf("\nEnter name of file to save (extension will automatically be .character): "); scanf("%s", fileName); strcat(fileName,fileType); //Open file rpgFile = fopen(fileName, "w"); //Saves the structure elements to the file fprintf(rpgFile, "%s", pCharacter->charname); fprintf(rpgFile, " %s", pCharacter->playername); fprintf(rpgFile, " %d", pCharacter->strength); fprintf(rpgFile, " %d", pCharacter->dexterity); fprintf(rpgFile, " %d", pCharacter->constitution); fprintf(rpgFile, " %d", pCharacter->intelligence); fprintf(rpgFile, " %d", pCharacter->wisdom); fprintf(rpgFile, " %d", pCharacter->charisma); fprintf(rpgFile, " %s", ancestry[pCharacter->ancestry]); fprintf(rpgFile, " %d", pCharacter->ancestry); //Closes file fclose(rpgFile); } void LoadCharacter(Character * pCharacter, char * fileName) { //Load the file FILE * loadFile = fopen(fileName, "r"); int strength[3], dexterity[3], constitution[3], intelligence[3], wisdom[3], charisma[3], ancestry[20], ancestryy[2]; printf("file is open, filename = %s\n", fileName); if(loadFile == NULL) { printf("There is nothing in this file.\n"); } else { fscanf(loadFile, "%s", pCharacter->charname); fscanf(loadFile, " %s", pCharacter->playername); fscanf(loadFile, " %s", strength); pCharacter->strength = atoi(strength); fscanf(loadFile, " %s", dexterity); pCharacter->dexterity = atoi(dexterity); fscanf(loadFile, " %s", constitution); pCharacter->constitution = atoi(constitution); fscanf(loadFile, " %s", intelligence); pCharacter->intelligence = atoi(constitution); fscanf(loadFile, " %s", wisdom); pCharacter->wisdom = atoi(wisdom); fscanf(loadFile, " %s", charisma); pCharacter->charisma = atoi(charisma); fscanf(loadFile, " %s", ancestry); fscanf(loadFile, " %s", ancestryy); pCharacter->ancestry = atoi(ancestryy); } fclose(loadFile); } int DisplayMenu() { int choice; scanf("%d", &choice); if(choice<1 || choice>5) { printf("*** Error: choice must be 1-5 ***\n"); } return choice; }
C
#include <stdio.h> #include <string.h> int Post[30], Pre[30], In[30]; int Left[30], Right[30], Parent[30]; // 模拟线索二叉树 int N, Another = 0; int Index = 0; void Init() { int i; scanf("%d", &N); for(i = 0; i < N; i++) scanf("%d", &Pre[i]); for(i = 0; i < N; i++) scanf("%d", &Post[i]); memset(Left, -1, sizeof(int) * 30); memset(Right, -1, sizeof(int) * 30); memset(Parent, -1, sizeof(int) * 30); } void Print() { if(Another == 0) printf("Yes\n"); else printf("No\n"); int i; for(i = 0; i < N; i++) { printf("%d", In[i]); if(i != N - 1) printf(" "); } printf("\n"); } int FindIndex(int X) { int i; for(i = 0; i < N; i++) if(Post[i] == X) break; return i; } void Tranverse(int r) { if(Left[r] != -1) Tranverse(Left[r]); In[Index++] = Pre[r]; if(Right[r] != -1) Tranverse(Right[r]); } void Solve() { int i, R; for(i = 1; i < N; i++) { R = i - 1; int index1 = FindIndex(Pre[R]); // 当前root int index2 = FindIndex(Pre[i]); if(index1 == index2 + 1 && R + 1 == i) Another = 1; while(index1 < index2) { R = Parent[R]; index1 = FindIndex(Pre[R]); } if(Left[R] == -1) { Left[R] = i; Parent[i] = R; } else { Right[R] = i; Parent[i] = R; } } } int main(int argc, char const *argv[]) { Init(); Solve(); Tranverse(0); Print(); return 0; }
C
#include <stdio.h> int main(void) { int i, j, n; scanf("%d", &n); for (i = 0; i < n; i++) { int year; int first_year = 1896; int olympic_count = 0; scanf("%d", &year); if (year % 4 != 0) { printf("-1\n"); } else { olympic_count = ((year - first_year) / 4) + 1; printf("%d\n", olympic_count); } } return 0; } // 問題文 // 今年、2016年はブラジルのリオデジャネイロで夏季オリンピックが開催される。また、この次の夏季オリンピックは2020年に日本の東京で第32回の夏季オリンピックが開催される予定である。 // 夏季オリンピックは1896年にギリシャのアテネで第1回が開催されてから、4年に一度ずつ、4の倍数の年に開催されている。この回数の数え方は、中止になってしまった大会にも番号が振られている。例えば、1916年のベルリン大会は中止になったが、第6回オリンピック競技大会と数字が付いている。 // 年が西暦で与えられるので、その年に行われる夏季オリンピックが第何回であるかを判定せよ。 // 制約 // NとYi (1 <= i <= N) は整数で与えられ、以下の制約を満たす。 // 1 <= N <= 100 // 1 <= Yi <= 100000 (1 <= i <= N) // 入力 // 入力は以下の形式で与えられる。 // N // Y1 // Y2 // : // YN // ここで、Nはデータセットの数、Yi (1 <= i <= N)は西暦の年を表す。 // 出力 // i (1 <= i <= N) 行目に、西暦Yi年に行われる夏季オリンピックが第何回であるかを出力せよ。ただし、その年に夏季オリンピックが開催されない時には-1を出力せよ。 // 入力例 // 5 // 1896 // 2020 // 1000 // 1916 // 99999 // 出力例 // 1 // 32 // -1 // 6 // -1
C
/****************************** (C) COPYRIGHT 2016 ******************************* * * ܣù30ֻŹ90ֻ㼦øֻ * Ҫ㣺ͳѧʹöԪһη磺x+y=30;2x+4y=90ֱx,y * Խһx,yóֵעҵ뷽 * ********************************************************************************/ #include <stdio.h> double SumMuti(int num); /************************************************* Function: main Description: Calls: scanf printf Called By: Input: Output: Return: 0 *************************************************/ int main(void) { int x = 0; int y = 30 - x; while (2 * x + 4 * y != 90) { x++; y = 30 - x; //ע䲻٣xy洢Ķdzֵyx仯Զ仯 } printf("the number of chicken is :%d\n", x); printf("the number of rabbit is :%d\n", y); }
C
#include <stdio.h> #include <string.h> #include <math.h> #include <stdlib.h> // N, Q <= 1000 // Length of string less than 21 characters. int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int N = 0, Q = 0; scanf("%d", &N); char str[N][20]; int idx= 0; memset(str, 0, N*20); for(; idx < N; idx++) { scanf("%s", str[idx]); } // for(idx = 0; idx < N; idx++) // { // printf("%s\n", str[idx]); // } scanf("%d", &Q); int occurrences[Q]; char query[Q][20]; memset(occurrences, 0, sizeof(occurrences)); memset(query, 0, Q*20); for(idx = 0; idx < Q; idx++) { scanf("%s", query[idx]); } // for(idx = 0; idx < Q; idx++) // { // printf("%s\n", query[idx]); // } for(idx = 0; idx < Q; idx++) { int temp_idx = 0; for(; temp_idx < N; temp_idx++) { if(!strcmp(query[idx], str[temp_idx])) { ++occurrences[idx]; } } } for(idx = 0; idx < Q; idx++) printf("%d\n", occurrences[idx]); return 0; }
C
inline void InsertionSort(int *v, int size) { int j; int key; for (int i = 1; i < size; i++) { key = v[i]; j = i - 1; while (j >= 0 && v[j] > key) { v[j + 1] = v[j]; j = j - 1; } v[j + 1] = key; } } int y[5] = { 5, 4, 3, 2, 1 }; int main(int argc, char* argv[]) { InsertionSort(y, 5); return y[0]; }
C
#include <stdio.h> #include <stdlib.h> /** * main - print lowercase * then uppercase. * Return: the function returns 0 */ int main(void) { char alpha, u_alpha; alpha = 'a'; u_alpha = 'A'; while (alpha <= 'z') { putchar(alpha); alpha = alpha + 1; } while (u_alpha <= 'Z') { putchar(u_alpha); u_alpha = u_alpha + 1; } putchar('\n'); return (0); }
C
#include<stdio.h> #include<string.h> void printall(char *arr, int max){ int i; for(i=0;i<max;++i){ if(arr[i] == '\0'){ printf("\\0"); } printf("%c ", arr[i]); } printf("\n"); } void resetarray(char *arr, int max){ int i; for(i=0;i<max;++i){ arr[i] = '\0'; } } void spacelessprint(char *arr){ int i; for(i=0;i<strlen(arr);++i){ if(arr[i] == '\0') break; else if(arr[i] != ' '){ printf("%c", arr[i]); } } printf("\n"); } void recieveInput(char *arr){ printf("enter something: "); scanf("%99[^\n]", arr); printf("\n"); getchar(); } int main(){ int i,n; char arr[100]; printf("How many times would you like to do this: "); scanf("%d", &n); getchar(); while(n>10 || n<0){ printf("Out of bounds\nEnter again: "); scanf("%d", &n); } fflush(stdin); for(i=0; i<n; ++i){ recieveInput(arr); spacelessprint(arr); resetarray(arr, 100); } return 0; }
C
#include <stdio.h> #include <string.h> int IsSecure(char floor[]); int main() { char floor[50]; scanf("%s",floor); if(IsSecure(floor)) printf("quiet"); else printf("ALARM"); return 0; } //Check if there is at least one guard between the money and the thief int IsSecure(char floor[]) { int i, j, len, guards = 0; len = strlen(floor); for(i = 0; i < len; i++) { if(floor[i] == '$' || floor[i] == 'T') { for(j = i+1; j < len ; j++) { if(floor[j] == '$' || floor[j] == 'T') { i = len; break; } if(floor[j] == 'G') guards++; if(guards > 0) return 1; } } } return 0; }
C
#include <stdio.h> #define MAX_DIGITS 7 #define DIGITS 10 #define HEIGHT 4 #define WIDTH 4 #define SEG 7 const int segments[DIGITS][MAX_DIGITS] = { {1, 1, 1, 1, 1, 1, 0}, // 0 {0, 1, 1, 0, 0, 0, 0}, // 1 {1, 1, 0, 1, 1, 0, 1}, // 2 {1, 1, 1, 1, 0, 0, 1}, // 3 {0, 1, 1, 0, 0, 1, 1}, // 4 {1, 0, 1, 1, 0, 1, 1}, // 5 {1, 0, 1, 1, 1, 1, 1}, // 6 {1, 1, 1, 0, 0, 0, 0}, // 7 {1, 1, 1, 1, 1, 1, 1}, // 8 {1, 1, 1, 1, 0, 1, 1}, // 9 }; char digits[HEIGHT][WIDTH*MAX_DIGITS]; void clear_digits_array(void); void process_digit(int digit, int position); void print_digits_array(void); int main() { int num_digit; int digit; char digit_ch; clear_digits_array(); num_digit = 0; while (num_digit < MAX_DIGITS) { digit_ch = getchar(); if('0' <= digit_ch && digit_ch <= '9') { digit = digit_ch - '0'; process_digit(digit, num_digit); num_digit++; } } print_digits_array(); return 0; } void clear_digits_array(void) { for (int i = 0; i < HEIGHT; i++) for (int j = 0; j < WIDTH*MAX_DIGITS; j++) digits[i][j] = ' '; } void process_digit(int digit, int position) { int abs_position = WIDTH*position; for (int seg = 0; seg < SEG; seg++) if(segments[digit][seg] == 1) switch (seg) { case 0: digits[0][abs_position+1] = '_'; break; case 1: digits[1][abs_position+2] = '|'; break; case 2: digits[2][abs_position+2] = '|'; break; case 3: digits[2][abs_position+1] = '_'; break; case 4: digits[2][abs_position+0] = '|'; break; case 5: digits[1][abs_position+0] = '|'; break; case 6: digits[1][abs_position+1] = '_'; break; } } void print_digits_array(void) { for (int i = 0; i < HEIGHT; i++) { for (int j = 0; j < WIDTH*MAX_DIGITS; j++) printf("%c", digits[i][j]); printf("\n"); } }
C
#include "libft.h" static char *ft_cpyitoa(char *strint, unsigned long long int len, uintmax_t n2) { int i; i = 0; while (len >= 1) { strint[i++] = (n2 / len) + '0'; n2 = n2 % len; len = len / 10; } strint[i] = '\0'; return (strint); } char *ft_uitoa(uintmax_t n) { int i; uintmax_t n2; char *strint; unsigned long long int len; i = 0; n2 = n; len = 1; while (n2 / len >= 10 ) { i++; len = len * 10; } if (!(strint = (char *)malloc(sizeof(char) * i + 2))) return (NULL); strint = ft_cpyitoa(strint, len, n2); return (strint); }
C
/* Title-:WAP for the factorial of function using only main function. Author-:Shubhi omar Date-:25/09/2019 Description-:Input-: Read a no from user. Output-: ./factoral_main.out Enter num: 4 Factorial:24 */ #include<stdio.h> int main() { //declaring variable static int return_value, num, temp=1, flag=1; //for taking no. if (flag == 1) { printf("Enter num:"); scanf("%d",&num); flag=0; } //for input validation if (num < 0) { printf("ERROR!"); return 1; } else if (num == 0) { printf("Factorial=1\n"); return 1; } else { //for factorial of number (temp = temp * num--); } //for num greater then one if(num < 1) { printf("Factorial:%d\n",temp); return 0; } else { main(); } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> struct Stu { char name[20]; int age; }; void Swap(char*buf1, char*buf2,int width) { int i = 0; for (i = 0; i < width; i++) { char tmp = *buf1; *buf1 = *buf2; *buf2 = tmp; buf1++; buf2++; } } void bubble_sort(void*base, int sz, int width, int(*cmp)(const void*e1, const void*e2)) { int i = 0; //趟数 for (i = 0; i < sz-1; i++) { //每一趟比较的对数 int j = 0; for(j = 0; j < sz - 1 - i; j++) { //两个元素的比较 if (cmp((char*)base+j*width, (char*)base +(j+1)* width)>0) { //交换 Swap((char*)base + j*width, (char*)base + (j + 1)* width,width); } } } } int cmp_int(const void* e1, const void* e2) { //比较两个整形值的 return *(int*)e1 - *(int*)e2; } void test1() { int arr[10] = { 9, 8, 7, 6, 5, 4, 3, 2, 1, 0 }; int sz = sizeof(arr) / sizeof(arr[0]); bubble_sort(arr,sz,sizeof(arr[0]),cmp_int); } int cmp_stu_by_age(const void*e1, const void*e2) { //强制类型转换成结构体类型指针 return ((struct Stu*)e1)->age - ((struct Stu*)e2)->age; } int cmp_stu_by_name(const void*e1, const void*e2) { //比较名字就是比较字符串 //字符串比较不能直接用><=来比较,应该用strcmp比较 return strcmp(((struct Stu*)e1)->name, ((struct Stu*)e2)->name); } void test2() { struct Stu s[3] = { { "zhangsan", 20 }, { "lisi", 30 }, { "wangwu", 10 } }; int sz = sizeof(s) / sizeof(s[0]); bubble_sort(s,sz,sizeof(s[0]),cmp_stu_by_age); } int main() { test1(); test2(); system("pause"); return 0; }
C
/************************************************************************/ /* /* tst.c /* /* A test program for the client library interface. /* /* Author: Noah Mendelsohn /* IBM T.J. Watson Research and Mit Project Athena /* /* Revised: 8/21/87 /* /* $Source: /afs/dev.mit.edu/source/repository/athena/lib/gdb/samps/tst.c,v $ /* $Author: probe $ /* $Header: /afs/dev.mit.edu/source/repository/athena/lib/gdb/samps/tst.c,v 1.1 1993-10-12 03:24:51 probe Exp $ /* /* Copyright 1987 by the Massachusetts Institute of Technology. /* For copying and distribution information, see the file mit-copyright.h /* /************************************************************************/ #ifndef lint static char rcsid_tst_c[] = "$Header: /afs/dev.mit.edu/source/repository/athena/lib/gdb/samps/tst.c,v 1.1 1993-10-12 03:24:51 probe Exp $"; #endif #include "mit-copyright.h" #include <stdio.h> #include "gdb.h" char *field_names[] = {"desc", "code", "man", "cost", "count"}; FIELD_TYPE field_types[] = {STRING_T, /* desc */ INTEGER_T, /* code */ STRING_T, /* man */ REAL_T, /* cost */ INTEGER_T}; /* count */ FILE *coded_file; int main(argc, argv) int argc; char *argv[]; { /************************************************************ * DECLARATIONS * ************************************************************/ /* * Declare the names of fields to be retrieved and their types */ int field_count = 5; int i; /* * The following defines are for convenience in addressing * the fields. */ #define DESC 0 #define CODE 1 #define MAN 2 #define COST 3 #define COUNT 4 /* * Declare the relation and related data structures for * storing the retrieved data. */ TUPLE_DESCRIPTOR tuple_desc; RELATION retrieved_data, decoded_rel; /* * Declarations for misc. variables */ TUPLE t; /* next tuple to print */ int coded_len; char *coded_dat; int rc; /* A return code */ /************************************************************ * EXECUTION BEGINS HERE * ************************************************************/ /* * Build the descriptor describing the layout of the tuples * to be retrieved, and create an empty relation into which * the retrieval will be done. */ gdb_init(); /* initialize the global */ /* database facility */ printf("tst.c: attempting to create tuple descriptor\n"); tuple_desc = create_tuple_descriptor(field_count, field_names, field_types); printf("tst.c: tuple desc created.. attempting to create relation\n"); retrieved_data = create_relation(tuple_desc); printf("tst.c: relation created, formatting descriptor\n"); print_tuple_descriptor("Test Tuple Descriptor", tuple_desc); printf("tst.c: descriptor formatted, formatting relation\n"); print_relation("Test Relation", retrieved_data); printf("Creating tuples\n"); for (i=0; i<3; i++) { t = create_tuple(tuple_desc); initialize_tuple(t); fprintf(stderr, "Following tuple should contain null fields:\n\n"); print_tuple("A NULL TUPLE", t); *(int *)FIELD_FROM_TUPLE(t, CODE) = i+1; *(double *)FIELD_FROM_TUPLE(t, COST) = 12.34 * (i+1); string_alloc((STRING *)FIELD_FROM_TUPLE(t,MAN), 20); strcpy(STRING_DATA(*((STRING *)FIELD_FROM_TUPLE(t,MAN))), "Manager field data"); ADD_TUPLE_TO_RELATION(retrieved_data, t); } printf("tst.c: relation initialized, formatting relation\n"); print_relation("Test Relation", retrieved_data); /* * Try to encode the entire relation!! */ printf("Attempting to encode the relation\n"); coded_len = FCN_PROPERTY(RELATION_T, CODED_LENGTH_PROPERTY) (&retrieved_data, NULL); coded_dat = (char *)malloc(coded_len); FCN_PROPERTY(RELATION_T, ENCODE_PROPERTY) (&retrieved_data, NULL, coded_dat); printf("Relation encoding complete, writing file \n\n"); coded_file = fopen("coded.dat", "w"); fwrite(coded_dat, 1, coded_len, coded_file); fclose(coded_file); printf("File written\n"); printf("Decoding relation\n\n"); FCN_PROPERTY(RELATION_T, DECODE_PROPERTY) (&decoded_rel, NULL, coded_dat); printf("Relation decoded!! Printing it\n\n"); print_relation("Decoded Relation", decoded_rel); printf("tst.c: exit\n"); return 0; }
C
#include "shapes.h" #include <stdio.h> #define PAC_ANG (4 * M_PI/3) #define PAC_DELT 300 #define PAC_DTHETA ((2 * M_PI - PAC_ANG) / PAC_DELT) List *make_square(double side) { /* List *sq = list_init(4, free); list_add(sq, vmalloc((Vector){side/2, side/2})); list_add(sq, vmalloc((Vector){-side/2, side/2})); list_add(sq, vmalloc((Vector){-side/2, -side/2})); list_add(sq, vmalloc((Vector){side/2, -side/2})); return sq; */ return make_rectangle(side, side); } List *make_rectangle(double height, double length) { List *rec = list_init(4, free); list_add(rec, vmalloc((Vector){length/2, height/2})); list_add(rec, vmalloc((Vector){-length/2, height/2})); list_add(rec, vmalloc((Vector){-length/2, -height/2})); list_add(rec, vmalloc((Vector){length/2, -height/2})); return rec; } List *make_pacman(double radius){ List *pac = list_init(PAC_DELT+2, free); list_add(pac, vmalloc(VEC_ZERO)); Vector pac_point = (Vector){radius, 0}; pac_point = vec_rotate(pac_point, PAC_ANG/2); for(int i = 0; i <= PAC_DELT; i++){ list_add(pac, vmalloc(pac_point)); pac_point = vec_rotate(pac_point, PAC_DTHETA); } return pac; } List *make_ngon(int sides, double radius){ List *gon = list_init(sides, free); Vector point = (Vector){0, radius}; for(int i = 0; i < sides; i++){ list_add(gon, vmalloc(point)); point = vec_rotate(point, 2 * M_PI / sides); } return gon; } List *make_rounded_paddle(int sides, double radius, double angle){ List *gon = list_init(sides, free); Vector point = (Vector){0, radius}; point = vec_rotate(point, -1 * angle / 2); for (int i = 0; i < sides; i++){ list_add(gon, vmalloc(point)); point = vec_rotate(point, angle / sides); } return gon; } List *make_n_star(int points, double radius){ // smol and lomg are vectors to the dips and points of the star double theta = 2 * M_PI / (points * 2); Vector lomg = { .x = 0, .y = radius }; Vector smol = vec_multiply(.35, lomg); smol = vec_rotate(smol, theta); List *star = list_init(points * 2, free); for(int i = 0; i < points; i++){ list_add(star, vmalloc(lomg)); list_add(star, vmalloc(smol)); lomg = vec_rotate(lomg, 2 * theta); smol = vec_rotate(smol, 2 * theta); } return star; }
C
#include <stdio.h> #include "predictor.h" // Define global variables int hLen; int btbBits; int verbose; // Define data structures uint32_t ghr; typedef struct { uint8_t valid; uint8_t counter; } pht_t; pht_t *pht; typedef struct { uint8_t valid; uint64_t tag; // uint64_t target; } btb_t; btb_t *btb; uint32_t hMask; uint32_t btbAddressMask; uint64_t btbTagMask; // Function definitions void initialize() { // Global history register ghr = 0; // PHT size_t phtSize = 1 << hLen; pht = (pht_t*) malloc(sizeof(pht_t) * phtSize); for (size_t i = 0; i < phtSize; i++) { pht[i].valid = 0; #ifdef ALTERNATE if (i % 2) pht[i].counter = 2; else pht[i].counter = 1; #else pht[i].counter = INIT_2BC; #endif } // BTB if (btbBits != 0) { size_t btbSize = 1 << btbBits; btb = (btb_t*) malloc(sizeof(btb_t) * btbSize); for (size_t i = 0; i < btbSize; i++) { btb[i].valid = 0; btb[i].tag = 0; } } else btb = NULL; // Masks hMask = (1 << hLen) - 1; btbAddressMask = (1 << btbBits) - 1; btbTagMask = (1 << (sizeof(uint64_t) - btbBits)) - 1; } uint8_t predict(uint64_t pc) { uint32_t maskedHistory = ghr & hMask; uint32_t maskedPc = (pc >> 2) & hMask; uint32_t index = maskedHistory ^ maskedPc; uint64_t btbAddress = (pc >> 2) & btbAddressMask; uint64_t btbTag = (pc >> (btbBits + 2)) & btbTagMask; #ifdef USE_VALID if (pht[index].counter > 1 && pht[index].valid) #else if (pht[index].counter > 1) #endif { if (btb == NULL) return TAKEN; else { if (btb[btbAddress].valid && btb[btbAddress].tag == btbTag) return TAKEN; else return NOT_TAKEN; } } else { return NOT_TAKEN; } } void update(uint64_t pc, uint8_t outcome) { uint32_t maskedHistory = ghr & hMask; uint32_t maskedPc = (pc >> 2) & hMask; uint32_t index = maskedHistory ^ maskedPc; uint64_t btbAddress = (pc >> 2) & btbAddressMask; uint64_t btbTag = (pc >> (btbBits + 2)) & btbTagMask; pht[index].valid = 1; if (outcome == TAKEN) { // Shift ghr ghr = (ghr << 1) | 1; ghr &= hMask; // Update PHT if (pht[index].counter < 3) { pht[index].counter++; } } else { // Shift ghr ghr = ghr << 1; ghr &= hMask; // Update PHT if (pht[index].counter > 0) { pht[index].counter--; } } if (btb != NULL) { btb[btbAddress].valid = 1; btb[btbAddress].tag = btbTag; } }
C
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * This is part of the DOWSER program * * DOWSER finds buried water molecules in proteins. * cf. Zhang & Hermans, Proteins: Structure, Function and Genetics 24: 433-438, 1996 * * DOWSER was developed by the Computational Structural Biology Group at the * University of North Carolina, Chapel Hill by Li Zhang, Xinfu Xia,Jan Hermans, * and Dave Cavanaugh. Revised 1998. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * chooser.c * Choose a set of low energy non-overlaping O out of an overlaping set * sparser.c * Reduce the number of waters so that the oxygens of two waters are never closer * than 2.3 Angstroms. * * Input: * argv[1] - pdb file of water molecules (tempFactor=energy) * argv[3] - selection criteria (distance, energy, or both (default)) * Output: * argv[2] - pdb file containing remaining waters * Returns: * number of waters remaining * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "dowser.h" #define ALIVE 1 #define DEAD -1 #define MAX_ENERGY -10.0 #define overlap 4.0 #define connect 2.3 #define contact connect*connect extern void readPDB10 (char *, int *, PDB **); extern void WritePDB (); void chooser(); void sparser(); void SortByEnergy(); int main(int argc, char *argv[]) { PDB *sparse, *wat, *dense; FILE *fp; char criteria[10]; int nWatAtom; int nAtoms_sparse; int nAtoms_dense; int i,j; if (argc < 3 || argc > 4) { fprintf(stderr,"USAGE: chooser input.pdb output.pdb selection_criteria (optional)\n"); exit(0); } if (argc == 3) { strcpy(criteria,"both"); } else { strcpy(criteria,argv[3]); } if (!strncmp(criteria,"dist",4) && !strncmp(criteria,"ener",4) && !strncmp(criteria,"both",4)) { fprintf(stderr,"Incorrect selection criteria - use default (both)\n"); strcpy(criteria,"both"); } readPDB10 (argv[1], &nWatAtom, &wat); sparse = (PDB *) malloc (nWatAtom * sizeof(PDB)); /* Sort the waters by ascending energy */ SortByEnergy(nWatAtom,wat); /* Use input criteria (or default) to "choose" waters */ switch (criteria[0]) { case ('d'): /* retain only non-overlapping set */ sparser(nWatAtom,wat,&nAtoms_sparse,sparse); break; case ('e'): /* retain only low energy set */ chooser(nWatAtom,wat,&nAtoms_sparse,sparse); break; default: /* retain both low energy and non-overlapping set */ dense = (PDB *) malloc (nWatAtom * sizeof(PDB)); chooser(nWatAtom,wat,&nAtoms_dense,dense); sparser(nAtoms_dense,dense,&nAtoms_sparse,sparse); break; } /* Sequentially order the Treasure waters */ j = 0; for (i=0;i<nAtoms_sparse;i++) { if (i%3 == 0) j++; sparse[i].serial = i+1; /* atom # */ sparse[i].resSeq = j; /* residue # */ strcpy(sparse[i].chainID,"W"); /* chain ID */ } fp = fopen(argv[2],"w"); if (!fp) { fprintf(stderr,"*** Unable to open file %s for writing - use stdout instead!\n",argv[2]); fp = stdout; } WritePDB (fp, nAtoms_sparse, sparse); return (nAtoms_sparse/3); } /* end main() */ /********************************************************************************* * void SortByEnergy() - Sequentially sort all waters by ascending energy *********************************************************************************/ void SortByEnergy(nWatAtom,water) int nWatAtom; /* number of input atoms */ PDB *water; /* input waters */ { PDB *temp; /* temporary storage of water */ REAL low_ener; /* lowest energy */ REAL next_ener; int *index; /* the ascending energy order */ int AllH; /* logical for whether waters have hydrogens */ int nWat; /* number of input waters */ int factor; int i,j,k,count; if ((water[0].resSeq==water[1].resSeq) && (water[0].resSeq==water[2].resSeq)) { AllH = TRUE; nWat = nWatAtom/3; } else { AllH = FALSE; nWat = nWatAtom; } temp = (PDB *) malloc (nWatAtom*sizeof(PDB)); index = (int *) malloc (nWat*sizeof(PDB)); for (i=0; i<nWat; i++) { index[i] = i; for (j=0; j<3; j++) temp[3*i+j] = water[3*i+j]; } if (AllH) factor = 3; else factor = 1; for (i=0; i<nWat; i++) { low_ener = temp[factor*index[i]].tempFactor; for (j=i+1;j<nWat;j++) { next_ener = temp[factor*index[j]].tempFactor; if (next_ener < low_ener) { low_ener = next_ener; k = index[i]; index[i] = index[j]; index[j] = k; } } } for (i=0;i<nWat;i++) { count = index[i]; for (j=0;j<3;j++) water[3*i+j] = temp[3*count+j]; } free (temp); return; } /********************************************************************************* * chooser() - retain waters with energies below -10 kcal/mol *********************************************************************************/ void chooser(nWatAtom,wat,nAtoms_dense,dense) int nWatAtom; /* number of input atoms */ PDB *wat; /* input waters */ int *nAtoms_dense; /* number of remaining waters */ PDB *dense; /* remaining waters */ { int nWat; /* number of input waters */ int AllH; /* logical for whether waters have hydrogens */ int i,j,k; if ((wat[0].resSeq==wat[1].resSeq) && (wat[0].resSeq==wat[2].resSeq)) { AllH = TRUE; nWat = nWatAtom/3; } else { AllH = FALSE; nWat = nWatAtom; } *(nAtoms_dense)=0; for (i=0; i<nWat; i++) { if (AllH) { if (wat[3*i].tempFactor < MAX_ENERGY) { dense[(*nAtoms_dense)++] = wat[3*i+0]; dense[(*nAtoms_dense)++] = wat[3*i+1]; dense[(*nAtoms_dense)++] = wat[3*i+2]; } } else { if (wat[i].tempFactor < MAX_ENERGY) dense[(*nAtoms_dense)++] = wat[3*i]; } } return; } /* end chooser() */ /********************************************************************************* * sparser() - Retain a non-overlapping set of waters, preserve low energy waters *********************************************************************************/ void sparser(nAtoms_dense,dense,nAtoms_sparse,sparse) int nAtoms_dense; /* number of input waters */ PDB *dense; /* input waters */ int *nAtoms_sparse; /* number of remaining waters */ PDB *sparse; /* remaining waters */ { int jat,iat,i,j,k; int near; /* water is too close (or not) */ REAL aa, bb, cc; /* distances */ PDB *anatom; /* PDB pointer */ if (nAtoms_dense == 0) { fprintf (stderr,"* No water molecules in the input of 'sparser'\n"); exit (0); } /* The first water is always assumed to be in the non-conflicting set */ for (i=0;i<3;i++) sparse[i] = dense[i]; *nAtoms_sparse = 1; for (jat=3; jat<nAtoms_dense; jat+=3) { near = FALSE; for (iat=0; iat<3* (*nAtoms_sparse); iat+=3) { anatom = sparse + iat; aa = dense[jat].XX - anatom->XX; bb = dense[jat].YY - anatom->YY; cc = dense[jat].ZZ - anatom->ZZ; if ((aa*aa + bb*bb + cc*cc) < contact) { near = TRUE; break; } } if (near) continue; /*then jat conflict with existing non-conflicting set*/ /* Read the oxygen and two hydrogens into sparse */ for (i=0;i<3;i++) { j=jat+i; k=3* *nAtoms_sparse+i; sparse[k] = dense[j]; } (*nAtoms_sparse)++; } (*nAtoms_sparse) *= 3; return; } /* end sparser */
C
/* * log.c * ----- * * A simple logger. It supports three log levels * (INFO, WARN, ERROR), more can be added easily. * Log files are rotated. */ #include <assert.h> #include <limits.h> #include <stdarg.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <time.h> #include <unistd.h> #include <sys/stat.h> #include "log.h" #include "main.h" #include "misc.h" #include "quit.h" // -------- static FILE *logfile; // -------- /********************************************************************* * * * Support Functions * * * *********************************************************************/ /* * Converts a logtype to a human readable * string. * * type: Logtype to convert * str: String to which the return value is copied * len: Length of the return string */ static boolean log_typetostr(logtype type, char *str, size_t len) { boolean ret; ret = TRUE; switch (type) { case LOG_INFO: misc_strlcpy(str, "INFO", len); break; case LOG_WARN: misc_strlcpy(str, "WARN", len); break; case LOG_ERROR: misc_strlcpy(str, "ERROR", len); break; default: misc_strlcpy(str, "UNKNOWN", len); ret = FALSE; break; } return ret; } // -------- /********************************************************************* * * * Public Interface * * * *********************************************************************/ void log_insert(logtype type, const char *func, int32_t line, const char *fmt, ...) { char *inpmsg; char *logmsg; char msgtime[32]; char status[32]; int msglen; struct tm *t; time_t tmp; va_list args; // 256 is enough room for the prepended stuff va_start(args, fmt); msglen = vsnprintf(NULL, 0, fmt, args) + 256; va_end(args); if ((inpmsg = malloc(msglen)) == NULL) { perror("Couldn't allocate memory"); } if ((logmsg = malloc(msglen)) == NULL) { quit_error(POUTOFMEM); } // Format the message va_start(args, fmt); vsnprintf(inpmsg, msglen, fmt, args); va_end(args); // Time tmp = time(NULL); if ((t = localtime(&tmp)) == NULL) { quit_error(PLOCALTIME); } strftime(msgtime, sizeof(msgtime), "%m-%d-%Y %H:%M:%S", t); // Status if (!log_typetostr(type, status, sizeof(status)) != 0) { quit_error(PUNKNOWNLOGTYPE); } // Prepend informational stuff #ifdef NDEBUG snprintf(logmsg, msglen, "%s [%s]: %s\n", msgtime, status, inpmsg); #else snprintf(logmsg, msglen, "%s [%s] (%s:%i): %s\n", msgtime, status, func, line, inpmsg); #endif // Write it if ((fwrite(logmsg, strlen(logmsg), 1, logfile)) != 1) { quit_error(PCOULDNTWRITELOGMSG); } fflush(logfile); #ifndef NDEBUG if (type == LOG_ERROR) { fprintf(stderr, "%s", logmsg); } #endif free(inpmsg); free(logmsg); } void log_init(const char *path, const char *name, int16_t seg) { char newfile[PATH_MAX]; char oldfile[PATH_MAX]; int16_t i; struct stat sb; assert(!logfile); assert(seg < 99); // Create directory if ((stat(path, &sb)) == 0) { if (!S_ISDIR(sb.st_mode)) { quit_error(PNOTADIR); } } else { misc_rmkdir(path); } // Rotate logs for (i = seg; i >= 0; i--) { snprintf(newfile, sizeof(newfile), "%s/%s.%02i", path, name, i + 1); snprintf(oldfile, sizeof(oldfile), "%s/%s.%02i", path, name, i); // Doesn't exists if ((stat(oldfile, &sb)) != 0) { continue; } // Delete the oldest file if (i == seg) { unlink(oldfile); continue; } if ((rename(oldfile, newfile)) != 0) { quit_error(PCOULDNTROTATELOGS); } } snprintf(newfile, sizeof(newfile), "%s/%s.00", path, name); snprintf(oldfile, sizeof(oldfile), "%s/%s", path, name); // Special case: First log file if ((stat(oldfile, &sb)) == 0) { if ((rename(oldfile, newfile)) != 0) { quit_error(PCOULDNTROTATELOGS); } } if ((logfile = fopen(oldfile, "w")) == NULL) { quit_error(PCOULDNTOPENFILE); } } void log_close(void) { if (logfile) { fflush(logfile); if ((fclose(logfile)) != 0) { quit_error(PCOULDNTCLOSEFILE); } logfile = NULL; } }
C
#include "comm.h" char *message; static char msg_buff[BUFF_MAX]; struct ic_request req; static struct ic_reply *rep; struct ic_reply IC_OK_REPLY[IC_CMD_MAX * 2]; struct ic_reply IC_ERROR_REPLY[IC_CMD_MAX + 2]; /* * define the interactive message, * if you need to add new modules and components, * then you need to add the corresponding messages here * */ static char *IC_OK_MSG[IC_CMD_MAX * 2] = { /* for control message transfer */ "200 OK: Connection Established\n", "200 OK: Closing Connection\n", "200 OK: Valid LPM Rule Filename Controle Message\n", "200 OK: Valid LPM Rule DATA Transfer Control Message\n", /* for data transfer */ "200 OK: Connection Established (Never Used!!!)\n", "200 OK: Closing Connection (Never Used!!!)\n", "200 OK: Valid LPM Rule Filename\n", "200 OK: Valid LPM Rule DATA\n", }; static char *IC_ERROR_MSG[IC_CMD_MAX + 2] = { "404 ERROR: Invalid Connection Setup Message\n", "404 ERROR: Invalid Connection Termination Message\n", "404 ERROR: Invalid LPM Rule Filename Message\n", "404 ERROR: Invalid LPM Rule DATA Transfer Message\n", "405 ERROR: Not Defined Command\n", //IC_CMD_MAX "406 ERROR: Cannot Receive Message\n", //IC_CMD_MAX + 1 }; int common_init() { int i = 0; for (i = 0; i < IC_CMD_MAX * 2; i++) { IC_OK_REPLY[i].status = IC_OK; IC_OK_REPLY[i].length = strlen(IC_OK_MSG[i]); IC_OK_REPLY[i].info = IC_OK_MSG[i]; } for (i = 0; i < IC_CMD_MAX + 2; i++) { IC_ERROR_REPLY[i].status = IC_ERROR; IC_ERROR_REPLY[i].length = strlen(IC_ERROR_MSG[i]); IC_ERROR_REPLY[i].info = IC_ERROR_MSG[i]; } /* init the data structures */ memset(msg_buff, 0, sizeof(msg_buff)); message = (char *)calloc((BUFF_MAX + PAYLOAD_MAX), sizeof(char)); memset(&req, 0, sizeof(struct ic_request)); req.data = (char *)calloc((BUFF_MAX + PAYLOAD_MAX), sizeof(char)); if (!message || !req.data) { printf("ERROR: allocate memory for message buffer!\n"); return -1; } return 0; } int common_cleanup() { if (message) free(message); if (req.data) free(req.data); return 0; } static int rcv_process(int sockfd, int recv_size) { if (recv_size < 0) { perror("Receive Error: "); #if 0 memset(msg_buff, 0, sizeof(msg_buff)); sprintf(msg_buff, "%u %u %s", IC_ERROR_REPLY[cmd].status, IC_ERROR_REPLY[cmd].length, IC_ERROR_REPLY[cmd].info); if (send(sockfd, msg_buff, BUFF_MAX, 0) < 0) { #endif if (send(sockfd, IC_ERROR_REPLY[IC_CMD_MAX + 1].info, IC_ERROR_REPLY[IC_CMD_MAX + 1].length, 0) < 0) { perror("Send Error: "); } return RCV_ERROR; } else if (recv_size == 0) { printf("Client disconnected!\n"); return RCV_DISCON; } return RCV_SUCC; } /* * @expected_cmd: -1 means any command is ok * */ int receive_ctrl_msg(int sockfd, int expected_cmd) { int ret = -1; int recv_size = -1; req.cmd_id = 0; req.length = 0; memset(req.data, 0, sizeof(char) * (BUFF_MAX + PAYLOAD_MAX)); memset(msg_buff, 0, sizeof(msg_buff)); memset(message, 0, sizeof(char) * (BUFF_MAX + PAYLOAD_MAX)); printf("recive control %d informatoin!\n", expected_cmd); /* receive the control information: * i.e., the command id and the length of the data part * */ while ((recv_size = recv(sockfd, msg_buff, BUFF_MAX, 0)) > 0 && msg_buff[recv_size - 1] != '\n') { strncat(message, msg_buff, recv_size); memset(msg_buff, 0, sizeof(msg_buff)); } printf("Receive control information of size %d\n", recv_size); ret = rcv_process(sockfd, recv_size); if (ret != RCV_SUCC) return -1; strncat(message, msg_buff, recv_size); int j = 0; for (j = 0; j < recv_size; j++) printf("%c", msg_buff[j]); printf("\n"); ret = sscanf(message, "%u %u\n", &req.cmd_id, &req.length); printf("Receive message: cmd = %u; data length = %u\n", req.cmd_id, req.length); if (ret != 2 || req.cmd_id >= IC_CMD_MAX || (expected_cmd != -1 && req.cmd_id != expected_cmd) || req.length >= PAYLOAD_MAX) { int error_id = IC_CMD_MAX + 1; if (req.cmd_id <= IC_CMD_MAX) error_id = req.cmd_id; if (expected_cmd != -1) error_id = expected_cmd; if (send(sockfd, IC_ERROR_REPLY[error_id].info, IC_ERROR_REPLY[error_id].length, 0) < 0) { perror("Send: "); } return -1; } /* valid control information, reply OK to the client */ if (send(sockfd, IC_OK_REPLY[req.cmd_id].info, IC_OK_REPLY[req.cmd_id].length, 0) < 0) { perror("Send: "); return -1; } if (req.cmd_id == IC_CONN_TERM_CMD) { printf("Client is asking for terminating the connection!\n"); } return 0; } int receive_data_msg(int sockfd, int data_len) { /* receive the data with specific length */ int ret = -1; int recv_size = -1; int file_size = data_len; printf("Receiving %d bytes of data!\n", file_size); if (file_size == 0) return 0; memset(msg_buff, 0, sizeof(msg_buff)); memset(message, 0, sizeof(char) * (BUFF_MAX + PAYLOAD_MAX)); while (file_size > 0 && (recv_size = recv(sockfd, msg_buff, BUFF_MAX, 0)) > 0) { strncat(message, msg_buff, recv_size); memset(msg_buff, 0, sizeof(msg_buff)); file_size -= recv_size; } printf("recv_size = %d; file_size = %d; file content = %s\n", recv_size, file_size, message); ret = rcv_process(sockfd, recv_size); if (ret != RCV_SUCC) return -1; if (file_size != 0) return -1; printf("receive_data_msg send message = %s\n", IC_OK_REPLY[req.cmd_id + IC_CMD_MAX].info); if (send(sockfd, IC_OK_REPLY[req.cmd_id + IC_CMD_MAX].info, IC_OK_REPLY[req.cmd_id + IC_CMD_MAX].length, 0) < 0) { perror("Send: "); return -1; } return 0; }
C
Status ex29(SqList *A,SqList *B,SqList *C){ void PrintElem(ElemType e); ElemType *pa,*pb,*pb_last,*pc,*pc_last; ElemType e; SqList temp; int i; i=0; pb=B->elem;pc=C->elem;pa=A->elem; pb_last=B->elem+B->length-1; pc_last=C->elem+C->length-1; InitList_Sq(&temp); while(pb<=pb_last&&pc<=pc_last){ if(*pb==*pc){ ListInsert_Sq(&temp,i,*pb); i++;pb++;pc++; } else if(*pb<*pc) pb++; else pc++; }//将相同元素存入线性表temp中 //printf("temp:\n");ListTraverse_Sq(temp,PrintElem); pb=temp.elem;pb_last=temp.elem+temp.length-1; while(pa<=A->elem+A->length-1&&pb<=pb_last){//注意:此处由于顺序列删除元素自动向前移一位,限制条件需要不断更新 if(*pa==*pb){ ListDelete_Sq(A,pa+1-(A->elem),&e); }//考虑到A中会有重复元素的删除法,且删除后元素自动向前移,故指针不需动 else if(*pa>*pb) pb++; else pa++; } return OK; }
C
#include <stdio.h> void printMatrix(int a[][5],int headRow,int headCol,int endRow,int endCol){ int i,j; j=headCol; while(j <= endCol){ printf("%d ",a[headRow][j]); j++; } i = headRow+1; while(i <= endRow){ printf("%d ",a[i][endCol]); i++; } j = endCol -1; while(j >= headCol){ printf("%d ",a[endRow][j]); j--; } i = endRow -1; while(i > headRow){ printf("%d ",a[i][headCol]); i--; } } void print(int a[][5]){ int headRow = 0,headCol = 0; int endRow = 4,endCol = 4; while(headRow <= endRow || headCol <= endCol){ printMatrix(a,headRow,headCol,endRow,endCol); printf("\n"); headRow++; headCol++; endRow--; endCol--; } } int main(){ int a[5][5]={{1,2,3,4,5},{6,7,8,9,10},{11,12,13,14,15},{16,17,18,19,20},{21,22,23,24,25}}; // printMatrix(a,0,0,3,3); print(a); return 0; }
C
#include <string.h> #include <stdio.h> #include <sys/types.h> #include <errno.h> #include <glob.h> #include <fcntl.h> #include <stdlib.h> #include <unistd.h> #include "eval.h" #include "parse.h" #include "builtins.h" #include "globbing.h" #include "environ.h" #include "redirect.h" #include "aliases.h" #include "options.h" void eval(char *command) { //strip_comments(command); strip_leading_ws(command); if (!strlen(command)) { return; // Blank command does nothing } // Substitute in aliases and expand variables if (get_setting("aliases?")) { expand_aliases(command); } // Splits command into array of tokens int spaces = count_spaces(command); char **tokens = calloc((spaces + 1), sizeof *tokens); int num_tokens = split_line(command, tokens); // Builtins int is_builtin = parse_builtins(tokens, &num_tokens); // Parse other builtins if (is_builtin) { while (num_tokens > 0) { free(tokens[num_tokens - 1]); num_tokens--; } return; } printf("nt: %d\n", num_tokens); num_tokens = check_background(tokens, num_tokens); printf("nt: %d\n", num_tokens); // Fork and run foreground processes pid_t pid; int ret; // Child process here if ((pid = fork()) == 0) { // fork again for a background process if (get_setting("background?")) { pid_t pid2; if ((pid2 = fork()) < 0) { error("fork", "second fork failed"); } else if (pid2 > 0) { exit(0); } fprintf(stdout, "[%d] %s\n", getpid(), command); } launch(tokens, num_tokens); } // Parent process here else if (pid > 0) { if (waitpid(pid, &ret, 0) != pid) { error("wait", "invalid pid returned"); } int exit_status = WEXITSTATUS(ret); fprintf(stderr, "process exited with status = %d, return = %d\n", exit_status, ret); } else { error("fork", "first fork failed"); exit(1); } while (num_tokens > 0) { free(tokens[num_tokens - 1]); num_tokens--; } } void launch(char **tokens, int num_tokens) { // Parse any stdin/stdout redirects char *in = "<"; char *out = ">"; char *app = ">>"; int in_fd = redirect(parse_redirect(tokens, &num_tokens, in), in); int app_fd = redirect(parse_redirect(tokens, &num_tokens, app), app); int out_fd = redirect(parse_redirect(tokens, &num_tokens, out), out); swap_fd(in_fd, app_fd, out_fd); // close all file descriptors for background process if (get_setting("background?")) { if (in_fd == -1) close(STDIN_FILENO); if (app_fd == -1 && out_fd == -1) close(STDOUT_FILENO); close(STDERR_FILENO); } // if globbing is enabled and necessary if (get_setting("glob?") && check_glob(tokens, num_tokens)) { glob_t globbuf = setup_glob(tokens, num_tokens); execvp(tokens[0], &globbuf.gl_pathv[0]); // Otherwise just run the command } else { tokens[num_tokens] = (char *) 0; execvp(tokens[0], tokens); } // exec exits itself, so if we got here then we failed _exit(EXIT_FAILURE); } int check_background(char **tokens, int num_tokens) { if (!strcmp(tokens[num_tokens - 1], "&")) { // take away the '&' token free(tokens[num_tokens - 1]); set_setting("background?", 1); return (num_tokens - 1); } else set_setting("background?", 0); return num_tokens; }
C
#include "../includes/motion.h" /* -------------------------------- VARIABLES ------------------------------- */ float curAngle = 0.0f; // Current Angle float curVeloc = 1.0f; // Current Velocity float rotAccel = 0.2f; // Rotation Acceleration float velLimit = 3.0f; // Velocity Limit float prevVeloc = 1.0f; // Previous velocity (store state when paused) GLfloat positionX = 0; GLfloat positionY = 0; char stopped = '0'; float getCurAngle() { return curAngle; } /* -------------------------------- VARIABLES ------------------------------- */ /* -------------------------------- ANIMATIONS ------------------------------ */ void checkMaxVelocity() { // Keep velocity within treshold if (curVeloc > velLimit) curVeloc = velLimit; else if (curVeloc < -velLimit) curVeloc = -velLimit; } void animator() { // Keep velocity within treshold checkMaxVelocity(); // Increase rotation if (stopped == '0') curAngle = curAngle + curVeloc; // Avoid overflow if (curAngle > 360) { curAngle = 0; } else if (curAngle < 0) { curAngle = 360; } } /* -------------------------------- ANIMATIONS ------------------------------ */ /* --------------------------------- MOTIONS -------------------------------- */ void increaseSpeed() { if (stopped == '0') { curVeloc = curVeloc + rotAccel; checkMaxVelocity(); curAngle = curAngle + curVeloc; } if (curAngle > 360) { curAngle = 0; } else if (curAngle < 0) { curAngle = 360; } IF_DEBUG printf(">[ANIM]: Angle: %.2f, Velocity: %.2f\n", curAngle, curVeloc); } void decreaseSpeed() { if (stopped == '0') { curVeloc = curVeloc - rotAccel; checkMaxVelocity(); curAngle = curAngle + curVeloc; } if (curAngle > 360) { curAngle = 0; } else if (curAngle < 0) { curAngle = 360; } IF_DEBUG printf(">[ANIM]: Angle: %.2f, Velocity: %.2f\n", curAngle, curVeloc); } void stop() { stopped = '1'; prevVeloc = curVeloc; } void resume() { stopped = '0'; curVeloc = prevVeloc; } /* --------------------------------- MOTIONS -------------------------------- */
C
/* * c practical data structure */ #ifndef _CDS_H #define _CDS_H #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #ifdef __cplusplus extern "C" { #endif /* base type */ #ifndef __cplusplus typedef enum{false, true} bool; #endif #ifndef uint #define uint unsigned #endif #ifndef nil #define nil NULL #endif /* base function */ #ifndef NOMINMAX #ifndef max #define max(a,b) ((a)>(b)?(a):(b)) #endif #ifndef min #define min(a,b) ((a)<(b)?(a):(b)) #endif #endif /* memory & string */ void* salloc (size_t size); #define sfree(p) if(p)free(p) /* safe free */ #define mclean(p,size) memset(p,0,size) void* mdump(void *data, size_t n); /* memory dump, malloc and memcpy */ char* sdumpn (const char* s, size_t len); char* sdump(const char *s); /* string dump */ char* fdump (const char* filename); /* load file to string */ char* trimn (const char* text, size_t len); char* trim (const char* text); /* string encode */ wchar_t* utf2unicode (char* utf8); /* hash-table */ typedef struct { void* list; size_t size; uint(*hashfunc)(void*k); bool(*cmpfunc)(void*k1,void*k2); void*(*kdumpfunc)(void*k); void(*kfreefunc)(void*k); } hst; hst* hscreat (const char* keytype, size_t size); void* hsputv (hst* t, void* k, void* v); void* hsgetv (hst* t, void* k); void* hsdelv (hst* t, void* k); void hsclose (hst* t, void(*vfreefunc)(void*)); #define hsput(t,k,v) hsputv(t,(void*)k, (void*)v) #define hsget(t,k) hsgetv(t,(void*)k) #define hsdel(t,k) hsdelv(t,(void*)k) /* variable-length string * * 在vscat之前要先保证长度正确, 用vsrelen. */ typedef char vchar; void vsinit (size_t tablesize); /* optional */ void vsclose (); /* optional */ vchar* vsdump (const char* s); /* create or copy a new vstring */ void vsfree (vchar* vs); vchar* vsresize (vchar* vs, size_t size); /* resize, realloc */ void vsrelen (vchar* vs); vchar* vsncpy (vchar* a, const char*b, size_t len); #define vscpy(a,b) vsncpy(a,b,strlen(b)) vchar* vsncat (vchar* a, const char* b, size_t n); #define vscat(a,b) vsncat(a,b,strlen(b)) vchar* vs_vsprintf (vchar* vs, const char* format, __VALIST p); vchar* vs_sprintf (vchar* vs, const char* format, ...); /* sprintf to a vstring */ vchar* vs_printf (const char* format, ...); /* create a new vstring */ bool isvs (const char* s); size_t vssize (vchar* vs); /* get mem size */ int vslen (vchar* vs); /* global list 广义表 */ typedef struct glnode { struct glnode *prev, *next; struct glnode *child, *dad; void* data; size_t cn; /* child count */ } glnode; glnode* glnewv (void* data); #define glnew(data) glnewv((void*)data) void glout (glnode* node); void* gldel (glnode* node, void(*datafreefunc)(void*)); glnode* glget (glnode* dad, int nth); /* get nth child */ size_t glchildn (glnode* dad); void gljoin (glnode* dad, glnode* node, int nth); #define glforeach(dad,p) for(p=dad->child;p;p=p->next) #ifdef __cplusplus } #endif #endif
C
#include<stdio.h> main() { float number; printf("Enter a number:"); scanf("%f",&number); if(number<0){ printf("%.2f number is negative",number); }else if(number>0){ printf("%.2f number is positive",number); }else{ printf("%.2f number is Zero",number); } }
C
#include<stdio.h> int mark[100009]; int ara[100009]; int main() { int n,i,j,a,b; scanf("%d %d",&a,&b); mark[0]=1; mark[1]=1; mark[2]=0; for(i=4;i<=b;i+=2) mark[i]=1; int root=sqrt(b); for(i=3;i<=root;i++) { if(mark[i]==0) { for(j=2;i*j<=b;j++) mark[i*j]=1; } } j=0; for(i=0;i<=root;i++) { if(mark[i]==0) {ara[j]=i; j++; } } // for(i=0;i<j;i++) printf("%d\n",ara[i]); for(i=0;i<j;i++) { int div=a/ara[i]; for(i=div;i*ara[i]<=b;i++) mark[i*ara[i]]=1; } for(i=a;i<=b;i++) { if(mark[i]==0) printf("%d\n",i); } return 0; }
C
/* +------------------------------------------------------------------------+ | Mobile Robot Programming Toolkit (MRPT) | | http://www.mrpt.org/ | | | | Copyright (c) 2005-2017, Individual contributors, see AUTHORS file | | See: http://www.mrpt.org/Authors - All rights reserved. | | Released under BSD License. See details in http://www.mrpt.org/License | +------------------------------------------------------------------------+ */ #ifndef XSUTCTIME_H #define XSUTCTIME_H #include "pstdint.h" /*! \brief A structure for storing UTC Time values. */ struct XsUtcTime { /** \brief Nanosecond part of the time */ uint32_t m_nano; /** \brief The year (if date is valid) */ uint16_t m_year; /** \brief The month (if date is valid) */ uint8_t m_month; /** \brief The day of the month (if date is valid) */ uint8_t m_day; /** \brief The hour (if time is valid) */ uint8_t m_hour; /** \brief The minute (if time is valid) */ uint8_t m_minute; /** \brief The second (if time is valid) */ uint8_t m_second; /** \brief Validity indicator \details When set to 1, the time is valid, * when set to 2, the time part is valid, but the date may not be valid. * when set to 0, the time is invalid and should be ignored. */ uint8_t m_valid; }; typedef struct XsUtcTime XsUtcTime; #endif // file guard
C
/* ** get_next_line.c for vatout_a in /home/vatout_a/rendu/CPE/CPE_2015_Allum1 ** ** Made by Vatoutine ** Login <[email protected]> ** ** Started on Fri Feb 26 17:29:32 2016 Vatoutine ** Last update Sat Feb 27 20:24:58 2016 Vatoutine Artem */ #include "get_next_line.h" #include "my.h" char *my_fill_buffer(char *buff) { int x; int y; x = 0; y = 0; while ((buff[x] != '\n')) x++; x++; while (buff[x] != '\0') { buff[y] = buff[x]; x++; y++; } buff[y] = '\0'; return (buff); } int nbr_len(char *str, int a) { int i; int j; i = 0; j = 0; if (a == 1) { while (str[i] != '\0') i++; return (i); } if (a == 2) { while (str[i] != '\0') { if (str[i] == '\n') j++; i++; } return (j); } return (-1); } char *my_realloc(char *buff, char *stock, int size) { char *tmp; int i; int j; j = i = 0; if ((tmp = malloc(size + 1)) == NULL) return (NULL); while (i <= size) tmp[i++] = 0; i = 0; if (stock != NULL) { while (stock[i] != 0) { tmp[i] = stock[i]; i++; } free(stock); } i = j = 0; while (tmp[i] != 0) i++; while ((buff[j] != 0) && (buff[j] != '\n')) tmp[i++] = buff[j++]; return (tmp); } char *my_switch_buffer(char *buffer, char *stack) { if (nbr_len(buffer, 2) <= 0) return (NULL); buffer = my_fill_buffer(buffer); if ((stack = my_realloc(buffer, stack, READ_SIZE)) == NULL) return (NULL); if (nbr_len(buffer, 2) < 0) return (stack); return (stack); } char *get_next_line(const int fd) { static char buffer[READ_SIZE + 1]; char *stack; int inc; int ret; stack = NULL; ret = inc = 0; stack = my_switch_buffer(buffer, stack); if (nbr_len(buffer, 2) > 0) return (stack); while ((inc = read(fd, buffer, READ_SIZE)) > 0) { buffer[inc] = '\0'; ret = ret + inc + READ_SIZE; stack = my_realloc(buffer, stack, ret); if (nbr_len(buffer, 2) > 0) return (stack); } if (inc == 0) return (NULL); if (buffer[0] != 0) return (stack); free(stack); return (NULL); }
C
#pragma once /* * @author Branium Academy */ typedef struct { int id; // mã công việc char name[40]; // tên công việc char description[40]; // mô tả công việc int mandatory; // số giờ làm việc bắt buộc } Work; // hàm tạo mới thông tin công việc void createWorkInfo(Work* w); // hàm hiển thị thông tin công việc void showWorksInfo(const Work* works, size_t n); // hàm tìm công việc theo mã int findWorkById(const Work* works, size_t n, int id); // hàm đọc file công việc void readFileWork(Work* works, size_t* n); // hàm ghi file công việc void writeFileWork(const Work* works, size_t n);
C
/* Singly-linked list that supports the following operations: createList deleteList findElem deleteElem insertInFront insertAfter */ #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include "linked_list.h" bool createList(ListElement **head) { *head = NULL; return true; } bool deleteList(ListElement **head) { if (!head) return false; ListElement *next; while (*head) { next = (*head)->next; free(*head); *head = next; } return true; } ListElement *findElem(ListElement *head, int data) { while (head) { if (head->data == data) return head; head = head->next; } return NULL; } bool deleteElem(ListElement **head, ListElement *toDelete) { if (!head || !*head || !toDelete) return false; if (*head == toDelete) { *head = toDelete->next; free(toDelete); return true; } ListElement *cur = *head; while (cur->next) { if (cur->next == toDelete) { cur->next = toDelete->next; free(toDelete); return true; } cur = cur->next; } return false; // could not find toDelete in list } bool insertInFront(ListElement **head, int data) { ListElement *newElem = (ListElement *)malloc(sizeof(ListElement)); if (!newElem) return false; newElem->data = data; newElem->next = *head; *head = newElem; return true; } bool insertAfter(ListElement **head, ListElement *node, int data) { ListElement *newElem = (ListElement *)malloc(sizeof(ListElement)); if (!newElem) return false; newElem->data = data; if (node == NULL) { // insert at front of list newElem->next = *head; *head = newElem; } else { newElem->next = node->next; node->next = newElem; } return true; } void printList(ListElement *head) { printf("List: "); while (head) { printf("%d", head->data); if (head = head->next) printf(", "); } printf("\n"); }
C
// // 4948.c // algorithm_2019 // // Created by bomin jung on 2019. 1. 23.. // Copyright © 2019년 bomin jung. All rights reserved. // 베르트랑 공준 n~2n사이에 소수의 개수를 구하기 #include <stdio.h> #include <math.h> #include <stdbool.h> int main(int argc, char * argv[]) { int n, i, sqrt_val , answer = 0; bool is_prime[246913]; while(1){ scanf("%d", &n); if(n == 0) break; sqrt_val = sqrt(2*n); for(i=2; i<=2*n; i++) is_prime[i] = true; /* 2n의 제곱근까지 배수들을 체크 */ for(i=2; i<=sqrt_val; i++){ if(!is_prime[i]) continue; for(int j=i*i; j<=2*n; j+=i){ if(is_prime[j]) is_prime[j] = false; } } for(i=n+1; i<2*n+1; i++){ if(is_prime[i]) answer++; } printf("%d\n", answer); answer = 0; } return 0; }
C
typedef enum PASS_TEST {PASS, FAIL} testPass; typedef enum boolean {F, T} boolean; #define PASS_TEST return 0 #define FAIL_TEST return 1 #define ASSERT_EQUALS(A, B)\ if ((A) != (B)) {\ return FAIL;\ } #define ASSERT_NOT_EQUALS(A, B)\ if ((A) != (B)) {\ return PASS;\ } #define ASSERT_PASS_TEST(A)\ if ((A) == PASS) {\ PASS_TEST;\ } else {\ FAIL_TEST;\ }
C
#include <stdio.h> int platform1D(int ar[], int size); int main() { int i, b[50], size; printf("Enter array size: \n"); scanf("%d", &size); printf("Enter %d data: \n", size); for (i = 0; i < size; i++) scanf("%d", &b[i]); printf("platform1D(): %d\n", platform1D(b, size)); return 0; } int platform1D(int ar[], int size) { int x = ar[0], c = 1, m = 1; for (int i = 1; i < size; i++) { if (x == ar[i]) { c++; } else { if (m < c) m = c; c = 1; } x = ar[i]; } return m; }
C
#include <stdio.h> #include <stdlib.h> #include <fcntl.h> unsigned char all[64*1024]; struct { int ch; int off; } rom_map[] = { '1', 0x0000, '2', 0x1000, '3', 0x2000, '4', 0x3000, '5', 0x4000, '6', 0x5000, '7', 0x6000, '8', 0x7000, '9', 0x8000, 'a', 0xd000, 'b', 0xe000, 'c', 0xf000, }; main() { int n, i, f, r, a; char name[1024]; f = open("BLITTEST.BIN", O_RDONLY); if (f < 0) { perror(name); exit(1); } r = read(f, all, 64*1024); close(f); printf("initial begin\n"); for (n = 0; n < 12; n++) { int c; c = rom_map[n].ch; a = rom_map[n].off; printf("\t// %s @ %04x\n", name, a); for (i = 0; i < 4096; i++) { printf("\trom%c[%d] = 8'h%02x; // 0x%04x\n", c, i, all[i+a], i+a); } } printf("end\n"); }
C
/*------------------------------------------------------------ * FileName: constant.h * Author: xlu * Date: 2016-03-14 ------------------------------------------------------------*/ #ifndef CONSTANT_H #define CONSTANT_H /** * Frequently used constant. */ /* #ifndef TRUE #define TRUE 1 #endif #ifndef FALSE #define FALSE 0 #endif */ #define min(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a < _b ? _a : _b; }) #define max(a,b) \ ({ __typeof__ (a) _a = (a); \ __typeof__ (b) _b = (b); \ _a > _b ? _a : _b; }) /** * Basic data type. */ /* #ifndef BYTE #define BYTE unsigned char #endif #ifndef WORD #define WORD unsigned short #endif #ifndef DWORD #define DWORD unsigned int #endif */ /** * RGB 888. */ // the r, g, b mask of RGB888 color is 0xFF0000, 0xFF00, 0xFF #define R_RGB888(x) (unsigned char) (((x) >> 16) & 0xFF) #define G_RGB888(x) (unsigned char) (((x) >> 8) & 0xFF) #define B_RGB888(x) (unsigned char) ((x) & 0xFF) // Generating RGB565 pixel by composing r, g, b components #ifndef RGB888 #define RGB888(r, g ,b) ((unsigned int) (((unsigned int) (r) << 16| ((unsigned short) (g) << 8)) | ((unsigned int) (unsigned char) (b)))) #endif #ifndef COLOR32 #define COLOR32 unsigned int #endif #define WHITE RGB888(0xff, 0xff, 0xff) #define BLACK RGB888(0x00, 0x00, 0x00) #define RED RGB888(0xff, 0, 0) #define GREEN RGB888(0, 0xff, 0) #define BLUE RGB888(0, 0, 0xff) #define GRAY RGB888(0xbe, 0xbe, 0xbe) /** * RGB 565. */ // the r, g, b value of RGB565 color is 0xF800, 0x7E0, 0x1F // R R R R R G G G G G G B B B B B #define R_RGB565(x) (unsigned char) (((x) >> 8) & 0xF8) #define G_RGB565(x) (unsigned char) (((x) >> 3) & 0xFC) #define B_RGB565(x) (unsigned char) ((x) << 3) // Generating RGB565 pixel by composing r, g, b components. #ifndef RGB565 #define RGB565(r, g, b) (unsigned short) ((((r) & 0xF8) << 8) | (((g) & 0xFC) << 3) | ((b) >> 3)) #endif #ifndef COLOR16 #define COLOR16 unsigned short #endif // Convert 32-bit color (RGB888) to 16-bit color (RGB565). #define COLOR_32_TO_16(x) RGB565(R_RGB888(x), G_RGB888(x), B_RGB888(x)) #define FONT_NAME "paxfont.ttf" #define KEYBOARD_NAME "/dev/keypad" #define TOUCHSCREEN_NAME "/dev/tp" #define LCD_NAME "/dev/fb" #endif
C
typedef struct{ int cod; char* name; float salary; } Element; typedef struct list_no List; typedef struct queue Queue; Queue* queue_create(); int queue_insert(Queue* pointer, Element element); int queue_remove(Queue* pointer); int queue_select(Queue* pointer, Element* element); int queue_isEmpty(Queue* pointer); void queue_delete(Queue* pointer);
C
#include <stdio.h> #include <stdlib.h> void rush00(int w, int h) { int x, y; for (y = 0; y < h; y++) { for (int x = 0; x < w; x++) if (y == 0 && x == 0) putchar('/'); else if (y == 0 && x == w - 1) putchar('\\'); else if (y == h - 1 && x == 0) putchar('\\'); else if (y == h - 1 && x == w - 1) putchar('/'); else if (y == 0 || y == h - 1) putchar('*'); else if (x == 0 || x == w - 1) putchar('*'); else putchar(' '); putchar('\n'); } } int main(int argc, char** argv) { int arg_w = atoi(argv[1]); int arg_h = atoi(argv[2]); rush00(arg_w, arg_h); return 0; }
C
/* * O exercicio nao atende ao enunciado. Nota 0. * Enunciado: escreva um programa que leia um inteiro do teclado, * e usando switch case, imprima o mes correspondente * ao numero digitado. */ #include <stdio.h> int main () { int x, y, z; scanf("%d", &x); scanf("%d", &y); scanf("%d", &z); if(x<y) { if(x<z) { if(y<z) // x<y<z { printf("ordem crescente: %d %d %d", x,y,z); } else // x<z<y { printf("ordem crescente: %d %d %d", x,z,y); } } else // z<x<y { printf("ordem crescente: %d %d %d", z,x,y); } } else // x>y if(y<z) { if(x<z) { printf("ordem crescente: %d %d %d", y,x,z); } else // z<y z>x>y { printf("ordem crescente: %d %d %d", y,z,x); } } else // x>y>z { printf("ordem crescente: %d %d %d", z,y,x); } return 0; }
C
#include<stdio.h> int main() { int remainder,input,sum=0; scanf("%d",&input); while(input) { remainder=input%10; sum=sum*10+remainder; input=input/10; } printf("%d",sum); return 0; }
C
/*** *mbtoupr.c - Convert character to upper case (MBCS) * * Copyright (c) 1985-1997, Microsoft Corporation. All rights reserved. * *Purpose: * Convert character to upper case (MBCS) * *******************************************************************************/ #ifdef _MBCS #if defined (_WIN32) #include <awint.h> #endif /* defined (_WIN32) */ #include <cruntime.h> #include <ctype.h> #include <mbdata.h> #include <mbctype.h> #include <mbstring.h> /*** * _mbctoupper - Convert character to upper case (MBCS) * *Purpose: * If the given character is lower case, convert to upper case. * Handles MBCS chars correctly. * * Note: Use test against 0x00FF instead of _ISLEADBYTE * to ensure that we don't call SBCS routine with a two-byte * value. * *Entry: * unsigned int c = character to convert * *Exit: * Returns converted character * *Exceptions: * *******************************************************************************/ unsigned int __cdecl _mbctoupper(unsigned int c) { unsigned char val[2]; #if defined (_WIN32) unsigned char ret[4]; #endif /* defined (_WIN32) */ if (c > 0x00FF) { val[0] = (c >> 8) & 0xFF; val[1] = c & 0xFF; if (!_ismbblead(val[0])) return c; #if defined (_WIN32) if (__crtLCMapStringA(__mblcid, LCMAP_UPPERCASE, val, 2, ret, 2, __mbcodepage, TRUE) == 0) return c; c = ret[1]; c += ret[0] << 8; return c; #else /* defined (_WIN32) */ if (c >= _MBLOWERLOW1 && c <= _MBLOWERHIGH1) c -= _MBCASEDIFF1; else if (c >= _MBLOWERLOW2 && c <= _MBLOWERHIGH2) c -= _MBCASEDIFF2; return c; #endif /* defined (_WIN32) */ } else return (unsigned int)_mbbtoupper((int)c); } #endif /* _MBCS */
C
#include <stdio.h> int main() { char a='3'; char* ptra= &a; // char is of 1 size int printf("%p\n", ptra); printf("The value of a is %c\n", *ptra); ptra++; // here we added 1 into ptra printf("%p\n", ptra); // the address of a printf("%p\n", ptra+1); return 0; }
C
#include <stdio.h> int main (){ int X,i; scanf("%d",&X); for(i = 1; i <= X;i++){ if (i % 2 != 0){ printf("%d",i); printf("\n"); } } }
C
/* Student Name: Zheyuan Xu Date: 11/7/2018 ======================= ECE 2035 Project 2-1: ======================= This file provides definition for the structs and functions declared in the header file. It also contains helper functions that are not accessible from outside of the file. FOR FULL CREDIT, BE SURE TO TRY MULTIPLE TEST CASES and DOCUMENT YOUR CODE. =================================== Naming conventions in this file: =================================== 1. All struct names use camel case where the first letter is capitalized. e.g. "HashTable", or "HashTableEntry" 2. Variable names with a preceding underscore "_" will not be called directly. e.g. "_HashTable", "_HashTableEntry" Recall that in C, we have to type "struct" together with the name of the struct in order to initialize a new variable. To avoid this, in hash_table.h we use typedef to provide new "nicknames" for "struct _HashTable" and "struct _HashTableEntry". As a result, we can create new struct variables by just using: - "HashTable myNewTable;" or - "HashTableEntry myNewHashTableEntry;" The preceding underscore "_" simply provides a distinction between the names of the actual struct defition and the "nicknames" that we use to initialize new structs. [See Hidden Definitions section for more information.] 3. Functions, their local variables and arguments are named with camel case, where the first letter is lower-case. e.g. "createHashTable" is a function. One of its arguments is "numBuckets". It also has a local var iable called "newTable". 4. The name of a struct member is divided by using underscores "_". This serves as a distinction between function local variables and struct members. e.g. "num_buckets" is a member of "HashTable". */ /**************************************************************************** * Include the Public Interface * * By including the public interface at the top of the file, the compiler can * enforce that the function declarations in the the header are not in * conflict with the definitions in the file. This is not a guarantee of * correctness, but it is better than nothing! ***************************************************************************/ #include "hash_table.h" /**************************************************************************** * Include other private dependencies * * These other modules are used in the implementation of the hash table module, * but are not required by users of the hash table. ***************************************************************************/ #include <stdlib.h> // For malloc and free #include <stdio.h> // For printf /**************************************************************************** * Hidden Definitions * * These definitions are not available outside of this file. However, because * the are forward declared in hash_table.h, the type names are * available everywhere and user code can hold pointers to these structs. ***************************************************************************/ /** * This structure represents an a hash table. * Use "HashTable" instead when you are creating a new variable. [See top comments] */ struct _HashTable { /** The array of pointers to the head of a singly linked list, whose nodes are HashTableEntry objects */ HashTableEntry** buckets; /** The hash function pointer */ HashFunction hash; /** The number of buckets in the hash table */ unsigned int num_buckets; }; /** * This structure represents a hash table entry. * Use "HashTableEntry" instead when you are creating a new variable. [See top comments] */ struct _HashTableEntry { /** The key for the hash table entry */ unsigned int key; /** The value associated with this hash table entry */ void* value; /** * A pointer pointing to the next hash table entry * NULL means there is no next entry (i.e. this is the tail) */ HashTableEntry* next; }; /**************************************************************************** * Private Functions * * These functions are not available outside of this file, since they are not * declared in hash_table.h. ***************************************************************************/ /** * createHashTableEntry * * Helper function that creates a hash table entry by allocating memory for it on * the heap. It initializes the entry with key and value, initialize pointer to * the next entry as NULL, and return the pointer to this hash table entry. * * @param key The key corresponds to the hash table entry * @param value The value stored in the hash table entry * @return The pointer to the hash table entry */ static HashTableEntry* createHashTableEntry(unsigned int key, void* value) { HashTableEntry* newEntry = (HashTableEntry*)malloc(sizeof(HashTableEntry)); newEntry->key = key; newEntry->value = value; newEntry->next = NULL; return newEntry; } /** * findItem * * Helper function that checks whether there exists the hash table entry that * contains a specific key. * * @param hashTable The pointer to the hash table. * @param key The key corresponds to the hash table entry * @return The pointer to the hash table entry, or NULL if key does not exist */ static HashTableEntry* findItem(HashTable* hashTable, unsigned int key) { //get the hash index unsigned int index = hashTable->hash(key); //point to the starting index of the bucket HashTableEntry* entry = hashTable->buckets[index]; //while entry is not null, i.e. not the end of the bucket while (entry) { //if key matches return that entry if (entry->key == key) { return entry; } //otherwise move to the next entry in that bucket entry = entry->next; } return entry; //return entry found, if not found it will point to the null entry pointed by the last entry in that bucket } /**************************************************************************** * Public Interface Functions * * These functions implement the public interface as specified in the header * file, and make use of the private functions and hidden definitions in the * above sections. ****************************************************************************/ // The createHashTable is provided for you as a starting point. HashTable* createHashTable(HashFunction hashFunction, unsigned int numBuckets) { // The hash table has to contain at least one bucket. Exit gracefully if // this condition is not met. if (numBuckets==0) { printf("Hash table has to contain at least 1 bucket...\n"); exit(1); } // Allocate memory for the new HashTable struct on heap. HashTable* newTable = (HashTable*)malloc(sizeof(HashTable)); // Initialize the components of the new HashTable struct. newTable->hash = hashFunction; newTable->num_buckets = numBuckets; newTable->buckets = (HashTableEntry**)malloc(numBuckets*sizeof(HashTableEntry*)); // As the new buckets contain indeterminant values, init each bucket as NULL. unsigned int i; for (i=0; i<numBuckets; ++i) { newTable->buckets[i] = NULL; } // Return the new HashTable struct. return newTable; } void destroyHashTable(HashTable* hashTable) { //iterate from 0 to the end of buckets for (int i = 0; i < (hashTable->num_buckets); i++) { if (hashTable->buckets[i]) { //create a pointer pointing to the start of the bucket and another pointing to the next entry HashTableEntry* entry = hashTable->buckets[i]; HashTableEntry* nextEntry = entry->next; //while nextEntry is not null while (nextEntry) { //free all the data stored in entry free(entry->value); free(entry); //move current entry to the next entry = nextEntry; //move next entry to next of next entry nextEntry = nextEntry->next; } //free current entry free(entry); } } //free the hashTable after it has emptied its buckets free(hashTable); return; } void* insertItem(HashTable* hashTable, unsigned int key, void* value) { //get the index to insert int index = hashTable->hash(key); //If there exists entry with matching key HashTableEntry* entry = findItem(hashTable,key); //if entry with same key is found, update the value if (entry) { //store the copy of old value void* oldValue; oldValue = entry -> value; entry-> value = value; return oldValue; } //create new entry HashTableEntry* newEntry = createHashTableEntry(key, value); //if newEntry is null if(!newEntry) { return NULL; } //insert new entry to the front newEntry->next = hashTable->buckets[index]; hashTable->buckets[index] = newEntry; return NULL; } void* getItem(HashTable* hashTable, unsigned int key) { HashTableEntry* entry = findItem(hashTable,key); //if entry with same key is found, i.e. entry is not null if(entry) { return entry->value; } //else return null return NULL; } void* removeItem(HashTable* hashTable, unsigned int key) { //get hash index int index = hashTable -> hash(key); //create a pointer pointing to the head of bucket HashTableEntry* entry = hashTable -> buckets[index]; //if head has the same key, remove head if(entry && entry->key == key) { //get value of entry to be removed void* toRemove = entry->value; // update head hashTable->buckets[index] = entry->next; //remove head entry free(entry); return toRemove; } //else, if key is not matching, keep probing the bucket while(entry && entry -> next) { //check if next entry is one to remove if(entry->next->key == key) { //save entry to be removed HashTableEntry* toRemove = entry -> next; //save value removed entry void* removedEntry = toRemove -> value; //remove the entry entry-> next = entry->next->next; free(toRemove); //return value of removed entry return removedEntry; } //keep probing entry = entry->next; } //entry not found, return null return NULL; } void deleteItem(HashTable* hashTable, unsigned int key) { //get bucket index int index = hashTable->hash(key); //get bucket pointer HashTableEntry* entry = hashTable->buckets[index]; //if not found end the function if (findItem(hashTable,key) == NULL) { return; } //if found and the starting entry matches the key, remove starting entry if (entry && entry->key == key) { //set starting entry equal to next entry in the bucket hashTable->buckets[index] = entry->next; //free starting entry value free(entry -> value); //free starting entry free(entry); //end the function return; } //delete if starting entry is not the entry to be deleted while(entry && entry-> next) { //if next entry is the one to be deleted if(entry -> next -> key == key) { //save pointer to the deleted entry HashTableEntry* toDelete = entry-> next; //remove entry entry->next = entry->next->next; //free value of removed entry free(toDelete -> value); //free entry free(toDelete); //end the function return; } //keep probing the bucket entry = entry -> next; } }
C
#include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #include <linux/cdev.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Jakub Werner"); MODULE_AUTHOR("SYSO Aufgabe 4"); #define MAJORNUM 112 #define NUMDEVICES 12 #define DEVNAME "jacksdevice" static struct cdev *driver_info = NULL; static struct file_operations fops; static int __init ModInit(void) { struct file_operations fop; if (register_chrdev_region(MKDEV(MAJORNUM, 0), NUMDEVICES, DEVNAME)) { pr_debug("Device number 0x%x not available ...\n" , MKDEV(MAJORNUM, 0)); return -EIO ; } else { pr_info("Device number 0x%x created", MKDEV(MAJORNUM, 0)); } driver_info = cdev_alloc(); if (driver_info == NULL) { pr_debug("cdev_alloc failed!\n"); goto free_devnum; } kobject_set_name(&driver_info->kobj, DEVNAME); driver_info->owner = THIS_MODULE; cdev_init(driver_info, &fops); if (cdev_add(driver_info, MKDEV(MAJORNUM,0), NUMDEVICES)) { pr_debug("cdev_add failed!\n"); goto free_cdev; } return 0; free_cdev: kobject_put(&driver_info->kobj); driver_info = NULL; free_devnum: unregister_chrdev_region(MKDEV(MAJORNUM,0), NUMDEVICES); return -1; } static void __exit ModExit(void) { printk(KERN_ALERT "Goodbye, cruel world\n"); if (driver_info) { cdev_del(driver_info); } unregister_chrdev_region(MKDEV(MAJORNUM, 0), NUMDEVICES); } module_init(ModInit); module_exit(ModExit);
C
#include "../Headers/Funcoes.h" int LeituraArquivo(int Matriz[][100]){ FILE *f; char NomeArquivo[20]; int QuantLinhas=-1; printf("\nDigite o nome do arquivo que deseja abrir:"); scanf("%s",NomeArquivo); f = fopen(NomeArquivo,"r"); if(f == NULL){ printf("\n\tErro!Nao foi possivel abrir arquivo!\n");} else{ printf("\n\tArquivo aberto com sucesso!\n"); /*for(int k=0;k<100;k++){ //Refleti muito e acredito q se o algoritmo estiver 100% dentro dos limites não ha necessidade de inicilizar toda matriz com 0; for(int l=0;l<100;l++){ //Porem durante a manipulacao e visualizacao da matriz,o tamanho QuantLinhas DEVE SER RESPEITADO! Matriz[k][l]=0; } }*/ for(int i=0;i<100;i++){ for(int j=0;j<i+1;j++){ fscanf(f,"%d",&Matriz[i][j]); if(feof(f)){ break; } } QuantLinhas++; if(feof(f)){ break; } } fclose(f); } return QuantLinhas; } int Maior(int a,int b){ if(a>=b){ return a; } return b; } int Menu(){ int a; printf("\n-----------------------Menu-----------------------\n"); printf("\n1 -> Metodo Recursivo:"); printf("\n2 -> Metodo Programacao Dinamica:"); printf("\n3 -> De Tras para Frente:"); printf("\n4 -> Imprimir Rota utilizando Programacao Dinamica:"); printf("\n5 -> Imprimir Rota utilizando De Tras para Frente:"); do{ printf("\nEntre com a opcao: "); scanf("%d",&a); if(a!=1 && a!=2 && a!=3 && a!=4 && a!=5){ printf("\nOpcao invalida!\n"); } }while(a!=1 && a!=2 && a!=3 && a!=4 && a!=5); return a; } void CopiaMatriz(int MatrizOrigem[][100],int MatrizDestino[][100],int QuantLinhas){ for(int i=0;i<QuantLinhas;i++) for(int j=0;j<i+1;j++){ MatrizDestino[i][j]=MatrizOrigem[i][j]; } } void MelhorCaminho(int QuantLinhas,int x,int y,int MatrizAux[][100]){ MatrizAux[x][y]=-2; //Valor de referencia. if(x<QuantLinhas-1){ if(MatrizAux[x+1][y]>MatrizAux[x+1][y+1]){ MelhorCaminho(QuantLinhas,x+1,y,MatrizAux); } else{ MelhorCaminho(QuantLinhas,x+1,y+1,MatrizAux); } } return; } //Funcoes para contagem de tempo de execucao// void IniciarTimer(Timer *timer){ timer->TempoInicial = clock(); } void PararTimer(Timer *timer){ timer->TempoFinal = clock(); timer->TempoTotal = (double)(timer->TempoFinal - timer->TempoInicial)/CLOCKS_PER_SEC; } double TempoTotal(Timer timer){ return timer.TempoTotal; }
C
#include "holberton.h" /** * _abs - prints the absolute value of a number * * @n: parameter to check * * Return: Always 0 (Success) */ int _abs(int n) { if (n >= 0) return (n); else return (-n); }
C
// Ejemplo operadores de incremento y expresiones de asignacin // Salida esperada: 4, 4, 4, 4, 7. //------------------------------------------------------------- int a; int suma(int x, int y) { return x+y; } int main () { int b; int i; i=0; for(;i<5;) { print(i); i++; } i=111; do { print(i); i--; } while(i!=100); if(false == not 1) print(100000); else print(55555); print(a=4); print(a++); print(--a); print(a); print(suma(a,b=3)); return 0; }
C
#include <stdio.h> int fun(int n1,int n2,int n3) { if((n1<=99)||(n1>=1000)) return 0; if((n2<=99)||(n2>=1000)) return 0; if((n3<=99)||(n3>=1000)) return 0; if(n2!=2*n1) return 0; if(n3!=3*n1) return 0; return 1; } int main() { int n1,n2,n3; scanf("%d%d%d",&n1,&n2,&n3); int res=fun(n1,n2,n3); printf("\n%d",res); return 0; }
C
#include "lists.h" #include <stdio.h> /** * check_cycle - Checks if cycle are present in linked list. * @list: A list. * * Return: 1 if cycle found. * 0 if not found. * */ int check_cycle(listint_t *list) { listint_t *hare; listint_t *tortoise; tortoise = list; hare = list; while (hare && hare->next) { tortoise = tortoise->next; hare = hare->next->next; if (tortoise == hare) return (1); } return (0); }
C
#include <stdio.h> #include <stdlib.h> void funHead(int x) { if(x>0) { funHead(x-1); // Recursively calling function printf("%d ", x); //printing Output : 1 2 3 } } int main() { int n=3; funHead(n); // Calling funHead() function return 0; }
C
#include "matrix.h" #include "stdlib.h" #include "math.h" #include "stdio.h" #define DATA_TYPE float //ֵֽⷨ //ֵС0ʾֵֽ, //еֵ60λδ㾫Ҫ. //ֵ0ʾء //a-Ϊm*n飬ʱԽθֵԪΪ0 //m- //n- //aa-Ϊn*m飬ʽAĹ //eps-Ҫ //u-Ϊm*m飬ʱֵֽU //v-Ϊn*n飬ʱֵֽV //ka-ͱֵΪmax(n,m)+1 //údluav() //int dluav(double a[],int m,int n,double u[],double v[],double eps,int ka); int dluav(DATA_TYPE a[],int m,int n,DATA_TYPE u[],DATA_TYPE v[],DATA_TYPE eps,int ka); static void ppp(DATA_TYPE a[],DATA_TYPE e[],DATA_TYPE s[],DATA_TYPE v[],int m,int n); static void sss(DATA_TYPE fg[2],DATA_TYPE cs[2]); #define KA(m,n) ((m)>(n)?((m)+1):((n)+1)) //int MATRIX_PInv(double a[],int m,int n,double aa[],double eps,double u[],double v[],int ka) int MATRIX_PInv(DATA_TYPE a[],int m,int n,DATA_TYPE a_inv[],DATA_TYPE eps,DATA_TYPE u[],DATA_TYPE v[]) { int i,j,k,l,t,p,q,f; int ka; ka=KA(m,n); i=dluav(a,m,n,u,v,eps,ka); if (i<0) { return(-1); } j=n; if (m<n) { j=m; } j=j-1; k=0; while ((k<=j)&&(a[k*n+k]!=0.0)) { k=k+1; } k=k-1; for (i=0; i<=n-1; i++) { for (j=0; j<=m-1; j++) { t=i*m+j; a_inv[t]=0.0; for (l=0; l<=k; l++) { f=l*n+i; p=j*m+l; q=l*n+l; a_inv[t]=a_inv[t]+v[f]*u[p]/a[q]; } } } return(1); } //ʵֵֽ //Householder任QR㷨 //a-Ϊm*n飬ʱԽθֵԪΪ0 //m- //n- //u-Ϊm*m飬ʱֵֽU //v-Ϊn*n飬ʱֵֽV //eps-Ҫ //ka-ͱֵΪmax(n,m)+1 //údluav(),ppp(),sss() //int dluav(double a[],int m,int n,double u[],double v[],double eps,int ka) int dluav(DATA_TYPE a[],int m,int n,DATA_TYPE u[],DATA_TYPE v[],DATA_TYPE eps,int ka) { int i,j,k,l,it,ll,kk,ix,iy,mm,nn,iz,m1,ks; DATA_TYPE d,dd,t,sm,sm1,em1,sk,ek,b,c,shh,fg[2],cs[2]; DATA_TYPE *s,*e,*w; s=(DATA_TYPE *)malloc(ka*sizeof(DATA_TYPE)); e=(DATA_TYPE *)malloc(ka*sizeof(DATA_TYPE)); w=(DATA_TYPE *)malloc(ka*sizeof(DATA_TYPE)); it=100; k=n; if (m-1<n) { k=m-1; } l=m; if (n-2<m) { l=n-2; } if (l<0) { l=0; } ll=k; if (l>k) { ll=l; } if (ll>=1) { for (kk=1; kk<=ll; kk++) { if (kk<=k) { d=0.0; for (i=kk; i<=m; i++) { ix=(i-1)*n+kk-1; d=d+a[ix]*a[ix]; } s[kk-1]=sqrt(d); if (s[kk-1]!=0.0) { ix=(kk-1)*n+kk-1; if (a[ix]!=0.0) { s[kk-1]=fabs(s[kk-1]); if (a[ix]<0.0) { s[kk-1]=-s[kk-1]; } } for (i=kk; i<=m; i++) { iy=(i-1)*n+kk-1; a[iy]=a[iy]/s[kk-1]; } a[ix]=1.0+a[ix]; } s[kk-1]=-s[kk-1]; } if (n>=kk+1) { for (j=kk+1; j<=n; j++) { if ((kk<=k)&&(s[kk-1]!=0.0)) { d=0.0; for (i=kk; i<=m; i++) { ix=(i-1)*n+kk-1; iy=(i-1)*n+j-1; d=d+a[ix]*a[iy]; } d=-d/a[(kk-1)*n+kk-1]; for (i=kk; i<=m; i++) { ix=(i-1)*n+j-1; iy=(i-1)*n+kk-1; a[ix]=a[ix]+d*a[iy]; } } e[j-1]=a[(kk-1)*n+j-1]; } } if (kk<=k) { for (i=kk; i<=m; i++) { ix=(i-1)*m+kk-1; iy=(i-1)*n+kk-1; u[ix]=a[iy]; } } if (kk<=l) { d=0.0; for (i=kk+1; i<=n; i++) { d=d+e[i-1]*e[i-1]; } e[kk-1]=sqrt(d); if (e[kk-1]!=0.0) { if (e[kk]!=0.0) { e[kk-1]=fabs(e[kk-1]); if (e[kk]<0.0) { e[kk-1]=-e[kk-1]; } } for (i=kk+1; i<=n; i++) { e[i-1]=e[i-1]/e[kk-1]; } e[kk]=1.0+e[kk]; } e[kk-1]=-e[kk-1]; if ((kk+1<=m)&&(e[kk-1]!=0.0)) { for (i=kk+1; i<=m; i++) { w[i-1]=0.0; } for (j=kk+1; j<=n; j++) { for (i=kk+1; i<=m; i++) { w[i-1]=w[i-1]+e[j-1]*a[(i-1)*n+j-1]; } } for (j=kk+1; j<=n; j++) { for (i=kk+1; i<=m; i++) { ix=(i-1)*n+j-1; a[ix]=a[ix]-w[i-1]*e[j-1]/e[kk]; } } } for (i=kk+1; i<=n; i++) { v[(i-1)*n+kk-1]=e[i-1]; } } } } mm=n; if (m+1<n) { mm=m+1; } if (k<n) { s[k]=a[k*n+k]; } if (m<mm) { s[mm-1]=0.0; } if (l+1<mm) { e[l]=a[l*n+mm-1]; } e[mm-1]=0.0; nn=m; if (m>n) { nn=n; } if (nn>=k+1) { for (j=k+1; j<=nn; j++) { for (i=1; i<=m; i++) { u[(i-1)*m+j-1]=0.0; } u[(j-1)*m+j-1]=1.0; } } if (k>=1) { for (ll=1; ll<=k; ll++) { kk=k-ll+1; iz=(kk-1)*m+kk-1; if (s[kk-1]!=0.0) { if (nn>=kk+1) { for (j=kk+1; j<=nn; j++) { d=0.0; for (i=kk; i<=m; i++) { ix=(i-1)*m+kk-1; iy=(i-1)*m+j-1; d=d+u[ix]*u[iy]/u[iz]; } d=-d; for (i=kk; i<=m; i++) { ix=(i-1)*m+j-1; iy=(i-1)*m+kk-1; u[ix]=u[ix]+d*u[iy]; } } } for (i=kk; i<=m; i++) { ix=(i-1)*m+kk-1; u[ix]=-u[ix]; } u[iz]=1.0+u[iz]; if (kk-1>=1) { for (i=1; i<=kk-1; i++) { u[(i-1)*m+kk-1]=0.0; } } } else { for (i=1; i<=m; i++) { u[(i-1)*m+kk-1]=0.0; } u[(kk-1)*m+kk-1]=1.0; } } } for (ll=1; ll<=n; ll++) { kk=n-ll+1; iz=kk*n+kk-1; if ((kk<=l)&&(e[kk-1]!=0.0)) { for (j=kk+1; j<=n; j++) { d=0.0; for (i=kk+1; i<=n; i++) { ix=(i-1)*n+kk-1; iy=(i-1)*n+j-1; d=d+v[ix]*v[iy]/v[iz]; } d=-d; for (i=kk+1; i<=n; i++) { ix=(i-1)*n+j-1; iy=(i-1)*n+kk-1; v[ix]=v[ix]+d*v[iy]; } } } for (i=1; i<=n; i++) { v[(i-1)*n+kk-1]=0.0; } v[iz-n]=1.0; } for (i=1; i<=m; i++) { for (j=1; j<=n; j++) { a[(i-1)*n+j-1]=0.0; } } m1=mm; it=100; while (1==1) { if (mm==0) { ppp(a,e,s,v,m,n); free(s); free(e); free(w); return(1); } if (it==0) { ppp(a,e,s,v,m,n); free(s); free(e); free(w); return(-1); } kk=mm-1; while ((kk!=0)&&(fabs(e[kk-1])!=0.0)) { d=fabs(s[kk-1])+fabs(s[kk]); dd=fabs(e[kk-1]); if (dd>eps*d) { kk=kk-1; } else { e[kk-1]=0.0; } } if (kk==mm-1) { kk=kk+1; if (s[kk-1]<0.0) { s[kk-1]=-s[kk-1]; for (i=1; i<=n; i++) { ix=(i-1)*n+kk-1; v[ix]=-v[ix]; } } while ((kk!=m1)&&(s[kk-1]<s[kk])) { d=s[kk-1]; s[kk-1]=s[kk]; s[kk]=d; if (kk<n) { for (i=1; i<=n; i++) { ix=(i-1)*n+kk-1; iy=(i-1)*n+kk; d=v[ix]; v[ix]=v[iy]; v[iy]=d; } } if (kk<m) { for (i=1; i<=m; i++) { ix=(i-1)*m+kk-1; iy=(i-1)*m+kk; d=u[ix]; u[ix]=u[iy]; u[iy]=d; } } kk=kk+1; } it=100; mm=mm-1; } else { ks=mm; while ((ks>kk)&&(fabs(s[ks-1])!=0.0)) { d=0.0; if (ks!=mm) { d=d+fabs(e[ks-1]); } if (ks!=kk+1) { d=d+fabs(e[ks-2]); } dd=fabs(s[ks-1]); if (dd>eps*d) { ks=ks-1; } else { s[ks-1]=0.0; } } if (ks==kk) { kk=kk+1; d=fabs(s[mm-1]); t=fabs(s[mm-2]); if (t>d) { d=t; } t=fabs(e[mm-2]); if (t>d) { d=t; } t=fabs(s[kk-1]); if (t>d) { d=t; } t=fabs(e[kk-1]); if (t>d) { d=t; } sm=s[mm-1]/d; sm1=s[mm-2]/d; em1=e[mm-2]/d; sk=s[kk-1]/d; ek=e[kk-1]/d; b=((sm1+sm)*(sm1-sm)+em1*em1)/2.0; c=sm*em1; c=c*c; shh=0.0; if ((b!=0.0)||(c!=0.0)) { shh=sqrt(b*b+c); if (b<0.0) { shh=-shh; } shh=c/(b+shh); } fg[0]=(sk+sm)*(sk-sm)-shh; fg[1]=sk*ek; for (i=kk; i<=mm-1; i++) { sss(fg,cs); if (i!=kk) { e[i-2]=fg[0]; } fg[0]=cs[0]*s[i-1]+cs[1]*e[i-1]; e[i-1]=cs[0]*e[i-1]-cs[1]*s[i-1]; fg[1]=cs[1]*s[i]; s[i]=cs[0]*s[i]; if ((cs[0]!=1.0)||(cs[1]!=0.0)) { for (j=1; j<=n; j++) { ix=(j-1)*n+i-1; iy=(j-1)*n+i; d=cs[0]*v[ix]+cs[1]*v[iy]; v[iy]=-cs[1]*v[ix]+cs[0]*v[iy]; v[ix]=d; } } sss(fg,cs); s[i-1]=fg[0]; fg[0]=cs[0]*e[i-1]+cs[1]*s[i]; s[i]=-cs[1]*e[i-1]+cs[0]*s[i]; fg[1]=cs[1]*e[i]; e[i]=cs[0]*e[i]; if (i<m) { if ((cs[0]!=1.0)||(cs[1]!=0.0)) { for (j=1; j<=m; j++) { ix=(j-1)*m+i-1; iy=(j-1)*m+i; d=cs[0]*u[ix]+cs[1]*u[iy]; u[iy]=-cs[1]*u[ix]+cs[0]*u[iy]; u[ix]=d; } } } } e[mm-2]=fg[0]; it=it-1; } else { if (ks==mm) { kk=kk+1; fg[1]=e[mm-2]; e[mm-2]=0.0; for (ll=kk; ll<=mm-1; ll++) { i=mm+kk-ll-1; fg[0]=s[i-1]; sss(fg,cs); s[i-1]=fg[0]; if (i!=kk) { fg[1]=-cs[1]*e[i-2]; e[i-2]=cs[0]*e[i-2]; } if ((cs[0]!=1.0)||(cs[1]!=0.0)) { for (j=1; j<=n; j++) { ix=(j-1)*n+i-1; iy=(j-1)*n+mm-1; d=cs[0]*v[ix]+cs[1]*v[iy]; v[iy]=-cs[1]*v[ix]+cs[0]*v[iy]; v[ix]=d; } } } } else { kk=ks+1; fg[1]=e[kk-2]; e[kk-2]=0.0; for (i=kk; i<=mm; i++) { fg[0]=s[i-1]; sss(fg,cs); s[i-1]=fg[0]; fg[1]=-cs[1]*e[i-1]; e[i-1]=cs[0]*e[i-1]; if ((cs[0]!=1.0)||(cs[1]!=0.0)) { for (j=1; j<=m; j++) { ix=(j-1)*m+i-1; iy=(j-1)*m+kk-2; d=cs[0]*u[ix]+cs[1]*u[iy]; u[iy]=-cs[1]*u[ix]+cs[0]*u[iy]; u[ix]=d; } } } } } } } return(1); } static void ppp(DATA_TYPE a[],DATA_TYPE e[],DATA_TYPE s[],DATA_TYPE v[],int m,int n) { int i,j,p,q; DATA_TYPE d; if (m>=n) { i=n; } else { i=m; } for (j=1; j<=i-1; j++) { a[(j-1)*n+j-1]=s[j-1]; a[(j-1)*n+j]=e[j-1]; } a[(i-1)*n+i-1]=s[i-1]; if (m<n) { a[(i-1)*n+i]=e[i-1]; } for (i=1; i<=n-1; i++) { for (j=i+1; j<=n; j++) { p=(i-1)*n+j-1; q=(j-1)*n+i-1; d=v[p]; v[p]=v[q]; v[q]=d; } } return; } static void sss(DATA_TYPE fg[2],DATA_TYPE cs[2]) { DATA_TYPE r,d; if ((fabs(fg[0])+fabs(fg[1]))==0.0) { cs[0]=1.0; cs[1]=0.0; d=0.0; } else { d=sqrt(fg[0]*fg[0]+fg[1]*fg[1]); if (fabs(fg[0])>fabs(fg[1])) { d=fabs(d); if (fg[0]<0.0) { d=-d; } } if (fabs(fg[1])>=fabs(fg[0])) { d=fabs(d); if (fg[1]<0.0) { d=-d; } } cs[0]=fg[0]/d; cs[1]=fg[1]/d; } r=1.0; if (fabs(fg[0])>fabs(fg[1])) { r=cs[1]; } else { if(cs[0]!=0.0) { r=1.0/cs[0]; } fg[0]=d; fg[1]=r; return; } }
C
#define MAX_SIZE 100 typedef struct Queue { int front,rear,size; Node *arr[MAX_SIZE]; }Queue; Queue *newQueue() { Queue *q=(Queue *)malloc(sizeof(Queue)); q->front=q->rear=-1; return q; } int isQEmpty(Queue *q) { return q->front==q->rear; } int isQFull(Queue *q) { return q->rear==MAX_SIZE-1; } void add(Queue *q,Node *data) { if(!isQFull(q)) q->arr[++q->rear]=data; else printf("\nOperation failed:Queue is Full"); } Node * dequeue(Queue *q) { if(!isQEmpty(q)) return q->arr[++q->front]; else printf("\nOperation failed:Queue is Empty:"); return NULL; } Node* peek(Queue *q) { if(!isQEmpty(q)) return q->arr[q->front+1]; else printf("\nOperation failed:Queue is Empty:"); return NULL; }
C
#include <stdio.h> /** * main - main function * * @argc: int is argv * * @argv: char is argv * * Return: 0 */ int main(int argc, char *argv[]) { (void)argc; printf("%s\n", argv[0]); return (0); }
C
#include <stdio.h> #include <string.h> char* del(char *s); int main(){ char str[]=" how r u"; puts(str); printf("%s\n",del(str)); puts(str); return 0; } char* del(char* s){ //char s=str char *r=s,*p=s; //r为数组打起始地址 *r为第一个字符 while (*s!='\0') { if(*s==' '){ s++; //s指针从头扫描到尾 到空格停下 } else{ *p=*s; //不是空格的字符放前面 s++; p++; } } *p='\0'; return r; //返回字符串起始地址 }
C
#include<stdio.h> #include<stdlib.h> struct Node{ int data; struct Node *next; }; struct Stack{ struct Node *list; int (*pop)(struct Stack*); void (*push)(struct Stack*, int); void (*clean)(struct Stack*); }; struct Stack *createStack();
C
#include <stdio.h> #include <math.h> long max_prime_factor(long n) { long max_prime = -1; while (n % 2 == 0) { max_prime = 2; n = n >> 1; // n = n / 2 } double sqrt_n = sqrt(n); for (long i = 3; i <= sqrt_n; i += 2) { while (n % i == 0) { max_prime = i; n = n / i; } } if (n > 2) max_prime = n; return max_prime; } int main() { long n = 600851475143; printf("%ld\n", max_prime_factor(n)); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include "../include/common_threads.h" typedef struct __myarg_t { int a; int b; } myarg_t; typedef struct __myret_t { int x; int y; } myret_t; void* mythread(void *arg) { myarg_t* args = (myarg_t*) arg; printf("%d %d\n", args->a, args->b); myret_t* rvals = malloc(sizeof(myret_t)); rvals->x = 1; rvals->y = 2; return (void*) rvals; // Be careful with how values are returned from a thread. In particular, // never return a pointer which refers to something allocated on the // thread's call stack. // myret_t rvals; // ALLOCATED ON STACK: BAD! // rvals.x = 1; // rvals.y = 2; // // This results in a seg fault! // return (void*) &rvals; // warning: address of stack memory associated with local variable 'rvals' returned } int main(int argc, char* argv[]) { pthread_t p; myret_t* rvals; myarg_t args = {10, 20}; Pthread_create(&p, NULL, mythread, &args); Pthread_join(p, (void*) &rvals); printf("returned %d %d\n", rvals->x, rvals->y); free(rvals); return 0; }
C
#include <stdio.h> char s1[7][10] = {"", "Yakk", "Doh", "Seh", "Ghar", "Bang", "Sheesh"}; char s2[7][10] = {"", "Habb Yakk", "Dobara", "Dousa", "Dorgy", "Dabash", "Dosh"}; int N, a, b; int main() { freopen("data.txt", "r", stdin); scanf("%d", &N) ; for (int i = 1; i <= N; i++) { scanf("%d %d",&a,&b); printf("Case %d: ", i); if ((a==5&&b==6)||(a==6&&b==5)) { printf("Sheesh Beesh\n"); continue; } if (a>b) { printf("%s %s\n",s1[a],s1[b]); }else if (b>a){ printf("%s %s\n", s1[b],s1[a]); }else { printf("%s\n", s2[a]); } } }
C
#include<stdio.h> void swap(int *i,int*j) { int temp=*i; *i=*j; *j=temp; } int main(void) { int a,b; printf("Enter the value of a="); scanf("%d",&a); printf("Enter the value of b="); scanf("%d",&b); swap(&a,&b); printf("a is %d and b is %d\n",a, b); return 0; }
C
#include <stdio.h> #include <string.h> int main(int argc, char *argv[]) { FILE *file = fopen(argv[1], "r"); char file_string[999]; int x = 10; int y = 20; int i; printf("These are printed in an (x, y) format\n\n"); while(!feof(file)) { x = 10; fscanf(file, "%s", file_string); if (file_string[0] == '.' || file_string[0] == '*') { for (i = 0; i < strlen(file_string); i++) { if (file_string[i] == '.') { printf("(%d, %d) = 0 ", x, y); } else { printf("(%d, %d) = 1 ", x, y); } x++; } } else { continue; } printf("\n"); y++; } return 0; }