language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <assert.h> #include "equivalence.h" #include "bryant.h" #include "var.h" #define HAS_CONTRADICTION(F) (F->pars[TRUE_VAR]==FALSE_VAR) #if !defined(max) #define max(a,b) ((a)<(b) ? (b) : (a)) #endif #if !defined(min) #define min(a,b) ((a)<(b) ? (a) : (b)) #endif #define MAX_DEP(F,G) (max(F->max_dep,G->max_dep)) #define NO_DEPENDENCE (-1) #define SWAP_PTRS(type,a,b) do {type tmp; tmp=a; a=b; b=tmp;} while(0) bitset emptyset; /*--------------------------- CONSTRUCTION -----------------------------*/ Equivalence *alloc_equiv(void) { return (Equivalence *) malloc(sizeof(Equivalence)); } Equivalence *make_identity_equiv(void) { Equivalence *F = alloc_equiv(); F->pars[FALSE_VAR] = FALSE_VAR; F->pars[TRUE_VAR] = TRUE_VAR; F->max_dep = NO_DEPENDENCE; return F; } Equivalence *make_equiv_copy(Equivalence *F) { if (IS_TRIVIAL_EQUIV(F)) return F; Equivalence *G = alloc_equiv(); int i; for (i=0; i<=F->max_dep; i++) G->pars[i] = F->pars[i]; G->max_dep = F->max_dep; return G; } void write_equiv_copy(Equivalence *src, Equivalence *dest) { if (IS_TRIVIAL_EQUIV(src)) {dest = src; return;} int i; for (i=0; i<=src->max_dep; i++) dest->pars[i] = src->pars[i]; dest->max_dep = src->max_dep; } /*--------------------------- HELPERS -----------------------------*/ // built from find algorithm on union-find_root wikipedia page // finds the least variable x such that x<->v // Assumes non-trivial Equivalence int find(Equivalence *F, int var){ if (var > F->max_dep) return var; int par=F->pars[var]; // case: par is not a root if (F->pars[par]!=par) { // set parent of var to root of par F->pars[var] = find(F, par); } // parent of var is now var's root return F->pars[var]; } // Are x and y equivalent variables? // Does F |= (x<->y) ? bool are_equiv(Equivalence *F, int x, int y){ return (x==y || find(F, x) == find(F, y)); } bool is_entailed(Equivalence *F, int v) { return are_equiv(F,v,TRUE_VAR); } bool is_disentailed(Equivalence *F, int v) { return are_equiv(F,v,FALSE_VAR); } // send every parent branch directly to root void flatten(Equivalence *F) { if (IS_TRIVIAL_EQUIV(F)) return; int i; for (i=F->max_dep; i>=2; i--) find(F, i); } void expand_max_dep(Equivalence *F, int new_max_dep) { int i; for (i=F->max_dep+1; i<new_max_dep; ++i) { F->pars[i] = i; } F->max_dep = new_max_dep; } void shrink_max_dep(Equivalence *F) { int i = F->max_dep; while (i>=0 && F->pars[i]==i) --i; F->max_dep = i; } bool equiv_equals(Equivalence *F, Equivalence *G) { if (IS_TRIVIAL_EQUIV(F) || IS_TRIVIAL_EQUIV(G)) return F==G; int i; if (F->max_dep != G->max_dep) return false; for (i=0; i<=F->max_dep; i++) { if (F->pars[i]!=G->pars[i]) return false; } return true; } bitset equiv_vars_entailed(Equivalence *F) { bitset entailed = emptyset; if (IS_TRIVIAL_EQUIV(F)) { if (F==FALSE_EQUIV) BITSET_UNIVERSE(entailed); return entailed; } int i; for (i = F->max_dep; i>=2; --i) { if (IS_ENTAILED(F, i)) BITSET_ADD_ELEMENT(entailed, i-VAR_SHIFT); } return entailed; } void compress_path_via(Equivalence *F, int v, int v_root) { int i; for (i=F->max_dep; i>v; i--) { if (F->pars[i]==v) F->pars[i] = v_root; } } /*--------------------------- MAIN ALGS -----------------------------*/ // unify the set containing x and the set containing y // collapses the equivalence to identity and returns false if contradiction arises, true otherwise Equivalence *onion(Equivalence *F, int x, int y) { int x_root, y_root; if (IS_TRIVIAL_EQUIV(F)){ if (F == FALSE_EQUIV || x == y) return F; else F = make_identity_equiv(); x_root = x; y_root = y; } else { x_root = find(F,x); y_root = find(F,y); } if (x_root < y_root) { F->pars[y_root] = x_root; if (y_root > F->max_dep) expand_max_dep(F, y_root); else compress_path_via(F, y_root, x_root); } else if (x_root > y_root) { F->pars[x_root] = y_root; if (x_root > F->max_dep) expand_max_dep(F, x_root); else compress_path_via(F, x_root, y_root); } if (HAS_CONTRADICTION(F)) return FALSE_EQUIV; return F; } Equivalence *init_onion(int x, int y) { return onion(TRUE_EQUIV, x, y); } //----------------------------------------------------- // Equivalence Operations //----------------------------------------------------- Equivalence *equiv_and(Equivalence *F, Equivalence *G) { if (IS_TRIVIAL_EQUIV(F)) { return F == FALSE_EQUIV ? FALSE_EQUIV : make_equiv_copy(G); } else if (IS_TRIVIAL_EQUIV(G)) { return G == FALSE_EQUIV ? FALSE_EQUIV : make_equiv_copy(F); } Equivalence *H = make_identity_equiv(); // turn parents into roots //flatten(F); flatten(G); // Ensure that F->max_dep <= G->max_dep to simplify next 2 for loops if (F->max_dep > G->max_dep) SWAP_PTRS(Equivalence *,F,G); H->max_dep = G->max_dep; int i; // Both F and G have correctly defined arrays up to F->max_dep (inclusive) for (i=0; i<=F->max_dep; i++) { H->pars[i] = i; if (FALSE_EQUIV == onion(H, F->pars[i], G->pars[i])) { free(H); return FALSE_EQUIV; } H->pars[i] = find(H, F->pars[i]); /* // case: H->pars[F->pars[i]] is the new smallest root for i, F->pars[i] and G->pars[i] in H if (H->pars[F->pars[i]] <= H->pars[G->pars[i]]) { H->pars[H->pars[G->pars[i]]] = H->pars[F->pars[i]]; H->pars[i] = H->pars[F->pars[i]]; // case: H->pars[G->pars[i]] is the new smallest root for i, F->pars[i] and G->pars[i] in H } else { H->pars[H->pars[F->pars[i]]] = H->pars[G->pars[i]]; H->pars[i] = H->pars[G->pars[i]]; } // Check for contradiction if HAS_CONTRADICTION(H) { free(H); return FALSE_EQUIV; }*/ } // We are beyond the max_dep for F, so we pretend all F parents are themselves // Therefore F adds no more equivalences, so we just get the rest from G for (i=F->max_dep+1; i<= G->max_dep; i++) { H->pars[i] = i; H->pars[i] = H->pars[G->pars[i]]; // This links i to G[i], by linking directly to it's root in H } flatten(H); return H; } static int common_roots[MAXVAR][MAXVAR]; void init_common_roots(int max_dep) { int i,j; for (i=0; i<=max_dep; ++i) { for (j=0; j<=max_dep; ++j) { common_roots[i][j] = INVALID_VAR; } } } Equivalence *equiv_or(Equivalence *F, Equivalence *G) { if (IS_TRIVIAL_EQUIV(F)) { return F==TRUE_EQUIV ? F : G; } else if (IS_TRIVIAL_EQUIV(G)) { return G==TRUE_EQUIV ? G : F; } Equivalence *H = make_identity_equiv(); H->max_dep = min(F->max_dep, G->max_dep); init_common_roots(H->max_dep); // turn parents into roots //flatten(F); flatten(G); int i, common_root; for (i=0; i<=H->max_dep; i++) { // F and G agree on equivalence to root if (F->pars[i] == G->pars[i]) { H->pars[i] = F->pars[i]; } else { // Check hash table for smaller equivalent variable in H // (a variable j<i that has identical F->pars[j] G->pars[j] pair) common_root = common_roots[F->pars[i]][G->pars[i]]; if (common_root!=INVALID_VAR) { H->pars[i] = common_root; } else { common_roots[F->pars[i]][G->pars[i]] = i; H->pars[i] = i; } } } shrink_max_dep(H); if (H->max_dep < 0) { free(H); return TRUE_EQUIV; } else { return H; } } Equivalence *equiv_or_destructive(Equivalence *F, Equivalence *G) { if (IS_TRIVIAL_EQUIV(F)) { return F==TRUE_EQUIV ? F : G; } else if (IS_TRIVIAL_EQUIV(G)) { return G==TRUE_EQUIV ? G : F; } Equivalence *H = make_identity_equiv(); H->max_dep = min(F->max_dep, G->max_dep); init_common_roots(H->max_dep); // turn parents into roots //flatten(F); flatten(G); int i, common_root; for (i=0; i<=H->max_dep; i++) { // F and G agree on equivalence to root if (F->pars[i] == G->pars[i]) { H->pars[i] = F->pars[i]; // write equivalence to H F->pars[i] = i; G->pars[i] = i; //remove connection to root from F and G } else { common_root = common_roots[F->pars[i]][G->pars[i]]; // case: pair seen before if (common_root!=INVALID_VAR) { H->pars[i] = common_root; // give H connection between them F->pars[i] = i; G->pars[i] = i; //remove connection from F and G } else /* case: pair not seen before */{ common_roots[F->pars[i]][G->pars[i]] = i; H->pars[i] = i; // leave smaller root knowledge in F and G } } } shrink_max_dep(H); if (H->max_dep < 0) { free(H); return TRUE_EQUIV; } else { return H; } } // Intersects T and E, while adding anything that is entailed by T and disentailed by E // as an equivalent variable to root var // T and E should NOT be trivial equivalences (Neither should be) /* Rough relationship between arguments (root_var) / \ T E */ Equivalence *equiv_then_or_else(int root_var, Equivalence *T, Equivalence *E) { Equivalence *H = make_identity_equiv(); H->max_dep = min(T->max_dep, E->max_dep); init_common_roots(H->max_dep); // turn parents into roots //flatten(T); flatten(E); int i, common_root; int temp_H_max_dep = H->max_dep; // This could change during loop for (i=0; i<=temp_H_max_dep; i++) { // case: Then and Else equivs agree on i's least equiv var if (T->pars[i] == E->pars[i]) { H->pars[i] = T->pars[i]; } else if (IS_ENTAILED(T,i) && IS_DISENTAILED(E,i)) { // Therefore (root_var <-> i) if (root_var < i) { H->pars[i] = H->pars[root_var]; } else if (i < root_var) { if (root_var > H->max_dep) expand_max_dep(H, root_var); H->pars[root_var] = H->pars[i] = i; } else { /* i==root_var */ H->pars[i] = i; } } else { // Then and Else disagree on root // Check hash table for smaller equivalent variable in H (var j<i that has identical T->pars[j] E->pars[j]) common_root = common_roots[T->pars[i]][E->pars[i]]; // Write it as root, if it was there if (common_root!=INVALID_VAR) { H->pars[i] = common_root; // Otherwise write i as the least equivalent variable for this key pair } else { common_roots[T->pars[i]][E->pars[i]] = i; H->pars[i] = i; } } } shrink_max_dep(H); if (H->max_dep < 0) { free(H); return TRUE_EQUIV; } else { return H; } } //----------------------------------------------------- // Other algorithms //----------------------------------------------------- Equivalence *equiv_renameArray(Equivalence *F, int count, int mapping[]) { if (IS_TRIVIAL_EQUIV(F)) return F; //flatten(F);--------------------------------------------------------------------------------------------- if (F->max_dep < count) expand_max_dep(F, count); // apply the mapping int i, child_map, par_map; for (i=2; i<=count; i++) { if ((child_map = mapping[i]) == UNUSED_MAPPING_COPY) { child_map = i; } if (F->pars[i] <= 1) { par_map = F->pars[i]; } else if ((par_map = mapping[F->pars[i]]) == UNUSED_MAPPING_COPY) { par_map = F->pars[i]; } else { par_map = mapping[F->pars[i]]; } F->pars[child_map] = par_map; } // redirect vars to their smallest root for (i=2; i<=count; i++) { F->pars[i] = F->pars[F->pars[i]]; // update parent to root if (F->pars[i] > i) { // case: i should actually be the root of its current parent F->pars[F->pars[i]] = i; F->pars[i] = i; } } shrink_max_dep(F); if (F->max_dep < 0) { free(F); return TRUE_EQUIV; } else { return F; } } //----------------------------------------------------- // Deconstructing algorithms //----------------------------------------------------- //remove from F any equivalence relation of the form //v <-> x (for x=/=v) //i.e. remove other variables from v's set void detach(Equivalence *F, int v) { int i; if (F->pars[v]==v) { //find the smallest equivalent variable bigger than v i = v+1; while (i<=F->max_dep && find(F,i)!=v) i++; // case: i is the least equivalent variable to v if (i<=F->max_dep) { int j; // attach all remaining equivalent vars to new root for (j=i; j<=F->max_dep; j++) { if (find(F,j)==v) { F->pars[j] = i; } } } // Otherwise no other equivalent variable - done. // case: v isn't a root } else { // ensure every variable that could be linked through v // is now directly connected to the common root (which isn't v) for (i=v; i<=F->max_dep; i++) find(F,i); F->pars[v]=v; } } void equiv_project_thresh(int thresh, Equivalence *F) { if (IS_TRIVIAL_EQUIV(F)) return; F->max_dep = min(F->max_dep, thresh); } //----------------------------------------------------- // Printing algorithms //----------------------------------------------------- // print roots of each variable void root_print(FILE *stream, Equivalence *F) { if (F == FALSE_EQUIV) {fprintf(stream, "FALSE EQUIV"); return;} if (F == TRUE_EQUIV) {fprintf(stream, "TRUE EQUIV"); return;} int i; flatten(F); printf("Roots:\n"); for (i=0; i<=F->max_dep; i++) { fprintf(stream, "var: %d, root: %d\n", i, F->pars[i]); } } // Not that efficient // Prints equivalent sets, headed by root void equiv_print(FILE *stream, Equivalence *F) { if (F == FALSE_EQUIV) {fprintf(stream, "FALSE EQUIV"); return;} if (F == TRUE_EQUIV) {fprintf(stream, "TRUE EQUIV"); return;} flatten(F); int i, j; bitset seen = emptyset; bitset curr_set; fprintf(stream, "def vars :( "); for (i=2; i<=F->max_dep; ++i) { if (IS_ENTAILED(F,i)) { BITSET_ADD_ELEMENT(seen, i); fprintf(stream, "%d ", i-VAR_SHIFT); } else if (IS_DISENTAILED(F,i)) { BITSET_ADD_ELEMENT(seen, i); fprintf(stream, "~%d ", i-VAR_SHIFT); } } fprintf(stream, ")"); fprintf(stream, "\nequiv sets:("); // print one set per unique root (except singleton sets) for (i=2; i<=F->max_dep; i++) { if (BITSET_IS_MEMBER(seen,i)) continue; BITSET_CLEAR(curr_set); for (j=i+1; j <= F->max_dep; j++) { if (ARE_EQUIV(F,i,j)) { BITSET_ADD_ELEMENT(curr_set, j); } } if (!BITSET_EMPTY(curr_set)) { fprintf(stream, " { %d ", i-VAR_SHIFT); for (j=i+1; j <= F->max_dep; j++) { if (BITSET_IS_MEMBER(curr_set, j)) { BITSET_ADD_ELEMENT(seen, j); fprintf(stream, "%d ", j-VAR_SHIFT); } } fprintf(stream, "} "); } BITSET_ADD_ELEMENT(seen, i); } fprintf(stream, ")"); }
C
/* file: Depuncture.c Description: Depuncture bits by zero-padding deleted bits. The calling syntax is: [output] = Depuncture(input, pun_pattern, tail_pattern ) output = Unpunctured codeword input = Punctured codeword pun_pattern = Puncturing pattern for encoded data bits tail_pattern = Puncturing pattern for encoded tail bits Copyright (C) 2005-2008, Matthew C. Valenti Last updated on May 22, 2008 Function Depuncture is part of the Iterative Solutions Coded Modulation Library. The Iterative Solutions Coded Modulation Library 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. This library 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 this library; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <math.h> #include <mex.h> #include <matrix.h> #include <stdlib.h> /* Input Arguments prhs[0] is input prhs[1] is pun_pattern prhs[2] is tail_pattern /* Output Arguments plhs[0] is output */ /* main function that interfaces with MATLAB */ void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { double *input, *pun_pattern, *tail_pattern; /* inputs */ double *output_p; /* output */ int height; /* height of input matrices */ int pun_period; /* period of puncturing pattern */ int tail_period; /* period of tail */ int pun_bits_per_frame; int unpun_bits_per_frame; int pun_bits_in_tail; int unpun_bits_in_tail; int pun_bits_in_payload; int unpun_bits_in_payload; int pun_bits_per_period; int unpun_bits_per_period; int number_pun_periods; /* number of puncture periods */ int partial_period = 0; /* length of last period (if partial) */ int number_fractional_bits; int temp_count; int i, j, count_punctured; /* counting variables */ /* Check for proper number of arguments */ if ((nrhs < 3 )||(nlhs > 1)) { mexErrMsgTxt("Usage: [output] = Puncture(input, pun_pattern, tail_pattern )"); } else { /* first input is the punctured word */ input = mxGetPr(prhs[0]); pun_bits_per_frame = mxGetN(prhs[0]); if ( mxGetM(prhs[0]) != 1 ) mexErrMsgTxt("Input must be a row vector"); /* second input is the puncturing pattern for coded data bits */ pun_pattern = mxGetPr(prhs[1]); pun_period = mxGetN(prhs[1]); height = mxGetM(prhs[1]); unpun_bits_per_period = height*pun_period; /* number of unpunctured bits per payload period */ /* third input is the puncturing pattern for coded tail bits */ tail_pattern = mxGetPr(prhs[2]); tail_period = mxGetN(prhs[2]); if ( ( mxGetM(prhs[2])!=height )&&( tail_period > 0 ) ) mexErrMsgTxt("Number rows in tail_pattern must match the number in pun_pattern"); unpun_bits_in_tail = height*tail_period; /* number of unpunctured bits in the tail */ /* printf( "Height = %d\n", height ); printf( "Puncture Period = %d\n", pun_period ); printf( "Tail Period = %d\n", tail_period ); */ /* determine number of punctured bits per payload period (non-tail) */ pun_bits_per_period = 0; for (i=0;i<pun_period*height;i++) pun_bits_per_period += (int) pun_pattern[i]; /* printf( "Punctured bits per payload period = %d\n", pun_bits_per_period ); */ /* determine number of punctured bits in the tail */ pun_bits_in_tail = 0; for (i=0;i<tail_period*height;i++) pun_bits_in_tail += (int) tail_pattern[i]; /* printf( "Punctured bits in the tail = %d\n", pun_bits_in_tail ); */ /* determine how many periods in payload */ pun_bits_in_payload = pun_bits_per_frame - pun_bits_in_tail; number_pun_periods = floor( pun_bits_in_payload/pun_bits_per_period ); /* printf( "Number Puncture Periods = %d\n", number_pun_periods ); */ /* determine if there is a fractional period in payload */ number_fractional_bits = pun_bits_in_payload - number_pun_periods*pun_bits_per_period; /* printf( "Number of punctured fractional bits = %d\n", number_fractional_bits ); */ if (number_fractional_bits > 0 ) { temp_count = 0; i = 0; /* column */ while (temp_count < number_fractional_bits ) { for (j = 0; j<height; j++ ) { /* row */ temp_count += pun_pattern[i*height+j]; } if ( temp_count > number_fractional_bits ) mexErrMsgTxt( "Incomplete column of puncturing pattern" ); i++; partial_period = i; } } /* printf( "Length of Partial Period = %d\n", partial_period ); */ unpun_bits_in_payload = unpun_bits_per_period*number_pun_periods + height*partial_period; unpun_bits_per_frame = unpun_bits_in_payload + unpun_bits_in_tail; /* printf( "Number of Unpunctured Bits = %d\n", unpun_bits_per_frame ); */ /* set up output */ plhs[0] = mxCreateDoubleMatrix(height, unpun_bits_per_frame/height, mxREAL ); output_p = mxGetPr(plhs[0]); /* unpuncture the coded data bits */ count_punctured = 0; for (j=0;j<number_pun_periods;j++) { /* go through each period */ for (i=0;i<height*pun_period;i++) { temp_count = pun_pattern[i]; while (temp_count > 0) { output_p[j*pun_period*height+i]+=input[count_punctured]; count_punctured++; temp_count--; } } } if (partial_period > 0) { /* go through last (partial) period */ for (i=0;i<height*partial_period;i++) { temp_count = pun_pattern[i]; while (temp_count > 0) { output_p[number_pun_periods*pun_period*height+i]+=input[count_punctured]; count_punctured++; temp_count--; } } } /* depuncture the coded tail bits New 11/21/05: if height = 4, then the tail bits are rearranged to conform to UMTS convention */ if ( height == 4 ) { /* upper RSC's tail bits */ for (i=0;i<tail_period;i++) { for (j=0;j<2;j++) { temp_count = tail_pattern[i*4+j]; while( temp_count > 0 ) { output_p[unpun_bits_in_payload + i*4+j] += input[count_punctured]; count_punctured++; temp_count--; } } } /* lower RSC's tail bits */ for (i=0;i<tail_period;i++) { for (j=0;j<2;j++) { temp_count = tail_pattern[i*4+j+2]; while( temp_count > 0 ) { output_p[unpun_bits_in_payload + i*4+j+2] += input[count_punctured]; count_punctured++; temp_count--; } } } } else { for (i=0;i<unpun_bits_in_tail;i++) { temp_count = tail_pattern[i]; while( temp_count > 0 ) { output_p[unpun_bits_in_payload + i] += input[count_punctured]; count_punctured++; temp_count--; } } } } return; }
C
/* ============================================================================ Name : CompoundInterst.c Author : Jerin Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> int main(void) { float re; float r; int t=0; int N; float principle; printf("Enter the interest rate \n"); scanf("%f",&re); r=(re/100); printf("Enter the interest amount \n"); scanf("%f",&principle); printf("Enter the year\n"); scanf("%d",&N); for(t=1;t<(N+1);t++) { principle=principle+principle*r; } printf("%f",principle); return 0; }
C
#include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ int arr[100000],i,j; arr[0]=-1; srand(time(NULL)); for(i=1;i<100000;i++){ arr[i]=rand(); } for(i=2;i<100000;i++){ int temp=arr[i]; for(j=i;temp<=arr[j-1];j--){ arr[j]=arr[j-1]; } arr[j]=temp; } for(i=0;i<100000;i++) printf("%d ",arr[i]); printf("\n"); return 0; system("psuse"); }
C
#include "Text_LCD.h" void LCD_pulse_enable(void) // 하강 에지에서 동작 { PORT_CONTROL |= (1 << E_PIN); // E를 HIGH로 _delay_us(1); PORT_CONTROL &= ~(1 << E_PIN); // E를 LOW로 _delay_ms(1); } void LCD_write_data(uint8_t data) { PORT_CONTROL |= (1 << RS_PIN); // 문자 출력에서 RS는 1 if(MODE == 8) { PORT_DATA = data; // 출력할 문자 데이터 LCD_pulse_enable(); } else { PORT_DATA = data & 0xF0; // 상위 4비트 LCD_pulse_enable(); PORT_DATA = (data << 4) & 0xF0; // 하위 4비트 LCD_pulse_enable(); } _delay_ms(2); } void LCD_write_command(uint8_t command) { PORT_CONTROL &= ~(1 << RS_PIN); // 명령어 실행에서 RS는 0 if(MODE == 8) { PORT_DATA = command; // 데이터 핀에 명령어 전달 LCD_pulse_enable(); // 명령어 실행 } else { PORT_DATA = command & 0xF0; // 상위 4비트 LCD_pulse_enable(); PORT_DATA = (command << 4) & 0xF0; // 하위 4비트 LCD_pulse_enable(); } _delay_ms(2); } void LCD_clear(void) { LCD_write_command(COMMAND_CLEAR_DISPLAY); _delay_ms(2); } void LCD_init(void) { _delay_ms(50); // 초기 구동 시간 // 연결 핀을 출력으로 설정 if(MODE == 8) DDR_DATA = 0xFF; else DDR_DATA |= 0xF0; PORT_DATA = 0x00; DDR_CONTROL |= (1 << RS_PIN) | (1 << RW_PIN) | (1 << E_PIN); // RW 핀으로 LOW를 출력하여 쓰기 전용으로 사용 PORT_CONTROL &= ~(1 << RW_PIN); if(MODE == 8) LCD_write_command(COMMAND_8_BIT_MODE); // 8비트 모드 else { LCD_write_command(0x02); // 4비트 모드 추가 명령 LCD_write_command(COMMAND_4_BIT_MODE); // 4비트 모드 } // display on/off control // 화면 on, 커서 off, 커서 깜빡임 off uint8_t command = 0x08 | (1 << COMMAND_DISPLAY_ON_OFF_BIT); LCD_write_command(command); LCD_clear(); // 화면 지움 // Entry Mode Set // 출력 후 커서를 오른쪽으로 옮김, 즉, DDRAM의 주소가 증가하며 화면 이동은 없음 LCD_write_command(0x06); } void LCD_write_string(char *string) { uint8_t i; for(i = 0; string[i]; i++) // 종료 문자를 만날 때까지 LCD_write_data(string[i]); // 문자 단위 출력 } void LCD_goto_XY(uint8_t row, uint8_t col) { col %= 16; // [0 15] row %= 2; // [0 1] // 첫째 라인 시작 주소는 0x00, 둘째 라인 시작 주소는 0x40 uint8_t address = (0x40 * row) + col; uint8_t command = 0x80 + address; LCD_write_command(command); // 커서 이동 }
C
#include <stdio.h> #include <getopt.h> #include <string.h> #include <stdlib.h> #include <string.h> void imprime_uso(); void procesarArchivo(const char * separador,int primeraLinea,int incremento,int numerarVacias,int cantidadVaciasJuntas,char * archivo); int main(int argc, char *argv[]) { int index; int primeraLinea,incremento,cantidadVaciasJuntas; int siguiente_opcion; char * ultimoParametro=NULL; char * archivo=NULL; const char * separador=NULL; int numerarVacias=1; incremento=1; primeraLinea=1; /* Una cadena que lista las opciones cortas válidas */ const char* const op_cortas = "hs:v:i:tl:" ; /* Una estructura de varios arrays describiendo los valores largos */ const struct option op_largas[] = { { "help", 0, NULL, 'h'}, { "number-separator", 2, NULL, 's'}, { "starting-line-number", 2, NULL, 'v'}, { "line-increment", 2, NULL, 'i'}, { "non-empty", 2, NULL, 't'}, { "join-blank-lines", 2, NULL, 'l'}, { NULL, 0, NULL, 0 } }; /*if (argc == 1){ imprime_uso(); exit(EXIT_SUCCESS); }*/ while (1){ /* Llamamos a la función getopt */ siguiente_opcion = getopt_long (argc, argv, op_cortas, op_largas, NULL); if (siguiente_opcion == -1) break; /* No hay más opciones*/ switch (siguiente_opcion) { case 'h' : /* -h o --help */ imprime_uso(); exit(EXIT_SUCCESS); case 's' : /* -s o --number-separator*/ separador=optarg; //printf("Separador %s\n",separador); break; case 'v' : /* -v o --starting-line-number */ primeraLinea = atoi(optarg); /* optarg contiene el argumento de -o */ //printf("primera linea %d\n",primeraLinea); break; case 'i' : /* -i o --line-increment */ incremento = atoi(optarg); /* optarg contiene el argumento de -o */ //printf("incremento %d\n",incremento); break; case 't' : /* -t o --non-empty */ numerarVacias=0; //printf("numerarVacias %d\n",numerarVacias); break; case 'l' : /* -l o --join-blank-lines */ cantidadVaciasJuntas = atoi(optarg); /* optarg contiene el argumento de -o */ //printf("cantidadVaciasJuntas %d\n",cantidadVaciasJuntas); break; case '?' : /* opción no valida */ imprime_uso(); exit(1); case -1 : /* No hay más opciones */ break; default : exit(1); } } index= optind; if(index==argc){ archivo=NULL; procesarArchivo(separador,primeraLinea,incremento,numerarVacias,cantidadVaciasJuntas,argv[index]); }else{ for (index = optind; index < argc; index++){ procesarArchivo(separador,primeraLinea,incremento,numerarVacias,cantidadVaciasJuntas,argv[index]);} } return 0; } void procesarArchivo(const char * separador,int primeraLinea,int incremento,int numerarVacias,int cantidadVaciasJuntas,char * archivo){ FILE * entrada=NULL; if (cantidadVaciasJuntas==0) cantidadVaciasJuntas=1; if (primeraLinea==0) primeraLinea=1; if(incremento==0) incremento=1; if(archivo==NULL){ entrada=stdin; }else{ entrada=fopen(archivo,"r"); //entrada=fopen("/home/nico/workspace/Tp Datos/ORGATP0/Debug/entrada.txt","r"); } char c; int imprimioPrimerLinea=0; int lineaActual=primeraLinea; int lineaVacia=0; int lineasVaciasAcumuladas=0; while((c=getc(entrada))!=EOF){ if (imprimioPrimerLinea==0){ imprimioPrimerLinea=1; printf("%i%s ",lineaActual,separador); } if (c=='\n'){ if (numerarVacias==1){ if (lineaVacia==1){ if (lineasVaciasAcumuladas==cantidadVaciasJuntas){ printf("%i%s ",lineaActual,separador); printf("\n"); lineaActual = lineaActual + incremento; lineasVaciasAcumuladas=1; } else { lineasVaciasAcumuladas++; } } else { if (lineasVaciasAcumuladas==cantidadVaciasJuntas){ printf("\n"); lineaActual= lineaActual + incremento; lineaVacia=1; lineasVaciasAcumuladas=1; } else{ lineasVaciasAcumuladas++; if (lineasVaciasAcumuladas==1){ printf("\n"); lineaVacia=1; lineaActual= lineaActual + incremento; } } } }else { if (lineasVaciasAcumuladas==cantidadVaciasJuntas){ printf("\n"); if (lineaVacia==0) lineaActual= lineaActual + incremento; lineaVacia=1; lineasVaciasAcumuladas=1; } else { lineasVaciasAcumuladas++; if (lineasVaciasAcumuladas==1){ printf("\n"); lineaVacia=1; lineaActual = lineaActual + incremento; } } } } else{ if (lineasVaciasAcumuladas>1){ if(numerarVacias==1){ int i=1; for (i=1;i<lineasVaciasAcumuladas;i++){ printf("%i%s \n",lineaActual,separador); lineaActual= lineaActual + incremento; } lineasVaciasAcumuladas=0; } else { int i=1; for (i=1;i<lineasVaciasAcumuladas;i++){ printf("\n"); lineaVacia=1; } lineasVaciasAcumuladas=0; } } if (lineaVacia==1){ lineaVacia=0; printf("%i%s ",lineaActual,separador); lineasVaciasAcumuladas=0; } printf("%c",c); } } fclose(entrada); } void imprime_uso(){ printf("USAGE:\n" "tp0 [OPTION]...[FILE]...\n" "Write each FILE to standard output, with line numbers added. With no FILE, or when FILE ir -,\n" "read standard input\n" "\n" "OPTIONS:\n" "-h, --help Print this message and quit\n" "-s, --number-separator (mandatory argument)\n" "-v, --starting-line-number (mandatory argument)\n" "-i, --line-increment (mandatory argument)\n" "-l, --join-blank-lines (mandatory argument)\n" "-t, --non-empty\n"); };
C
/************************************************************************** * Copyright 2015 Sensel, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **************************************************************************/ /** * Read Contacts * by Aaron Zarraga - Sensel, Inc * * This opens a Sensel sensor, reads contact data, and prints the data to the console. */ //Inclue a sleep function #ifdef WIN32 #include <Windows.h> #else #include <unistd.h> #endif #include <stdio.h> #include <signal.h> //so we can catch a ctrl+c key event #include "sensel.h" volatile sig_atomic_t ctrl_c_requested = false; contact_t *contacts; int n_contacts = 0; void handle_ctrl_c(int sig) { ctrl_c_requested = true; } int main() { signal (SIGINT, handle_ctrl_c); bool sensel_sensor_opened = false; sensel_sensor_opened = senselOpenConnection(0); if(!sensel_sensor_opened) { printf("Unable to open Sensel sensor!\n"); return -1; } //Enable contact sending senselSetFrameContentControl(SENSEL_FRAME_CONTENT_CONTACTS_MASK); //Enable scanning senselStartScanning(); printf("Touch sensor! (press ctrl-c to quit)...\n"); while(!ctrl_c_requested) { senselReadFrame(&contacts, &n_contacts, NULL, NULL); for(int i = 0; i < n_contacts; i++) { float force = contacts[i].total_force; float x_mm = contacts[i].x_pos_mm; float y_mm = contacts[i].y_pos_mm; //Read out shape information (ellipses) float major = contacts[i].major_axis_mm; float minor = contacts[i].minor_axis_mm; float orientation = contacts[i].orientation_degrees; int id = contacts[i].id; int event_type = contacts[i].type; char* event; switch (event_type) { case SENSEL_EVENT_CONTACT_INVALID: event = "invalid"; break; case SENSEL_EVENT_CONTACT_START: senselSetLEDBrightness(id, 100); //turn on LED event = "start"; break; case SENSEL_EVENT_CONTACT_MOVE: event = "move"; break; case SENSEL_EVENT_CONTACT_END: senselSetLEDBrightness(id, 0); //turn LED off event = "end"; break; default: event = "error"; } printf("Contact ID %d, event=%s, mm coord: (%f, %f), force=%f, " \ "major=%f, minor=%f, orientation=%f\n", id, event, x_mm, y_mm, force, major, minor, orientation); } if(n_contacts > 0) printf("****\n"); } printf("Closing application\n"); if(sensel_sensor_opened) { #ifdef WIN32 Sleep(1000); #else sleep(1); //Let ctrl-c-trashed packets clear out #endif senselSetLEDBrightnessAll(0); senselStopScanning(); senselCloseConnection(); } printf("Done!\n"); }
C
#include<stdio.h> main() { char ch; printf("enter the hex value.."); scanf("%x",&ch); printf("before swaping nibble....%x\n",ch); ch=ch>>4|ch<<4; printf("after swaping nibble....%x\n",ch); }
C
/* ** in_str.c for 42shlib in /media/data/all/projects/42sh-v1/lib/my/src/string ** ** Made by kevin labbe ** Login <labbe_k@epitech.net> ** ** Started on Tue Apr 23 14:26:16 2013 kevin labbe ** Last update Tue Apr 23 14:26:23 2013 kevin labbe */ #include "my.h" int in_str(char chr, char *str) { while (*str) { if (chr == *str) return (1); str++; } return (0); }
C
#include<stdio.h> void main(void) { int a; for(a = 0; a < 5; a++) { printf("a is equal to %d\n", a); } printf("a is equal to %d and I've finished\n", a); }
C
#include "main.h" static int usage() { printf("./rpi-toolbox util read|write [port] [0|1]"); return -1; } int util_main(int argc, const char* argv[]) { if (argc < 5) { return usage(); } init_gpio(); int port = atoi(argv[3]); int on = atoi(argv[4]); if (strcmp(argv[2], "write") == 0) { OUT_GPIO(port); printf("enabled port for writing %d\n", port); if (on) { GPIO_WRITE(port, 1); printf("turn on port %d\n", port); } else { GPIO_WRITE(port, 0); printf("turn off port %d\n", port); } } else { INP_GPIO(port); printf("enabled port for reading %d\n", port); int on = GPIO_READ(port); printf("port %d status %d", port, on ? 1 : 0); } clean_gpio(); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdbool.h> typedef struct graph graph; struct graph{ size_t v_count; bool *isvisited; bool **adj_matrix; int *prev_list; }; graph* create_graph(int); void set_edge(graph*,int,int,bool); bool dfs(graph*,int,int); int main(){ graph *g = create_graph(7); set_edge(g,0,1,1); set_edge(g,0,2,1); set_edge(g,1,3,1); set_edge(g,1,4,1); set_edge(g,2,5,1); set_edge(g,2,6,1); int start_node = 0,goal_node = 5; if(dfs(g,start_node,goal_node)){ while(goal_node != -1){ printf("%d, ",goal_node); goal_node = g->prev_list[goal_node]; } } } graph* create_graph(int v){ graph *g = malloc(sizeof(graph)); g->v_count = v; g->isvisited = calloc(v,sizeof(bool)); g->adj_matrix = malloc(sizeof(bool*) * v); for(int i = 0;i < v;i++){ g->adj_matrix[i] = calloc(v,sizeof(bool)); } g->prev_list = malloc(sizeof(int) * v); memset(g->prev_list,-1,sizeof(int) * v); return g; } void set_edge(graph *g,int v1,int v2,bool w){ g->adj_matrix[v1][v2] = w; g->adj_matrix[v2][v1] = w; } bool dfs(graph *g,int at,int goal){ g->isvisited[at] = 1; for(int to = 0;to < g->v_count;to++){ if(g->adj_matrix[at][to] && !g->isvisited[to]){ g->prev_list[to] = at; if(to == goal){ return 1; } if(dfs(g,to,goal)){ return 1; } } } return 0; }
C
// run it by gcc -o pthread pthread.c -lpthread #include<stdio.h> #include<stdlib.h> #include<pthread.h> #include<unistd.h> void *myfunc(void *myvar); int main() { pthread_t thread1, thread2; char *msg1="First thread"; char *msg2="Second thread"; int ret1,ret2; ret1=pthread_create(&thread1,NULL,myfunc,(void *) msg1); ret2=pthread_create(&thread2,NULL,myfunc,(void *) msg2); printf("Main function after pthread_create\n"); pthread_join(thread1,NULL); pthread_join(thread2,NULL); printf("First thread ret1= %d\n",ret1); printf("Second thread ret1= %d\n",ret2); return 0; } void *myfunc(void *myvar){ char *msg; msg=(char *) myvar; int i; for(i=0;i<10;i++){ printf("%s %d\n",msg,i); sleep(1); } return NULL; }
C
#include <stdio.h> int main() { int num; int m,n; printf("请输入A(B)矩阵的行数(列数)和列数(行数)[行数小于列数]:"); scanf("%d %d",&m,&n); int a[m][n]; int b[n][m]; for(int i = 0;i < m;i++) { for(int j = 0; j < n; j++) { printf("请输入a[%d][%d](b[%d][%d])的值:",i,j,j,i); scanf("%d",&num); a[i][j]= num; b[j][i]= num; } } int c[m][m]; for(int i = 0;i < m; i++) { for(int j = 0; j < m; j++) { c[i][j]= 0; for(int k = 0; k < n; k++)//该循环得到每一个变量的值 { c[i][j]= c[i][j]+a[i][k]*b[k][j]; } } } //以行为单位对结果进行输入 //每一行的特定位置都要判断是否输入'|' , ' ' , '*' , '=' for(int i = 0; i < n; i++) { if(i < m) { printf("| "); } else { printf(" "); } for(int j = 0; j< n; j++) { if(i < m) { printf("%-2d ",a[i][j]); } else { printf(" "); } } if(i< m) { printf("|"); } else { printf(" "); } if(i == n / 2) { printf(" * "); } else { printf(" "); } printf("| "); for(int k = 0;k < m; k++) { printf("%-2d ",b[i][k]); } printf("|"); if(i == n / 2) { printf("= "); } else { printf(" "); } if(i < m) { printf("| "); } else { printf(" "); } for(int l = 0; l < m; l++) { if(i < m) { printf(" %-4d ",c[i][l]); } else { printf(" "); } } if(i < m) { printf("|"); } else { printf(" "); } printf("\n"); } return 0; }
C
#include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "numstoany.h" #include "xmemtools.h" int main(int argc, char *argv[], __attribute__((unused)) char *envp[]) { unsigned short inpbase = 0; unsigned short outbase = 0; char *number = NULL; char *characters = NULL; char *output; unsigned long length; int opt; while((opt = getopt(argc, argv, ":i:o:n:s:")) != -1) { switch(opt) { case 'i': inpbase = atoi(optarg); break; case 'o': outbase = atoi(optarg); break; case 'n': number = strdup(optarg); break; case 's': length = strlen(optarg); characters = strdup(optarg); break; case ':': die("Option -%c requires an argument\n", optopt); break; case '?': die("Unknown option -%c\n", optopt); break; } } if (inpbase && number && outbase) { output = numberconv(number, inpbase, outbase); puts(output); xfree(output); } else if (characters && outbase) { number = xmalloc(4); for (unsigned long i = 0; i < length; ++i) { snprintf(number, 4, "%d", characters[i]); output = numberconv(number, 10, outbase); printf("%s ", output); xfree(output); } xfree(characters); putc('\n', stdout); } else { die("Not enough parameters or wrong values\n"); } xfree(number); return 0; }
C
//////////////////////////////////////////////////////////// // reg.h // Library Management Interface register contents to KSZ9896 switch // b.r.koball // k.i.fire // V1.0 // 2018-11-07 // //////////////////////////////////////////////////////////// #include "reg.h" //#ifdef HELP #include <stdio.h> #include <string.h> //#endif const char *bit_rep[16] = { [ 0] = "0000", [ 1] = "0001", [ 2] = "0010", [ 3] = "0011", [ 4] = "0100", [ 5] = "0101", [ 6] = "0110", [ 7] = "0111", [ 8] = "1000", [ 9] = "1001", [10] = "1010", [11] = "1011", [12] = "1100", [13] = "1101", [14] = "1110", [15] = "1111", }; void spi_execute(uchar command, uint reg_adr, uint* reg_val, uint reg_valN) { uint spi_bufferN = 4 + (reg_valN ? reg_valN : 1); uchar spi_buffer[spi_bufferN]; // assemble byte-wise spi serial command in spi_buffer[] array spi_buffer[0] = command; // align spi address for spi command format reg_adr <<= 5; spi_buffer[3] = (unsigned char) (reg_adr & 0x000000E0); reg_adr >>= 8; spi_buffer[2] = (unsigned char) (reg_adr & 0x000000FF); reg_adr >>= 8; spi_buffer[1] = (unsigned char) (reg_adr & 0x000000FF); if (reg_valN == 0) { spi_buffer[4] = 0; } for (uint i=0; i<reg_valN; i++) { spi_buffer[4+i] = reg_val[i]; } #ifdef HELP // write buffer contents to console printf("SPI command\n"); for (uint i=0; i<spi_bufferN; i++) { printf("spi_buffer[%i]= 0x%02X\n",i,spi_buffer[i]); } printf("\n"); #endif wiringPiSPIDataRW(CHANNEL, spi_buffer, spi_bufferN); #ifdef HELP printf("returned\n"); if (reg_valN == 0) { printf("0x%02X\n",spi_buffer[4]); } else for (int i=0; i< spi_bufferN;i++) { printf("0x%02X\n",spi_buffer[4+i]); } #endif if (reg_valN == 0) { reg_val[0] = spi_buffer[4]; } else for (int i=0; i< reg_valN;i++) { reg_val[i] = spi_buffer[4+i]; } } void spi_write_reg(uint reg_adr, uint* reg_val, uint reg_valN) { spi_execute(0x40, reg_adr, reg_val, reg_valN); } void spi_write_reg(uint reg_adr, uint reg_val) { spi_write_reg(reg_adr, &reg_val, 1); } void spi_read_reg(uint reg_adr, uint* reg_val, uint reg_valN) { for (uint i=0; i < reg_valN; i++) { reg_val[i] = 0; } spi_execute(0x60, reg_adr, reg_val, reg_valN); } uint spi_read_reg(uint reg_adr) { uint reg_val; spi_execute(0x60, reg_adr, &reg_val, 0); return reg_val; } // various setup for spi bus and our mux selection int spi_setup() { // Init wiringPi bitwise interface. if(wiringPiSetup() == -1){ // initialize wiringPi failed return EXIT_FAILURE; } pinMode(spi_mux_sel, OUTPUT); digitalWrite(spi_mux_sel, HIGH); // Init wiringPi spi interface. // CHANNEL = chip select, // bus speed = 500KHz // returns fd, but we don't use it? wiringPiSPISetup(CHANNEL, 500000); /* regval = read_reg(regadr); printf("Reg 0x%04X value is now: 0x%02X ", regadr, regval); printf("0b%s%s\n", bit_rep[regval >> 4], bit_rep[regval & 0x0F]); printf("Reg 0x%04X value will be: 0x%02X ", regadr, newregval); printf("0b%s%s\n", bit_rep[newregval >> 4], bit_rep[newregval & 0x0F]); printf("OK (y/n)?"); c = getc(stdin); if (c != 'y') { printf("reg write ABORTED\n"); exit(EXIT_FAILURE); } */ return EXIT_SUCCESS; } void spi_teardown() { digitalWrite(spi_mux_sel, LOW); }
C
#include <stdio.h> int cube(int x) { return x*x*x; } int s(int n) { int i, sum=0; for (i = 1; i <= n; i++) { sum += cube(i); } return sum; } int main(int argc, const char *argv[]) { int n, i; scanf("%d", &n); for (i = 1; s(i) <= n; i++) {} printf("%d\n", i-1); return 0; }
C
// Use a PWM to adjust the brightness of LED1 #include "wiced.h" #define PWM_PIN WICED_PWM_5 void application_start( ) { float duty_cycle = 50.0; wiced_init(); /* Initialize the WICED device */ wiced_gpio_deinit(WICED_SH_LED1); // Need to de-init the GPIO if it is already set to drive the LED while ( 1 ) { wiced_pwm_init(PWM_PIN, 1000, duty_cycle); wiced_pwm_start(PWM_PIN); duty_cycle += 1.0; if(duty_cycle > 100.0) { duty_cycle = 0.0; } wiced_rtos_delay_milliseconds( 10 ); } }
C
/** * @author: Anthony Palumbo * date: 12-27-2016 * description: Generates a text file with random numbers. */ #include <stdlib.h> #include <stdio.h> #define NUM_OF_INTEGERS 50000 #define MAX_VAL 1000 /** * Main function that is run. * @return: 0 on exit success */ int main(void) { FILE *pFile = fopen("input/test.txt", "a"); int ctr, num; // Generates the random numbers and adds them to the file. for (ctr = 0; ctr < NUM_OF_INTEGERS - 1; ctr++) { num = rand() % MAX_VAL; fprintf(pFile, "%d\n", num); } // Adds the last number without a newline character. num = rand() % MAX_VAL; fprintf(pFile, "%d", num); fclose(pFile); return 0; }
C
#include<stdio.h> int main(void) { int i,c,n,a=1,b=10; printf("\n enter the number"); scanf("%d",&n); if(a<b) { for(i=1;i<=n;i++); { c++; } } if(c==2) { printf("\n given no.is a prime no"); } else { printf("\n ginen no. is not a prime no."); } }
C
/*! \file \brief Library for implementing linkedlists */ #include "linkedlist.h" #include <stdlib.h> #include <string.h> #define SUCCESS 1 #define FAIL 0 #define COMP_CALLBACK int (*comparator)(void *a, void *b) #ifdef DEBUG #define DEBUG_OUTPUT(string) (printf("[debug] %s\n",string)) #else #define DEBUG_OUTPUT(string) #endif /* PRIVATE */ /*! * \brief Search item in the list in position index starting from the first element * \param[in] start item * \param[in] index of the item * \return Item in the list in position index starting from the first element */ void *get_item_fwd(item *list, unsigned int index) { if (list == NULL) { return NULL; } if (index == 0) { return list->value; } return get_item_fwd(list->next, --index); } /*! * \brief Search item in the list in position index starting from the last element * \param[in] start item * \param[in] index of the item * \return Item in the list in position index starting from the last element */ void *get_item_rev(item *list, unsigned int index) { if (list == NULL) { return NULL; } if (index == 0) { return list->value; } return get_item_rev(list->prev, --index); } /*! * \brief Determine if an item exists in a list * \param[in] current item compared * \param[in] value of the item searched * \param[in] comparator function for items * \return 1 if the item is found, 0 if not */ int item_exists(item *list, void *value, int (*comparator)(void *a, void *b)) { if (list == NULL) { return 0; } if (comparator(value, list->value) == 0) { return 1; } return item_exists(list->next, value, comparator); } /*! * \brief Determine the position of an item exists in a list * \param[in] current item compared * \param[in] value of the item searched * \param[in] comparator function for items * \param[in] current position evaluated * \return pos value if the item is found, -1 if not */ int item_position(item *list, void *value, int (*comparator)(void *a, void *b), int pos) { if (list == NULL) { return -1; } if (comparator(value, list->value) == 0) { return pos; } return item_position(list->next, value, comparator,pos+1); } /*! * \brief Remove the first ocurrence of an item in the list * \param[in] current item compared * \param[in] value of the item searched * \param[in] comparator function for items * \return 1 if the item is found, 0 if not */ int item_remove(item *list, void *value, int (*comparator)(void *a, void *b)) { if (list == NULL) { return 0; } if (comparator(value, list->value) == 0) { //it is necessary to free the list->value //free(temp); list->next->prev=list->prev; *list=*list->next; return 1; } return item_remove(list->next, value, comparator); } /*! * \brief Sort the list using bubble sort algorithm (ascending) * \param[in] list to order * \param[in] comparator function for items * \return head of the ordered list */ item *bubble_sort(item *list, int (*comparator)(void *a, void *b)) { item *head = list; register int swapped; do { list = head; swapped = 0; while (list->next) { if (comparator(list->value, list->next->value) > 0) { void *temp = list->value; list->value = list->next->value; list->next->value = temp; swapped = 1; } list = list->next; } } while (swapped); return head; } /*! * \brief Sort the list using bubble sort algorithm (ascending) * \param[in] list to order * \param[in] comparator function for items * \return ordered list, NULL if the list as no item */ item *sort_list(item *list, int (*comparator)(void *a, void *b)) { if (list == NULL) { return NULL; } return bubble_sort(list, comparator); } /*! * \brief Clear the list from memory * \param[in] list to clear * \param[in] method for clear the list * \return SUCCESS if the list is cleared */ int clear_list(item *list, void (*free_value)(void *)) { if (list == NULL) { return SUCCESS; } clear_list(list->next, free_value); list->next = NULL; if (free_value != NULL) { free_value(list->value); } else { free(list->value); } list->value = NULL; free(list); //DEBUG_OUTPUT("item removed"); return SUCCESS; } /*! * \brief Print the elements of a list * \param[in] list/item to print * \param[in,out] output in which the list is printed * \param[in] method for printing the value of the item * \param[in] method for determining if the item is visible */ void print_list(item *list, FILE *output, void to_string(FILE *,void *), int (*is_visible)(void *)) { if (list != NULL) { if (is_visible == NULL || is_visible(list->value)) { to_string(output, list->value); } print_list(list->next, output, to_string, is_visible); } } /* PUBLIC */ /*! * \brief Create empty list * \return List created */ linkedlist *ll_create() { linkedlist *list = malloc(sizeof(linkedlist)); if (list == NULL) { fprintf(stderr, "Error: could not allocate memory for linkedlist\n"); exit(EXIT_FAILURE); } list->head = NULL; list->leaf = NULL; list->current = NULL; list->size = 0; //DEBUG_OUTPUT("linkedlist created"); return list; } /*! * \brief Push element in the first position of a list * \param[in,out] list to modify * \param[in] item to include in the first position * \return SUCCESS if the element is pushed correctly, EXIT_FAILURE if not */ int ll_push_first(linkedlist *list, void *value) { item *temp = malloc(sizeof(item)); if (temp == NULL) { fprintf(stderr, "Error: could not allocate memory for item\n"); exit(EXIT_FAILURE); } temp->value = value; temp->prev = NULL; temp->next = list->head; if (list->head == NULL) { list->leaf = temp; } else { list->head->prev = temp; } list->head = temp; list->size += 1; return SUCCESS; } /*! * \brief Push element in the last position of a list * \param[in,out] list to modify * \param[in] item to include in the last position * \return SUCCESS if the element is pushed correctly, EXIT_FAILURE if not */ int ll_push_last(linkedlist *list, void *value) { item *temp = malloc(sizeof(item)); if (temp == NULL) { fprintf(stderr, "Error: could not allocate memory for item\n"); exit(EXIT_FAILURE); } temp->value = value; temp->prev = list->leaf; temp->next = NULL; if (list->head == NULL) { list->head = temp; list->leaf = temp; } else { list->leaf->next = temp; list->leaf = temp; } list->size += 1; return SUCCESS; } /*! * \brief Obtain first element of the list * \param[in] list * \return First element of the list */ void *ll_get_first(linkedlist *list) { return list->head->value; } /*! * \brief Obtain last element of the list * \param[in] list * \return Last element of the list */ void *ll_get_last(linkedlist *list) { return list->leaf->value; } /*! * \brief Obtain first element of the list and delete it from the list * \param[in,out] list * \return First element of the list */ void *ll_pop_first(linkedlist *list) { item *temp = list->head; void *value; if (temp == NULL) { //DEBUG_OUTPUT("nothing to pop from beginning of list"); return NULL; } list->head = temp->next; if (list->head != NULL) { list->head->prev = NULL; } value = temp->value; free(temp); list->size--; //DEBUG_OUTPUT("first item popped from list"); return value; } /*! * \brief Obtain last element of the list and delete it from the list * \param[in,out] list * \return Last element of the list */ void *ll_pop_last(linkedlist *list) { item *temp = list->leaf; void *value; if (temp == NULL) { //DEBUG_OUTPUT("nothing to pop from end of list"); return NULL; } list->leaf = temp->prev; if (list->leaf != NULL) { list->leaf->next = NULL; } value = temp->value; free(temp); list->size--; //DEBUG_OUTPUT("last item popped from list"); return value; } /*! * \brief Remove all elements of the list * \param[in,out] list * \return 1 if finished */ int ll_pop_all(linkedlist *list) { while(list->size>0){ ll_pop_first(list); } return 1; } /*! * \brief Obtain the element situated on index position on the list * \param[in] list * \param[in] index of the element * \return Index element of the list */ void *ll_get_index(linkedlist *list, unsigned int index) { if (index >= list->size) { fprintf(stderr, "Warning: index out of bounds\n"); return NULL; } if (index < list->size / 2) { //DEBUG_OUTPUT("get item by index, starting from head"); return get_item_fwd(list->head, index); } else { //DEBUG_OUTPUT("get item by index, starting from leaf"); return get_item_rev(list->leaf, list->size - 1 - index); } } /*! * \brief Obtain the next element of the list * \param[in] list * \return Next element of the list */ void *ll_get_next(linkedlist *list) { if (list->current == NULL) { if (list->head == NULL) { return NULL; } else { list->current = list->head; return list->current->value; } } else { list->current = list->current->next; if (list->current == NULL) { return NULL; } else { return list->current->value; } } } /*! * \brief Obtain the previous element of the list * \param[in] list * \return Previous element of the list */ void *ll_get_prev(linkedlist *list) { if (list->current == NULL) { if (list->leaf == NULL) { return NULL; } else { list->current = list->leaf; return list->current->value; } } else { list->current = list->current->prev; if (list->current == NULL) { return NULL; } else { return list->current->value; } } } /*! * \brief Test if an item exists in the list * \param[in] list * \param[in] item to be searched * \param[in] comparator function for items * \return 1 if exists, 0 if not */ int ll_exists(linkedlist *list, void *value, int (*comparator)(void *, void *)) { return item_exists(list->head, value, comparator); } /*! * \brief Obtain the position of an item in the list * \param[in] list * \param[in] item to be searched * \param[in] comparator function for items * \return position of the item if found, -1 if not */ int ll_item_position(linkedlist *list, void *value, int (*comparator)(void *, void *)) { return item_position(list->head, value, comparator, 0); } /*! * \brief Remove an item from the list * \param[in] list * \param[in] item to be removed * \param[in] comparator function for items * \return 1 if removed, 0 if not */ int ll_remove_item(linkedlist *list, void *value, int (*comparator)(void *, void *)) { int result=0; if(comparator(list->head->value,value)==0){ ll_pop_first(list); result=1; } else if(comparator(list->leaf->value,value)==0){ ll_pop_last(list); result=1; } else{ result=item_remove(list->head, value, comparator); if(result==1) list->size--; } return result; } /*! * \brief Sort list (ascending) * \param[in] list * \param[in] comparator function for items * \return SUCCESS if sorted, FAIL if not (1 and 0) */ int ll_sort(linkedlist *list, int (*comparator)(void *a, void *b)) { if (comparator == NULL) { fprintf(stderr, "Warning: comparator function is NULL, cannot sort\n"); return FAIL; } else { list->head = sort_list(list->head, comparator); //DEBUG_OUTPUT("linkedlist sorted"); return SUCCESS; } } /*! * \brief Clear the list from memory * \param[in] list to clear * \param[in] method for clear the list * \return SUCCESS if the list is cleared */ int ll_clear(linkedlist *list, void (*free_value)(void *)) { if (list->head != NULL) { clear_list(list->head, free_value); list->head = NULL; } list->size = 0; //DEBUG_OUTPUT("linkedlist cleared"); return SUCCESS; } /*! * \brief Delete the list from memory * \param[in] list to clear * \param[in] method for clear the list * \return SUCCESS if the list is deleted */ int ll_delete(linkedlist *list, void (*free_value)(void *)) { ll_clear(list, free_value); list->head = NULL; free(list); //DEBUG_OUTPUT("linkedlist deleted"); return SUCCESS; } /*! * \brief Print the elements of a list * \param[in] list/item to print * \param[in,out] output in which the list is printevid * \param[in] method for printing the value of the item */ void ll_print(linkedlist *list, FILE *output, void (*to_string)(FILE *, void *)) { print_list(list->head, output, to_string, NULL); } /*! * \brief Print the elements of a list using a filter * \param[in] list/item to print * \param[in,out] output in which the list is printed * \param[in] method for printing the value of the item * \param[in] method for the filter */ void ll_print_filter(linkedlist *list, FILE *output, void (*to_string)(FILE *, void *), int (*is_visible)(void *)) { print_list(list->head, output, to_string, is_visible); } /*! * \brief Dump and print the complete information of a list * \param[in] list/item to print * \param[in,out] output in which the list is printed * \param[in] method for printing the value of the item */ void ll_dump(linkedlist *list, FILE *output, void (*to_string)(FILE *, void *)) { fprintf(output, "\n### linkedlist dump ############################################################\n\n"); fprintf(output, " Version: %s\n", LL_VERSION); fprintf(output, " Head: %lX\n", (long)list->head); fprintf(output, " Leaf: %lX\n", (long)list->leaf); fprintf(output, " Current: %lX\n", (long)list->current); fprintf(output, " Items: %d\n", list->size); fprintf(output, "\n################################################################################\n\n"); if (list->size > 0) { item *next = list->head; unsigned int index = 0; while (next != NULL) { fprintf(output, " index %d: %-8.lX prev: %-8.lX next: %-8.lX ", index++, (long)next, (long)next->prev, (long)next->next); if (to_string != NULL) { to_string(output, next->value); } else { fprintf(output, "value: %-8.lX", (long)next->value); } fprintf(output, "\n"); next = next->next; } } else { fprintf(output, " (no items)\n"); } fprintf(output, "\n################################################################################\n\n"); }
C
/* REQUIRED REGISTERS (defined in REGS.h in HWL folder): (OCRn) for reading/writing value to be compared with in comparison modes. (TCCRn) for choosing which mode from the modes mentioned below is active. (TIFR) for getting the status of the different flags used below. (TIMSK) for masking (aka enabling or disabling) interrupts. (TCNTn) for reading/writing the timer/counter value. TIMER MODES: normal/overflow mode: since timer register is 8 bits, and it is continuously incrementing at 1MHz (so increments once per microsecond), this means that it overflows after 256 microseconds. This raises the overflow flag (TOVn). If required delay is less than that all good. If more, you need prescaler. A prescaler of 2 for example halves the frequency, making the 256 bits overflow in 512 microseconds. Setting the delay is done by loading TCNTn at the max value (in prev. example, 512,) minus the number required. ____________________________________________________________________________________________________________________________________ ctc mode: (uses a flag to interrupt its loop at satisfied comparison, (OCFn) flag to be exact) *** *** *** NOTE: The OCFn Flag can be cleared by software by writing a logical one to its I/O bit location *** *** *** instead of always overflowing, the value required is set as the cap of the timer, so once it reaches it it becomes 0. This "comparison" is done via comparing the value stored in a register "OCR" (output compare register) ____________________________________________________________________________________________________________________________________ fast-pwm mode: makes use of the OCFn flag but instead of zeroing the counter register, it controls the 5V output compare pin "OC0", where while lower than OCFn flag it sets it as 0V (or 5V) and once higher flips. mode 1: non-inverting: while lower than OCR, LOW, else, HIGH mode 2: inverting: ... opposite ____________________________________________________________________________________________________________________________________ phase-correct-pwm mode: like fast-pwm but instead of going up then overflowing it goes up then goes down. ____________________________________________________________________________________________________________________________________ counter mode: external source (Tn) gives you input, based on which you count via detecting rising edges or falling edges ____________________________________________________________________________________________________________________________________ For PWM modes: Duty Cycle %ge = OCR/max "which is 256 for 8-bit timers", hence: OCR = 256 Duty Cycle %ge */ #ifndef TIMER_H_ #define TIMER_H_ #include "../../Application/typedefs.h" #include "../../HWL/REGS.h" void TIMER_init(EN_TIMER_t t, EN_TIMERMODE_t tm); void TIMER_setValue(EN_TIMER_t t, vuint8_t value); void TIMER_setOCR(EN_TIMER_t t, vuint8_t value); void TIMER_start(EN_TIMER_t t, EN_CLOCKSOURCE_t cs, vuint8_t startVal); void TIMER_stop(EN_TIMER_t t); void TIMER_delay_us(EN_TIMER_t t, uint32_t micros); void TIMER_delay_ms(EN_TIMER_t t, uint16_t millis); #endif /* TIMER_H_ */
C
#include<bits/stdc++.h> using namespace std; int rows,columns; char park[1000][1000]; int gate1[1][2],gate2[1][2],gate3[1][2],cage[1][2]; int persondistance,dinodistance; int numberofgrasslands=0; int safeareas=0; class QItem { public: int row; int col; int dist; QItem(int x, int y, int w) : row(x), col(y), dist(w) { } }; int personlength() { QItem source(0, 0, 0); bool visited[1000][1000]; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { if (park[i][j] == 'W') visited[i][j] = true; else if (park[i][j] == 'M') visited[i][j] = true; else visited[i][j] = false; if (park[i][j] == '1') { source.row = i; source.col = j; } } } queue<QItem> q; q.push(source); visited[source.row][source.col] = true; while (!q.empty()) { QItem p = q.front(); q.pop(); if (park[p.row][p.col] == 'S') return p.dist; if (p.row - 1 >= 0 && visited[p.row - 1][p.col] == false) { q.push(QItem(p.row - 1, p.col, p.dist + 1)); visited[p.row - 1][p.col] = true; } if (p.row + 1 < 1000 && visited[p.row + 1][p.col] == false) { q.push(QItem(p.row + 1, p.col, p.dist + 1)); visited[p.row + 1][p.col] = true; } if (p.col - 1 >= 0 && visited[p.row][p.col - 1] == false) { q.push(QItem(p.row, p.col - 1, p.dist + 1)); visited[p.row][p.col - 1] = true; } if (p.col + 1 < 1000 && visited[p.row][p.col + 1] == false) { q.push(QItem(p.row, p.col + 1, p.dist + 1)); visited[p.row][p.col + 1] = true; } } return -1; } int dinolength() { QItem source(0, 0, 0); bool visited[1000][1000]; for (int i = 0; i < 1000; i++) { for (int j = 0; j < 1000; j++) { if (park[i][j] == 'W') visited[i][j] = true; else visited[i][j] = false; if (park[i][j] == '0') { source.row = i; source.col = j; } } } queue<QItem> q; q.push(source); visited[source.row][source.col] = true; while (!q.empty()) { QItem p = q.front(); q.pop(); if (park[p.row][p.col] == 'S') return p.dist; if (p.row - 1 >= 0 && visited[p.row - 1][p.col] == false) { q.push(QItem(p.row - 1, p.col, p.dist + 1)); visited[p.row - 1][p.col] = true; } if (p.row + 1 < 1000 && visited[p.row + 1][p.col] == false) { q.push(QItem(p.row + 1, p.col, p.dist + 1)); visited[p.row + 1][p.col] = true; } if (p.col - 1 >= 0 && visited[p.row][p.col - 1] == false) { q.push(QItem(p.row, p.col - 1, p.dist + 1)); visited[p.row][p.col - 1] = true; } if (p.col + 1 < 1000 && visited[p.row][p.col + 1] == false) { q.push(QItem(p.row, p.col + 1, p.dist + 1)); visited[p.row][p.col + 1] = true; } } return -1; } int main(){ cout<<"Enter the dimensions of Park : "<<endl; cin>>rows; cin>>columns; cout<<"Enter the Gate positions as Row Column : "<<endl; cin>>gate1[0][0]>>gate1[0][1]>>gate2[0][0]>>gate2[0][1]>>gate3[0][0]>>gate3[0][1]; cout<<"Enter cage coordinates : "<<endl; cin>>cage[0][0]>>cage[0][1]; cout<<"Enter the park layout in W,G and M : "<<endl; for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++) { cin>>park[i][j]; } } for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++) { if(park[i][j]=='G') numberofgrasslands++; } } cout<<endl<<"Park Layout :"<<endl; park[gate1[0][0]-1][gate1[0][1]-1]='S'; park[gate2[0][0]-1][gate2[0][1]-1]='S'; park[gate3[0][0]-1][gate3[0][1]-1]='S'; park[cage[0][0]-1][cage[0][1]-1]='0'; dinodistance=dinolength(); for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++) { if(park[i][j]=='G') { park[i][j]='1'; if(dinodistance<personlength()){ park[i][j]='U'; } } } } for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++) { cout<<park[i][j]<<"\t"; } cout<<endl; } for(int i=0;i<rows;i++){ for(int j=0;j<columns;j++) { if(park[i][j]=='S') safeareas++; if(park[i][j]=='1'){ safeareas++; } } } cout<<endl<<(safeareas*100)/numberofgrasslands; return 0; }
C
/* ESTE CÓDIGO ES UN CONVERSOR * DE DÍAS A SEGUNDOS*/ #include <stdio.h> int main() { int numero_de_dias; int hora = 24; int minuto; int segundo; printf ("===========CONVERSOR DE DIAS A SEGUNDOS===============\n"); printf ("Ingrese el numero de días: "); scanf ("%d", &numero_de_dias); minuto = ((numero_de_dias * hora) * 60); segundo = (minuto * 60); printf ("El número de días dio como resultado: %d segundos.", segundo); return 0; }
C
#include "utils.h" #include <assert.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> int GetStringCharCount(char const *str) { int size = -1; while (str[++size] != '\0') ; return size; } int GetIntCharCount(int num) { if (num = 0) { return 0; } int size = 0; while (num != 0) { num /= 10; size++; } return size; } void PrintGridOutline(int size) { printf("|"); for (int i = 0; i < size; ++i) { printf("-"); } printf("|\n"); } void PrintGridColums(int size, int num) { printf("| "); for (int j = 0; j < num - 2; ++j) { printf(" "); } for (int i = 0; i < size; ++i) { printf("| %d", i); int size_pre_cell = num - GetIntCharCount(i); for (int j = 0; j < size_pre_cell - 2; ++j) { printf(" "); } } printf("|\n"); } void PrintGridInnerline(int size, int num) { for (int i = 0; i < size; ++i) { printf("|"); for (int j = 0; j < num; ++j) { printf("-"); } } printf("|\n"); } char *FloatToString(int size, float num) { int len = snprintf(NULL, 0, "%f", num); if (size == 0) { size = len; } if (pow(10, size + 1) - 1 < num) { char *s = calloc(size + 1, sizeof(char)); memset(s, 'A', size); s[size] = '\0'; return s; } if (-pow(10, size + 1) + 1 > num) { char *s = calloc(size + 2, sizeof(char)); s[0] = ' '; memset(s + 1, 'A', size); s[size + 1] = '\0'; return s; } if (num < 0) { size++; } char *ret = malloc((len + 1) * sizeof(char)); snprintf(ret, (len + 1), "%f", num); if (ret[size - 1] == '.') { printf("float print size too small... please puls 1\n"); assert(ret[size - 1] != '.'); } ret = realloc(ret, (size + 1) * sizeof(char)); ret[size] = '\0'; return ret; } void PrintTensor2D(float *Tensor, int n, int m) { for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { printf("%f ", Tensor[i * m + j]); } printf("\n"); } } char *GetOptimizerStr(OptType opt_type) { char *opt_str; if (opt_type == ADAM) { opt_str = "adam"; } else if (opt_type == SGD) { opt_str = "sgd"; } else if (opt_type == ADAGRAD) { opt_str = "adagrad"; } else if (opt_type == RMSPROP) { opt_str = "rmsprop"; } else { opt_str = "error"; } return opt_str; } char *GetLayerTypeStr(LayerType layer_type) { char *layer_type_str; if (layer_type == DENSE) { layer_type_str = "Dense"; } else if (layer_type == BATCHNORMALIZATION) { layer_type_str = "BatchNorm"; } else if (layer_type == SOFTMAX) { layer_type_str = "SoftMax"; } else if (layer_type == DROPOUT) { layer_type_str = "DropOut"; } else if (layer_type == ACTIVATION) { layer_type_str = "Activation"; } else if (layer_type == LOSS) { layer_type_str = "Loss"; } else { layer_type_str = "error"; } return layer_type_str; }
C
#include <stdio.h> int a ; // BSS or uninitialized data int b =10 ; // Data Segment or DS static int c ; // BSS static int d = 10 ; // DS int sum( int a , int b) // stack { return a + b ; // stack } void main() { static int e ; // BSS static int f = 20 ; // DS int g = 20 ; // stack int h ; // stack h = 50 ; // CS int result ; // stack result = sum ( a + b); // stack + cs ; }
C
/* * File: timer.c * Author: Cesar Aguirre * * */ #include <xc.h> void initTimer1(){ //TODO: Initialize Timer 1 to have a period of // 1 seconds. Enable its interrupt TMR1 = 0; PR1 = 39062; // 1 Second T1CONbits.TCKPS = 3; // Prescalar 256 T1CONbits.TCS = 0; IEC0bits.T1IE = 1; IFS0bits.T1IF = 0; IPC1bits.T1IP = 7; T1CONbits.ON = 1; } void delay() { TMR1 = 1; PR1 = 39062; // 1 Second T1CONbits.TCKPS = 3; // Prescalar 256 T1CONbits.TCS = 0; T1CONbits.TON = 1; // Start the timer while(IFS0bits.T1IF == 0); // Do nothing until the flag goes up IFS0bits.T1IF = 0; // Put the flag back down T1CONbits.TON = 0; // Turn off the timer }
C
#include "header.h" int main(int argc, char* argv[]) { struct sockaddr_un serverAddr = { 0 }; int serverFd = 0; if ((serverFd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) { perror("socket error"); goto ErrorExit; } // bind the server. serverAddr.sun_family = AF_UNIX; strncpy(serverAddr.sun_path, BIND_SOCKET, sizeof(serverAddr.sun_path) - 1); printf("binding to: '%s'\n", BIND_SOCKET); if (bind(serverFd, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == -1) { perror("server bind error"); goto ErrorExit; } ErrorExit: unlink(BIND_SOCKET); return 0; }
C
// goldpan.c #include <std.h> inherit OBJECT; int count; void create(){ ::create(); set_id(({"pan","gold pan"})); set_name("pan"); set_short("a pan"); set_long("This is a small circular aluminum pan. It is somewhat cone shaped and the inside edge of one side has a set of ridges built into it that look like they are designed to catch something. Tiny %^YELLOW%^golden flecks %^RESET%^catch your eye from the inside of the pan. On the bottom of the pan is a small inscription."); set_read("%^BOLD%^BLUE%^%^To the fair townsfolk of Levinshire, I gift you each" " with this to help you live long your simple yet prosperous lifestyle. May the" " bounties brought forth by this gift add to the beauty of your fine city.%^RESET%^"); set_language("common"); set_weight(1); set_size(2); } void init(){ ::init(); add_action("panning","pan"); } int panning(string str){ if(!str) return notify_fail("Pan what?\n"); if(member_array(str,({"water","stream","river","for gold"})) == -1) return notify_fail("You cannot pan that!\n"); if(!ETP->is_goldriver()) return notify_fail("This doesn't look like a good place to pan.\n"); if(TP->query_property("is_panning")) return notify_fail("You are already panning!\n"); if(!TO->query_wielded()) return notify_fail("You must be wielding the pan to use it.\n"); else{ tell_object(TP,"%^RESET%^You sit down near the edge of the %^CYAN%^rive" "r %^RESET%^and fill the pan with %^ORANGE%^dirt %^RESET%^and %^BOLD%^%^BLACK%^rock." " %^RESET%^You begin %^BOLD%^%^CYAN%^swirling %^RESET%^the %^BOLD%^%^CYAN%^water" " %^RESET%^in the pan around, washing away all the lighter %^BOLD%^%^BLACK%^debris." "%^RESET%^"); tell_room(ETP,"%^RESET%^%^CYAN%^"+TP->query_cap_name()+" kneels down by the rivers edge and begins to pan for gold.%^RESET%^",TP); } TP->set_property("is_panning",1); TP->set_paralyzed(5,"You are still panning for gold."); call_out("while_panning",5,TP); TP->use_stamina(10); count = 1; return 1; } void while_panning(string str2){ count++; if(!TO->query_wielded()) { tell_object(TP,"You cannot continue panning without the pan."); TP->remove_property("is_panning"); return; } if(!ETP->is_goldriver()) { tell_object(TP,"You cannot pan here."); TP->remove_property("is_panning"); return; } if(TP->query_unconscious()) { tell_object(TP,"You are lucky you didn't drown."); TP->remove_property("is_panning"); return; } TP->set_paralyzed(5,"You are busy panning."); switch(random(50)){ case 0..48: switch (count) { case 1..2: tell_object(TP,"%^BOLD%^%^CYAN%^Water splashes around you from the moving stream.%^RESET%^"); TP->use_stamina(5); call_out("while_panning",5,TP); break; case 3: tell_object(TP,"The pan is slowly getting empty, but you still see no gold."); tell_room(ETP,"The pan "+TPQCN+" is holding is getting empty but there still doesn't seem to be any gold.",TP); TP->use_stamina(5); call_out("while_panning",5,TP); break; case 4: tell_object(TP,"%^RESET%^%^CYAN%^You're getting wet from all the water.%^RESET%^"); tell_room(ETP,"%^RESET%^%^CYAN%^"+TPQCN+" is getting soaked from the moving waters of the stream.%^RESET%^",TP); TP->use_stamina(5); call_out("while_panning",5,TP); break; case 5: tell_object(TP,"Your arms are getting sore and you realize you're going to need some rest after this."); tell_room(ETP,""+TPQCN+" is beginning to look tired from constantly swirling the water around.",TP); TP->use_stamina(5); call_out("end_panning",5,TP); break; } break; case 49: tell_object(TP,"Darn! You got overzealous in your panning efforts and have accidentally splashed everything out!"); tell_room(ETP,""+TPQCN+" starts to swirl the water faster and faster until... Oops! There is nothing left in the pan!",TP); TP->use_stamina(15); call_out("stop_panning",5,TP); break; } } int end_panning(object who){ int total, found, i; object ob, where; if(!objectp(who)) return 1; where = environment(who); if(!objectp(where)) return 1; tell_object(who,"You see that the pan is nearly empty and you stop to inspect it."); tell_room(where,who->query_cap_name()+" stops swirling the water and peers into the pan.",who); who->remove_property("is_panning"); total = where->query_to_find(); if(!random(2)){ found = random(total)+1; where->set_found(found); for(i=0;i<found;i++) { ob = where->get_found_ob(); ob->move(where); } tell_room(where,"%^BOLD%^%^MAGENTA%^You see something solid inside the pan and watch as "+TPQCN+" dumps the contents of the pan onto the ground beside the river.%^RESET%^",TP); tell_object(who,"%^BOLD%^%^MAGENTA%^Woo-Hoo! A chunk of something! Very carefully you dump the contents of the pan onto the ground beside the river.%^RESET%^"); } else{ tell_object(who,"%^RESET%^%^ORANGE%^After all your work, there is nothing but flecks of dirt left!%^RESET%^"); } count = 1; return 1; } int stop_panning(object who){ object ob, where; if(!objectp(who)) return 1; where = environment(who); if(!objectp(where)) return 1; tell_object(who,"%^RESET%^%^ORANGE%^Well, the pan is completely empty now. Maybe you should calm down and try again%^RESET%^."); tell_room(where,"%^RESET%^%^ORANGE%^"+who->query_cap_name()+" sighs slightly%^RESET%^.",who); who->remove_property("is_panning"); }
C
#include "tidbot.h" #include "cfg.h" #include "time.h" #define MACHINE_FILE "machine_list.txt" int balls_locked = 0; char* random_machine (const char *target, const char *channel) { FILE *machine_file; char lineread[1024] = ""; char reply[1024]; char *machine; char *manufacturer; char *year; char *players; char *type; char *theme; int machine_count = 0; int random_pick = 0; machine_file = fopen (MACHINE_FILE, "r"); if (machine_file == NULL) { fprintf (stderr, "Error opening %s for reading\n", MACHINE_FILE); return NULL; } while (fgets (lineread, 1024, machine_file) != NULL) machine_count++; rewind (machine_file); random_pick = rand () % machine_count; machine_count = 0; strcpy (reply, ""); //Read throught the manual file line by line while (fgets (lineread, 1024, machine_file) != NULL) { if (machine_count == random_pick) { machine = strtok (lineread, "|"); manufacturer = strtok (NULL, "|"); year = strtok (NULL, "|"); players = strtok (NULL, "|"); type = strtok (NULL, "|"); theme = strtok (NULL, "|"); sprintf (reply, "%s by %s. Made %s. Players: %s, type: %s. Theme: %s\n", machine, manufacturer, year, players, type, theme); if (strcmp (target, "tidbot") == 0) return machine; if (channel == NULL) irc_cmd_msg (session, target, reply); else irc_cmd_msg (session, irc_cfg.channel, reply); break; } machine_count++; } fclose (machine_file); return NULL; } void multiball (const char *channel) { if (balls_locked == 3) { irc_cmd_msg (session, channel, "MULTIBALL!"); balls_locked = 0; } else irc_cmd_msg (session, channel, "You need to !lock some more balls"); return; } void lock (const char *channel) { if (balls_locked < 3) balls_locked++; switch (balls_locked) { case 1: irc_cmd_msg (session, channel, "Ball 1 locked"); break; case 2: irc_cmd_msg (session, channel, "Ball 2 locked"); break; case 3: irc_cmd_msg (session, channel, "Ball 3 locked, shoot !multiball to start"); break; default: irc_cmd_msg (session, channel, "Ball locked"); break; } return; } void skillshot (const char *channel) { switch (rand () % 3) { case 0: irc_cmd_msg (session, channel, "Skillshot missed!"); break; case 1: irc_cmd_msg (session, channel, "Skillshot hit!"); break; default: case 2: irc_cmd_msg (session, channel, "Super duper mega-skill shot"); break; } }
C
#include "stdio.h" #define M 3 #define N 4 #define Max ((M)>(N)?(M):(N)) /* 34оΪ */ typedef struct mtxn { int row; int col; struct mtxn *right,*down; union {int value; struct mtxn *link; }tag; }manode; /* ʮĽͶ */ /* һά󴴽ʮʾ */ manode *creacroslist(manode *h[],int A[M][N]) { int i,j; manode *p,*q; p=(manode *)malloc(sizeof(manode)); h[0]=p; p->row=M;p->col=N; for(i=1;i<=Max;i++) { p=(manode *)malloc(sizeof(manode)); p->row=p->col=-1; h[i]=p;h[i-1]->tag.link=p; p->down=p->right=p; } h[Max]->tag.link=h[0]; for(i=0;i<M;i++) for(j=0;j<N;j++) if(A[i][j]!=0) { p=(manode *)malloc(sizeof(manode)); p->row=i;p->col=j;p->tag.value=A[i][j]; q=h[i+1]; while(q->right!=h[i+1]&&q->right->col<j) q=q->right; p->right=q->right;q->right=p; q=h[j+1]; while(q->down!=h[j+1]&&q->down->row<i) q=q->down; p->down=q->down;q->down=p; } return h[0]; } /* Ѳʮ洢ϡ󰴾ʽ */ list(manode *h) { manode *p,*q; int i,j,e; p=h->tag.link; for(i=0;i<M;i++) { q=p->right; for(j=0;j<N;j++) { e=0; if(i==q->row&&j==q->col) { e=q->tag.value; q=q->right; } printf("%4d",e); } p=p->tag.link; printf("\n"); } } /* 4.4ʮ洢ṹʵ־ӷ㷨 */ manode *pred(manode *h[],int i,int j) { manode *p=h[j+1]; while(p->down->col!=-1&&p->down->row<i-1) p=p->down; return p; } void matrixadd(manode *ha,manode *hb,manode *h[]) { manode *p,*q,*ca,*cb,*pa,*pb,*qa; if(ha->row!=hb->row||ha->col!=hb->col) return ; ca=ha->tag.link; cb=hb->tag.link; do { pa=ca->right; pb=cb->right; qa=ca; while(pb->col!=-1) if(pa->col!=-1&&pa->col<pb->col) { qa=pa;pa=pa->right;} else if(pa->col==-1||pa->col>pb->col) { p=(manode *)malloc(sizeof(manode)); p->row=pb->row; p->col=pb->col; p->tag.value=pb->tag.value; p->right=pa; qa->right=p;qa=p;q=pred(h,p->row,p->col); p->down=q->down; q->down=p; pb=pb->right; } else { pa->tag.value+=pb->tag.value; if(pa->tag.value==0) { qa->right=pa->right; q=pred(h,pa->row,pa->col); q->down=pa->down; free(pa); } else qa=pa; pa=pa->right;pb=pb->right; } ca=ca->tag.link; cb=cb->tag.link; } while(ca->row==-1); } main() { int A[M][N]={{1,0,0,2},{6,0,3,0},{0,0,2,4}}; int B[M][N]={{1,0,0,2},{0,3,1,0},{5,0,1,0}}; manode *h1[5],*h2[5],*r1,*r2; clrscr(); r1=creacroslist(h1,A); printf("A=\n"); list(r1); printf("\n"); r2=creacroslist(h2,B); printf("B=\n"); list(r2); printf("\n"); matrixadd(r1,r2,h1); printf("A+B=\n"); list(r1); } 
C
/*1 3 2 4 5 6 10 9 8 7 11 12 13 14 15*/ #include <stdio.h> int main() { int i, j, count, value, N; printf("Enter rows: "); scanf("%d", &N); count = 0; for(i=1; i<=N; i++) { value = (i & 1) ? (count + 1) : (count + i); for(j=1; j<=i; j++) { printf("%-3d", value); if(i & 1) value++; else value--; count++; } printf("\n"); } return 0; }
C
#include<stdio.h> int main() { int a,b,i,sum=0; scanf("%d", &a); while(1 == scanf("%d", &b)) { if(b>0) break; } for(i=a;i<a+b;i++) { sum += i; } printf("%d\n", sum); return 0; }
C
#include "bst.h" #include "asserts.h" #include "mem.h" #include "stack.h" #include "string_utils.h" #include <inttypes.h> typedef enum { UBST_NODE_BLACK, UBST_NODE_RED, } ubst_color_t; struct ubst_node { ugeneric_t k; ugeneric_t v; struct ubst_node *left; struct ubst_node *right; ubst_color_t color; }; typedef struct ubst_node ubst_node_t; typedef bool (*ubst_node_cb_t)(ubst_node_t *node, void *data); struct ubst_opaq { uvoid_handlers_t void_handlers; bool is_data_owner; ubst_node_t *root; ubst_balancing_mode_t balancing_mode; size_t size; }; struct ubst_iterator_opaq { const ubst_t *bst; ustack_t *stack; ubst_node_t *node; }; static ubst_balancing_mode_t _default_balancing_mode = UBST_NO_BALANCING; void ubst_set_default_balancing_mode(ubst_balancing_mode_t mode) { UASSERT_INPUT(mode > UBST_DEFAULT_BALANCING); UASSERT_INPUT(mode < UBST_BALANCING_MODES_COUNT); _default_balancing_mode = mode; } ubst_node_t **_lookup(ubst_t *b, ubst_node_t **root, ugeneric_t k) { ubst_node_t **node = root; while (*node) { int cmp = ugeneric_compare_v(k, (*node)->k, b->void_handlers.cmp); if (cmp < 0) { node = &(*node)->left; } else if (cmp > 0) { node = &(*node)->right; } else { break; } } return node; } static ubst_node_t **_get_min(ubst_node_t **root) { ubst_node_t **pos = root; while ((*pos)->left) { pos = &(*pos)->left; } return pos; } static ubst_node_t **_get_max(ubst_node_t **root) { ubst_node_t **pos = root; while ((*pos)->right) { pos = &(*pos)->right; } return pos; } static ubst_node_t **_get_inorder_predecessor(ubst_t *b, ubst_node_t **node) { ubst_node_t **predecessor = NULL; if ((*node)->left) { predecessor = _get_max(&(*node)->left); } else { ugeneric_t k = (*node)->k; ubst_node_t **pos = &b->root; while (*pos) { int cmp = ugeneric_compare_v(k, (*pos)->k, b->void_handlers.cmp); if (cmp < 0) { pos = &(*pos)->left; } else if (cmp > 0) { predecessor = pos; pos = &(*pos)->right; } else { break; } } } return predecessor; } static ubst_node_t **_get_inorder_successor(ubst_t *b, ubst_node_t **node) { ubst_node_t **successor = NULL; if ((*node)->right) { successor = _get_min(&(*node)->right); } else { ugeneric_t k = (*node)->k; ubst_node_t **pos = &b->root; while (*pos) { int cmp = ugeneric_compare_v(k, (*pos)->k, b->void_handlers.cmp); if (cmp < 0) { successor = pos; pos = &(*pos)->left; } else if (cmp > 0) { pos = &(*pos)->right; } else { break; } } } return successor; } void _ubst_nodes_destroy(ubst_t *b, ubst_node_t *node) { if (node) { _ubst_nodes_destroy(b, node->left); _ubst_nodes_destroy(b, node->right); if (b->is_data_owner) { ugeneric_destroy_v(node->k, b->void_handlers.dtr); ugeneric_destroy_v(node->v, b->void_handlers.dtr); } ufree(node); } } bool _iterate_kv(const ubst_node_t *node, ubst_traverse_mode_t mode, ugeneric_kv_iter_t cb, void *data) { if (node) { if (mode == UBST_PREORDER) { if (cb(node->k, node->v, data)) return true; if (_iterate_kv(node->left, mode, cb, data)) return true; if (_iterate_kv(node->right, mode, cb, data)) return true; } else if (mode == UBST_POSTORDER) { if (_iterate_kv(node->left, mode, cb, data)) return true; if (_iterate_kv(node->right, mode, cb, data)) return true; if (cb(node->k, node->v, data)) return true; } else if (mode == UBST_INORDER) { if (_iterate_kv(node->left, mode, cb, data)) return true; if (cb(node->k, node->v, data)) return true; if (_iterate_kv(node->right, mode, cb, data)) return true; } } return false; } bool _iterate_nodes(ubst_node_t *node, ubst_traverse_mode_t mode, ubst_node_cb_t cb, void *data) { if (node) { if (mode == UBST_PREORDER) { if (cb(node, data)) return true; if (_iterate_nodes(node->left, mode, cb, data)) return true; if (_iterate_nodes(node->right, mode, cb, data)) return true; } else if (mode == UBST_POSTORDER) { if (_iterate_nodes(node->left, mode, cb, data)) return true; if (_iterate_nodes(node->right, mode, cb, data)) return true; if (cb(node, data)) return true; } else if (mode == UBST_INORDER) { if (_iterate_nodes(node->left, mode, cb, data)) return true; if (cb(node, data)) return true; if (_iterate_nodes(node->right, mode, cb, data)) return true; } } return false; } static inline bool _is_black(ubst_node_t *node) { return !node || (node->color == UBST_NODE_BLACK); } static inline bool _is_red(ubst_node_t *node) { return node && (node->color == UBST_NODE_RED); } static inline void _set_red(ubst_node_t *node) { node->color = UBST_NODE_RED; } static inline void _set_black(ubst_node_t *node) { node->color = UBST_NODE_BLACK; } static ubst_node_t *_rotate_left_once(ubst_node_t *node) { ubst_node_t *t = node->right; node->right = t->left; t->left = node; _set_black(t); _set_red(node); return t; } static ubst_node_t *_rotate_right_once(ubst_node_t *node) { ubst_node_t *t = node->left; node->left = t->right; t->right = node; _set_black(t); _set_red(node); return t; } static ubst_node_t *_rotate_left_twice(ubst_node_t *node) { node->right = _rotate_right_once(node->right); return _rotate_left_once(node); } static ubst_node_t *_rotate_right_twice(ubst_node_t *node) { node->left = _rotate_left_once(node->left); return _rotate_right_once(node); } static ubst_node_t *_make_new_node(ugeneric_t k, ugeneric_t v) { ubst_node_t *n = umalloc(sizeof(*n)); n->k = k; n->v = v; n->left = NULL; n->right = NULL; n->color = UBST_NODE_RED; return n; } static void _put_not_balanced(ubst_t *b, ugeneric_t k, ugeneric_t v) { ubst_node_t **node = _lookup(b, &b->root, k); if (*node) { /* Update case. */ ugeneric_destroy_v((*node)->k, b->void_handlers.dtr); ugeneric_destroy_v((*node)->v, b->void_handlers.dtr); (*node)->k = k; (*node)->v = v; } else { /* Insert case. */ *node = _make_new_node(k, v); b->size += 1; } } /* * Top-down nonrecursive updating (insert/update or delete) of red-black tree * inspired by Mark Allen Weiss "Data Structures and Algorithm Analysis in C++" * (4th edition, ch. 12.2.2) and Julienne Walker's brilliant implementation * provided at http://www.eternallyconfuzzled.com */ static void _put_red_black(ubst_t *b, ugeneric_t k, ugeneric_t v) { // If we rotate the whole tree around the root we need // to store the link to a new root somewhere (as old root gets // rotated). Right link of the of sentinel node below is this place. ubst_node_t sentinel_root = {0}; sentinel_root.right = b->root; ubst_node_t *x = b->root; // current node ubst_node_t *p = NULL; // current node parent ubst_node_t *g = NULL; // current node grandpa ubst_node_t *gg = &sentinel_root; // current node great-grandpa ubst_node_t **npos = &b->root; // new node insertion position unsigned int path = 0; bool inserted = false; for (;;) { if (!x) { *npos = x = _make_new_node(k, v); inserted = true; } if (_is_red(x->left) && _is_red(x->right)) { _set_red(x); _set_black(x->left); _set_black(x->right); } // Handle red violation caused either by re-coloring above // or by inserting a new red node at x. if (_is_red(p) && _is_red(x)) { // Address of a link in great grand parent to be // updated for reattachment process after rotation. ubst_node_t **gg_link = (gg->right == g) ? &(gg->right) : &(gg->left); switch (path & 0xff) { case 0x00: *gg_link = _rotate_right_once(g); break; // LL case 0x01: *gg_link = _rotate_right_twice(g); break; // LR case 0x10: *gg_link = _rotate_left_twice(g); break; // RL case 0x11: *gg_link = _rotate_left_once(g); break; // RR } } if (inserted) { // As a new node was inserted there is no need for the logic below. // However the logic above to address possible red violation still // needs to be applied, so that's why breaking the loop only here. break; } // Move pointers down the tree. if (g != NULL) { gg = g; } g = p; p = x; int cmp = ugeneric_compare_v(k, x->k, b->void_handlers.cmp); if (cmp < 0) { npos = &x->left; x = x->left; path = (path << 4); } else if (cmp > 0) { npos = &x->right; x = x->right; path = (path << 4) | 0x01; } else { // Found the node to be updated, update and get out of here. ugeneric_destroy_v(p->k, b->void_handlers.dtr); ugeneric_destroy_v(p->v, b->void_handlers.dtr); p->k = k; p->v = v; break; } } // If right link in sentinel node is NULL it means the tree was empty // before this call and no rotations around the root was possible, // nothing to restore. if (sentinel_root.right) { b->root = sentinel_root.right; } _set_black(b->root); if (inserted) { b->size += 1; } } static ugeneric_t _pop_red_black(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { (void)b; (void)k; (void)vdef; UABORT("not implemented"); } static void _put_splay(ubst_t *b, ugeneric_t k, ugeneric_t v) { (void)b; (void)k; (void)v; UABORT("not implemented"); } static ugeneric_t _pop_not_balanced(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { ubst_node_t **pos = &b->root; ubst_node_t **n = NULL; ugeneric_t ret = vdef; while (*pos) { /* Look up for the node to be deleted */ int cmp = ugeneric_compare_v(k, (*pos)->k, b->void_handlers.cmp); if (cmp < 0) { pos = &(*pos)->left; } else if (cmp > 0) { pos = &(*pos)->right; } else { /* Case 1: both child nodes are present, the trickiest. */ if ((*pos)->left && (*pos)->right) { n = _get_inorder_predecessor(b, pos); ugeneric_swap(&(*n)->k, &(*pos)->k); ugeneric_swap(&(*n)->v, &(*pos)->v); pos = n; } ret = (*pos)->v; if (b->is_data_owner) { ugeneric_destroy_v((*pos)->k, b->void_handlers.dtr); } b->size -= 1; /* Case 2: no child nodes, just delete the node. */ if (!(*pos)->left && !(*pos)->right) { ufree(*pos); // free node *pos = NULL; // clear pointer in the parent node } /* Case 3: one child */ else if (!(*pos)->left) { ubst_node_t *t = *pos; *pos = (*pos)->right; ufree(t); } else if (!(*pos)->right) { ubst_node_t *t = *pos; *pos = (*pos)->left; ufree(t); } else { UABORT("Internal error"); } } } return ret; } static ugeneric_t _pop_splay(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { (void)b; (void)k; (void)vdef; UABORT("not implemented"); } ubst_t *ubst_create_ext(ubst_balancing_mode_t mode) { UASSERT_INPUT(mode >= UBST_DEFAULT_BALANCING); UASSERT_INPUT(mode < UBST_BALANCING_MODES_COUNT); ubst_t *b = umalloc(sizeof(*b)); b->root = NULL; b->size = 0; b->is_data_owner = true; memset(&b->void_handlers, 0, sizeof(b->void_handlers)); if (mode == UBST_DEFAULT_BALANCING) { b->balancing_mode = _default_balancing_mode; } else { b->balancing_mode = mode; } return b; } ubst_t *ubst_create(void) { return ubst_create_ext(UBST_DEFAULT_BALANCING); } void ubst_put(ubst_t *b, ugeneric_t k, ugeneric_t v) { UASSERT_INPUT(b); switch (b->balancing_mode) { case UBST_NO_BALANCING: _put_not_balanced(b, k, v); break; case UBST_RB_BALANCING: _put_red_black(b, k, v); break; case UBST_SPLAY_BALANCING: _put_splay(b, k, v); break; default: UABORT("internal error"); } } ugeneric_t ubst_pop(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { UASSERT_INPUT(b); ugeneric_t ret; switch (b->balancing_mode) { case UBST_NO_BALANCING: ret = _pop_not_balanced(b, k, vdef); break; case UBST_RB_BALANCING: ret = _pop_red_black(b, k, vdef); break; case UBST_SPLAY_BALANCING: ret = _pop_splay(b, k, vdef); break; default: UABORT("internal error"); } return ret; } bool ubst_remove(ubst_t *b, ugeneric_t k) { ugeneric_t r = ubst_pop(b, k, G_ERROR("")); bool ret = !G_IS_ERROR(r); if (ret) { ugeneric_destroy_v(r, b->void_handlers.dtr); } return ret; } ugeneric_t ubst_get(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { UASSERT_INPUT(b); ubst_node_t *node = *_lookup(b, &b->root, k); return node ? node->v : vdef; } bool ubst_has_key(const ubst_t *b, ugeneric_t k) { UASSERT_INPUT(b); ubst_t *t = (ubst_t *)b; // cast away const qualifier return *_lookup(t, &t->root, k); } ugeneric_t ubst_get_min(ubst_t *b) { UASSERT_INPUT(b); return (*_get_min(&b->root))->v; } ugeneric_t ubst_get_max(ubst_t *b) { UASSERT_INPUT(b); return (*_get_max(&b->root))->v; } size_t ubst_get_size(ubst_t *b) { UASSERT_INPUT(b); return b->size; } bool ubst_is_empty(ubst_t *b) { UASSERT_INPUT(b); return b->size == 0; } void ubst_destroy(ubst_t *b) { if (b) { _ubst_nodes_destroy(b, b->root); ufree(b); } } void ubst_clear(ubst_t *b) { UASSERT_INPUT(b); _ubst_nodes_destroy(b, b->root); b->root = NULL; b->size = 0; } void ubst_traverse(const ubst_t *b, ubst_traverse_mode_t mode, ugeneric_kv_iter_t iter, void *data) { UASSERT_INPUT(b); (void)_iterate_kv(b->root, mode, iter, data); } ugeneric_t ubst_get_inorder_predecessor(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { UASSERT_INPUT(b); ubst_node_t **node = _lookup(b, &b->root, k); if (*node) { node = _get_inorder_predecessor(b, node); if (node) { return (*node)->v; } } return vdef; } ugeneric_t ubst_get_inorder_successor(ubst_t *b, ugeneric_t k, ugeneric_t vdef) { UASSERT_INPUT(b); ubst_node_t **node = _lookup(b, &b->root, k); if (*node) { node = _get_inorder_successor(b, node); if (node) { return (*node)->v; } } return vdef; } typedef struct { const ubst_t *b; size_t nodes_left; ubuffer_t *buf; } _serialize_data_t; bool _serialize(ubst_node_t *node, void *data) { _serialize_data_t *d = data; d->nodes_left -= 1; ugeneric_serialize_v(node->k, d->buf, d->b->void_handlers.s8r); ubuffer_append_data(d->buf, ": ", 2); ugeneric_serialize_v(node->v, d->buf, d->b->void_handlers.s8r); if (d->nodes_left) { ubuffer_append_data(d->buf, ", ", 2); } return false; } void ubst_serialize(const ubst_t *b, ubuffer_t *buf) { UASSERT_INPUT(b); UASSERT_INPUT(buf); ubuffer_append_byte(buf, '{'); _serialize_data_t d = {.b = b, .nodes_left = b->size, .buf = buf}; _iterate_nodes(b->root, UBST_INORDER, _serialize, &d); ubuffer_append_byte(buf, '}'); } char *ubst_as_str(const ubst_t *b) { UASSERT_INPUT(b); ubuffer_t buf = {0}; ubst_serialize(b, &buf); ubuffer_null_terminate(&buf); return buf.data; } int ubst_fprint(const ubst_t *b, FILE *out) { UASSERT_INPUT(b); UASSERT_INPUT(out); char *str = ubst_as_str(b); int ret = fprintf(out, "%s\n", str); ufree(str); return ret; } ubst_iterator_t *ubst_iterator_create(const ubst_t *b) { UASSERT_INPUT(b); ubst_iterator_t *bi = umalloc(sizeof(*bi)); bi->bst = b; bi->stack = ustack_create(); ustack_drop_data_ownership(bi->stack); bi->node = b->root; return bi; } bool ubst_is_balanced(const ubst_t *b) { UASSERT_INPUT(b); UABORT("not implemented"); } ugeneric_kv_t ubst_iterator_get_next(ubst_iterator_t *bi) { UASSERT_INPUT(bi); ubst_node_t *n = bi->node; UASSERT_MSG(bi->bst->size, "container is empty"); UASSERT_MSG(bi->node || !ustack_is_empty(bi->stack), "iteration is done"); if (n) { if (n->left) { while (n->left) { ustack_push(bi->stack, G_PTR(n)); n = n->left; } bi->node = n->right; } else if (n->right) { bi->node = n->right; } else { bi->node = NULL; } } else if (!ustack_is_empty(bi->stack)) { n = G_AS_PTR(ustack_pop(bi->stack)); bi->node = n->right; } else { UABORT("internal error"); } return (ugeneric_kv_t){.k = n->k, .v = n->v}; } bool ubst_iterator_has_next(const ubst_iterator_t *bi) { UASSERT_INPUT(bi); return bi->node || !ustack_is_empty(bi->stack); } void ubst_iterator_reset(ubst_iterator_t *bi) { UASSERT_INPUT(bi); bi->node = bi->bst->root; ustack_clear(bi->stack); } void ubst_iterator_destroy(ubst_iterator_t *bi) { if (bi) { ustack_destroy(bi->stack); ufree(bi); } } uvector_t *ubst_get_items(const ubst_t *b, udict_items_kind_t kind, bool deep) { UASSERT_INPUT(b); (void)deep; //TODO: implement it ubst_iterator_t *bi = ubst_iterator_create(b); uvector_t *v = uvector_create(); uvector_reserve_capacity(v, b->size); while (ubst_iterator_has_next(bi)) { ugeneric_kv_t item = ubst_iterator_get_next(bi); switch (kind) { case UDICT_KEYS: uvector_append(v, item.k); break; case UDICT_VALUES: uvector_append(v, item.v); break; case UDICT_KV: uvector_append(v, item.k); uvector_append(v, item.v); break; default: UABORT("internal error"); } } ubst_iterator_destroy(bi); uvector_drop_data_ownership(v); uvector_set_void_comparator(v, b->void_handlers.cmp); // vector sort should use original cmp uvector_set_void_serializer(v, b->void_handlers.s8r); uvector_shrink_to_size(v); return v; } typedef struct { size_t nullcnt; FILE *out; bool dump_values; ubst_balancing_mode_t balancing_mode; } _dump2dot_data_t; bool _dump2dot(ubst_node_t *node, void *data) { _dump2dot_data_t *d = data; char *kstr = ugeneric_as_str_v(node->k, NULL); char *vstr = d->dump_values ? ugeneric_as_str_v(node->v, NULL) : NULL; char *str = ustring_fmt("\"%08" PRIxPTR "\"", node); char *lstr = NULL; if (node->left) { lstr = ustring_fmt("\"%08" PRIxPTR "\"", (uintptr_t)node->left); } else if (d->balancing_mode == UBST_RB_BALANCING) { fprintf(d->out, " nullnode%zu [style = filled, fillcolor = black, label = null];\n", d->nullcnt); lstr = ustring_fmt("nullnode%zu", d->nullcnt++); } char *rstr = NULL; if (node->right) { rstr = ustring_fmt("\"%08" PRIxPTR "\"", (uintptr_t)node->right); } else if (d->balancing_mode == UBST_RB_BALANCING) { fprintf(d->out, " nullnode%zu [style = filled, fillcolor = black, label = null];\n", d->nullcnt); rstr = ustring_fmt("nullnode%zu", d->nullcnt++); } fprintf(d->out, " %s [style = filled, fillcolor = %s, fontcolor = %s, label = %s%s%s];\n", str, _is_black(node) ? "black" : "red", _is_black(node) ? "red" : "black", kstr, d->dump_values ? "->" : "", d->dump_values ? vstr : ""); if (lstr) { fprintf(d->out, " %s -> %s;\n", str, lstr); } if (rstr) { fprintf(d->out, " %s -> %s;\n", str, rstr); } ufree(str); ufree(kstr); ufree(vstr); ufree(lstr); ufree(rstr); return false; } void ubst_dump_to_dot(const ubst_t *b, const char *name, bool dump_values, FILE *out) { UASSERT_INPUT(b); fprintf(out, "digraph %s {\n", name); fprintf(out, " label=\"%s\";\n", name); fprintf(out, " labelloc=top;\n"); _dump2dot_data_t d = {.nullcnt = 0, .out = out, .dump_values = dump_values, .balancing_mode = b->balancing_mode}; _iterate_nodes(b->root, UBST_INORDER, _dump2dot, &d); fprintf(out, "}\n"); }
C
/*6. Desenvolva um algoritimoque o usurio informe dois nmeros e que atravs de chamada de funes seja retornado em tela o seguinte: */ #include<stdio.h> void dobro(int a ,int b){ a = a*2; b = b*2; printf( "dobro = a[ %d ]b[ %d ] \n",a,b); } void qudrado (int a ,int b){ a = (a*a); b = (b*b); printf( "qudrado = a[ %d ]b[ %d ]\n",a,b); } void div (int a , int b){ int d; d = a /b; printf( "div = %d \n ",d); } void resto(int a , int b){ int m; m = a%b ; printf( "\n resto = %d",m); } void somapn(int a , int b){ int soma; soma = a+b; if(soma > 0 ){ printf("[ %d ] = positivo",soma); }else{ printf(" [ %d ] = negativo",soma); } } main() { float x ,y , result; printf("Insira dois numeros : \n"); scanf("%f %f",&x,&y); dobro(x,y); qudrado(x,y); div(x,y); somapn(x,y); resto(x,y); }
C
#include <stdio.h> int main() { int a; float b; const float c = 3.141592; b = 3.14; printf("%f\n", b); printf("%.3f\n", c); scanf_s("%d", &a); a = a << 3; printf("a=%d\n", a); }
C
/* * LinkedList.c * * Created on: Sep 8, 2017 * Author: Alex Lim * * Description: Basic singly linked list with user input to append * to head element dynamically. */ #include <stdlib.h> #include <stdio.h> // the type for the node that makes up the body of the list struct node { int data; // data struct node *next; // node pointer }; // create a NULL pointer (head) of data type node struct node *head = NULL; // declare functions void append_Head(int element); int main() { int number = 0; // keeps asking for user input to append to linked list until a -1 is entered while(1) { printf("Enter element to append to head (-1 to end): \n"); scanf("%d", &number); // user input for number if(number == -1) return 0; else append_Head(number); // passes input and appends to head } return 0; // ends program } void append_Head(int element){ // creates a pointer to newNode object of node data type struct node *newNode; // allocates a block of memory in the "heap" and // returns a pointer to the new block. // argument is integer size of the block in bytes newNode = malloc(sizeof(struct node)); // assigns element to newNode data newNode->data = element ; // links newNode next as head newNode->next = head; // newNode is now the head of the link list head = newNode; // prints linked list // create new pointer object of data type node struct node *ptr = head; // start from the beginning scan until reaches NULL next pointer (end of list) while(ptr != NULL){ printf("(%d) ",ptr->data); // prints data element that ptr points to ptr = ptr->next; // point to next element } }
C
/* * fixeddict->c * * Implements a fixed-size dictionary sorted alphabetically * * Created on: 21/12/2011 * Author: piranna */ #include "fixedDict.h" #include <string.h> // memset, strcmp, strncpy void fixedDict_init(fixedDict* dict, pairKeyValue* pairs) { dict->pairs = pairs; dict->length = 0; } void fixedDict_del(fixedDict* dict, char* key) { // Look for the element int i = 0; for(; i < dict->length; ++i) { int cmp = strcmp(dict->pairs[i].key, key); // We have found the dict entry, remove it and move the next ones if(cmp == 0) { // Put on every entry the content of the next one for(; i < dict->length-1; ++i) dict->pairs[i] = dict->pairs[i+1]; // Remove the last one memset((unsigned char*)&dict->pairs[dict->length-1], 0, sizeof(pairKeyValue)); dict->length--; } // Dict entry was not on the dict, do nothing else if(cmp > 0) return; } } void* fixedDict_get(fixedDict* dict, char* key) { // Look for the element int i = 0; for(; i < dict->length; ++i) { int cmp = strcmp(dict->pairs[i].key, key); // We have found the dict entry, return it if(cmp == 0) return dict->pairs[i].value; // We found a dict entry greater than the one we wanted, exit loop else if(cmp > 0) break; } // Dict entry was not on the dict, return nothing return 0; } void fixedDict_set(fixedDict* dict, char* key, void* value) { // Look for the element int i = 0; for(; i < dict->length; ++i) { int cmp = strcmp(dict->pairs[i].key, key); // We have found the dict entry, update it if(cmp == 0) { dict->pairs[i].value = value; return; } // We have found the dict entry position, move the next ones else if(cmp > 0) { // Get capacity of the dict unsigned int capacity = sizeof(*(dict->pairs))/sizeof(pairKeyValue); // Check if we have enought space to add the new entry if(dict->length == capacity) // We should raise an exception... return; // Put on every entry the content of the next one int j = dict->length; for(; j > i; --j) dict->pairs[j] = dict->pairs[j-1]; break; } } // Set the new entry strncpy(dict->pairs[i].key, key, sizeof(dict->pairs[i].key)); dict->pairs[i].value = value; dict->length++; }
C
#include <signal.h> #include <stdio.h> #include <unistd.h> #include <time.h> static int signals = 0; void handler(int sig_no, siginfo_t *info, void *context) { printf("I received a signal %d from a process with pid: %d ", info->si_signo, info->si_pid); if (sig_no == SIGUSR2) printf("(SIGUSR2)!\n"); if (sig_no == SIGUSR1) printf("(SIGUSR1)!\n"); if (sig_no == SIGRTMAX) printf("(SIGRTMAX)!\n"); printf("Time:\n"); printf("user %lf\n", (double) info->si_utime / sysconf(_SC_CLK_TCK)); printf("sys %lf\n", (double) info->si_stime / sysconf(_SC_CLK_TCK)); printf("Error number: %d\n", info->si_errno); } void ez_handler(int sig_no, siginfo_t *info, void *context) { printf("Received signal %d\n", info->si_signo); int value = signals; printf("Sum before: %d ", value); struct timespec ts; ts.tv_sec = 0; ts.tv_nsec = 50; nanosleep(&ts, &ts); signals++; printf("After: %d\n", signals); } int main(void) { struct sigaction siginfoact1; siginfoact1.sa_flags = SA_SIGINFO; siginfoact1.sa_sigaction = ez_handler; sigset_t sigset; sigemptyset(&sigset); sigaddset(&sigset, SIGUSR1); siginfoact1.sa_mask = sigset; sigaction(SIGUSR2, &siginfoact1, NULL); sigaction(SIGUSR1, &siginfoact1, NULL); sigaction(SIGRTMAX, &siginfoact1, NULL); for (int i = 0; i < 10000; i++) { kill(getpid(), SIGUSR1); } raise(SIGUSR2); struct sigaction siginfoact2; siginfoact2.sa_flags = SA_SIGINFO | SA_RESETHAND; siginfoact2.sa_sigaction = handler; sigaction(SIGUSR2, &siginfoact2, NULL); sigaction(SIGUSR1, &siginfoact2, NULL); sigaction(SIGRTMAX, &siginfoact2, NULL); raise(SIGUSR1); raise(SIGRTMAX); raise(SIGUSR2); raise(SIGRTMAX); return 0; }
C
/* Thomas Stoeckert COP 3223H - Final Project This file holds all the structs and helper functions related to the structs. It's quite massive. But anything that deals with an ll object is very similar to each other, since I have to repeat it for each type of node. I've documented the first set, but it's still a lot I looked into null-pointer ll nodes, but decided not to for this project */ #include "data.h" #include "wizards.h" #include <stdlib.h> #include <stdio.h> #include <string.h> // Adds the item data to the end of the linked list that starts at the head struct ll_item * iAppend(struct ll_item *head, struct item data) { struct ll_item *newEntry = (struct ll_item*) malloc(sizeof(struct ll_item)); struct ll_item *helper = head; newEntry->data = data; newEntry->next = NULL; if(head == NULL) { return newEntry; } while(helper->next != NULL) { helper = helper->next; } helper->next = newEntry; return head; }; // Returns a pointer to the item at the index specified struct ll_item * iFindItemByIndex(struct ll_item *head, int index) { struct ll_item *helper = head; int currIndex = 0; while(helper != NULL) { if(currIndex == index) { return helper; } else { helper = helper->next; currIndex++; } } return head; }; // Searches for the item ID instead of the item index in the list struct ll_item * iFindItemByID(struct ll_item *head, int id) { struct ll_item *helper = head; while(helper != NULL) { if(helper->data.id == id){ return helper; } else { helper = helper->next; } } return head; }; // Deletes the item index in the list by the items index struct ll_item * iDeleteItemByIndex(struct ll_item *head, int index) { struct ll_item * helper = head, *temp; int currIndex = 0; if(head==NULL) { return head; } // Delete if the index is now if(currIndex == index){ temp = helper; helper = helper->next; free(temp); return helper; } // Check for middle indexes while (helper->next->next != NULL) { if((currIndex+1) == index) { temp = helper->next; helper->next = helper->next->next; free(temp); return head; } helper = helper->next; currIndex++; } // Check to see if the index is out of range if(index > currIndex + 1){ return head; } // At this point, we know the target index is the last point in the list. Delete the end. return iDeleteEnd(head); }; // Same as index, but searching for the ID struct ll_item * iDeleteItemByID(struct ll_item *head, int id) { struct ll_item *helper = head, *temp; if(head == NULL){ return head; } if(head->data.id == id){ temp = helper; helper = helper->next; free(temp); return helper; } while(helper->next->next != NULL){ if(helper->next->data.id == id){ temp = helper->next; helper->next = helper->next->next; free(temp); return head; } helper = helper->next; } return iDeleteEnd(head); }; // Removes the last element in the linked list struct ll_item * iDeleteEnd(struct ll_item *head) { struct ll_item *helper = head; if(head==NULL) { return head; } if(helper->next == NULL) { free(helper); return NULL; } // Loop until we have the second to last item in the list while(helper->next->next != NULL) { helper = helper->next; } // Free the last item in the list free(helper->next); // Remove any reference to it helper->next = NULL; return head; }; // Just does end over and over again struct ll_item * iDeleteAll(struct ll_item *head) { while(head!= NULL) { head = iDeleteEnd(head); } return NULL; }; struct ll_room * rAppend(struct ll_room *head, struct room data) { struct ll_room *newEntry = (struct ll_room*) malloc(sizeof(struct ll_room)); struct ll_room *helper = head; newEntry->data = data; newEntry->next = NULL; if(head == NULL) { return newEntry; } while(helper->next != NULL) { helper = helper->next; } helper->next = newEntry; return head; }; struct ll_room * rFindRoomByIndex(struct ll_room *head, int index) { struct ll_room *helper = head; int currIndex = 0; while(helper != NULL) { if(currIndex == index) { return helper; } else { helper = helper->next; currIndex++; } } return head; }; struct ll_room * rFindRoomByID(struct ll_room *head, int id) { struct ll_room *helper = head; while(helper != NULL) { if(helper->data.id == id){ return helper; } else { helper = helper->next; } } return NULL; }; struct ll_room * rDeleteRoomByIndex(struct ll_room *head, int index) { struct ll_room * helper = head, *temp; int currIndex = 0; if(head==NULL) { return head; } // Delete if the index is now if(currIndex == index){ temp = helper; helper = helper->next; free(temp); return helper; } // Check for middle indexes while (helper->next->next != NULL) { if((currIndex+1) == index) { temp = helper->next; helper->next = helper->next->next; free(temp); return head; } helper = helper->next; currIndex++; } // Check to see if the index is out of range if(index > currIndex + 1){ return head; } // At this point, we know the target index is the last point in the list. Delete the end. return rDeleteEnd(head); }; struct ll_room * rDeleteRoomByID(struct ll_room *head, int id) { struct ll_room *helper = head, *temp; if(head == NULL){ return head; } if(head->data.id == id){ temp = helper; helper = helper->next; free(temp); return helper; } while(helper->next->next != NULL){ if(helper->next->data.id == id){ temp = helper->next; helper->next = helper->next->next; free(temp); return head; } helper = helper->next; } return rDeleteEnd(head); }; struct ll_room * rDeleteEnd(struct ll_room *head) { struct ll_room *helper = head; if(head==NULL) { return head; } if(helper->next == NULL) { free(helper); return NULL; } // Loop until we have the second to last item in the list while(helper->next->next != NULL) { helper = helper->next; } // Free the last item in the list free(helper->next); // Remove any reference to it helper->next = NULL; return head; }; struct ll_room * rDeleteAll(struct ll_room *head) { while(head!= NULL) { head = rDeleteEnd(head); } return NULL; }; struct ll_door * dAppend(struct ll_door *head, struct door data) { struct ll_door *newEntry = (struct ll_door*) malloc(sizeof(struct ll_door)); struct ll_door *helper = head; newEntry->data = data; newEntry->next = NULL; if(head == NULL) { return newEntry; } while(helper->next != NULL) { helper = helper->next; } helper->next = newEntry; return head; }; struct ll_door * dFindDoorByIndex(struct ll_door *head, int index) { struct ll_door *helper = head; int currIndex = 0; while(helper != NULL) { if(currIndex == index) { return helper; } else { helper = helper->next; currIndex++; } } return head; }; struct ll_door * dDeleteDoorByIndex(struct ll_door *head, int index) { struct ll_door * helper = head, *temp; int currIndex = 0; if(head==NULL) { return head; } // Delete if the index is now if(currIndex == index){ temp = helper; helper = helper->next; free(temp); return helper; } // Check for middle indexes while (helper->next->next != NULL) { if((currIndex+1) == index) { temp = helper->next; helper->next = helper->next->next; free(temp); return head; } helper = helper->next; currIndex++; } // Check to see if the index is out of range if(index > currIndex + 1){ return head; } // At this point, we know the target index is the last point in the list. Delete the end. return dDeleteEnd(head); }; struct ll_door * dDeleteEnd(struct ll_door *head) { struct ll_door *helper = head; if(head==NULL) { return head; } if(helper->next == NULL) { free(helper); return NULL; } // Loop until we have the second to last item in the list while(helper->next->next != NULL) { helper = helper->next; } // Free the last item in the list free(helper->next); // Remove any reference to it helper->next = NULL; return head; }; struct ll_door * dDeleteAll(struct ll_door *head) { while(head!= NULL) { head = dDeleteEnd(head); } return NULL; }; struct ll_combo * cAppend(struct ll_combo *head, struct combo data) { struct ll_combo *newEntry = (struct ll_combo*) malloc(sizeof(struct ll_combo)); struct ll_combo *helper = head; newEntry->data = data; newEntry->next = NULL; if(head == NULL) { return newEntry; } while(helper->next != NULL) { helper = helper->next; } helper->next = newEntry; return head; }; struct ll_combo * cFindComboByIndex(struct ll_combo *head, int index) { struct ll_combo *helper = head; int currIndex = 0; while(helper != NULL) { if(currIndex == index) { return helper; } else { helper = helper->next; currIndex++; } } return head; }; struct ll_combo * cDeleteComboByIndex(struct ll_combo *head, int index) { struct ll_combo * helper = head, *temp; int currIndex = 0; if(head==NULL) { return head; } // Delete if the index is now if(currIndex == index){ temp = helper; helper = helper->next; free(temp); return helper; } // Check for middle indexes while (helper->next->next != NULL) { if((currIndex+1) == index) { temp = helper->next; helper->next = helper->next->next; free(temp); return head; } helper = helper->next; currIndex++; } // Check to see if the index is out of range if(index > currIndex + 1){ return head; } // At this point, we know the target index is the last point in the list. Delete the end. return cDeleteEnd(head); }; struct ll_combo * cDeleteEnd(struct ll_combo *head) { struct ll_combo *helper = head; if(head==NULL) { return head; } if(helper->next == NULL) { free(helper); return NULL; } // Loop until we have the second to last item in the list while(helper->next->next != NULL) { helper = helper->next; } // Free the last item in the list free(helper->next); // Remove any reference to it helper->next = NULL; return head; }; struct ll_combo * cDeleteAll(struct ll_combo *head) { while(head!= NULL) { head = cDeleteEnd(head); } return NULL; }; // This function generates a new blank gameWorld and initializes variables all proper-like struct world initWorld(void){ struct world gameWorld; // ItemData must be null, otherwise the functions segFault gameWorld.inventory.numItems = 0; gameWorld.inventory.itemData = NULL; // Same here gameWorld.itemPrototypes.numItems = 0; gameWorld.itemPrototypes.itemData = NULL; // Again gameWorld.recipes.numCombos = 0; gameWorld.recipes.data = NULL; gameWorld.worldRooms.numRooms = 0; gameWorld.worldRooms.roomData = NULL; // Using smartStringCopy to prevent any overflow, memory leaks, or segfaults smartStringCopy(&gameWorld.introMessage, ""); gameWorld.playing = 0; gameWorld.currentRoomId = 0; return gameWorld; }; // Generates a new room room object with id id, and initializes variables properly struct room initRoom(int id){ struct room newRoom; newRoom.id = id; // Again here, prevent segmentation faults further down the line smartStringCopy(&newRoom.name, "Blank Room"); smartStringCopy(&newRoom.desc, "Blank"); newRoom.inventory.itemData = NULL; newRoom.inventory.numItems = 0; newRoom.paths.paths = NULL; newRoom.paths.numDoors = 0; return newRoom; }; // Simple helper to get the current room struct room * getCurrentRoom(struct rooms worldRooms, int roomId){ return &rFindRoomByID(worldRooms.roomData, roomId)->data; }; // This function looks through recipes to find a combo with both target1ID and target2ID and returns it struct combo *findCombo(struct combos recipes, int target1ID, int target2ID){ struct ll_combo *helper; helper = recipes.data; while(helper != NULL){ if(target1ID == helper->data.primaryID && target2ID == helper->data.secondaryID){ return &helper->data; } else if(target2ID == helper->data.primaryID && target1ID == helper->data.secondaryID){ return &helper->data; } helper = helper->next; } return NULL; }; // Simple function to print the room and the player's items void printRoom(struct room currentRoom, struct items playerItems){ printf("\nYou're in the %s\n%s\n", currentRoom.name, currentRoom.desc); printPaths(currentRoom.paths); printItems(currentRoom.inventory, playerItems); return; } // This prints all the paths in the struct doors void printPaths(struct doors possibleDoors){ struct ll_door *helper; int printIndex = 0; if(possibleDoors.numDoors <= 0 || possibleDoors.paths == NULL){ return; } helper = possibleDoors.paths; printf("You can see the following paths: \n"); while(helper != NULL){ printf(" %d) %s\n", printIndex + 1, helper->data.path); printIndex++; helper = helper->next; } return; } // Prints the items, both the ones in the room and the ones in the user's bag void printItems(struct items roomItems, struct items bagItems){ struct ll_item *helper; int printIndex = 0; // Only print the items if there actually are any if(roomItems.numItems > 0 && roomItems.itemData != NULL){ printf("You can see the following items in the room: \n"); helper = roomItems.itemData; while(helper != NULL){ printf(" %d) %s\n", printIndex + 1, helper->data.name); helper = helper->next; printIndex++; } } if(bagItems.numItems > 0 && bagItems.itemData != NULL){ printf("You have the following items in your bag: \n"); helper = bagItems.itemData; while(helper != NULL){ printf(" %d) %s\n", printIndex + 1, helper->data.name); helper = helper->next; printIndex++; } } } // Used for the editor, prints rooms in a kinda debug fancy way void printRoomVerbose(struct room targetRoom){ printf("| ID: %10d | Name: %19s |\n", targetRoom.id, targetRoom.name); printf("| Num Items: %3d | Num Doors: %14d |\n", targetRoom.inventory.numItems, targetRoom.paths.numDoors); printf("| Desc: %-36.36s |\n", targetRoom.desc); if(targetRoom.inventory.numItems > 0){ printf("---------- Room Items -------\n"); printItemsVerbose(targetRoom.inventory); } else { printf("----- Room has no items -----\n"); } if(targetRoom.paths.numDoors > 0){ printf("---------- Room Doors -------\n"); printPathsVerbose(targetRoom.paths); } else { printf("----- Room has no doors -----\n"); } return; } // Prints all items it is handed in a fancy table void printItemsVerbose(struct items toPrint){ struct ll_item *helper; if(toPrint.itemData == NULL){ return; } printf("| ID | Name | Action Type | Desc | \n"); helper = toPrint.itemData; while(helper != NULL){ printf("| %-3d | %-16.16s | %-11d | %-33.33s |\n", helper->data.id, helper->data.name, helper->data.itemAction.actionType, helper->data.desc); helper = helper->next; } } // Prints all paths it is handed in a fancy table void printPathsVerbose(struct doors toPrint){ struct ll_door *helper; int index = 0; if(toPrint.paths == NULL){ return; } printf("| Index | Destination | Description |\n"); helper = toPrint.paths; while(helper != NULL){ printf("| %-5d | %-11d | %-50.50s |\n", index, helper->data.dest, helper->data.path); helper = helper->next; index++; } } // Prints all rooms it is handed in a fancy table void printRoomsVerbose(struct rooms toPrint){ struct ll_room *helper; int index = 0; if(toPrint.roomData == NULL){ return; } printf("| ID | NumDoors | Name |\n"); helper = toPrint.roomData; while(helper != NULL){ printf("| %-3d | %-8d | %-55.55s |\n", helper->data.id, helper->data.paths.numDoors, helper->data.name); helper = helper->next; index++; } } // same but combos void printCombosVerbose(struct combos toPrint){ struct ll_combo *helper; int index = 0; if(toPrint.data == NULL){ return; } printf("| Index | Primary | Secondary | Result | Desc |\n"); helper = toPrint.data; while(helper != NULL){ printf("| %-5d | %-7d | %-9d | %-6d | %-32.32s |\n", index, helper->data.primaryID, helper->data.secondaryID, helper->data.resultID, helper->data.desc); // on string formatting - the negative prefix and a number mean it needs 32 spaces, with the text left justified // - the dot prefix and a number means it will shorten the string to a max of 32 spaces while printing helper = helper->next; index++; } }
C
/* libco.amd64_gcc (2015-04-22) author: byuu, Alex W. Jackson license: public domain */ #define LIBCO_C #include "libco.h" #include <assert.h> #include <stdlib.h> #ifdef __cplusplus extern "C" { #endif static thread_local long long co_active_buffer[64]; static thread_local cothread_t co_active_handle = 0; static void crash() { assert(0); /* called only if cothread_t entrypoint returns */ } cothread_t co_active() { if(!co_active_handle) co_active_handle = &co_active_buffer; return co_active_handle; } cothread_t co_create(unsigned int size, void (*entrypoint)(void)) { cothread_t handle; if(!co_active_handle) co_active_handle = &co_active_buffer; size += 512; /* allocate additional space for storage */ size &= ~15; /* align stack to 16-byte boundary */ if(handle = (cothread_t)malloc(size)) { long long *p = (long long*)((char*)handle + size); /* seek to top of stack */ *--p = (long long)crash; /* crash if entrypoint returns */ *--p = (long long)entrypoint; /* start of function */ *(long long*)handle = (long long)p; /* stack pointer */ } return handle; } void co_delete(cothread_t handle) { free(handle); } /* The compiler *must not* create a stack frame for this function! Unfortunately, GCC does not support __attribute__((naked)) on x86, so we must do the best we can by forcing omit-frame-pointer and explicitly specifying a volatile register for the local variable (some GCCs have brain damage and may put a local variable in rbp even when volatile registers are available) */ #ifdef __clang__ #ifndef __OPTIMIZE__ #error "libco: please enable optimization or define LIBCO_NO_INLINE_ASM" #else #define NAKED __attribute__((naked)) #endif #else #define NAKED __attribute__((optimize("omit-frame-pointer"))) #endif void NAKED co_switch(cothread_t to) { register cothread_t from __asm__("rdx") = co_active_handle; co_active_handle = to; __asm__ __volatile__( "movq %%rsp,(%[from]) \n\t" /* save old stack pointer */ "movq (%[to]),%%rsp \n\t" /* load new stack pointer */ "popq %%rax \n\t" /* pop return address off stack */ #ifdef _WIN32 /* Windows ABI: rbp, rsi, rdi, rbx, r12-r15 and xmm6-xmm15 are non-volatile */ "movq %%rbp, 8(%[from]) \n\t" /* backup non-volatile registers */ "movq %%rsi,16(%[from]) \n\t" "movq %%rdi,24(%[from]) \n\t" "movq %%rbx,32(%[from]) \n\t" "movq %%r12,40(%[from]) \n\t" "movq %%r13,48(%[from]) \n\t" "movq %%r14,56(%[from]) \n\t" "movq %%r15,64(%[from]) \n\t" "movaps %%xmm6, 80(%[from])\n\t" "movaps %%xmm7, 96(%[from])\n\t" "movaps %%xmm8, 112(%[from])\n\t" "addq $112,%[from] \n\t" "movaps %%xmm9, 16(%[from])\n\t" "movaps %%xmm10, 32(%[from])\n\t" "movaps %%xmm11, 48(%[from])\n\t" "movaps %%xmm12, 64(%[from])\n\t" "movaps %%xmm13, 80(%[from])\n\t" "movaps %%xmm14, 96(%[from])\n\t" "movaps %%xmm15,112(%[from])\n\t" "movq 8(%[to]),%%rbp \n\t" /* restore non-volatile registers */ "movq 16(%[to]),%%rsi \n\t" "movq 24(%[to]),%%rdi \n\t" "movq 32(%[to]),%%rbx \n\t" "movq 40(%[to]),%%r12 \n\t" "movq 48(%[to]),%%r13 \n\t" "movq 56(%[to]),%%r14 \n\t" "movq 64(%[to]),%%r15 \n\t" "movaps 80(%[to]),%%xmm6 \n\t" "movaps 96(%[to]),%%xmm7 \n\t" "movaps 112(%[to]),%%xmm8 \n\t" "addq $112,%[to] \n\t" "movaps 16(%[to]),%%xmm9 \n\t" "movaps 32(%[to]),%%xmm10 \n\t" "movaps 48(%[to]),%%xmm11 \n\t" "movaps 64(%[to]),%%xmm12 \n\t" "movaps 80(%[to]),%%xmm13 \n\t" "movaps 96(%[to]),%%xmm14 \n\t" "movaps 112(%[to]),%%xmm15 \n\t" #else /* System V ABI: rbp, rbx, and r12-r15 are non-volatile */ "movq %%rbp, 8(%[from]) \n\t" /* backup non-volatile registers */ "movq %%rbx,16(%[from]) \n\t" "movq %%r12,24(%[from]) \n\t" "movq %%r13,32(%[from]) \n\t" "movq %%r14,40(%[from]) \n\t" "movq %%r15,48(%[from]) \n\t" "movq 8(%[to]),%%rbp \n\t" /* restore non-volatile registers */ "movq 16(%[to]),%%rbx \n\t" "movq 24(%[to]),%%r12 \n\t" "movq 32(%[to]),%%r13 \n\t" "movq 40(%[to]),%%r14 \n\t" "movq 48(%[to]),%%r15 \n\t" #endif "jmp *%%rax \n\t" /* jump to "to" thread */ : /* no outputs */ : [to] "r" (to), [from] "r" (from) : "rax" ); } #ifdef __cplusplus } #endif
C
#pragma once //--- Calculation with DP ----------------------------------------------------- // PRECONDITION: 0 <= n <= 66 struct CombAllDP { vector<vector<long long>> C; CombAllDP() { } CombAllDP(int n) { build(n); } // find all nCr (0 <= n <= N, 0 <= r <= n) void build(int n) { C.assign(n + 1, vector<long long>(n + 1)); C[0][0] = 1; for (int i = 1; i <= n; i++) { C[i][0] = 1; for (int j = 1; j < i; j++) C[i][j] = C[i - 1][j - 1] + C[i - 1][j]; C[i][i] = 1; } } long long comb(int n, int r) const { return C[n][r]; } }; // PRECONDITION: 0 <= n <= 66 struct CombCompactDP { vector<long long> C; CombCompactDP() { } CombCompactDP(int n) { build(n); } // find all nCr (0 <= r <= n) void build(int n) { C.assign(n + 1, 0); C[0] = 1; for (int i = 1; i <= n; i++) { C[i] = 1; for (int j = i - 1; j > 0; j--) C[j] += C[j - 1]; } } long long comb(int r) const { return C[r]; } }; // PRECONDITION: 0 <= n <= 66 struct FastCombCompactDP { vector<long long> C; vector<long long> S; FastCombCompactDP() { } FastCombCompactDP(int n) { build(n); } void build(int n) { C.assign(n + 1, 0); S.assign(n + 1, 0); C[0] = 1; S[0] = 1; for (int i = 1; i <= n; i++) { C[i] = C[i - 1] * (n - i + 1) / i; S[i] = S[i - 1] + C[i]; } } // nCr long long comb(int r) const { return C[r]; } // r // SUM nCk // k=0 long long sum(int r) const { return S[r]; } };
C
/* run.config COMMENT: Temporal analysis with respect to scopes */ #include <stddef.h> int main() { int *p = NULL, *q = NULL; { int i = 9; p = &i; q = p; } /*@assert ! \valid(p); */ /*@assert ! \valid(q); */ { int j = 8; p = &j; /*@assert \valid(p); */ *p = 1; /* `q` now may point to `j`, bit not necessarily */ /*@assert ! \valid(q); */ /*@assert \valid(&j); */ } /* Example from Arvid's report (Listing 3.12) */ int len = 3; p = NULL, q = NULL; while (len) { int a; /*@assert ! \valid(p); */ q = &a; p = q; /*@assert \valid(p); */ len--; } return 0; }
C
/* help.c - Routines having to do with help XRogue: Expeditions into the Dungeons of Doom Copyright (C) 1991 Robert Pietkivitch All rights reserved. Based on "Advanced Rogue" Copyright (C) 1984, 1985 Michael Morgan, Ken Dalka and AT&T All rights reserved. Based on "Rogue: Exploring the Dungeons of Doom" Copyright (C) 1980, 1981 Michael Toy, Ken Arnold and Glenn Wichman All rights reserved. See the file LICENSE.TXT for full copyright and licensing information. */ #include <curses.h> #include <ctype.h> #include "mach_dep.h" #include "rogue.h" /* * Give character descripts */ static char *game_fighter = "Strength is the main attribute of the Fighter. \ He can wield any weapon and the two-handed sword is his weapon of choice. He \ can also wear any type of armor. Plate armor being the best choice and \ leather armor the worst. The Fighter is able to sense both traps and gold \ at higher experience levels. His natural quest item is the Axe of Aklad. \ Due to his superior form, the Fighter usually receives more hit-points per \ new experience level than the other characters. The Fighter is neither good \ or evil; he is a neutral character. The default attribute values of the \ Fighter are: Int=7, Str=16, Wis=7, Dxt=16, Con=17, and Chr=11. Default gold \ amount is 2000 pieces and default hit-points are 24."; static char *game_thief = "Dexterity is the main attribute of the Thief. His \ stealth allows him to move quietly, thus disturbing less monsters. He can \ sense traps and gold and can take (steal) things from the monsters. The \ Thief can not wield the two-handed sword so the bastard sword is his weapon \ of choice. He can only wear studded leather armor. The Thief's natural \ quest item is the Daggers of Musty Doit. With higher dexterity the Thief \ is able to \"backstab\" monsters, thereby killing them with a single blow. \ His character type fluctuates between that of good, neutral, and evil. The \ default attribute values of the Thief are: Int=7, Str=14, Wis=7, Dxt=18, \ Con=17, and Chr=11. Default gold amount is 2000 pieces and default \ hit-points are 23."; static char *game_assassin = "Dexterity is the main attribute of the \ Assassin. Like the Thief, he moves with an extra degree of stealth. He can \ sense gold and steal things from monsters. The ability to sense traps comes \ at higher experience levels. The Assassin can not wield the two-handed sword \ and he can only wear studded leather armor. The natural quest item of the \ Assassin is the Eye of Vecna. He is also skilled in the use of poison. \ Higher dexterity enables him to \"assassinate\" monsters with a single blow. \ The Assassin is aligned with the powers of evil. The default attribute \ values of the Assassin are: Int=7, Str=14, Wis=7, Dxt=18, Con=17, and \ Chr=11. Default gold amount is 2000 pieces and default hit-points are 23."; static char *game_ranger = "Charisma is the main attribute of the Ranger who \ also has a secondary attribute of Intelligence. Like the Magician, this \ gives him the ability to cast spells which increases as he attains higher \ experience levels. Like the Fighter, he can wield any weapon and wear any \ armor. The Ranger's natural quest item is the Mandolin of Brian. He is \ aligned with the powers of good. Therefore, he can be made to suffer and \ even become cursed by the very powers that allow him to cast spells if he \ happens to cause the demise of a likewise good creature. The default \ attribute values of the Ranger are: Int=11, Str=11, Wis=7, Dxt=16, Con=16, \ and Chr=13. Default gold amount is 2000 pieces and default hit-points \ are 22."; static char *game_paladin = "Charisma is the main attribute of the Paladin \ who has a secondary attribute of Wisdom. Like the Cleric, this gives him \ the ability to offer prayers, receive what his heart desires, and an ability \ to turn the undead. This ability will increase as he gains higher \ experience levels. Like the Fighter, he can wield any weapon and wear any \ armor. The Ankh of Heil is the Paladin's natural quest item. Like the \ Ranger, the Paladin is aligned with the powers of good. This can cause \ him to suffer and become cursed if he brings ruin to a likewise good \ creature. The default attribute values of the Paladin are: Int=7, \ Str=11, Wis=11, Dxt=16, Con=16, and Chr=13. Default gold amount is \ 2000 pieces and default hit-points are 22."; static char *game_druid = "Wisdom is the main attribute of the Druid. This \ gives him the ability to chant secret words and mantras, which is much \ greater than that of the Monk. The Druid can not wield the two-handed or \ bastard swords but he can wear any armor. His natural quest item is the Quill \ of Nagrom. Like the Magician and Cleric, the Druid is aligned neutral. He \ therefore, must rely upon his Wisdom and his chanting ability in order to \ remain alive. Likewise, he does not receive as many new hit-points per \ new experience level. The default attribute values of the Druid are: Int=7, \ Str=10, Wis=14, Dxt=16, Con=15, and Chr=12. Default gold amount is 2000 \ pieces and default hit-points are 21."; static char *game_monk = "Constitution is the main attribute of the Monk who \ has a secondary aspect of Wisdom. Like the Druid, this gives him the \ ability to chant mantras which will increase as he gains higher experience. \ The Monk can not wield the two-handed sword and he can not wear any armor. \ The Cloak of Emori is the Monk's natural quest item. The Monk can also \ sense traps, though much less than the Thief or Assassin. He is the most \ healthy character. Like the Ranger and Paladin, he is aligned with the \ powers of good. Therefore, he is made to suffer and can become cursed if \ he kills a likewise good creature. The default attribute values of the \ Monk are: Int=7, Str=11, Wis=11, Dxt=16, Con=18, and Chr=11. Default \ gold amount is 2000 pieces and default hit-points are 22."; static char *game_magician = "Intelligence is the main attribute of the \ Magician. The Magician's ability to cast spells is much greater than that \ of the Ranger. He can not wield the two- handed or bastard swords, but he \ can wear any kind of armor. His natural quest item is the Amulet of \ Stonebones. The Magician is aligned neutral. He must rely upon his \ Intelligence and spell casting abilities to remain alive. There- fore, he \ does not receive as many new hit-points per new experience level. The \ default attribute values of the Magician are: Int=14, Str=10, Wis=7, \ Dxt=16, Con=15, and Chr=12. Default gold amount is 2000 pieces and \ default hit-points are 21."; static char *game_cleric = "Wisdom is the main attribute of the Cleric. The \ Cleric's ability to give or offer prayers, receive their due, and affect \ the undead are much greater than that of the Paladin. Like the Magician, \ the Cleric can not wield the two- handed or bastard swords, but he can \ wear any armor. His natural quest item is the Horn of Geryon. The Cleric \ is aligned neutral and he must rely upon his Wisdom and prayer ability to \ remain alive. He therefore, does not receive as many new hit-points per \ new experience level. The default attribute values of the Cleric are: Int=7, \ Str=10, Wis=14, Dxt=16, Con=15, and Chr=12. The default gold amount is 2000 \ pieces and default hit-points are 21."; static char *game_food ="There are three types of food, regular food rations, \ various fruits, and slime- molds. Eating regular food will add 750 points to \ your current food level [see the CTRL(E) command]. Eating fruit adds \ 300 points. Certain fruits also cure you, add an attribute point, add a \ hit-point, increase your armor, give you additional prayer, chant, or spell \ casting abilities, or add experience points. Eating slime-mold (monster \ food) can make you ill, but they will add 100 points to your current food \ level. If your food level points drop below 100 you will become weak. You \ will faint and might die if they drop to 0 or below. At the other extreme, \ if your food level points reach 2000 (and above) you will become satiated. \ Risk eating more and you could choke to death."; /* static char *game_monst ="To be updated."; static char *game_potion ="To be updated..."; static char *game_scroll ="To be updated..."; static char *game_ring ="To be updated..."; static char *game_stick ="To be updated..."; static char *game_weapon ="To be updated..."; static char *game_armor ="To be updated..."; static char *game_miscm ="To be updated..."; static char *game_qitems ="To be updated..."; static char *game_dungeon ="To be updated..."; static char *game_traps ="To be updated..."; static char *game_mazes ="To be updated..."; static char *game_option ="To be updated..."; static char *game_begin ="To be updated..."; */ /* help list */ static struct h_list helpstr[] = { '?', " Print help", '/', " Identify object", '=', " Identify a screen character", ' ', "", 'h', " Move left", 'j', " Move down", 'k', " Move up", 'l', " Move right", 'y', " Move up and left", 'u', " Move up and right", 'b', " Move down and left", 'n', " Move down and right", 'H', " Run left", 'J', " Run down", 'K', " Run up", 'L', " Run right", 'Y', " Run up & left", 'U', " Run up & right", 'B', " Run down & left", 'N', " Run down & right", ' ', "", '>', " Go down a staircase", '<', " Go up a staircase", '\\', " Game descriptions", '.', " Rest for a while", '*', " Count gold pieces", 'a', " Affect the undead", 'A', " Choose artifact (equipage)", 'c', " Chant a mantra", 'C', " Cast a spell", 'd', " Drop something", 'D', " Dip something (into a pool)", 'e', " Eat food or fruit", 'f', "<dir> Forward until find something", 'F', " Frighten a monster", 'g', " Give food to monster", 'G', " Sense for gold", 'i', " Inventory", 'I', " Inventory (single item)", 'm', " Mark an object (specific)", 'o', " Examine and/or set options", 'O', " Character type and quest item", 'p', " Pray to the powers that be", 'P', " Pick up object(s)", 'q', " Quaff a potion", 'Q', " Quit the game", 'r', " Read a scroll", 's', " Search for a trap/secret door", 'S', " Save your game", 't', "<dir> Throw something", 'T', " Take off something", 'v', " Print program version", 'w', " Wield a weapon", 'W', " Wear something", 'X', " Sense for traps", 'z', "<dir> Zap a wand or staff", ' ', "", '^', " Set a trap", '$', " Price an item (trading post)", '#', " Buy an item (trading post)", '%', " Sell an item (trading post)", '!', " Shell escape", ESC, " Cancel command (Esc)", ' ', "", CTRL('B'), " Current score (if you win)", CTRL('E'), " Current food level", CTRL('L'), " Redraw the screen", CTRL('N'), " Name an object or a monster", CTRL('O'), " Character affect status", CTRL('R'), " Repeat last message", CTRL('T'), "<dir> Take (steal) from (direction)", CTRL('U'), " Use a magic item", 0, 0 } ; /* wizard help list */ static struct h_list wiz_help[] = { ' ', "", '+', " Random fortunes", 'M', " Make an object", 'V', " Display vlevel and turns", CTRL('A'), " System activity", CTRL('C'), " Move to another dungeon level", CTRL('D'), " Go down 1 dungeon level", CTRL('F'), " Display the entire level", CTRL('G'), " Charge wands and staffs", CTRL('H'), " Jump 9 experience levels", CTRL('I'), " Inventory of level", CTRL('J'), " Teleport somewhere", CTRL('K'), " Identify an object", CTRL('M'), " Recharge wand or staff", CTRL('P'), " Toggle wizard status", CTRL('X'), " Detect monsters", CTRL('Y'), " Display food levels", 0, 0 }; /* item help list */ static struct item_list item_help[] = { '@', " You (visible)", '_', " You (invisible)", ' ', "", ':', " Food ration or fruit (eat)", '!', " Potion (quaff)", '?', " Scroll (read)", '=', " Ring (wear)", ')', " Weapon (wield)", ']', " Armor (wear)", '/', " Wand or staff (zap)", ';', " Magic item (use)", ',', " Artifact (quest item)", '*', " Gold or zapped missile", ' ', "", '$', " Magical item in room", '>', " Blessed magical item", '<', " Cursed magical item", ' ', " ", '`', " Dart trap", '{', " Arrow trap", '}', " Bear trap", '~', " Teleport trap", '$', " Sleeping gas trap", '>', " Trap door", '<', " Outer region entrance", '\'', " Maze entrance", '^', " Trading post entrance", '"', " Magic pool or lake", ' ', " Solid rock or mountain", '.', " Floor of a room or meadow", '%', " Stairs (up or down)", '+', " Doorway", '&', " Secret doorway", '#', " Passage between rooms", '\\', " Forest", HORZWALL, " Horizontal wall of a room", VERTWALL, " Vertical wall of a room", 0, 0 }; ident_hero() { bool doit = TRUE; wclear(hw); wprintw(hw, "Characters, Items, and Game Descriptions:\n"); wprintw(hw, "-----------------------------------------\n"); wprintw(hw, "a) Fighter m) Scrolls\n"); wprintw(hw, "b) Thief n) Rings\n"); wprintw(hw, "c) Assassin o) Wands and Staffs\n"); wprintw(hw, "d) Ranger p) Weapons\n"); wprintw(hw, "e) Paladin q) Armors\n"); wprintw(hw, "f) Monk r) Miscellaneous Magic Items\n"); wprintw(hw, "g) Magician s) Quest Items (Artifacts and Relics)\n"); wprintw(hw, "h) Cleric t) The Dungeon\n"); wprintw(hw, "i) Druid u) Traps\n"); wprintw(hw, "j) Monsters v) Mazes and Outer Regions\n"); wprintw(hw, "k) Foods w) Setting game options\n"); wprintw(hw, "l) Potions x) Starting out\n"); wprintw(hw, "\nEnter a letter: "); draw(hw); while (doit) { switch (wgetch(cw)) { case EOF: case ESC: doit = FALSE; when 'a': wclear(hw); wprintw(hw, "Fighter Characteristics:"); mvwaddstr(hw, 2, 0, game_fighter); draw(hw); doit = FALSE; when 'b': wclear(hw); wprintw(hw, "Thief Characteristics:"); mvwaddstr(hw, 2, 0, game_thief); draw(hw); doit = FALSE; when 'c': wclear(hw); wprintw(hw, "Assassin Characteristics:"); mvwaddstr(hw, 2, 0, game_assassin); draw(hw); doit = FALSE; when 'd': wclear(hw); wprintw(hw, "Ranger Characteristics:"); mvwaddstr(hw, 2, 0, game_ranger); draw(hw); doit = FALSE; when 'e': wclear(hw); wprintw(hw, "Paladin Characteristics:"); mvwaddstr(hw, 2, 0, game_paladin); draw(hw); doit = FALSE; when 'f': wclear(hw); wprintw(hw, "Monk Characteristics:"); mvwaddstr(hw, 2, 0, game_monk); draw(hw); doit = FALSE; when 'g': wclear(hw); wprintw(hw, "Magician Characteristics:"); mvwaddstr(hw, 2, 0, game_magician); draw(hw); doit = FALSE; when 'h': wclear(hw); wprintw(hw, "Cleric Characteristics:"); mvwaddstr(hw, 2, 0, game_cleric); draw(hw); doit = FALSE; when 'i': wclear(hw); wprintw(hw, "Druid Characteristics:"); mvwaddstr(hw, 2, 0, game_druid); draw(hw); doit = FALSE; when 'j': wclear(hw); wprintw(hw, "Monster Characteristics:"); draw(hw); doit = FALSE; when 'k': wclear(hw); wprintw(hw, "Foods:"); mvwaddstr(hw, 2, 0, game_food); draw(hw); doit = FALSE; when 'l': wclear(hw); wprintw(hw, "Potions:"); draw(hw); doit = FALSE; when 'm': wclear(hw); wprintw(hw, "Scrolls:"); draw(hw); doit = FALSE; when 'n': wclear(hw); wprintw(hw, "Rings:"); draw(hw); doit = FALSE; when 'o': wclear(hw); wprintw(hw, "Wands and Staffs:"); draw(hw); doit = FALSE; when 'p': wclear(hw); wprintw(hw, "Weapons:"); draw(hw); doit = FALSE; when 'q': wclear(hw); wprintw(hw, "Armors:"); draw(hw); doit = FALSE; when 'r': wclear(hw); wprintw(hw, "Miscellaneous Magic Items:"); draw(hw); doit = FALSE; when 's': wclear(hw); wprintw(hw, "Quest Items (Artifacts and Relics):"); draw(hw); doit = FALSE; when 't': wclear(hw); wprintw(hw, "The Dungeon:"); draw(hw); doit = FALSE; when 'u': wclear(hw); wprintw(hw, "Traps:"); draw(hw); doit = FALSE; when 'v': wclear(hw); wprintw(hw, "Mazes and Outer Regions:"); draw(hw); doit = FALSE; when 'w': wclear(hw); wprintw(hw, "Setting game options:"); draw(hw); doit = FALSE; when 'x': wclear(hw); wprintw(hw, "Starting out:"); draw(hw); doit = FALSE; otherwise: doit = TRUE; } } wmove(hw, lines-1, 0); wprintw(hw, spacemsg); draw(hw); wait_for(' '); wclear(hw); draw(hw); wmove(cw, 0, 0); wclrtoeol(cw); status(FALSE); touchwin(cw); } /* * Real Help */ help() { register struct h_list *strp = helpstr; register struct item_list *itemp = item_help; struct h_list *wizp = wiz_help; register char helpch; register int cnt; msg("Character you want help for (* for commands, @ for items): "); helpch = wgetch(cw); mpos = 0; /* * If it's not a *, @, or +, then just print help string * for the character entered. */ if (helpch != '*' && helpch != '@' && helpch != '+') { wmove(msgw, 0, 0); while (strp->h_ch) { if (strp->h_ch == helpch) { msg("%s%s", unctrl(strp->h_ch), strp->h_desc); return; } strp++; } if (wizard) { while (wizp->h_ch) { if (wizp->h_ch == helpch) { msg("%s%s", unctrl(wizp->h_ch), wizp->h_desc); return; } wizp++; } } msg("Unknown command '%s'", unctrl(helpch)); return; } /* fortunes - but let's not say so - explicitly */ if (helpch == '+') { msg("Meaningless command '+'"); return; } /* * Print help for everything else */ if (helpch == '*') { wclear(hw); cnt = 0; while (strp->h_ch) { mvwaddstr(hw, cnt % 23, cnt > 22 ? 40 : 0, unctrl(strp->h_ch)); waddstr(hw, strp->h_desc); strp++; if (++cnt >= 46 && strp->h_ch) { wmove(hw, lines-1, 0); wprintw(hw, morestr); draw(hw); wait_for(' '); wclear(hw); cnt = 0; } } if (wizard) { while (wizp->h_ch) { mvwaddstr(hw, cnt % 23, cnt > 22 ? 40 : 0, unctrl(wizp->h_ch)); waddstr(hw, wizp->h_desc); wizp++; if (++cnt >= 46 && wizp->h_ch) { wmove(hw, lines-1, 0); wprintw(hw, morestr); draw(hw); wait_for(' '); wclear(hw); cnt = 0; } } } } if (helpch == '@') { wclear(hw); cnt = 0; while (itemp->item_ch) { mvwaddstr(hw, cnt % 23, cnt > 22 ? 40 : 0, unctrl(itemp->item_ch)); waddstr(hw, itemp->item_desc); itemp++; if (++cnt >= 46 && itemp->item_ch) { wmove(hw, lines-1, 0); wprintw(hw, morestr); draw(hw); wait_for(' '); wclear(hw); cnt = 0; } } } wmove(hw, lines-1, 0); wprintw(hw, spacemsg); draw(hw); wait_for(' '); wclear(hw); draw(hw); wmove(cw, 0, 0); wclrtoeol(cw); status(FALSE); touchwin(cw); } /* * identify: * Tell the player what a certain thing is. */ identify(ch) register unsigned char ch; { register char *str = NULL; if (ch == 0) { msg("What do you want identified? "); ch = wgetch(cw); mpos = 0; if (ch == ESC) { msg(""); return; } } if (isalpha(ch)) msg("Use the \"=\" command to identify monsters. "); else switch(ch) { case VPLAYER: str = "You (visibly)"; when IPLAYER: str = "You (invisibly)"; when GOLD: str = "Gold"; when STAIRS: str = (levtype == OUTSIDE) ? "Entrance to the dungeon" : "Stairway"; when DOOR: str = "Doorway"; when SECRETDOOR:str = "Secret door"; when FLOOR: str = (levtype == OUTSIDE) ? "Meadow" : "Room floor"; when PASSAGE: str = "Passage"; when VERTWALL: case HORZWALL: str = (levtype == OUTSIDE) ? "Boundary of sector" : "Wall of a room"; when POST: str = "Trading post"; when POOL: str = (levtype == OUTSIDE) ? "Lake" : "A shimmering pool"; when TRAPDOOR: str = "Trap door"; when ARROWTRAP: str = "Arrow trap"; when SLEEPTRAP: str = "Sleeping gas trap"; when BEARTRAP: str = "Bear trap"; when TELTRAP: str = "Teleport trap"; when DARTTRAP: str = "Dart trap"; when MAZETRAP: str = "Entrance to a maze"; when WORMHOLE: str = "Entrance to a worm hole"; when FOREST: str = "Forest"; when ' ' : str = (levtype == OUTSIDE) ? "Mountain" : "Solid rock"; when FOOD: str = "Food"; when POTION: str = "Potion"; when SCROLL: str = "Scroll"; when RING: str = "Ring"; when WEAPON: str = "Weapon"; when ARMOR: str = "Armor"; when MM: str = "Miscellaneous magic"; when STICK: str = "Wand or staff"; when RELIC: str = "Artifact"; otherwise: str = "Unknown character"; } if (!isalpha(ch)) msg("%s %s", unctrl(ch), str); }
C
/* Copyright (C) 2011-2012,2018 G.P. Halkes This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** @file */ #include <stdlib.h> #include <string.h> #include <unictype.h> #include "internal.h" #include "log.h" #include "utf8.h" #include "window.h" /** @internal @brief The maximum size of a UTF-8 character in bytes. Used in ::t3_win_addnstr. */ #define UTF8_MAX_BYTES 4 /* Attribute to index mapping. To make the mapping quick, a simple hash table with hash chaining is used. */ typedef struct attr_map_t attr_map_t; struct attr_map_t { t3_attr_t attr; int next; }; /** @internal @brief The initial allocation for ::attr_map. */ #define ATTR_MAP_START_SIZE 32 /** @internal @brief The size of the hash map used for ::t3_attr_t mapping. */ #define ATTR_HASH_MAP_SIZE 337 static attr_map_t *attr_map; /**< @internal @brief The map of indices to attribute sets. */ static int attr_map_fill, /**< @internal @brief The number of elements used in ::attr_map. */ attr_map_allocated; /**< @internal @brief The number of elements allocated in ::attr_map. */ static int attr_hash_map[ATTR_HASH_MAP_SIZE]; /**< @internal @brief Hash map for quickly mapping ::t3_attr_t's to indices. */ /** @addtogroup t3window_win */ /** @{ */ /** Ensure that a line_data_t struct has at least a specified number of bytes of unused space. @param line The line_data_t struct to check. @param n The required unused space in bytes. @return A boolean indicating whether, after possibly reallocating, the requested number of bytes is available. */ static t3_bool ensure_space(line_data_t *line, size_t n) { int newsize; char *resized; if (n > INT_MAX || INT_MAX - (int)n < line->length) { return t3_false; } if (line->allocated > line->length + (int)n) { return t3_true; } newsize = line->allocated; do { /* Sanity check for overflow of allocated variable. Prevents infinite loops. */ if (newsize > INT_MAX / 2) { newsize = INT_MAX; } else { newsize *= 2; } } while (newsize - line->length < (int)n); if ((resized = realloc(line->data, sizeof(t3_attr_t) * newsize)) == NULL) { return t3_false; } line->data = resized; line->allocated = newsize; return t3_true; } /** @internal @brief Map a set of attributes to an integer. @param attr The attribute set to map. */ int _t3_map_attr(t3_attr_t attr) { int ptr; for (ptr = attr_hash_map[attr % ATTR_HASH_MAP_SIZE]; ptr != -1 && attr_map[ptr].attr != attr; ptr = attr_map[ptr].next) { } if (ptr != -1) { return ptr; } if (attr_map_fill >= attr_map_allocated) { int new_allocation = attr_map_allocated == 0 ? ATTR_MAP_START_SIZE : attr_map_allocated * 2; attr_map_t *new_map; if ((new_map = realloc(attr_map, new_allocation * sizeof(attr_map_t))) == NULL) { return -1; } attr_map = new_map; attr_map_allocated = new_allocation; } attr_map[attr_map_fill].attr = attr; attr_map[attr_map_fill].next = attr_hash_map[attr % ATTR_HASH_MAP_SIZE]; attr_hash_map[attr % ATTR_HASH_MAP_SIZE] = attr_map_fill; return attr_map_fill++; } /** @internal @brief Get the set of attributes associated with a mapped integer. @param idx The mapped attribute index as returned by ::_t3_map_attr. */ t3_attr_t _t3_get_attr(int idx) { if (idx < 0 || idx > attr_map_fill) { return 0; } return attr_map[idx].attr; } /** @internal @brief Initialize data structures used for attribute set mappings. */ void _t3_init_attr_map(void) { int i; for (i = 0; i < ATTR_HASH_MAP_SIZE; i++) { attr_hash_map[i] = -1; } } /** @internal @brief Clean up the memory used for attribute set mappings. */ void _t3_free_attr_map(void) { #ifdef _T3_WINDOW_DEBUG { int ptr, chain, avg = 0, max = 0, chains = 0; int chain_length = 0; for (chain = 0; chain < ATTR_HASH_MAP_SIZE; chain++) { for (ptr = attr_hash_map[chain], chain_length = 0; ptr != -1; ptr = attr_map[ptr].next, chain_length++) { } if (chain_length > max) max = chain_length; if (chain_length > 0) { chains++; avg += chain_length; } } lprintf("max: %d, chains: %d, avg: %.2f, attrs: %d\n", max, chains, (double)avg / chains, attr_map_fill); } #endif free(attr_map); attr_map = NULL; attr_map_allocated = 0; attr_map_fill = 0; _t3_init_attr_map(); } /** Get the first UTF-8 value encoded in a string. @param src The UTF-8 string to parse. @param size The location to store the size of the character. @return The value at the start of @p src. @note This function assumes that the input is a valid UTF-8 encoded value. */ uint32_t _t3_get_value_int(const char *src, size_t *size) { int bytes_left; uint32_t retval; switch ((uint8_t)src[0]) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47: case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: case 58: case 59: case 60: case 61: case 62: case 63: case 64: case 65: case 66: case 67: case 68: case 69: case 70: case 71: case 72: case 73: case 74: case 75: case 76: case 77: case 78: case 79: case 80: case 81: case 82: case 83: case 84: case 85: case 86: case 87: case 88: case 89: case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97: case 98: case 99: case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107: case 108: case 109: case 110: case 111: case 112: case 113: case 114: case 115: case 116: case 117: case 118: case 119: case 120: case 121: case 122: case 123: case 124: case 125: case 126: case 127: *size = 1; return src[0]; case 194: case 195: case 196: case 197: case 198: case 199: case 200: case 201: case 202: case 203: case 204: case 205: case 206: case 207: case 208: case 209: case 210: case 211: case 212: case 213: case 214: case 215: case 216: case 217: case 218: case 219: case 220: case 221: case 222: case 223: bytes_left = 1; retval = src[0] & 0x1F; break; case 224: case 225: case 226: case 227: case 228: case 229: case 230: case 231: case 232: case 233: case 234: case 235: case 236: case 237: case 238: case 239: bytes_left = 2; retval = src[0] & 0x0F; break; case 240: case 241: case 242: case 243: case 244: case 245: case 246: case 247: bytes_left = 3; retval = src[0] & 0x07; break; case 248: case 249: case 250: case 251: bytes_left = 4; retval = src[0] & 0x03; break; case 252: case 253: bytes_left = 5; retval = src[1] & 1; break; default: /* This should never occur, as we only use this to read values we generated ourselves. However, the compiler will start fussing if we don't add this. */ *size = 0; return 0; } *size = bytes_left + 1; src++; for (; bytes_left > 0; bytes_left--) { retval = (retval << 6) | (src++[0] & 0x3f); } return retval; } /** Write a UTF-8 encoded value. @param c The codepoint to convert. @param dst The location to store the result. @return The number of bytes stored in @p dst. The value must be lower than 0x80000000 (i.e. at most 31 bits may be used). No check is made for this however, so the calling code must ensure that this is the case. */ size_t _t3_put_value(uint32_t c, char *dst) { if (c < 0x80) { dst[0] = c; return 1; } else if (c < 0x800) { dst[0] = 0xc0 | (c >> 6); dst[1] = 0x80 | (c & 0x3f); return 2; } else if (c < 0x10000) { dst[0] = 0xe0 | (c >> 12); dst[1] = 0x80 | ((c >> 6) & 0x3f); dst[2] = 0x80 | (c & 0x3f); return 3; } else if (c < 0x200000) { dst[0] = 0xf0 | (c >> 18); dst[1] = 0x80 | ((c >> 12) & 0x3f); dst[2] = 0x80 | ((c >> 6) & 0x3f); dst[3] = 0x80 | (c & 0x3f); return 4; } else if (c < 0x4000000) { dst[0] = 0xf8 | (c >> 24); dst[1] = 0x80 | ((c >> 18) & 0x3f); dst[1] = 0x80 | ((c >> 12) & 0x3f); dst[2] = 0x80 | ((c >> 6) & 0x3f); dst[3] = 0x80 | (c & 0x3f); return 5; } else { dst[0] = 0xfc | (c >> 30); dst[1] = 0x80 | ((c >> 24) & 0x3f); dst[1] = 0x80 | ((c >> 18) & 0x3f); dst[1] = 0x80 | ((c >> 12) & 0x3f); dst[2] = 0x80 | ((c >> 6) & 0x3f); dst[3] = 0x80 | (c & 0x3f); return 6; } } /** Create memory block representing a space character with specific attributes. @param attr The attribute index to use. @param out An array of size at least 8 to write to. @return The number of bytes written to @p out. */ static size_t create_space_block(int attr, char *out) { size_t result_size; result_size = _t3_put_value(attr, out + 1); result_size++; out[result_size] = ' '; out[0] = result_size << 1; result_size++; return result_size; } /** Get the attribute index from a block. */ static uint32_t get_block_attr(const char *block) { size_t discard; for (block++; ((*block) & 0xc0) == 0x80; block++) { } return _t3_get_value(block, &discard); } /** Insert a zero-width character into an existing block. @param win The window to write to. @param str The string containing the UTF-8 encoded zero-width character. @param n The number of bytes in @p str. @return A boolean indicating success. */ static t3_bool _win_add_zerowidth(t3_window_t *win, const char *str, size_t n) { uint32_t block_size, new_block_size; size_t block_size_bytes, new_block_size_bytes; char new_block_size_str[6]; int pos_width, i; if (win->lines == NULL) { return t3_false; } if (win->paint_y >= win->height) { return t3_true; } /* Combining characters may be added _at_ width. */ if (win->paint_x > win->width) { return t3_true; } if (win->cached_pos_line != win->paint_y || win->cached_pos_width >= win->paint_x) { win->cached_pos_line = win->paint_y; win->cached_pos = 0; win->cached_pos_width = win->lines[win->paint_y].start; } /* Simply drop characters that don't belong to any other character. */ if (win->lines[win->paint_y].length == 0 || win->paint_x <= win->lines[win->paint_y].start || win->paint_x > win->lines[win->paint_y].start + win->lines[win->paint_y].width) { return t3_true; } /* Ensure we have space for n characters, and possibly extend the block size header by 1. */ if (!ensure_space(win->lines + win->paint_y, n + 1)) { return t3_false; } pos_width = win->cached_pos_width; /* Locate the first character that at least partially overlaps the position where this string is supposed to go. Note that this loop will iterate at least once, because if win->cached_pos == win->lines[win->paint_y].length, then win->cached_pos_width will equal win->paint_x, and thereby get invalidated above. */ block_size = 0; /* Shut up the compiler. */ for (i = win->cached_pos; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) { block_size = _t3_get_value(win->lines[win->paint_y].data + i, &block_size_bytes); pos_width += _T3_BLOCK_SIZE_TO_WIDTH(block_size); /* Do the check for whether we found the insertion point here, so we don't update i. */ if (pos_width >= win->paint_x) { break; } } /* Check whether we are being asked to add a zero-width character in the middle of a double-width character. If so, ignore. */ if (pos_width > win->paint_x) { return t3_true; } new_block_size = block_size + (n << 1); new_block_size_bytes = _t3_put_value(new_block_size, new_block_size_str); /* WARNING: from this point on, the block_size and new_block_size variables have a new meaning: the actual size of the block, rather than including the bit indicating the width of the character as well. */ block_size >>= 1; new_block_size >>= 1; /* Move the data after the insertion point up by the size of the character string to insert and the difference in block size header size. */ memmove(win->lines[win->paint_y].data + i + new_block_size + new_block_size_bytes, win->lines[win->paint_y].data + i + block_size + block_size_bytes, win->lines[win->paint_y].length - i - block_size - block_size_bytes); /* Copy the bytes of the new character into the string. */ memcpy(win->lines[win->paint_y].data + i + block_size + block_size_bytes, str, n); /* If applicable, move the data for this block by the difference in block size header size. */ if (new_block_size_bytes != block_size_bytes) { memmove(win->lines[win->paint_y].data + i + new_block_size_bytes, win->lines[win->paint_y].data + i + block_size_bytes, new_block_size); } /* Copy in the new block size header. */ memcpy(win->lines[win->paint_y].data + i, new_block_size_str, new_block_size_bytes); win->lines[win->paint_y].length += n + (new_block_size_bytes - block_size_bytes); return t3_true; } /** Write one or more blocks to a window. @param win The window to write to. @param blocks The string containing the blocks. @param n The number of bytes in @p blocks. @return A boolean indicating success. */ static t3_bool _win_write_blocks(t3_window_t *win, const char *blocks, size_t n) { uint32_t block_size; size_t block_size_bytes; size_t k; int i; int width = 0; int extra_spaces = 0; uint32_t extra_spaces_attr; t3_bool result = t3_true; if (win->lines == NULL) { return t3_false; } if (win->paint_y >= win->height || win->paint_x >= win->width || n == 0) { return t3_true; } for (k = 0; k < n; k += (block_size >> 1) + block_size_bytes) { block_size = _t3_get_value(blocks + k, &block_size_bytes); if (win->paint_x + width + _T3_BLOCK_SIZE_TO_WIDTH(block_size) > win->width) { break; } width += _T3_BLOCK_SIZE_TO_WIDTH(block_size); } if (k < n) { extra_spaces = win->width - win->paint_x - width; extra_spaces_attr = get_block_attr(blocks + k); } n = k; if (win->cached_pos_line != win->paint_y || win->cached_pos_width > win->paint_x) { win->cached_pos_line = win->paint_y; win->cached_pos = 0; win->cached_pos_width = win->lines[win->paint_y].start; } if (win->lines[win->paint_y].length == 0) { /* Empty line. */ if (!ensure_space(win->lines + win->paint_y, n)) { return t3_false; } win->lines[win->paint_y].start = win->paint_x; memcpy(win->lines[win->paint_y].data, blocks, n); win->lines[win->paint_y].length += n; win->lines[win->paint_y].width = width; win->cached_pos_line = -1; } else if (win->lines[win->paint_y].start + win->lines[win->paint_y].width <= win->paint_x) { /* Add characters after existing characters. */ char default_attr_str[8]; size_t default_attr_size; int diff = win->paint_x - (win->lines[win->paint_y].start + win->lines[win->paint_y].width); default_attr_size = create_space_block(_t3_map_attr(win->default_attrs), default_attr_str); if (!ensure_space(win->lines + win->paint_y, n + diff * (default_attr_size))) { return t3_false; } for (i = diff; i > 0; i--) { memcpy(win->lines[win->paint_y].data + win->lines[win->paint_y].length, default_attr_str, default_attr_size); win->lines[win->paint_y].length += default_attr_size; } memcpy(win->lines[win->paint_y].data + win->lines[win->paint_y].length, blocks, n); win->lines[win->paint_y].length += n; win->lines[win->paint_y].width += width + diff; } else if (win->paint_x + width <= win->lines[win->paint_y].start) { /* Add characters before existing characters. */ char default_attr_str[8]; size_t default_attr_size; int diff = win->lines[win->paint_y].start - (win->paint_x + width); default_attr_size = create_space_block(_t3_map_attr(win->default_attrs), default_attr_str); if (!ensure_space(win->lines + win->paint_y, n + diff * default_attr_size)) { return t3_false; } memmove(win->lines[win->paint_y].data + n + diff * default_attr_size, win->lines[win->paint_y].data, win->lines[win->paint_y].length); memcpy(win->lines[win->paint_y].data, blocks, n); for (i = diff; i > 0; i--) { memcpy(win->lines[win->paint_y].data + n, default_attr_str, default_attr_size); n += default_attr_size; } win->lines[win->paint_y].length += n; win->lines[win->paint_y].width += width + diff; win->lines[win->paint_y].start = win->paint_x; /* Inserting before existing characters invalidates the cached position. */ win->cached_pos_line = -1; } else { /* Character (partly) overwrite existing chars. */ int pos_width = win->cached_pos_width; size_t start_replace = 0, start_space_attr, start_spaces, end_replace, end_space_attr, end_spaces; int sdiff; char start_space_str[8], end_space_str[8]; size_t start_space_bytes, end_space_bytes; /* Locate the first character that at least partially overlaps the position where this string is supposed to go. Note that this loop will always be entered once, because win->cached_pos will always be < line length. To see why this is the case, consider that when win->cached_pos equals the line length. Then win->paint_x equals the width of the line and that case will be handled above. */ block_size = 0; /* Shut up the compiler. */ for (i = win->cached_pos; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) { block_size = _t3_get_value(win->lines[win->paint_y].data + i, &block_size_bytes); if (_T3_BLOCK_SIZE_TO_WIDTH(block_size) + pos_width > win->paint_x) { break; } pos_width += _T3_BLOCK_SIZE_TO_WIDTH(block_size); } win->cached_pos = i; win->cached_pos_width = pos_width; start_replace = i; /* If the character only partially overlaps, we replace the first part with spaces with the attributes of the old character. */ start_space_attr = get_block_attr(win->lines[win->paint_y].data + start_replace); start_spaces = win->paint_x >= win->lines[win->paint_y].start ? win->paint_x - pos_width : 0; /* Now we need to find which other character(s) overlap. However, the current string may overlap with a double width character but only for a single position. In that case we will replace the trailing portion of the character with spaces with the old character's attributes. */ pos_width += _T3_BLOCK_SIZE_TO_WIDTH(block_size); i += (block_size >> 1) + block_size_bytes; /* If the character where we start overwriting already fully overlaps with the new string, then we need to only replace this and any spaces that result from replacing the trailing portion need to use the start space attribute */ if (pos_width >= win->paint_x + width) { end_space_attr = start_space_attr; end_replace = i; } else { for (; i < win->lines[win->paint_y].length; i += (block_size >> 1) + block_size_bytes) { block_size = _t3_get_value(win->lines[win->paint_y].data + i, &block_size_bytes); pos_width += _T3_BLOCK_SIZE_TO_WIDTH(block_size); if (pos_width >= win->paint_x + width) { break; } } end_space_attr = get_block_attr(win->lines[win->paint_y].data + i); end_replace = i < win->lines[win->paint_y].length ? (int)(i + (block_size >> 1) + block_size_bytes) : i; } end_spaces = pos_width > win->paint_x + width ? pos_width - win->paint_x - width : 0; start_space_bytes = create_space_block(start_space_attr, start_space_str); end_space_bytes = create_space_block(end_space_attr, end_space_str); /* Move the existing characters out of the way. */ sdiff = n + end_spaces * end_space_bytes + start_spaces * start_space_bytes - (end_replace - start_replace); if (sdiff > 0 && !ensure_space(win->lines + win->paint_y, sdiff)) { return t3_false; } memmove(win->lines[win->paint_y].data + end_replace + sdiff, win->lines[win->paint_y].data + end_replace, win->lines[win->paint_y].length - end_replace); for (i = start_replace; start_spaces > 0; start_spaces--) { memcpy(win->lines[win->paint_y].data + i, start_space_str, start_space_bytes); i += start_space_bytes; } memcpy(win->lines[win->paint_y].data + i, blocks, n); i += n; for (; end_spaces > 0; end_spaces--) { memcpy(win->lines[win->paint_y].data + i, end_space_str, end_space_bytes); i += end_space_bytes; } win->lines[win->paint_y].length += sdiff; if (win->lines[win->paint_y].start + win->lines[win->paint_y].width < width + win->paint_x) { win->lines[win->paint_y].width = width + win->paint_x - win->lines[win->paint_y].start; } if (win->lines[win->paint_y].start > win->paint_x) { win->lines[win->paint_y].width += win->lines[win->paint_y].start - win->paint_x; win->lines[win->paint_y].start = win->paint_x; win->cached_pos_line = -1; } } win->paint_x += width; if (extra_spaces > 0) { char extra_space_str[8]; size_t extra_space_bytes; extra_space_bytes = create_space_block(extra_spaces_attr, extra_space_str); for (i = 0; i < extra_spaces; i++) { result &= _win_write_blocks(win, extra_space_str, extra_space_bytes); } } return result; } /** Add a string with explicitly specified size to a t3_window_t with specified attributes. @param win The t3_window_t to add the string to. @param str The string to add. @param n The size of @p str. @param attrs The attributes to use. @retval ::T3_ERR_SUCCESS on succes @retval ::T3_ERR_NONPRINT if a control character was encountered. @retval ::T3_ERR_ERRNO otherwise. The default attributes are combined with the specified attributes, with @p attr used as the priority attributes. All other t3_win_add* functions are (indirectly) implemented using this function. It is important that combining characters are provided in the same string as the characters they are to combine with. In particular, this function does not check for conjoining Jamo in the existing window data and explicitly prevents joining. */ int t3_win_addnstr(t3_window_t *win, const char *str, size_t n, t3_attr_t attrs) { size_t bytes_read; char block[1 + 6 + UTF8_MAX_BYTES]; uint32_t c; int retval = T3_ERR_SUCCESS; int width; int attrs_idx; size_t block_bytes; attrs = _t3_term_sanitize_attrs(attrs); attrs = t3_term_combine_attrs(attrs, win->default_attrs); /* From this point on, there is no need to keep information about explicit setting of attributes, as there will be no more combining. Thus we scrub that information to keep the number of mapped attributes to a minimum. */ attrs &= ~T3_ATTR_SET_MASK; attrs_idx = _t3_map_attr(attrs); if (attrs_idx < 0) { return T3_ERR_OUT_OF_MEMORY; } int width_state = 0; for (; n > 0; n -= bytes_read, str += bytes_read) { bytes_read = n; c = t3_utf8_get(str, &bytes_read); int old_width_state = width_state; width = t3_utf8_wcwidth_ext(c, &width_state); if (old_width_state != 0 && width_state == 0) { /* Ending a block with a conjoining Jamo character can cause problems when the succeeding cell later is overwritten with a joining character. To prevent this issue, insert a zero-with non-joiner. */ if (width_state != 0) { _win_add_zerowidth(win, "\xE2\x80\x8C", 3); } } /* UC_CATEGORY_MASK_Cn is for unassigned/reserved code points. These are not necessarily unprintable. */ if (width < 0 || uc_is_general_category_withtable(c, T3_UTF8_CONTROL_MASK)) { retval = T3_ERR_NONPRINT; continue; } else if (width == 0) { _win_add_zerowidth(win, str, bytes_read); continue; } block_bytes = _t3_put_value(attrs_idx, block + 1); memcpy(block + 1 + block_bytes, str, bytes_read); block_bytes += bytes_read; _t3_put_value((block_bytes << 1) + (width == 2 ? 1 : 0), block); block_bytes++; if (!_win_write_blocks(win, block, block_bytes)) { return T3_ERR_ERRNO; } } /* Ending a block with a conjoining Jamo character can cause problems when the succeeding cell later is overwritten with a joining character. To prevent this issue, insert a zero-with non-joiner. */ if (width_state != 0) { _win_add_zerowidth(win, "\xE2\x80\x8C", 3); } return retval; } /** Add a nul-terminated string to a t3_window_t with specified attributes. @param win The t3_window_t to add the string to. @param str The nul-terminated string to add. @param attr The attributes to use. @return See ::t3_win_addnstr. See ::t3_win_addnstr for further information. */ int t3_win_addstr(t3_window_t *win, const char *str, t3_attr_t attr) { return t3_win_addnstr(win, str, strlen(str), attr); } /** Add a single character to a t3_window_t with specified attributes. @param win The t3_window_t to add the string to. @param c The character to add. @param attr The attributes to use. @return See ::t3_win_addnstr. @p c must be an ASCII character. See ::t3_win_addnstr for further information. */ int t3_win_addch(t3_window_t *win, char c, t3_attr_t attr) { return t3_win_addnstr(win, &c, 1, attr); } /** Add a string with explicitly specified size to a t3_window_t with specified attributes and repetition. @param win The t3_window_t to add the string to. @param str The string to add. @param n The size of @p str. @param attr The attributes to use. @param rep The number of times to repeat @p str. @return See ::t3_win_addnstr. All other t3_win_add*rep functions are (indirectly) implemented using this function. See ::t3_win_addnstr for further information. */ int t3_win_addnstrrep(t3_window_t *win, const char *str, size_t n, t3_attr_t attr, int rep) { int i, ret; for (i = 0; i < rep; i++) { ret = t3_win_addnstr(win, str, n, attr); if (ret != 0) { return ret; } } return 0; } /** Add a nul-terminated string to a t3_window_t with specified attributes and repetition. @param win The t3_window_t to add the string to. @param str The nul-terminated string to add. @param attr The attributes to use. @param rep The number of times to repeat @p str. @return See ::t3_win_addnstr. See ::t3_win_addnstrrep for further information. */ int t3_win_addstrrep(t3_window_t *win, const char *str, t3_attr_t attr, int rep) { return t3_win_addnstrrep(win, str, strlen(str), attr, rep); } /** Add a character to a t3_window_t with specified attributes and repetition. @param win The t3_window_t to add the string to. @param c The character to add. @param attr The attributes to use. @param rep The number of times to repeat @p c. @return See ::t3_win_addnstr. See ::t3_win_addnstrrep for further information. */ int t3_win_addchrep(t3_window_t *win, char c, t3_attr_t attr, int rep) { return t3_win_addnstrrep(win, &c, 1, attr, rep); } /** Get the next t3_window_t, when iterating over the t3_window_t's for drawing. @param ptr The last t3_window_t that was handled. */ static t3_window_t *get_previous_window(t3_window_t *ptr) { if (ptr->shown && ptr->tail != NULL) { ptr = ptr->tail; if (ptr->shown) { return ptr; } } do { while (ptr->prev != NULL) { ptr = ptr->prev; if (ptr->shown) { return ptr; } } ptr = ptr->parent; } while (ptr != NULL); return NULL; } static t3_bool write_spaces_to_terminal_window(int attr_idx, int count) { char space_str[64]; size_t space_str_bytes; int i; t3_bool result = true; space_str_bytes = create_space_block(attr_idx, space_str); if (count > 1) { memcpy(space_str + space_str_bytes, space_str, space_str_bytes); if (count > 2) { memcpy(space_str + space_str_bytes * 2, space_str, space_str_bytes * 2); if (count > 4) { memcpy(space_str + space_str_bytes * 4, space_str, space_str_bytes * 4); } } } for (i = count / 8; i > 0; i--) { result &= _win_write_blocks(_t3_terminal_window, space_str, space_str_bytes * 8); } result &= _win_write_blocks(_t3_terminal_window, space_str, space_str_bytes * (count & 7)); return result; } /** @internal @brief Redraw a terminal line, based on all visible t3_window_t structs. @param terminal The t3_window_t representing the cached terminal contents. @param line The line to redraw. @return A boolean indicating whether redrawing succeeded without memory errors. */ t3_bool _t3_win_refresh_term_line(int line) { line_data_t *draw; t3_window_t *ptr; int y, x, parent_y, parent_x, parent_max_y, parent_max_x; int data_start, length, paint_x; t3_bool result = t3_true; uint32_t block_size; size_t block_size_bytes; _t3_terminal_window->paint_y = line; _t3_terminal_window->lines[line].width = 0; _t3_terminal_window->lines[line].length = 0; _t3_terminal_window->lines[line].start = 0; for (ptr = _t3_tail != NULL && !_t3_tail->shown ? get_previous_window(_t3_tail) : _t3_tail; ptr != NULL; ptr = get_previous_window(ptr)) { if (ptr->lines == NULL) { continue; } y = t3_win_get_abs_y(ptr); if (y > line || y + ptr->height <= line) { continue; } if (ptr->parent == NULL) { parent_y = 0; parent_max_y = _t3_terminal_window->height; parent_x = 0; parent_max_x = _t3_terminal_window->width; } else { t3_window_t *parent = ptr->parent; parent_y = INT_MIN; parent_max_y = INT_MAX; parent_x = INT_MIN; parent_max_x = INT_MAX; do { int tmp; tmp = t3_win_get_abs_y(parent); if (tmp > parent_y) { parent_y = tmp; } tmp += parent->height; if (tmp < parent_max_y) { parent_max_y = tmp; } tmp = t3_win_get_abs_x(parent); if (tmp > parent_x) { parent_x = tmp; } tmp += parent->width; if (tmp < parent_max_x) { parent_max_x = tmp; } parent = parent->parent; } while (parent != NULL); } /* Skip lines that are clipped by the parent window. */ if (line < parent_y || line >= parent_max_y) { continue; } if (parent_x < 0) { parent_x = 0; } if (parent_max_x > _t3_terminal_window->width) { parent_max_x = _t3_terminal_window->width; } draw = ptr->lines + line - y; x = t3_win_get_abs_x(ptr); /* Skip lines that are fully clipped by the parent window. */ if (x >= parent_max_x || x + draw->start + draw->width < parent_x) { continue; } data_start = 0; /* Draw/skip unused leading part of line. */ if (x + draw->start >= parent_x) { int start; if (x + draw->start > parent_max_x) { start = parent_max_x - x; } else { start = draw->start; } if (ptr->default_attrs == 0) { _t3_terminal_window->paint_x = x + start; } else if (x >= parent_x) { _t3_terminal_window->paint_x = x; result &= write_spaces_to_terminal_window(_t3_map_attr(ptr->default_attrs), start); } else { _t3_terminal_window->paint_x = parent_x; result &= write_spaces_to_terminal_window(_t3_map_attr(ptr->default_attrs), start - parent_x + x); } } else /* if (x < parent_x) */ { _t3_terminal_window->paint_x = parent_x; for (paint_x = x + draw->start; data_start < draw->length; data_start += (block_size >> 1) + block_size_bytes) { block_size = _t3_get_value(draw->data + data_start, &block_size_bytes); if (paint_x + _T3_BLOCK_SIZE_TO_WIDTH(block_size) > _t3_terminal_window->paint_x) { break; } paint_x += _T3_BLOCK_SIZE_TO_WIDTH(block_size); } if (data_start < draw->length && paint_x < _t3_terminal_window->paint_x) { paint_x += _T3_BLOCK_SIZE_TO_WIDTH(block_size); result &= write_spaces_to_terminal_window(get_block_attr(draw->data + data_start), paint_x - _t3_terminal_window->paint_x); data_start += (block_size >> 1) + block_size_bytes; } } paint_x = _t3_terminal_window->paint_x; for (length = data_start; length < draw->length; length += (block_size >> 1) + block_size_bytes) { block_size = _t3_get_value(draw->data + length, &block_size_bytes); if (paint_x + _T3_BLOCK_SIZE_TO_WIDTH(block_size) > parent_max_x) { break; } paint_x += _T3_BLOCK_SIZE_TO_WIDTH(block_size); } if (length != data_start) { result &= _win_write_blocks(_t3_terminal_window, draw->data + data_start, length - data_start); } /* Add a space for the multi-cell character that is crossed by the parent clipping. */ if (length < draw->length && paint_x == parent_max_x - 1) { result &= write_spaces_to_terminal_window(get_block_attr(draw->data + length), 1); } if (ptr->default_attrs != 0 && draw->start + draw->width < ptr->width && x + draw->start + draw->width < parent_max_x) { result &= write_spaces_to_terminal_window(_t3_map_attr(ptr->default_attrs), x + ptr->width <= parent_max_x ? ptr->width - draw->start - draw->width : parent_max_x - x - draw->start - draw->width); } } /* If the default attributes for the terminal are not only a foreground color, we need to ensure that we paint the terminal. */ if ((_t3_terminal_window->default_attrs & ~T3_ATTR_FG_MASK) != 0) { if (_t3_terminal_window->lines[line].start != 0) { _t3_terminal_window->paint_x = 0; result &= write_spaces_to_terminal_window(_t3_map_attr(_t3_terminal_window->default_attrs), 1); } if (_t3_terminal_window->lines[line].width + _t3_terminal_window->lines[line].start < _t3_terminal_window->width) { /* Make sure we fill the whole line. Adding the final character to an otherwise empty line doesn't do anything for us. */ if (_t3_terminal_window->lines[line].width == 0) { _t3_terminal_window->paint_x = 0; result &= write_spaces_to_terminal_window(_t3_map_attr(_t3_terminal_window->default_attrs), 1); } _t3_terminal_window->paint_x = _t3_terminal_window->width - 1; result &= write_spaces_to_terminal_window(_t3_map_attr(_t3_terminal_window->default_attrs), 1); } } return result; } /** Clear current t3_window_t painting line to end. */ void t3_win_clrtoeol(t3_window_t *win) { if (win->paint_y >= win->height || win->lines == NULL) { return; } if (win->paint_x <= win->lines[win->paint_y].start) { win->lines[win->paint_y].length = 0; win->lines[win->paint_y].width = 0; win->lines[win->paint_y].start = 0; } else if (win->paint_x < win->lines[win->paint_y].start + win->lines[win->paint_y].width) { int sumwidth = win->lines[win->paint_y].start, i; uint32_t block_size; size_t block_size_bytes; block_size = _t3_get_value(win->lines[win->paint_y].data, &block_size_bytes); for (i = 0; i < win->lines[win->paint_y].length && sumwidth + _T3_BLOCK_SIZE_TO_WIDTH(block_size) <= win->paint_x; i += (block_size >> 1) + block_size_bytes) { sumwidth += _T3_BLOCK_SIZE_TO_WIDTH(block_size); block_size = _t3_get_value(win->lines[win->paint_y].data + i, &block_size_bytes); } win->lines[win->paint_y].length = i; if (sumwidth < win->paint_x) { int spaces = win->paint_x - sumwidth; char space_str[8]; size_t space_str_bytes; win->paint_x = sumwidth; space_str_bytes = create_space_block(_t3_map_attr(win->default_attrs), space_str); if (ensure_space(win->lines + win->paint_y, spaces * space_str_bytes - win->lines[win->paint_y].length + i)) { for (; spaces > 0; spaces--) { _win_write_blocks(win, space_str, space_str_bytes); } } } win->lines[win->paint_y].width = win->paint_x - win->lines[win->paint_y].start; } } #define ABORT_ON_FAIL(x) \ do { \ int retval; \ if ((retval = (x)) != 0) return retval; \ } while (0) /** Draw a box on a t3_window_t. @param win The t3_window_t to draw on. @param y The line of the t3_window_t to start drawing on. @param x The column of the t3_window_t to start drawing on. @param height The height of the box to draw. @param width The width of the box to draw. @param attr The attributes to use for drawing. @return See ::t3_win_addnstr. */ int t3_win_box(t3_window_t *win, int y, int x, int height, int width, t3_attr_t attr) { int i; attr = t3_term_combine_attrs(attr | T3_ATTR_ACS, win->default_attrs); if (y >= win->height || y + height > win->height || x >= win->width || x + width > win->width || win->lines == NULL) { return -1; } t3_win_set_paint(win, y, x); ABORT_ON_FAIL(t3_win_addch(win, T3_ACS_ULCORNER, attr)); ABORT_ON_FAIL(t3_win_addchrep(win, T3_ACS_HLINE, attr, width - 2)); ABORT_ON_FAIL(t3_win_addch(win, T3_ACS_URCORNER, attr)); for (i = 1; i < height - 1; i++) { t3_win_set_paint(win, y + i, x); ABORT_ON_FAIL(t3_win_addch(win, T3_ACS_VLINE, attr)); t3_win_set_paint(win, y + i, x + width - 1); ABORT_ON_FAIL(t3_win_addch(win, T3_ACS_VLINE, attr)); } t3_win_set_paint(win, y + height - 1, x); ABORT_ON_FAIL(t3_win_addch(win, T3_ACS_LLCORNER, attr)); ABORT_ON_FAIL(t3_win_addchrep(win, T3_ACS_HLINE, attr, width - 2)); ABORT_ON_FAIL(t3_win_addch(win, T3_ACS_LRCORNER, attr)); return T3_ERR_SUCCESS; } /** Clear current t3_window_t painting line to end and all subsequent lines fully. */ void t3_win_clrtobot(t3_window_t *win) { if (win->lines == NULL) { return; } t3_win_clrtoeol(win); for (win->paint_y++; win->paint_y < win->height; win->paint_y++) { win->lines[win->paint_y].length = 0; win->lines[win->paint_y].width = 0; win->lines[win->paint_y].start = 0; } } /** Find the top-most window at a location @return The top-most window at the specified location, or @c NULL if no window covers the specified location. */ t3_window_t *t3_win_at_location(int search_y, int search_x) { t3_window_t *ptr, *result = NULL; int y, x, parent_y, parent_x, parent_max_y, parent_max_x; for (ptr = _t3_tail != NULL && !_t3_tail->shown ? get_previous_window(_t3_tail) : _t3_tail; ptr != NULL; ptr = get_previous_window(ptr)) { y = t3_win_get_abs_y(ptr); if (y > search_y || y + ptr->height <= search_y) { continue; } x = t3_win_get_abs_x(ptr); if (x > search_x || x + ptr->width <= search_x) { continue; } if (ptr->parent != NULL) { t3_window_t *parent = ptr->parent; parent_y = INT_MIN; parent_max_y = INT_MAX; parent_x = INT_MIN; parent_max_x = INT_MAX; do { int tmp; tmp = t3_win_get_abs_y(parent); if (tmp > parent_y) { parent_y = tmp; } tmp += parent->height; if (tmp < parent_max_y) { parent_max_y = tmp; } tmp = t3_win_get_abs_x(parent); if (tmp > parent_x) { parent_x = tmp; } tmp += parent->width; if (tmp < parent_max_x) { parent_max_x = tmp; } parent = parent->parent; } while (parent != NULL); if (search_y < parent_y || search_y >= parent_max_y) { continue; } if (search_x < parent_x || search_x >= parent_max_x) { continue; } } result = ptr; } return result; } /** @} */
C
#include <stdio.h> int main(int argc, char const *argv[]) { int const array[5] = {1, 2, 3, 4, 5}; printf("Puvoni hodnoty: "); for (int i = 0; i < 5; i++) { printf("%d, ", array[i]); } printf("\n"); printf("Nove hodnoty: "); for (int i = 4; i >= 0; i--) { printf("%d, ", array[i]); } printf("\n"); return 0; }
C
#ifndef WRITE_POPULATION_STATISTICS_IN_FILE_H #define WRITE_POPULATION_STATISTICS_IN_FILE_H #include "create_population.h" #include "agent_struct.h" #include "counters_struct.h" //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Write Population Statistics in File void writePopulationStatisticsInFile( FILE *simulation_statistics_file , struct counters *population_info_struct_ , int day_int_ ) { int i_int, j_int; fprintf( simulation_statistics_file,\ "\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~day - %d\n", day_int_ ) ; fprintf( simulation_statistics_file , "\nPopulation Status:\n" ) ; fprintf( simulation_statistics_file, "\tAverage Age = %.2f\n", ( population_info_struct_->average_age_int/(size_x_int*size_y_int)) ) ; fprintf( simulation_statistics_file , "\tpercentage_of_male_float = %.2f\n" , ( population_info_struct_->number_of_male_int/(size_x_int*size_y_int)) ) ; fprintf( simulation_statistics_file, "\tpercentage_of_vaccination_float = %.2f\n", ( population_info_struct_->number_of_vaccinated_int / (size_x_int*size_y_int) ) ) ; fprintf( simulation_statistics_file , "\nDisease Status:\n" ) ; fprintf( simulation_statistics_file, "\tpercentage_of_susceptible_float = %.2f\n", ( population_info_struct_->number_of_susceptible_int / (size_x_int*size_y_int) ) ) ; fprintf( simulation_statistics_file, "\tpercentage_of_infected_float = %.2f\n", ( population_info_struct_->number_of_infected_int /(size_x_int*size_y_int)) ) ; fprintf( simulation_statistics_file, "\tpercentage_of_recovered_float = %.2f\n", ( population_info_struct_->number_of_recovered_int /(size_x_int*size_y_int)) ) ; fprintf( simulation_statistics_file, "\n" ) ; } #endif
C
#include <stdio.h> #include <stdlib.h> #ifndef DECOMPRESSIONE_H_ #define DECOMPRESSIONE_H_ /* * Metodo per la lettura del file codificato un bit alla volta */ int leggiBitPerBit(FILE *fp, unsigned char *buffer, int *dimBuffer, long int dimFile, int leggiBit); /* * Metodo per la lettura di un intero carattere dal file codificato (8 bit) */ char leggiNuovoCarattere(FILE *fp, unsigned char *buffer, int *dimBuffer, long int dimFile, int leggiBit); /* * Metodo che contiene la decodifica (lettura bit a bit, lettura carattere, scorrimento e aggiunta nell'albero) */ void decompressione(FILE *fp_in, FILE *fp_out); #endif
C
/** * @file spi.c * @author Stanislav Bobovych * @details * Bare bones master spi driver. */ #include <avr/io.h> #include "spi.h" void SPI_init(void) { /* Set MOSI and SCK output, all others input */ DDR_SPI |= (1<<DD_MOSI)|(1<<DD_SCK); //DDRB |= ( 1 << PB5 ) | ( 1 << PB7 ); /* Enable SPI, Master, set clock rate fck/16 */ SPCR = (1<<SPE)|(1<<MSTR)|(1<<SPR0); } void SPI_send(char cData) { /* Start transmission */ SPDR = cData; /* Wait for transmission complete */ while(!(SPSR & (1<<SPIF))); } char SPI_receive(void) { /* Wait for reception complete */ while(!(SPSR & (1<<SPIF))); /* Return Data Register */ return SPDR; }
C
//~ Input: 234567 //~ Output: sum of left half even number is: 6 #include<stdio.h> int rv(int u) { int r=0; while(u!=0) { r = r*10+u%10; u = u/10; } return r; } int lgt(int w) { int y; while(w!=0) { w = w/10; y++; } return y; } int LftEvSm(int rev,int s) { int c=0,y=0,h; while(rev!=0) { if(c > (s%2==0)+1) { break; } else { h = rev%10; if(h%2==0) { y = y+h; } } rev = rev/10; c++; } return y; } int main() { int n,tr,e,le; scanf("%d",&n); e = rv(n); printf("Reverse number is: %d\n",e); le = lgt(n); printf("Length of number is: %d\n",le); tr = LftEvSm(e,le); //~ tr = LftEvSm(rv(n),lgt(n)); printf("Sum of Left half even number is: %d",tr); return 0; }
C
//Primos #include <stdlib.h> #include <stdio.h> int main() { int i, cont = 0; for(i = 2; i < 100; i++) { if(i % 2 != 0 && i % 3 != 0 && i % 5 != 0 && i % 7 != 0) { cont ++; printf("\n %d es un numero primo! \n", i); } else { if(i == 2 || i == 3 || i == 5 || i == 7) { cont++; printf("\n %d es un numero primo! \n", i); } } } printf("\n La cantidad de numeros primos entre 1 y 100 es de %d \n", cont); system("pause"); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <sys/types.h> #include <unistd.h> #include <string.h> #include <pthread.h> #include <math.h> #include <sys/time.h> typedef struct imageMatrix { int width; int height; unsigned char** matrix; } imageMatrix; imageMatrix inFileMatrix; imageMatrix filterMatrix; imageMatrix outFileMatrix; int threadsNo; int max(int first, int second) { return first > second ? first : second; } int stringToInt(char* string) { int result = 0; int len = strlen(string); for(int i=0; i<len; i++){ result = result*10 + (string[i] - '0'); } return result; } long getMicrotime(){ struct timeval currentTime; gettimeofday(&currentTime, NULL); return currentTime.tv_sec * (int)1e6 + currentTime.tv_usec; } void missLines(FILE* file, int linesNo) { char* line = NULL; size_t len; for(int i=0; i<linesNo; ++i) { getline(&line, &len, file); } } void getMatrix(imageMatrix* matrix, FILE* inFile) { missLines(inFile, 2); size_t len = 0; char* line = NULL; if(getline(&line, &len, inFile) != -1) { strtok(line, " "); matrix->width = stringToInt(line); line = strtok(NULL, " \n\r"); matrix->height = stringToInt(line); } matrix->matrix = calloc(matrix->height, sizeof(char*)); for(int i=0; i<matrix->height; ++i) { unsigned char* row = calloc(matrix->width, sizeof(char)); matrix->matrix[i] = row; } missLines(inFile, 1); getline(&line, &len, inFile); line = strtok(NULL, " \n\r"); for(int i=0; i<matrix->height; ++i) { for(int j=0; j<matrix->width; ++j) { if(!line) { getline(&line, &len, inFile); line = strtok(line, " \n\r"); if(!line) break; } matrix->matrix[i][j] = stringToInt(line); line = strtok(NULL, " \n\r"); } } } void getOutMatrix(imageMatrix* matrix) { matrix->height = inFileMatrix.height; matrix->width = inFileMatrix.width; matrix->matrix = calloc(matrix->height, sizeof(char*)); for(int i=0; i<matrix->height; ++i) { unsigned char* row = calloc(matrix->width, sizeof(char)); matrix->matrix[i] = row; for(int j=0; j<matrix->width; ++j) { matrix->matrix[i][j] = 0; } } } void filter(int i, int j) { for(int k=0; k<filterMatrix.height; ++k) { for(int l=0; l<filterMatrix.height; ++l) { int half = (int) ceil(0.5*filterMatrix.width); int processedPixel = inFileMatrix.matrix[max(1, i - half + k)][max(1, j - half + l)]; outFileMatrix.matrix[i][j] += processedPixel * filterMatrix.matrix[k][l]/100; } } } void* blockMode(void* id) { long int start = getMicrotime(); int thisId = *((int *) id) + 1; int height = outFileMatrix.height; int sector = (int) ceil(1.0*height/threadsNo); for(int i=(thisId-1)*sector; i<thisId*sector && i<outFileMatrix.height - filterMatrix.height/2; ++i) { for(int j=0; j<inFileMatrix.width; ++j) { filter(i, j); } } printf(" Czas wątku %d: %ld\n", thisId, getMicrotime() - start); pthread_exit(0); } void* interleavedMode(void* id) { long int start = getMicrotime(); int thisId = *((int *) id) + 1; int height = outFileMatrix.height; for(int i=thisId-1;i<outFileMatrix.height - filterMatrix.height/2; i+=threadsNo) { for(int j=0; j<inFileMatrix.width; ++j) { filter(i, j); } } printf(" Czas wątku %d: %ld\n", thisId, getMicrotime() - start); pthread_exit(0); } void createOutImage(FILE* outFile) { char* text = calloc(20, sizeof(char)); sprintf(text, "P2\n%d %d\n255\n", outFileMatrix.width, outFileMatrix.height); fwrite(text, sizeof(char), strlen(text), outFile); for(int i=0; i<outFileMatrix.height; ++i) { char* buffer = calloc(outFileMatrix.width*4, sizeof(char)); for(int j=0; j<outFileMatrix.width; ++j) { char one[4]; sprintf(one, "%d ", outFileMatrix.matrix[i][j]); strcat(buffer, one); } fwrite(buffer, sizeof(char), strlen(buffer), outFile); free(buffer); } } int main(int argc, char** argv) { long int start = getMicrotime(); if(argc != 6) { fprintf(stderr, "Podano złą liczbę argumentów\n"); exit(0); } FILE* inFile = fopen(argv[3], "r"); FILE* filterFile = fopen(argv[4], "r"); FILE* outFile = fopen(argv[5], "w"); threadsNo = stringToInt(argv[1]); pthread_t threads[threadsNo]; char* mode = argv[2]; printf("%d wątków %s\n", threadsNo, mode); getMatrix(&inFileMatrix, inFile); getMatrix(&filterMatrix, filterFile); getOutMatrix(&outFileMatrix); for(int i=0; i<threadsNo; ++i) { pthread_t thread; pthread_attr_t attr; pthread_attr_init(&attr); int *arg = malloc(sizeof(*arg)); *arg = i; if(!strcmp(mode, "block")) { pthread_create(&thread, &attr, &blockMode, arg); } else if(!strcmp(mode, "interleaved")) { pthread_create(&thread, &attr, &interleavedMode, arg); } else { fprintf(stderr, "Podano zły tryb\n"); exit(0); } threads[i] = thread; } for(int i=0; i<threadsNo; ++i) { pthread_join(threads[i], NULL); } createOutImage(outFile); printf(" Całkowity czas: %ld\n", getMicrotime() - start); return 0; }
C
#ifndef MAIN_MENU_H #define MAIN_MENU_H #include "menus.h" /// this enum contains the choices available in main menu typedef enum mainMenuChoices { MusicsMenu, PlaylistsMenu, ExitApplication } MainMenuChoices; /// this struct contains all UI elements present in main menu typedef struct mainMenuUI { MenuUI *info; UIElement *mainMenuHeader; //< Page Header UIElement *musicMenuButton, *playlistMenuButton, *exitAppButton; //< Buttons } MainMenuUI; /** @brief main menu logic of application @param db, app database @precondition db is initialized and not NULL @postcondition main menu will be shown */ void mainMenu(AppDatabase *db); /** @brief initializes main menu's ui elements struct @return struct initialized @precondition NONE @postcondition struct is initialized and returned */ MainMenuUI *initializeMainMenuUI(); /** @brief draws main menu's ui elements on screen @param mainMenuUI has all menu's UI elements @precondition mainMenuUI is initialized and not NULL @postcondition menu is shown on screen */ void drawMainMenu(MainMenuUI *mainMenuUI); #endif //< MAIN_MENU_H
C
/*! * @file running_mean.c * * @brief ECE 486 Spring 2019 Lab 1 running_mean.c calculates the running mean * * @author ECE486 Lab Group 9 * @author Spencer Goulette, Jason Millette, Steven Ferrarese * * @date Feb 4, 2019 * * Contains three major functions. The first function is the init_running_mean * function, which initializes a struct. The second function is the * calc_running_mean which takes the input buffer and averages the values * and returns an output buffer of the averaged values. The third function * is the free_memory function which frees up the memory allocated for the * array element in the blockData struct. */ /*! * Includes stdio.h for input and output, stdlib.h for freeing memory, and * running_mean.h to use the blockData struct */ #include <stdio.h> #include <stdlib.h> #include "running_mean.h" /*! * init_running_mean is a function that initializes a blockData struct. The * M parameter is assigned to the M element. The blockSize parameter is * assigned to the blockSize element. 0 is assigned to position element so * that the position recorded is the first position. Memory of size M number * of doubles is allocated for the array element. 0.0 is assigned to the * total element to sum up the inputs to be averaged. The blockData struct * is then returned. */ struct blockData init_running_mean(int M, int blockSize) { struct blockData data; data.M = M; data.blockSize = blockSize; data.position = 0; data.array = (double*)malloc(sizeof(double)*M); data.total = 0.0; return data; } /*! * calc_running_mean takes the running mean from a buffer of floats. The * running mean is then saved to another buffer. The address for the input * buffer is obtained from the x parameter. The address for the output buffer * is obtained from the y parameter. The running mean works by having the * function take the nth element of the input buffer and adding it to the array * in the blockData struct called data. The array is then totalled and the * mean is calculated and assigned to the nth element of the output buffer. * The position element in the struct is then increased. The position element * is used for the position of the array in the struct, while n is used for * position of the x input buffer. Once the array has reached M elements its * position goes back to the start to replace the oldest elements in the array. * After the for loop has gone through all the elements in the input buffer, * the loop exits and the struct is returned primarily to save the position * element in the struct. This allows for the calc_running_mean function to * constantly keep going. */ struct blockData calc_running_mean(double *x, double *y, struct blockData data) { for(int n = 0; n < data.blockSize; n++) { data.array[data.position] = x[n]; for(int i = 0; i < data.M; i++) { data.total += data.array[i]; } y[n] = data.total / data.M; data.position += 1; data.total = 0; if(data.position >= data.M) { data.position = 0; } } return data; } /*! * The free_memory function takes in a blockData struct and frees up the * memory allocated for the array element in the struct. */ void free_memory(struct blockData data) { free(data.array); }
C
#include<stdio.h> void main() { char n; printf("enter the letter"); scanf("%c",&n); if(n==a||n==e||n==i||n==o||n==u) { printf("VOWELS"); } else { printf("consonants"); } }
C
#include "klib.h" #if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__) size_t strlen(const char *s) { size_t ret = 0; while (s[ret] != '\0') { ret++; } return ret; } char *strcpy(char *dst,const char *src) { size_t i = 0; for (i = 0; src[i] != '\0'; ++i) { dst[i] = src[i]; } dst[i] = '\0'; return dst; } char *strncpy(char *dst, const char *src, size_t n) { size_t i = 0; for (i = 0; i < n && src[i] != '\0'; ++i) { dst[i] = src[i]; } dst[i] = '\0'; return dst; } char *strcat(char *dst, const char *src) { size_t dst_len = strlen(dst); size_t i = 0; for (i = 0; src[i] != '\0'; ++i) { dst[dst_len + i] = src[i]; } dst[dst_len + i] = '\0'; return dst; } int strcmp(const char *s1, const char *s2) { size_t i = 0; for (i = 0; s1[i] != '\0' && s2[i] != '\0'; ++i) { if (s1[i] != s2[i]) { return s1[i] < s2[i] ? -1 : 1; } } return s1[i] == s2[i] ? 0 : (s1[i] < s2[i] ? -1 : 1); } int strncmp(const char *s1, const char *s2, size_t n) { size_t i = 0; for (i = 0; i < n && s1[i] != '\0' && s2[i] != '\0'; ++i) { if (s1[i] != s2[i]) { return s1[i] < s2[i] ? -1 : 1; } } return i == n ? 0 : (s1[i] < s2[i] ? -1 : 1); } void *memset(void *v, int c, size_t n) { uint8_t c8 = (uint8_t) c & 0xff; uint32_t c32 = (uint32_t) c8 | ((uint32_t) c8 << 8) | ((uint32_t) c8 << 16) | ((uint32_t) c8 << 24); uint8_t *pv = (uint8_t *) v; int i = 0, loops = (n / sizeof(uint32_t)); for (i = 0; i < loops; ++i) { *((uint32_t *) pv) = c32; pv += sizeof(uint32_t); } loops = (n % sizeof(uint32_t)); for (i = 0; i < loops; ++i) { *pv = c8; pv++; } return v; } void *memcpy(void *out, const void *in, size_t n) { int8_t *pout = (int8_t *) out; int8_t *pin = (int8_t *) in; int i = 0, loops = (n / sizeof(int32_t)); for (i = 0; i < loops; ++i) { *((int32_t *) pout) = *((int32_t *) pin); pout += sizeof(int32_t); pin += sizeof(int32_t); } loops = (n % sizeof(int32_t)); for (i = 0; i < loops; ++i) { *pout = *pin; pout++; pin++; } return NULL; } void *memmove(void *dest, const void *src, size_t n) { if (src + n < dest || src > dest + n) { // no overlap memcpy(dest, src, n); } else if (src >= dest) { // front to end int8_t *pin = (int8_t *) src; int8_t *pout = (int8_t *) dest; for (int i = 0; i < n; ++i) { *pout = *pin; ++pout, ++pin; } } else { // end to front int8_t *pin = (int8_t *) (src + n); int8_t *pout = (int8_t *) (dest + n); for (int i = 0; i < n; ++i) { *pout = *pin; --pout, --pin; } } return dest; } int memcmp(const void *s1, const void *s2, size_t n) { int8_t *p1 = (int8_t *) s1; int8_t *p2 = (int8_t *) s2; int i = 0, loops = (n / sizeof(int32_t)); for (i = 0; i < loops; ++i) { if (*((int32_t *) p1) != *((int32_t *) p2)) { return *((int32_t *) p1) < *((int32_t *) p2) ? -1 : 1; } p1 += sizeof(int32_t); p2 += sizeof(int32_t); } loops = (n % sizeof(int32_t)); for (i = 0; i < loops; ++i) { if (*p1 != *p2) { return *p1 < *p2 ? -1 : 1; } p1++; p2++; } return 0; } #endif
C
/* * CS 24000 First mid-semester exam. * Problem #3-3 * * void censorWord(char * str, char * badword) * * Arguments: * char * str -- a pointer to a string * char * badword -- a word to replace in string * * Description: * Given a string of input, replace all occurrences of the word badword in str * with X's. The word must have whitespace on both sides (space, tab, newline * or carriage return), unless it is at the beginning/end of the string str, * and must match case. Word will not have any whitespace characters in it. * For example, * str = "The penguin is in the theater" * censorWord(str, "the"); * This would result in str pointing to "The penguin is in XXX theater" * */ /* ======================== Start your edits here =========================== */ /* * NOTE NOTE NOTE NOTE NOTE * You are not allowed to add any other libraries or library includes in addition * to <stdlib.h> other than <math.h> (if you believe you need it). */ #include <stdlib.h> /* * Complete the function below for the exam */ void censorWord(char * str, char * badword) { } /* ======================== End your edits here =========================== */ /* ************************************************************************ * Do NOT change any of the lines between here and the end of the file! ************************************************************************ */ #include <stdio.h> #include <assert.h> char *Usage = "Usage: %s <string> <word>\n"; int main(int argc, char *argv[]) { extern char * strdup(const char *); char * copy; if (argc != 3) { fprintf(stderr, Usage, argv[0]); exit(1); } assert(copy = strdup(argv[1])); censorWord(copy, argv[2]); printf("String \"%s\" after censorWord is \"%s\"\n", argv[1], copy); return 0; }
C
// 剑指 Offer 13. 机器人的运动范围 // 地上有一个m行n列的方格,从坐标 [0,0] 到坐标 [m-1,n-1] 。一个机器人从坐标 [0, 0] 的格子开始移动,它每次可以向左、右、上、下移动一格(不能移动到方格外),也不能进入行坐标和列坐标的数位之和大于k的格子。例如,当k为18时,机器人能够进入方格 [35, 37] ,因为3+5+3+7=18。但它不能进入方格 [35, 38],因为3+5+3+8=19。请问该机器人能够到达多少个格子? //   // 示例 1: // 输入:m = 2, n = 3, k = 1 // 输出:3 // 示例 2: // 输入:m = 3, n = 1, k = 0 // 输出:1 // 提示: // 1 <= n,m <= 100 // 0 <= k <= 20 // 来源:力扣(LeetCode) // 链接:https://leetcode-cn.com/problems/ji-qi-ren-de-yun-dong-fan-wei-lcof // 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 //BFS typedef struct point{ int x; int y; }Point; typedef struct queue{ Point point[10000]; int head; int tail; int length; }Queue; void push(Queue* queue, Point point){ queue->point[queue->tail].x = point.x; queue->point[queue->tail].y = point.y; queue->tail = (queue->tail + 1) % 10000; queue->length++; } void pop(Queue* queue, Point* point){ point->x = queue->point[queue->head].x; point->y = queue->point[queue->head].y; queue->head = (queue->head + 1) % 10000; queue->length--; } int add(int x, int y){ return x % 10 + (x - (x % 10)) / 10 + y % 10 + (y - (y % 10)) / 10; } int movingCount(int m, int n, int k){ if(m == 0 || n == 0) return 0; Point point, temp; point.x = 0, point.y = 0; Queue *queue = (Queue*)malloc(sizeof(Queue)); queue->head = 0; queue->tail = 0; queue->length = 0; push(queue, point); int path[100][100]={1}; int ans = 1; for(;queue->length;){ pop(queue, &point); if(point.x - 1 >= 0 && path[point.x - 1][point.y] == 0){ if(add(point.x - 1, point.y) <= k){ path[point.x - 1][point.y] = 1; temp.x = point.x - 1, temp.y = point.y; push(queue, temp); ans++; } } if(point.x + 1 < n && path[point.x + 1][point.y] == 0){ if(add(point.x + 1, point.y) <= k){ path[point.x + 1][point.y] = 1; temp.x = point.x + 1, temp.y = point.y; push(queue, temp); ans++; } } if(point.y - 1 >=0 && path[point.x][point.y - 1] == 0){ if(add(point.x, point.y - 1) <= k){ path[point.x][point.y - 1] = 1; temp.x = point.x, temp.y = point.y - 1; push(queue, temp); ans++; } } if(point.y + 1 < m && path[point.x][point.y + 1] == 0){ if(add(point.x, point.y + 1) <= k){ path[point.x][point.y + 1] = 1; temp.x = point.x, temp.y = point.y + 1; push(queue, temp); ans++; } } } return ans; }
C
/********************************************************************************************** Program srchedge.c Written by Young K. Kwon For Charlie Avis, JPL Date complete: March 12, 1996 srchedge.c: INPUT IMAGE: Only black and white halfword(2 bytes) vicar images are valid. The input image only has a dark and light dn value - that is one side of the image is dark and the other side of the image is light. A clear distinctive straight line created by the transition edges(from dark to light) separates the two values. e.g. ddddddddddddddddddddddddll dddddddddddddddddddddlllll ddddddddddddddddddllllllll dddddddddddddddlllllllllll ddddddddddddllllllllllllll d=dark dn value ddddddddllllllllllllllllll ddddllllllllllllllllllllll l=light dn value dlllllllllllllllllllllllll lllllllllllllllllllllllll| llllllllllllllllllllllllll llllllllllllllllllllllllll llllllllllllllllllllllllll PROCESSING: srchedge.c does the following: 1) finds the transition edges(the point where dark dn value and light dn value touch)) 2) creates an output image file(vicar image file out) containing only the transition edges 3) does a least squares fit on the transition edges(done by function fitpts()) 4) and gets the angle of the line create by the least fit square *********************************************************************************************** *********************************************************************************************** ***********************************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <math.h> #include <string.h> #include "vicmain_c" #include "taeextproto.h" #define PTDN 20000 /* Dn value of edge in output image out */ /******** #define SMALL_SL 400 #define SMALL_SS 400 #define SMALL_NL 250 #define SMALL_NS 250 **********/ typedef unsigned short image_element_type; /* input image element type */ /* Globals */ image_element_type *image; /* input image array */ unsigned int ptcnt=0; /* edge count */ /*** Finds one transition edge in the row of the input image ***/ void oneedge_row(image_element_type *,unsigned int *, unsigned int *, unsigned int, unsigned int, unsigned int, unsigned int); /*** Finds one transition edge in the column of the input image ***/ void oneedge_col(image_element_type *,unsigned int *, unsigned int *, unsigned int, unsigned int, unsigned int, unsigned int, unsigned int); /*** Fits a set of data points to a line ***/ void fitpts(unsigned int *, unsigned int *, unsigned int *, unsigned int *, unsigned int, unsigned int *, double *, double *, double *, double *, double *); void main44() { int i, j, k, inunit, outunit, status, size, nl, ns, cut; int true_ns=0,true_nl=0, small_sl, small_ss, small_nl, small_ns; char inp[100], out[100], small[11]; unsigned int skipns, skipnl, dark, darkskip; image_element_type *imageptr, *smallimag; int count, def; double angle; unsigned int *x=NULL, *y=NULL; unsigned int *nx=NULL, *ny=NULL; unsigned int ntos=0, ston=0, wtoe=0, etow=0; zvmessage("SRCHEDGE version 2019-06-14", ""); /* fitpts, a function in dave3.h, output parameters */ unsigned int fitpts_nndata=0; double fitpts_mean,fitpts_sigma, fitpts_angle, fitpts_maxdiff, fitpts_b; /* use to find averages of dark and light side of image */ long unsigned int total1=0; long unsigned int cnt1=0; struct PARBLK parb; /* output angle to vicar pdf parmameter */ status=zveaction("AS"," "); status=zvparm("INP",inp,&count,&def,1,0); status=zvparm("OUT",out,&count,&def,1,0); status=zvparm("SKIPNS",&skipns,&count,&def,1,0); status=zvparm("SKIPNL",&skipnl,&count,&def,1,0); /** status=zvparm("DIFF",&diff,&count,&def,1,0);**/ status=zvparm("DARKSKIP",&darkskip,&count,&def,1,0); /** status=zvparm("LIGHT",&light,&count,&def,1,0);**/ status=zvparm("CUT",&cut,&count,&def,1,0); status=zvparm("SMALL",small,&count,&def,1,0); status=zvpone("SMALLSIZE",&small_sl,1,0); status=zvpone("SMALLSIZE",&small_ss,2,0); status=zvpone("SMALLSIZE",&small_nl,3,0); status=zvpone("SMALLSIZE",&small_ns,4,0); status=zvunit(&inunit, "INP", 1, NULL); zvsignal(inunit,status,1); status=zvunit(&outunit, "OUT", 1, NULL); zvsignal(outunit,status,1); status=zvopen(inunit, "OP", "READ", "U_FORMAT", "HALF", NULL); zvsignal(inunit,status,1); status=zvopen(outunit, "OP", "WRITE", "O_FORMAT", "HALF", NULL); zvsignal(inunit,status,1); status=zvget(inunit, "NL", &nl, "NS" ,&ns, "RECSIZE", &size, NULL); zvsignal(inunit,status,1); if (skipnl >= nl-2*cut) { fprintf(stderr,"\n\nERROR: No of lines in image < SKIPNL\n"); zabend(); /*** exit(10); ****/ } else if (skipns >= ns-2*cut) { fprintf(stderr,"\n\nERROR: No of samples in image < SKIPNS\n"); zabend(); /**** exit(10); ****/ } if (nl < 3*cut || ns < 3*cut) { fprintf(stderr,"\n\nERROR: Image is to small. Image size "); fprintf(stderr,"must be greater than or equal to %dX%d.\n", 3*cut,3*cut); zabend(); } size = ns*nl; if ( ((image=(unsigned short *)calloc(nl*ns,sizeof(image_element_type))) == NULL ) || ((x=(unsigned int *)calloc(nl+ns,sizeof(unsigned int))) == NULL) || ((y=(unsigned int *)calloc(nl+ns,sizeof(unsigned int))) == NULL) ) { fprintf(stderr,"\n\nOut of memory(image file might be to big)\n\n"); zabend(); /******** exit(11); *********/ } imageptr=image; for(i=0; i < nl; i++) { status=zvread(inunit,imageptr,"LINE",i+1, NULL); zvsignal(inunit,status,1); imageptr+=ns; } imageptr=image; if (strcmp(small,"small")==0) { if((smallimag=(unsigned short *)calloc(small_nl*small_ns, sizeof(image_element_type))) == NULL) { fprintf(stderr,"\n\nOut of memory(for WACFM)\n"); zabend(); } for(k=0,i=small_sl; i < small_sl+small_nl; i++) for(j=small_ss; j <small_ss+small_ns; j++) smallimag[k++]=image[i*ns+j]; image=smallimag; true_nl=nl; true_ns=ns; nl=small_nl; ns=small_ns; skipnl=1; skipns=1; cut=0; } total1=cnt1=0; for(i=cut; i < nl-cut; i+=darkskip) for(j=cut; j < ns-cut; j+=darkskip,cnt1++) total1+=image[ns*i+j]; dark=1.0*total1/cnt1; /**fprintf(stderr,"\n\ndark=%d\n\n",dark);**/ for(j=1+cut; j < ns-1-cut; j+=skipns) { if (image[j] > image[ns*(nl-2)+j]) { for(i=nl-2-cut; i > 0+cut; i -= skipnl) { if (image[ns*i+j] > dark) { if (i==nl-2-cut) break; oneedge_col(image,x,y,i,j,nl,ns,skipnl); ston++; break; } } } else { for(i=1+cut; i < nl-1-cut; i += skipnl) { if (image[ns*i+j] > dark) { if (i==1+cut) break; oneedge_col(image,x,y,i,j,nl,ns,skipnl); ntos++; break; } } } } for(i=1+cut; i < nl-1-cut; i+=skipnl) { if (image[i*ns] > image[i*ns+ns-2]) { for(j=ns-2-cut; j > 0+cut; j -= skipns) { if (image[ns*i+j] > dark) { if (j==ns-2-cut) break; oneedge_row(image,x,y,i,j,ns,skipns); etow++; break; } } } else { for(j=1+cut; j < ns-1-cut; j += skipns) { if (image[ns*i+j] > dark) { if (j==1+cut) break; oneedge_row(image,x,y,i,j,ns,skipns); wtoe++; break; } } } } if (strcmp(small,"small") == 0) { image=imageptr; nl=true_nl; ns=true_ns; for (i=0; i<ptcnt; i++) { /*fprintf(stderr,"\n %d %d", x[i], y[i]);*/ x[i]=x[i]+small_ss; y[i]=y[i]+small_sl; } } /******* for(i=0; i < ptcnt; i++) { image[ns*y[i]+x[i]-1] = PTDN; image[ns*y[i]+x[i]] = PTDN; image[ns*y[i]+x[i]+1] = PTDN; } for(i=0, imageptr=image; i < nl; i++) { status=zvwrit(outunit,imageptr,"LINE",i+1, NULL); zvsignal(outunit,status,1); imageptr+=nl; } zabend(); **********/ /********************************************************************/ /***********************dave3.h**************************************/ /********************************************************************/ if ( ((nx=(unsigned int *)calloc(ptcnt,sizeof(double))) == NULL) || ((ny=(unsigned int *)calloc(ptcnt,sizeof(double))) == NULL) ) { fprintf(stderr,"\n\nOut of memory\n"); zabend(); /******** exit(11); ********/ } if (ptcnt > 2) fitpts(x,y,nx,ny,ptcnt,&fitpts_nndata,&fitpts_mean, &fitpts_sigma,&fitpts_angle,&fitpts_maxdiff,&fitpts_b); else if (ptcnt==2) { fprintf(stderr,"\nWARNING: only two transition edges discovered\n"); nx[0]=x[0]; nx[1]=x[1]; ny[0]=y[0]; ny[1]=y[1]; } else { fprintf(stderr,"\n\nWARNING. %d transition edges found ", ptcnt); fprintf(stderr,"(check parameters and/or input image %s)\n\n", inp); zabend(); /***** exit(9); ******/ } /****/ angle=fitpts_angle; /******/ if (wtoe > etow && angle > 0) angle=360-angle; else if (wtoe < etow && angle > 0) angle=180-angle; else if (wtoe > etow && angle < 0) angle= 180-angle; else if (wtoe < etow && angle < 0) angle = -angle; else if (wtoe == 0 && etow==0) { if (ntos > ston) angle=180; else angle=0; } if (angle < 0) { fprintf(stderr,"\n\nERROR: Processing Error\n"); fprintf(stderr,"Angle is less then zero when it "); fprintf(stderr,"should always be zero or greater then zeo.\n"); zabend(); /******** exit(4); ******/ } /**********/ if(angle >= 0 && angle <= 180) angle=180-angle; /**********/ else if(angle >=180 && angle <= 360) angle=540-angle; /**********/ /********************************************************************/ /************* mark transition edges and output to output file *******/ /**********************************************************************/ for(i=0; i < fitpts_nndata; i++) { image[ns*ny[i]+nx[i]-1] = PTDN; image[ns*ny[i]+nx[i]] = PTDN; image[ns*ny[i]+nx[i]+1] = PTDN; } for(i=0, imageptr=image; i < nl; i++) { status=zvwrit(outunit,imageptr,"LINE",i+1, NULL); zvsignal(outunit,status,1); imageptr+=nl; } /********************************************************************/ /******** outputs to vicar pdf parameter ***************************/ /********************************************************************/ q_init(&parb,P_BYTES, P_ABORT); q_real(&parb, "ANGLE", 1, &angle, P_ADD); zvq_out(&parb); /********************************************************************/ /********************************************************************/ return; } /*end of main*/ void oneedge_col(image_element_type *array, unsigned int *x, unsigned int *y, unsigned int i, unsigned int j, unsigned int nl,unsigned int ns,unsigned int skip) { unsigned int beg=0, end=0, mid=0, *edgearray; unsigned int c=0,a=0,b=0,d=0, max=0; if ((edgearray=(unsigned int *)calloc(skip*2,sizeof(unsigned int))) == NULL) { fprintf(stderr,"\n\nOut of memory(SKIPNS might be too big)\n"); zabend(); /*********8 exit(11); ***********/ } if(i < skip) { beg=j; mid=i; } else { beg=i*ns+j-(skip*ns); mid=skip; } if((nl-i-1) < skip) end=i*ns+j+(ns-i-1)*ns; else end=i*ns+j+(ns*skip); for (c=0,a=beg; a < end; c++, a+=ns) { edgearray[c]=abs(array[a]-array[a+ns]); } for (d=0, max=0; d < c-1; d++) { if(edgearray[max] < edgearray[d+1]) max=d+1; } for (b=0; b < ptcnt; b++) if (y[b] == i + (max-mid) && x[b] == j) break; if ( b == ptcnt ) { y[ptcnt]=i+(max-mid); x[ptcnt++]=j; } } void oneedge_row(image_element_type *array, unsigned int *x, unsigned int *y, unsigned int i, unsigned int j, unsigned int ns,unsigned int skip) { unsigned int beg=0, end=0, mid=0, *edgearray; unsigned int c=0,a=0,b=0,d=0, max=0; if ((edgearray=(unsigned int *)calloc(skip*2,sizeof(unsigned int))) == NULL) { fprintf(stderr,"\n\nOut of memory(SKIPNS might be too big)\n"); zabend(); /****** exit(11); *********/ } if(j < skip) { beg=(i*ns); mid=j; } else { beg=i*ns+j-skip; mid=skip; } if(ns-1-j < skip) end=(i+1)*ns-1; else end=i*ns+j+skip; for (c=0, a=beg; a < end; c++, a++) edgearray[c]=abs(array[a]-array[a+1]); for (d=0, max=0; d < c-1; d++) if(edgearray[max] < edgearray[d+1]) max=d+1; for (b=0; b < ptcnt; b++) /*****/ if (y[b] == i && x[b] == j + (max-mid)) break; /*****/ if ( b == ptcnt ) { y[ptcnt]=i; x[ptcnt++]=j+(max-mid); } } /******************************************************************** * Given a set of ndata points x(), y(), fit them to a straight line * y= ax + b and angle of the slope angle = atan(,). Return are a,b,angle, * mean and sigma, nx[] and ny[](good data points)*/ void fitpts(unsigned int *x, unsigned int *y, unsigned int *nx, unsigned int *ny, unsigned int ndata, unsigned int *outnndata, double *outmean, double *outsigma, double *outangle, double *outmaxdiff, double *outb) { double mean=0,/*sigma,*/ /**x[1500],y[1500],absres,**/res[1500]; long int sx,sy,sxy,sxx,sumres,sres,absres; /** double sumres,sres;*/ double maxdiff,newy,a,b=0/**,ny[1500],nx[1500]**/; /* long int maxdiff; long int*/double delta_y; double angle,n,d; int i,nnd, nndata; /* input test data points. To be remove after the program have work properly*/ /*** for (i=0;i<ndata;i++){ fprintf(stderr"x[%d]:%d y[%d]:%d\n", i, x[i], i, y[i]); } ***/ /* copy data into new location*/ for (i=1;i<=ndata;i++){ nx[i]=x[i-1]; ny[i]=y[i-1]; } nndata=ndata; recalc_linefit:; sx=0; sy=0; sxy=0; sxx=0; sumres=0; sres=0; maxdiff=0; nnd=0; for (i=1;i<=nndata;i++){ sx=sx+nx[i]; sy=sy+ny[i]; sxy=sxy+nx[i]*ny[i]; sxx=sxx+nx[i]*nx[i]; } n=(1.0)*sxy-(1.0)*sx*sy/nndata; d=(1.0)*sxx-(1.0)*sx*sx/nndata; if(d==0.00000){ goto find_angle;} a=n/d; /**** a=((1.0)*sxy-(1.0)*sx*sy/nndata)/((1.0)*sxx-(1.0)*sx*sx/nndata);*****/ b=(1.0)*sy/nndata-a*sx/nndata; for(i=1;i<=nndata;i++){ newy=a*nx[i]+b; delta_y=sqrt((ny[i]-newy)*(ny[i]-newy)); res[i]=delta_y*cos(atan2(n,d)); absres=sqrt(res[i]*res[i]); if (absres > maxdiff) { maxdiff=absres;} sres = sres + absres; sumres = sumres + res[i]*res[i]; } mean=(1.0)*sres/nndata; /* sigma=sqrt(sumres/nndata - mean*mean); */ /* test to remove bad data points*/ /******fprintf(stderr,"maxdiff:%f\n2*sigma:%f sigma:%f\n", maxdiff, 2*sigma, sigma); ********/ /* if (maxdiff <= 2*sigma){ goto find_angle;} */ for (i=1;i<=nndata;i++){ if (maxdiff > sqrt(res[i]*res[i])) { nnd = nnd + 1; nx[nnd]=nx[i]; ny[nnd]=ny[i];} } if (nnd > 2) nndata=nnd; else goto find_angle; goto recalc_linefit; find_angle:; if (d==0.00000){ angle = 90;} else {angle=atan2(n,d)*180/3.14159265359;} /** printf("\n angle = %f",angle); printf(" deg."); **/ for (i=0; i<nndata; i++) { nx[i]=nx[i+1]; ny[i]=ny[i+1]; } /*fprintf(stderr,"\nnndata: %d\n",nndata);*/ *outnndata=nndata; *outmean=mean; /* *outsigma=sigma; */ *outangle=angle; *outmaxdiff=maxdiff; *outb=b; }
C
/*robot.c neural network robot of craziness */ # include < mega32.h > #include < stdlib.h > #include < stdio.h > #include < math.h > #include < delay.h > // Timeout Values for each task #define t1 2 //2 5 is debugging # define t4 20 //20 5000 is debugging # define t5 14000 //14000 10000 is debugging maybe 3000? # define t6 180000 //180000 # define { {# define } } // These defines effect values everywhere and the majority of the program will adjust when these are changes // The two sections that will not adjust is the membrane potential update and the sensor update, please be aware of this # define numneuron 8# define numsensor 15 // Bits of Sensor # define numindivid 6 // These defines give range values for the sensors to indicate amount of spiking necessary (not is nothing, col is colission), temperature can really effect these values so they should be rechecked often # define sensor1not 4.658# define sensor1top 4.556# define sensor1mid 4.33# define sensor1bot 4.14# define sensor1col 3.403 # define sensor2not 4.551# define sensor2top 4.531# define sensor2mid 4.512# define sensor2bot 4.492# define sensor2col 4.243 # define sensor3not 4.79# define sensor3top 4.64# define sensor3mid 4.52# define sensor3bot 4.219# define sensor3col 3.300 # define sensor4not 4.219# define sensor4top 4.141# define sensor4mid 4.102# define sensor4bot 3.965# define sensor4col 3.5 # define sensor5not 4.375# define sensor5top 4.336# define sensor5mid 4.297# define sensor5bot 4.238# define sensor5col 3.535 // Thse defines are noise ranges for a random seed generation # define sensor6bot 1.30# define sensor6top 1.36 void task1(void); // Neuron Implementation void task2(void); // Left Stepper Motor Control void task3(void); // Right Stepper Motor Control void task4(void); // Sensor/Motor Speed Update void task5(void); // Neuron Individual Selection and Mutation void task6(void); // Best Fitness Store void initialize(void); // Initialize // Task variables unsigned long time1, time2, time3, time4, time5, time6; // Task scheduling timeout counters unsigned int t2, t3; // Timeout Values for task 2 and 3, speed of motors will be determined by these values unsigned char sensorflag; // Flag that indicates Sensors have been updated (1 updated, 0 not updated) unsigned char evolveflag; // Flag that indicates a mutation has just occurred unsigned long tsk4cnt; // Counter for task 4 to allow us to update motors every 160 ms to allow for actual movement // Neuron Variables unsigned char individual; // Currently Selected Individual of the population (0 - 5) unsigned char neuron; // Output of Neurons (1 is spike, 0 is no spike), ie. 0b11001100 means neurons 2, 3, 6, 7 are spiking, neurons 0, 1, 4, 5 are not unsigned int sensor; // Output of Sensors (1 is spike, 0 is no spike), ie. 0b11001100 means sensors 2, 3, 6, 7 are spiking, sensors 0, 1, 4, 5 are not unsigned char signs[numindivid]; // Sign of Neurons (1 is positive, 0 is negative), ie. 0b00001111 means neurons 0, 1, 2, 3 are positive, neurons 4, 5, 6, 7 are not unsigned char nconnection[numindivid][numneuron]; // Connections from Neurons, each char describes connections for one neuron (1 is connection, 0 is no connection), ie. 0b11001010 means there are connections to this neuron from neurons 1, 3, 6, 7 and no connection from neurons 0, 2, 4, 5 unsigned int sconnection[numindivid][numneuron]; // Connections from Sensors, each char describes connections from one sensor (1 is connection, 0 is no connection) to each neuron signed int memb[numneuron]; // Membrane Potential of each Neuron (minimum value of 0, initialized to 0) float fitness[numindivid]; // Fitness value for an individual unsigned int threshold[numindivid]; // Membrane Threshold (5) - DEBUG BEING SET TO EVOLVE RANDOMLY BETWEEN 2 AND 6 unsigned char leaking; // Leaking Constant (1) unsigned char minimum; // Miminum Membrane Potential (0) unsigned int randomint; // Randomly generated integer // Old Variables unsigned char oldsigns; unsigned char oldnconnection[numneuron]; unsigned int oldsconnection[numneuron]; unsigned int oldthreshold; // ADC Variables unsigned int Ain; // Current ADC input unsigned int Ain2; // DEBUG for Noise for ADCL float voltage; // Current ADC input converted into voltage unsigned int sensorread; // Values of Sensors being read float probability; // Probability of getting a random noise spike float randomprob; // Random probability // Motor Variables unsigned char stepL; // Step variable for Left Motor unsigned char stepR; // Step variable for Right Motor unsigned char dirL; // Direction variable for Left Motor (0 Forward or 1 Backward) unsigned char dirR; // Direction variable for Right Motor (0 Forward or 1 Backward) unsigned char spikeFL; // Number of spikes during sensor update period (20 ms) generated by forward left neuron unsigned char totalspikeFL; // Total spikes between evolution unsigned char spikeBL; // Number of spikes during sensor update period (20 ms) generated by backward left neuron unsigned char totalspikeBL; // Total spikes between evolution unsigned char spikeFR; // Number of spikes during sensor update period (20 ms) generated by forward right neuron unsigned char totalspikeFR; // Total spikes between evolution unsigned char spikeBR; // Number of spikes during sensor update period (20 ms) generated by backward right neuron unsigned char totalspikeBR; // Total spikes between evolution unsigned long maxspikes; // Number of possible spikes during sensor update period float v2, v3; // Motor Velocities // Evolution Variables float newfitness; // Calculates new fitness to compare with old fitnesses unsigned char keep; // Keep determines if we will keep a mutation, is 1 if it the current individuals fitness is >= worst individuals fitness unsigned char collision; // Indicates a collision for fitness calculation (0 is no collision, 1 collision) float sensormaxactivity; // Most active sensor value for fitness calculation (5 values for this based on most active sensor: 0 if nothing, .25 if between top and mid, .5 if between mid and bot, .75 if between bot and col, 1 if below or equal to col) float sensoractivity[numsensor / 3]; // Activity of 5 sensors based on values above to be maxed unsigned char worstindivid; // Worst indiviudal used to determine keep unsigned char randn, rands; // Random Variables to access blocks in random individual for mutation unsigned int randomseed; float change; // Change in fitness (debugging) // Fitness Store variables unsigned int bestfitness; // Best Fitness so far unsigned int bestindivid; // Best Individual // EEPROM STUFF eeprom unsigned char eeindex = 0; // Index of fitness values/replacements eeprom unsigned char eesigns[numindivid]; eeprom unsigned char eenconnection[numindivid][numneuron]; eeprom unsigned int eesconnection[numindivid][numneuron]; eeprom int eefitness[numindivid]; eeprom int eethreshold[numindivid]; eeprom int eebestfitnessmem[200]; eeprom unsigned char eebestsigns; eeprom unsigned char eebestnconnection[numneuron]; eeprom unsigned int eebestsconnection[numneuron]; eeprom int eebestfitness; eeprom int eebestthreshold; // For loop variables unsigned int i, j, k, x, a, b, c, d, e, f, y, z, g, h, ii, jj, kk, xx, yy, zz; //////////////////////////////////////////////////////////////// //timer 0 Compare Match ISR interrupt[TIM0_COMP] void timer0_overflow(void) { if (time1 > 0) --time1; if (time2 > 0) --time2; if (time3 > 0) --time3; if (time4 > 0) --time4; if (time5 > 0) --time5; if (time6 > 0) --time6; if (tsk4cnt > 0) --tsk4cnt; } //////////////////////////////////////////////////////////////// void task1(void) { time1 = t1; // Sensor/Motor Updating if (sensorflag == 0) { sensor = 0; // If sensors aren't ready, sensor nodes shouldn't be spiking } else { sensor = sensorread; sensorflag = 0; spikeFL = 0; spikeBL = 0; spikeFR = 0; spikeBR = 0; maxspikes = 0; } if (evolveflag == 1) { // If just evolved // Spike Forward Motor Neurons to start memb[0] = threshold[individual] + 20; memb[2] = threshold[individual] + 20; // Debugging //memb[4] = threshold[individual] + 20; //memb[5] = threshold[individual] + 20; //memb[6] = threshold[individual] + 20; //memb[7] = threshold[individual] + 20; evolveflag = 0; totalspikeFL = 0; totalspikeBL = 0; totalspikeFR = 0; totalspikeBR = 0; } // Debugging //printf("%lx\n\r", neuron); //////////////Refractory Period/Contribution of Incoming Spikes/Membrane Potential Update////////////// for (i = 0; i < numneuron; i++) { // Refractory Period Check (if spike generated in previous update, don't update membrane potential) if (((neuron >> i) & 0x01) == 0) { // Calculate Contribution of Sensors and update membrane potential memb[i] = (memb[i] + (((sensor & sconnection[individual][i]) & 0b10000000) >> 7) + (((sensor & sconnection[individual][i]) & 0b01000000) >> 6) + (((sensor & sconnection[individual][i]) & 0b00100000) >> 5) + (((sensor & sconnection[individual][i]) & 0b00010000) >> 4) + (((sensor & sconnection[individual][i]) & 0b00001000) >> 3) + (((sensor & sconnection[individual][i]) & 0b00000100) >> 2) + (((sensor & sconnection[individual][i]) & 0b00000010) >> 1) + (((sensor & sconnection[individual][i]) & 0b00000001) >> 0)); // Calculate Contribution of Positive Neurons and update membrane potential memb[i] = (memb[i] + (((neuron & signs[individual] & nconnection[individual][i]) & 0b10000000) >> 7) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b01000000) >> 6) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b00100000) >> 5) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b00010000) >> 4) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b00001000) >> 3) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b00000100) >> 2) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b00000010) >> 1) + (((neuron & signs[individual] & nconnection[individual][i]) & 0b00000001) >> 0)); // Calculate Contribution of Negative Neurons and update membrane potential memb[i] = (memb[i] - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b10000000) >> 7) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b01000000) >> 6) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b00100000) >> 5) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b00010000) >> 4) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b00001000) >> 3) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b00000100) >> 2) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b00000010) >> 1) - (((neuron & ((~signs[individual]) & 0xFF) & nconnection[individual][i]) & 0b00000001) >> 0)); // Minumimum of memb is 0 if (memb[i] < minimum) { memb[i] = minimum; } } } ///////////////////////////////////////////Spike Generation//////////////////////////////////////////// for (j = 0; j < numneuron; j++) { randomint = rand(); // rand generates 15 bits (need to generate random number between 2 and -2, 0 - 6553 is -2, 6554 - 13107 is -1, 13108 - 19660 is 0, 19661 - 26214 is 1, 26215 - 32767 is 2 if (randomint >= 0 && randomint <= 6553) { // 6554 if (memb[j] >= (threshold[individual] - 2)) { neuron = (neuron | (1 << j)); memb[j] = minimum; } else { neuron = (neuron & (~(1 << j))); } } else if (randomint >= 6554 && randomint <= 13107) { // 6554 if (memb[j] >= (threshold[individual] - 1)) { neuron = (neuron | (1 << j)); memb[j] = minimum; } else { neuron = (neuron & (~(1 << j))); } } else if (randomint >= 13108 && randomint <= 19660) { // 6553 if (memb[j] >= (threshold[individual])) { neuron = (neuron | (1 << j)); memb[j] = minimum; } else { neuron = (neuron & (~(1 << j))); } } else if (randomint >= 19661 && randomint <= 26214) { // 6554 if (memb[j] >= (threshold[individual] + 1)) { neuron = (neuron | (1 << j)); memb[j] = minimum; } else { neuron = (neuron & (~(1 << j))); } } else if (randomint >= 26215 && randomint <= 32767) { // 6553 if (memb[j] >= (threshold[individual] + 2)) { neuron = (neuron | (1 << j)); memb[j] = minimum; } else { neuron = (neuron & (~(1 << j))); } } } //printf("%x\n\r", neuron); //////////////////////////////////////////Motor Spike////////////////////////////////////////////////// // 1st neuron is left forward motor, 2nd is left backward motor, 3rd if right forward motor, 4th is right backward motor // If spiking add to total number of spikes if ((neuron & 0x01) == 1) { spikeFL++; totalspikeFL++; } if ((neuron & 0x02) == 2) { spikeBL++; totalspikeBL++; } if ((neuron & 0x04) == 4) { spikeFR++; totalspikeFR++; } if ((neuron & 0x08) == 8) { spikeBR++; totalspikeBR++; } maxspikes++; //printf("%x %i %i %i %i\n\r", neuron, spikeFL, spikeBL, spikeFR, spikeBR); ///////////////////////////////////////////Leakage///////////////////////////////////////////////////// for (k = 0; k < numneuron; k++) { if ((memb[k] - leaking) >= minimum) { memb[k] = memb[k] - leaking; } else { memb[k] = minimum; } } } //////////////////////////////////////////////////////////////// void task2(void) { time2 = t2; // Left Motor // Stepper Motor moves 7.5 degree per step, so 48 steps / rev (360 / 7.5). Circumference of wheel is 15.9593 cm / rev (2 inch * 2.54 cm/ in * pi / 2). // Velocity = 15.9593 cm / rev * 1/48 rev / (t2 / 1000 s) = .332485 cm / (t2/1000 s) // Wire Configuration: Orange to C.0, Yellow to C.1, Brown to C.2, Black to C.3, Red and Green to 12V if (stepL == 3) PORTC = (PORTC & 0b11110000) | 1; if (stepL == 2) PORTC = (PORTC & 0b11110000) | 4; if (stepL == 1) PORTC = (PORTC & 0b11110000) | 2; if (stepL == 0) PORTC = (PORTC & 0b11110000) | 8; if (dirL) // 0 is forward, 1 is backward { if (stepL > 0) stepL--; else stepL = 3; } else { if (stepL < 3) stepL++; else stepL = 0; } } //////////////////////////////////////////////////////////////// void task3(void) { time3 = t3; // Right Motor // Stepper Motor moves 7.5 degree per step, so 48 steps / rev (360 / 7.5). Circumference of wheel is 15.9593 cm / rev (2 inch * 2.54 cm/ in * pi / 2). // Velocity = 15.9593 cm / rev * 1/48 rev / (t2 / 1000 s) = .332485 cm / (t3/1000 s) // Wire Configuration: Orange to C.4, Yellow to C.5, Brown to C.6, Black to C.7, Red and Green to 12V if (stepR == 3) PORTC = (PORTC & 0b00001111) | 16; if (stepR == 2) PORTC = (PORTC & 0b00001111) | 64; if (stepR == 1) PORTC = (PORTC & 0b00001111) | 32; if (stepR == 0) PORTC = (PORTC & 0b00001111) | 128; if (!dirR) // 0 is forward, 1 is backward { if (stepR > 0) stepR--; else stepR = 3; } else { if (stepR < 3) stepR++; else stepR = 0; } } // Ends task 3 //////////////////////////////////////////////////////////////// void task4(void) { time4 = t4; ////////////////////////////////////////Sensor Update////////////////////////////////////////////////// collision = 0; // Reset collision before recalculating for (x = 1; x <= ((numsensor / 3) + 1); x++) { ADCSR .6 = 1; // Start Another Conversion while (ADCSR .6); // Debugging - testing ADCL for noise Ain2 = (ADCL >> 6); Ain = ADCH; randomseed = randomseed + Ain; // Randomness is good Ain = (Ain2 | (Ain << 2)); //Ain = ADCH; // Read ADC for Sensor 0 //voltage = ((float)((float)Ain*5.0/256.0)); // Convert to voltage, 256 instead of 1024 since only using 8 bits voltage = ((float)((float) Ain * 5.0 / 1024.0)); // Depending on Voltage, set three bits per sensor // Debugging //if(x==6) printf("%ld %ld %12.8f\n\r", Ain, Ain2, voltage); // Debug ADC // NEED SENSOR ALGORITHM HERE // Sensor algorithm: // We use measured distance-voltage values of the IR sensors to establish a range for which a certain number of sensor bits will be set // There are three bits so there are four cases (000, 001, 011, 111) // 111 covers more distance than 011 // Sensoractivity, for fitness is also set // We also use a collision else statement to force fitness to zero in a collision (in addition to three bits being set in sensor) // To allow the robot to move when nothing is around, there will also be random spikes between sensor1not and sensor1top depending on the distance between them // The distance is used as a probability and we calculate a random value to decide if there will be a single spike if (x == 1) // Calculate Sensor 1 Spikes { if (voltage >= (float) sensor1top) { probability = (((float) sensor1not - voltage) / ((float) sensor1not - (float) sensor1top)); randomprob = (float) rand() / 32767.0; if (randomprob <= probability) { sensorread = ((sensorread & (0b111111111111000)) | 0b000000000000001); // Debug // printf("hi %5.2f %5.2f\n\r", randomprob, probability); } else { sensorread = ((sensorread & (0b111111111111000)) | 0b000000000000000); sensoractivity[0] = 0; // Debug //printf("YES %5.2f %5.2f\n\r", randomprob, probability); } } else if (voltage < (float) sensor1top && voltage >= (float) sensor1mid) { sensorread = ((sensorread & (0b111111111111000)) | 0b000000000000001); sensoractivity[0] = .25; } else if (voltage < (float) sensor1mid && voltage >= (float) sensor1bot) { sensorread = ((sensorread & (0b111111111111000)) | 0b000000000000011); sensoractivity[0] = .50; } else if (voltage < (float) sensor1bot && voltage > (float) sensor1col) { sensorread = ((sensorread & (0b111111111111000)) | 0b000000000000111); sensoractivity[0] = .75; } else if (voltage <= (float) sensor1col) { sensorread = ((sensorread & (0b111111111111000)) | 0b000000000000111); sensoractivity[0] = 1.0; collision = 1; } } // } Sensor 1 else if (x == 2) // Calculate Sensor 2 Spikes { if (voltage >= (float) sensor2top) { probability = (((float) sensor2not - voltage) / ((float) sensor2not - (float) sensor2top)); randomprob = (float) rand() / 32767.0; if (randomprob <= probability) { sensorread = ((sensorread & (0b111111111000111)) | 0b000000000001000); // Debug //printf("hi %5.2f %5.2f\n\r", randomprob, probability); } else { sensorread = ((sensorread & (0b111111111000111)) | 0b000000000000000); sensoractivity[1] = 0; // Debug //printf("YES %5.2f %5.2f\n\r", randomprob, probability); } } else if (voltage < (float) sensor2top && voltage >= (float) sensor2mid) { sensorread = ((sensorread & (0b111111111000111)) | 0b000000000001000); sensoractivity[1] = .25; } else if (voltage < (float) sensor2mid && voltage >= (float) sensor2bot) { sensorread = ((sensorread & (0b111111111000111)) | 0b000000000011000); sensoractivity[1] = .50; } else if (voltage < (float) sensor2bot && voltage > (float) sensor2col) { sensorread = ((sensorread & (0b111111111000111)) | 0b000000000111000); sensoractivity[1] = .75; } else if (voltage <= (float) sensor2col) { sensorread = ((sensorread & (0b111111111000111)) | 0b000000000111000); sensoractivity[1] = 1.0; collision = 1; } } // } Sensor 2 else if (x == 3) // Calculate Sensor 3 Spikes { if (voltage >= (float) sensor3top) { probability = (((float) sensor3not - voltage) / ((float) sensor3not - (float) sensor3top)); randomprob = (float) rand() / 32767.0; if (randomprob <= probability) { sensorread = ((sensorread & (0b111111000111111)) | 0b000000001000000); // Debug //printf("hi %5.2f %5.2f\n\r", randomprob, probability); } else { sensorread = ((sensorread & (0b111111000111111)) | 0b000000000000000); sensoractivity[2] = 0; // Debug //printf("YES %5.2f %5.2f\n\r", randomprob, probability); } } else if (voltage < (float) sensor3top && voltage >= (float) sensor3mid) { sensorread = ((sensorread & (0b111111000111111)) | 0b000000001000000); sensoractivity[2] = .25; } else if (voltage < (float) sensor3mid && voltage >= (float) sensor3bot) { sensorread = ((sensorread & (0b111111000111111)) | 0b000000011000000); sensoractivity[2] = .50; } else if (voltage < (float) sensor3bot && voltage > (float) sensor3col) { sensorread = ((sensorread & (0b111111000111111)) | 0b000000111000000); sensoractivity[2] = .75; } else if (voltage <= (float) sensor3col) { sensorread = ((sensorread & (0b111111000111111)) | 0b000000111000000); sensoractivity[2] = 1.0; collision = 1; } } // } Sensor 3 else if (x == 4) // Calculate Sensor 4 Spikes { if (voltage >= (float) sensor4top) { probability = (((float) sensor4not - voltage) / ((float) sensor4not - (float) sensor4top)); randomprob = (float) rand() / 32767.0; if (randomprob <= probability) { sensorread = ((sensorread & (0b111000111111111)) | 0b000001000000000); // Debug //printf("hi %5.2f %5.2f\n\r", randomprob, probability); } else { sensorread = ((sensorread & (0b111000111111111)) | 0b000000000000000); sensoractivity[3] = 0; // Debug //printf("YES %5.2f %5.2f\n\r", randomprob, probability); } } else if (voltage < (float) sensor4top && voltage >= (float) sensor4mid) { sensorread = ((sensorread & (0b111000111111111)) | 0b000001000000000); sensoractivity[3] = .25; } else if (voltage < (float) sensor4mid && voltage >= (float) sensor4bot) { sensorread = ((sensorread & (0b111000111111111)) | 0b000011000000000); sensoractivity[3] = .50; } else if (voltage < (float) sensor4bot && voltage > (float) sensor4col) { sensorread = ((sensorread & (0b111000111111111)) | 0b000111000000000); sensoractivity[3] = .75; } else if (voltage <= (float) sensor4col) { sensorread = ((sensorread & (0b111000111111111)) | 0b000111000000000); sensoractivity[3] = 1.0; collision = 1; } } // } Sensor 4 else if (x == 5) // Calculate Sensor 5 Spikes { if (voltage >= (float) sensor5top) { probability = (((float) sensor5not - voltage) / ((float) sensor5not - (float) sensor5top)); randomprob = (float) rand() / 32767.0; if (randomprob <= probability) { sensorread = ((sensorread & (0b000111111111111)) | 0b001000000000000); // Debug //printf("hi %5.2f %5.2f\n\r", randomprob, probability); } else { sensorread = ((sensorread & (0b000111111111111)) | 0b000000000000000); sensoractivity[4] = 0; // Debug //printf("YES %5.2f %5.2f\n\r", randomprob, probability); } } else if (voltage < (float) sensor5top && voltage >= (float) sensor5mid) { sensorread = ((sensorread & (0b000111111111111)) | 0b001000000000000); sensoractivity[4] = .25; } else if (voltage < (float) sensor5mid && voltage >= (float) sensor5bot) { sensorread = ((sensorread & (0b000111111111111)) | 0b011000000000000); sensoractivity[4] = .50; } else if (voltage < (float) sensor5bot && voltage > (float) sensor5col) { sensorread = ((sensorread & (0b000111111111111)) | 0b111000000000000); sensoractivity[4] = .75; } else if (voltage <= (float) sensor5col) { sensorread = ((sensorread & (0b000111111111111)) | 0b111000000000000); sensoractivity[4] = 1.0; collision = 1; } } // } Sensor 5 else if (x == 6) // Calculate Sensor 6 Noises { if (voltage >= (float) sensor6bot && voltage <= (float) sensor6top) { probability = (((float) sensor6top - voltage) / ((float) sensor6top - (float) sensor6bot)); srand(probability * 1000); randomprob = (float) rand() / 32767.0; if (randomprob <= probability) { //sensorread = ((sensorread&(0b000111111111111))|0b001000000000000); // Debug //printf("hi %5.2f %5.2f\n\r", randomprob, probability); } else { //sensorread = ((sensorread&(0b000111111111111))|0b000000000000000); //sensoractivity[4] = 0; // Debug // printf("YES %5.2f %5.2f\n\r", randomprob, probability); } } } // } Sensor 6 (noise) // Debugging //sensorread = (~0); if (x >= ((numsensor / 3) + 1)) { ADMUX = (ADMUX & (0b11100000) | 0); } else { ADMUX = (ADMUX & (0b11100000) | x); // Set to read Sensor 1, Take ADMUX and zero out last 5 bits, and set to the next sensor coming in } } // Ends for loop for sensor update //randomseed = randomseed/(numsensor/3); //srand(randomseed); // Calculate max sensor actiivty sensormaxactivity = sensoractivity[0]; for (g = 1; g < (numsensor / 3); g++) { if (sensoractivity[g] > sensormaxactivity) { sensormaxactivity = sensoractivity[g]; } } // Debugging // This is the way to get the most random bits in, based on noise, will OR with regular senorread to get sensor values when plugged back into robot sensorread = (sensorread | (((rand() % 2) << 0) | ((rand() % 2) << 3) | ((rand() % 2) << 6) | ((rand() % 2) << 9) | ((rand() % 2) << 12))); //sensorread = (((rand()%2) << 0)|((rand() %2) << 3)|((rand() %2) << 6)|((rand() %2) << 9)|((rand() %2) << 12)); //collision = 0; //sensormaxactivity = 0; //printf("%x\n\r", sensorread); // Only do Motor Speed Update every 160 ms, this allows for max 8 cm/s at least one movemnet since it takes 41ms to execute if (tsk4cnt == 0) { ///////////////////////////////////////Motor Speed Update////////////////////////////////////////////// // Motor speed for next 20ms is for each motor: spikesforward-spikesbackward scaled to [-8 cm/s, 8 cm/s] // Velocity will be determined by time of each step which is equal to .332485 cm / (spikesforward-spikesbackward) // Ie. this is initialized to .332485 cm / 3.32483 cm / s = .1 s = 100 ms // Concern here is that time will always be significantly higher than next motor udpate time, risk? //printf("%li %li %li %li %ld\n\r", spikeFL, spikeBL, spikeFR, spikeBR, maxspikes); if (spikeFL >= spikeBL) // If more forward then back, direction is forward { // Debugging dirL = 0; // Multiply by 8.0 since maxspikes is actually maxspikes * 2 since if a neuron does spike it won't spike twice in a row because of the refractory period v2 = ((float)((float)((float) spikeFL - (float) spikeBL) / (float) maxspikes) * 2.0 * 8.0); // Debugging (comment out t2 change) t2 = (0.332485 / v2 * 1000.0); time2 = t2; } else { // Debugging dirL = 1; v2 = ((float)((float)((float) spikeBL - (float) spikeFL) / (float) maxspikes) * 2.0 * 8.0); // Debugging t2 = (0.332485 / v2 * 1000.0); time2 = t2; } if (spikeFR >= spikeBR) // If more forward then back, direction is forward { // Debugging dirR = 0; v3 = ((float)((float)((float) spikeFR - (float) spikeBR) / (float) maxspikes) * 2.0 * 8.0); // Debugging t3 = (0.332485 / v3 * 1000.0); time3 = t3; } else { // Debugging dirR = 1; v3 = ((float)((float)((float) spikeBR - (float) spikeFR) / (float) maxspikes) * 2.0 * 8.0); // Debugging t3 = (0.332485 / v3 * 1000.0); time3 = t3; } // } Motor Speed update // Set tsk4cnt to be the greater of the times 350>tsk4cnt>60 if (t2 > t3 && t2 <= 350) { tsk4cnt = t2 + 10; } else if (t3 > t2 && t3 <= 350) { tsk4cnt = t3 + 10; } else tsk4cnt = 60; //printf("%li %li\n\r", t2, t3); } // } Motor Speed if statement // Fitness Calculation if (dirL == 0 && dirR == 0 && collision == 0) // As long as going forward on both wheels and no collision { if (v2 >= v3) { newfitness = newfitness + (v2 + v3) * (1.0 - ((v2 - v3) / 8.0)) * (1.0 - (sensormaxactivity)); // Need to add something to sensor //change = (v2+v3)*(1.0-((v2-v3)/8.0))*(1.0-(sensormaxactivity)); //printf("%5.2f", change); } else { newfitness = newfitness + (v2 + v3) * (1.0 - ((v3 - v2) / 8.0)) * (1.0 - (sensormaxactivity)); // Need to add something to sensor //change = (v2+v3)*(1.0-((v3-v2)/8.0))*(1.0-(sensormaxactivity)); //printf("%5.2f", change); } } else if ((dirL == 1 || dirR == 1) && collision == 0) { newfitness = newfitness + 0; //printf("YES\n\r"); } else if (collision == 1) { newfitness = newfitness + 0; //printf("NO\n\r"); } // Ready sensor and motor update sensorflag = 1; } // Ends task 4 //////////////////////////////////////////////////////////////// void task5(void) { time5 = t5; // Fitness Check - If not greater return to old version in population // Debugging printf("%i %i %li %li %li %li %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f %7.1f\n\r", individual, threshold[individual], totalspikeFL, totalspikeBL, totalspikeFR, totalspikeBR, newfitness, fitness[0], fitness[1], fitness[2], fitness[3], fitness[4], fitness[5]); worstindivid = 0; for (z = 1; z < numindivid; z++) // Calculate Worst Individual { if (fitness[z] < fitness[worstindivid]) { worstindivid = z; } } if (newfitness >= fitness[worstindivid] && newfitness >= fitness[individual]) { keep = 1; fitness[individual] = newfitness; } else keep = 0; newfitness = 0; // Reset newfitness if (keep == 0) { signs[individual] = oldsigns; for (d = 0; d < numneuron; d++) { nconnection[individual][d] = oldnconnection[d]; sconnection[individual][d] = oldsconnection[d]; } threshold[individual] = oldthreshold; } // Pick a random individual and mutate it individual = (rand() % numindivid); // Debugging //individual = 0; // Save old version oldsigns = signs[individual]; for (e = 0; e < numneuron; e++) { oldnconnection[e] = nconnection[individual][e]; oldsconnection[e] = sconnection[individual][e]; } oldthreshold = threshold[individual]; // Mutate signs[individual] = (signs[individual] ^ (1 << (rand() % numneuron))); randn = (rand() % numneuron); rands = (rand() % numsensor); nconnection[individual][randn] = (nconnection[individual][randn] ^ (1 << (rand() % numneuron))); sconnection[individual][rands] = (sconnection[individual][rands] ^ (1 << (rand() % numsensor))); threshold[individual] = (threshold[individual] ^ (1 << (rand() % 4))); if (threshold[individual] > 6 || threshold[individual] < 2) threshold[individual] = oldthreshold; // Send signal evolveflag = 1; // Debugging //printf("%i %lx %lx %lx %lx\n\r", individual, signs[individual], nconnection[individual][randn], sconnection[individual][rands], sensor); } // Ends task 5 //////////////////////////////////////////////////////////////// void task6(void) { time6 = t6; // Store Best Fitness Individual in EEPROM for (f = 0; f < numindivid; f++) { if (fitness[f] >= bestfitness) { bestfitness = fitness[f]; bestindivid = f; } // Debugging //printf("%li\n\r", bestfitness); } // STORE BEST INDIVID/FITNESS/GENETIC STRING IN EEPROM // EEPROM STUFF for (ii = 0; ii < numindivid; ii++) { // Save best individual if (ii == bestindivid) { eebestsigns = signs[ii]; for (zz = 0; zz < numneuron; zz++) { eebestnconnection[zz] = nconnection[ii][zz]; eebestsconnection[zz] = sconnection[ii][zz]; } eebestthreshold = threshold[ii]; eebestfitness = fitness[ii]; } eesigns[ii] = signs[ii]; for (jj = 0; jj < numneuron; jj++) { eenconnection[ii][jj] = nconnection[ii][jj]; eesconnection[ii][jj] = sconnection[ii][jj]; } eefitness[ii] = fitness[ii]; eethreshold[ii] = threshold[ii]; } eebestfitnessmem[eeindex] = bestfitness; eeindex = eeindex + 1;; // Index of fitness values/replacements } // Ends task 6 //////////////////////////////////////////////////////////////// void main(void) { initialize(); while (1) { if (time1 == 0) task1(); if (time2 == 0) task2(); if (time3 == 0) task3(); if (time4 == 0) task4(); if (time5 == 0) task5(); if (time6 == 0) task6(); } } //////////////////////////////////////////////////////////////// void initialize(void) { // PORTS DDRC = 0xff; // PORTC is set to output for motor control PORTC = 0x00; // TIMERS // timer0 is a 1 ms timer OCR0 = 250; // 1 ms ((1 / 16 MHZ) * 64 * 250 = 1 ms) TIMSK = 2; // Timer0 Compare Match Interrupt Enable TCCR0 = 0b00001011; // Prescalar set to 64, Clear on Compare Match //HYPERTERM //serial setup for debugging using printf, etc. UCSRB = 0x18; UBRRL = 103; printf("\r\nStarting...\r\n"); // ADC // ADC will be read by watching bit 6 in ADCSR, the ADSC bit, which is cleared when a conversion is finished ADMUX = 0b01100000; // Use AVCC (5V), Left Aligned, Start with ADC0 ADCSR = 0b10000111; // ADC Enabled, Not Started First Conversion, No Interrupt, Prescaler of 128 // Debug - Speed up ADC to get some noise! //ADCSR = 0b10000100; // Generate Random Seed randomseed = 0; for (y = 1; y <= ((numsensor / 3) + 1); y++) { ADCSR .6 = 1; // Start Another Conversion while (ADCSR .6); Ain = ADCH; // Read ADC for Sensor 0 randomseed = randomseed + Ain; if (y == 6) // Calculate Sensor 6 Noises { if (voltage >= (float) sensor6bot && voltage <= (float) sensor6top) { //probability = (((float)sensor6top - voltage)/((float)sensor6top-(float)sensor6bot)); //srand(probability*1000); } } if (y >= ((numsensor / 3) + 1)) { ADMUX = (ADMUX & (0b11100000) | 0); } else { ADMUX = (ADMUX & (0b11100000) | y); // Set to read Sensor 1, Take ADMUX and zero out last 5 bits, and set to the next sensor coming in } } randomseed = randomseed / (numsensor / 3); srand(randomseed); // Variables time1 = t1; t2 = 100; // 100 ms is initialized value for how long in between each step of left/right motors (10 steps / second) t3 = 100; // Each step is 7.5 degrees so this will give 3.32483 cm/second (10 steps / second * 7.5 degree / step * .044331 cm / degree) time2 = t2; time3 = t3; time4 = t4; time5 = t5; time6 = t6; sensorflag = 0; evolveflag = 0; // Flag that indicates a mutation has just occurred tsk4cnt = 100; // Counter for task 4 to allow us to update motors every 60 ms to allow for actual movement // Neuron Variables neuron = 0; // Output of Neurons (1 is spike, 0 is no spike), ie. 0b11001100 means neurons 2, 3, 6, 7 are spiking, sensors 0, 1, 4, 5 are not sensor = 0; // Output of Sensors (1 is spike, 0 is no spike), ie. 0b11001100 means sensors 2, 3, 6, 7 are spiking, sensors 0, 1, 4, 5 are not individual = (rand() % (numindivid)); // Current Individual (0 - 5) // The population will be initialized using random numbers and all fitness values will be set to zero // Use EEPROM if already started a population if (eeindex == 0) { for (b = 0; b < numindivid; b++) { signs[b] = (rand() % (1 << numneuron)); // Sign of Neurons (1 is positive, 0 is negative), ie. 0b00001111 means neurons 0, 1, 2, 3 are positive, neurons 4, 5, 6, 7 are not // Debugging printf("%lx\n\r", signs[b]); for (a = 0; a < numneuron; a++) { nconnection[b][a] = (rand() % (1 << numneuron)); // Connections from Neurons, each char describes connections for one neuron (1 is connection, 0 is no connection), ie. 0b11001010 means there are connections to this neuron from neurons 1, 3, 6, 7 and no connection from neurons 0, 2, 4, 5 sconnection[b][a] = (rand() % (1 << numsensor)); // Connections from Sensors, each char describes connections from one sensor (1 is connection, 0 is no connection) memb[a] = 0; // Membrane Potential of each Neuron (minimum value of 0, initialized to 0) } // Debugging printf("%lx\n\r", sconnection[b][0]); fitness[b] = 0; // Fitness value for an individual threshold[b] = (rand() % 4 + 3); // Membrane Threshold (5) } } else { for (b = 0; b < numindivid; b++) { signs[b] = eesigns[b]; // Sign of Neurons (1 is positive, 0 is negative), ie. 0b00001111 means neurons 0, 1, 2, 3 are positive, neurons 4, 5, 6, 7 are not // Debugging printf("%lx\n\r", signs[b]); for (a = 0; a < numneuron; a++) { nconnection[b][a] = eenconnection[b][a]; // Connections from Neurons, each char describes connections for one neuron (1 is connection, 0 is no connection), ie. 0b11001010 means there are connections to this neuron from neurons 1, 3, 6, 7 and no connection from neurons 0, 2, 4, 5 sconnection[b][a] = eesconnection[b][a]; // Connections from Sensors, each char describes connections from one sensor (1 is connection, 0 is no connection) memb[a] = 0; // Membrane Potential of each Neuron (minimum value of 0, initialized to 0) } // Debugging printf("%lx\n\r", sconnection[b][0]); fitness[b] = (float) eefitness[b]; // Fitness value for an individual threshold[b] = eethreshold[b]; // Membrane Threshold (5) } } leaking = 1; // Leaking Constant (1) minimum = 0; // Miminum Membrane Potential (0) randomint = 0; // Randomly generated integer // Spike Forward Motor Neurons to start memb[0] = threshold[individual] + 20; memb[2] = threshold[individual] + 20; //memb[4] = threshold[individual] + 20; //memb[5] = threshold[individual] + 20; //memb[6] = threshold[individual] + 20; //memb[7] = threshold[individual] + 20; // Old Values oldsigns = signs[individual]; for (c = 0; c < numneuron; c++) { oldnconnection[c] = nconnection[individual][c]; oldsconnection[c] = sconnection[individual][c]; } oldthreshold = 0; // ADC Variables Ain = 0; // Current ADC input voltage = 0; // Current ADC input converted into voltage sensorread = 0; // Values of Sensors being read probability = 0; // Probability of getting a random noise spike randomprob = 0; // Random probability // Motor Variables stepL = 0; stepR = 0; dirL = 0; // Forward dirR = 0; // Forward spikeFL = 0; // Number of spikes during sensor update period (20 ms) generated by forward left neuron totalspikeFL = 0; // Total spikes between evolution spikeBL = 0; // Number of spikes during sensor update period (20 ms) generated by backward left neuron totalspikeBL = 0; // Total spikes between evolution spikeFR = 0; // Number of spikes during sensor update period (20 ms) generated by forward right neuron totalspikeFR = 0; // Total spikes between evolution spikeBR = 0; // Number of spikes during sensor update period (20 ms) generated by backward right neuron totalspikeBR = 0; // Total spikes between evolution maxspikes = 0; // Number of possible spikes during sensor update period v2 = 0; // Motor Velocities v3 = 0; // Evolution Variables newfitness = 0; // Calculates new fitness to compare with old fitnesses keep = 0; // Keep determines if we will keep a mutation, is 1 if it the current individuals fitness is >= worst individuals fitness collision = 0; // Indicates a collision for fitness calculation (0 no collision, 1 collision) sensormaxactivity = 0; // Most active sensor value for fitness calculation (5 values for this based on most active sensor: 0 if nothing, .25 if between top and mid, .5 if between mid and bot, .75 if between bot and col, 1 if below or equal to col) for (h = 0; h < (numsensor / 3); h++) { sensoractivity[h] = 0; // Activity of 5 sensors based on values above to be maxed }; worstindivid = 0; // Worst indiviudal used to determine keep randn = 0; // Random Variables to access blocks in random individual for mutation rands = 0; change = 0; // Change in fitness (debugging) // Fitness Store variables bestfitness = 0; // Best Fitness so far bestindivid = 0; // Best Individual // Print out Current EEPROM Best Individual (if avaliable) // Print out Current EEPROM Best Fitness (if avaliable) if (eeindex != 0) { printf("\n\r"); printf("%lx\n\r", eebestsigns); delay_ms(10); for (yy = 0; yy < numneuron; yy++) { printf("%lx\n\r", eebestnconnection[yy]); delay_ms(2); printf("%lx\n\r", eebestsconnection[yy]); } printf("%i\n\r", eebestthreshold); delay_ms(10); printf("%li\n\r", eebestfitness); delay_ms(10); printf("\n\r"); for (xx = 0; xx < eeindex; xx++) { printf("%li\n\r", eebestfitnessmem[xx]); delay_ms(2); } } //crank up the ISRs # asm sei# endasm }
C
/* * This file is part of the AprilTag library. * * AprilTag 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. * * AprilTag 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 Libav; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA */ #include <stdint.h> #include <stdlib.h> #include <assert.h> #include "apriltag/graymodel.h" #include "apriltag/matd.h" graymodel_t *graymodel_create() { graymodel_t *gm = calloc(1, sizeof(graymodel_t)); gm->A = matd_create(4, 4); gm->b = matd_create(4, 1); return gm; } void graymodel_add_observation(graymodel_t *gm, double x, double y, double v) { double xy = x * y; // update only upper-right elements. A'A is symmetric, // we'll fill the other elements in later. MAT_EL(gm->A, 0, 0) += x * x; MAT_EL(gm->A, 0, 1) += x * y; MAT_EL(gm->A, 0, 2) += x * xy; MAT_EL(gm->A, 0, 3) += x; MAT_EL(gm->A, 1, 1) += y * y; MAT_EL(gm->A, 1, 2) += y * xy; MAT_EL(gm->A, 1, 3) += y; MAT_EL(gm->A, 2, 2) += xy * xy; MAT_EL(gm->A, 2, 3) += xy; MAT_EL(gm->A, 3, 3) += 1; MAT_EL(gm->b, 0, 0) += x * v; MAT_EL(gm->b, 1, 0) += y * v; MAT_EL(gm->b, 2, 0) += xy * v; MAT_EL(gm->b, 3, 0) += v; gm->n++; } void graymodel_solve(graymodel_t *gm) { if (gm->n > 6) { // make symmetric for (int i = 0; i < 4; i++) for (int j = i + 1; j < 4; j++) MAT_EL(gm->A, j, i) = MAT_EL(gm->A, i, j); gm->x = matd_solve(gm->A, gm->b); } else { // use flat model gm->x = matd_create(4, 1); MAT_EL(gm->x, 3, 0) = MAT_EL(gm->b, 3, 0) / gm->n; } } double graymodel_interpolate(graymodel_t *gm, double x, double y) { assert(gm->x != NULL); return MAT_EL(gm->x, 0, 0) * x + MAT_EL(gm->x, 1, 0) * y + MAT_EL(gm->x, 2, 0) * x * y + MAT_EL(gm->x, 3, 0); } void graymodel_destroy(graymodel_t *gm) { matd_destroy(gm->A); matd_destroy(gm->b); if (gm->x != NULL) matd_destroy(gm->x); free(gm); }
C
/* * Largest Palindrome in the String * * Created on: September 28, 2012 * Author: Swapnil */ // Find the longest palindrome in a string // Returns the length of the maximum palindrome and stores the position in pointer int find_largest_palindrome(char *str, int *pos) { int length = 1, max = 1; // char *left,*current,*right; current = str; *pos = 1; while(*current) { left = current - 1; right = current + 1; length = 1; while(current >= str && ((*current) == (*left))) { left--; length++; } while(*right && ((*right) == (*current))) { right++; length++; } while(left >= str && *right && ((*right) == (*left))) { left--;right++; length += 2; } if(length > max) { *pos = left + 1 - str; max = length; } current++; } return max; }
C
/* ex4-5c.c */ #include <stdio.h> #include <stdlib.h> int main() { /* 將範例4-4b的else-if敘述更改為switch敘述,並 將int改為char型態,示範switch在字元常數下的用法 */ char level; printf("請問你是幾年級的學生(1…5): "); scanf("%c", &level); switch(level) { case '1': printf("你是大一新生\n"); break; case '2': printf("你是大二學生\n"); break; case '3': printf("你是大三學生\n"); break; case '4': printf("你是大四學生\n"); break; case '5': printf("你是研究生\n"); break; default: printf("錯誤的代碼!!\n"); } system("PAUSE"); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* main.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: mmahasim <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/10/21 19:16:38 by mmahasim #+# #+# */ /* Updated: 2019/11/24 18:22:55 by mmahasim ### ########.fr */ /* */ /* ************************************************************************** */ #include "../fdf.h" int ft_cube(int d_x, int d_x1) { int cube; cube = 50; if (d_x != d_x1) { ft_putstr("Found wrong line length. Exiting.\n"); exit(0); } while (d_x * cube > HEIGHT) { cube = cube / 2; } return (cube); } int ft_len_y(char *argv) { int j; char *str; int fd; int error; j = 0; fd = open(argv, O_RDONLY); if (get_next_line(fd, &str) == 0) { ft_putstr("No data found.\n"); exit(0); } j++; while ((error = get_next_line(fd, &str)) != 0) { if (error == -1) { ft_putstr("No data found.\n"); exit(-1); } free(str); j++; } ft_cube(j, j); return (j); } char **ft_m(char *argv, t_m *m) { int j; char **str; int fd; int error; j = 0; fd = open(argv, O_RDONLY); if (!(str = (char **)malloc(sizeof(char *) * m->len_y))) return (0); while ((error = (get_next_line(fd, &str[j]))) != 0) { if (error == -1) { ft_putstr("No data found.\n"); exit(-1); } j++; } return (str); } int ft_cor_z(t_m *m) { int i; int j; i = -1; j = -1; if (!(m->top_z = (t_tops_z **)malloc(sizeof(t_tops_z *) * m->len_y))) return (0); m->len_x = ft_count(m->m[0], ' '); while (++j != m->len_y) { m->k = ft_strsplit(m->m[j], ' '); m->cube = ft_cube(m->len_x, ft_count(m->m[j], ' ')); free(m->m[j]); if (!(m->top_z[j] = (t_tops_z *)malloc(sizeof(t_tops_z) * m->len_x))) return (0); while (m->k[++i] != 0) { m->top_z[j][i].z = ft_atoi(m->k[i]); free(m->k[i]); } i = -1; } free(m->k); free(m->m); return (0); } int main(int argc, char **argv) { t_m *m; if (argc != 2) { ft_putstr("enter 1 fdf map\n"); return (-1); } if (!(m = (t_m *)malloc(sizeof(t_m)))) return (0); m->len_y = ft_len_y(argv[1]); m->m = ft_m(argv[1], m); ft_start(m); ft_cor_z(m); m->mlx_ptr = mlx_init(); m->win_ptr = mlx_new_window(m->mlx_ptr, WIDHT, HEIGHT, ft_strjoin("Fdf - ", argv[1])); ft_draw(m); mlx_key_hook(m->win_ptr, ft_key, m); mlx_loop(m->mlx_ptr); ft_free(m); return (0); }
C
/* Student Name :kamal rokka Roll no.: Lab no.: Program:assighment operator Date: subject: */ #include<stdio.h> int main() { int a,b; printf("enter first no.:\n"); scanf("%d",&a); printf("enter secod no.:\n"); scanf("%d",&b); a+=b; //a=a+b printf("result of a+=b::%d\n",a); a-=b; printf("result of a-=b:%d\n",a); a*=b; printf("result of a*=b:%d\n",a); a/=b; printf("result of a/=b:%d\n",a); return 0; }
C
#include "udp_task.h" static void udpTask(RingbufHandle_t buffer); TaskHandle_t createUdpTask(RingbufHandle_t buffer) { xTaskHandle xHandle = NULL; xTaskCreate(udpTask, UDP_TASK_TAG, 8192, buffer, 5, &xHandle); if (xHandle == NULL) { ESP_LOGE(UDP_TASK_TAG, "Could not create task"); abort(); } return xHandle; } static void udpTask(RingbufHandle_t buffer) { char rx[UDP_BUFFER_SIZE]; for (;;) { struct sockaddr_in dest_addr; dest_addr.sin_addr.s_addr = htonl(INADDR_ANY); dest_addr.sin_family = AF_INET; dest_addr.sin_port = htons(UDP_PORT); int sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP); if (sock < 0) { ESP_LOGE(UDP_TASK_TAG, "Unable to create socket: errno %d", errno); abort(); } ESP_LOGI(UDP_TASK_TAG, "Socket created"); int err = bind(sock, (struct sockaddr *)&dest_addr, sizeof(dest_addr)); if (err < 0) { ESP_LOGE(UDP_TASK_TAG, "Socket unable to bind: errno %d", errno); abort(); } ESP_LOGI(UDP_TASK_TAG, "Socket bound, port %d", UDP_PORT); for (;;) { ESP_LOGV(UDP_TASK_TAG, "Waiting for data"); int len = recvfrom(sock, rx, UDP_BUFFER_SIZE, 0, NULL, NULL); if (len < 0) { ESP_LOGE(UDP_TASK_TAG, "recvfrom failed: errno %d", errno); } else { ESP_LOGV(UDP_TASK_TAG, "recvfrom success"); xRingbufferSend(buffer, rx, len, 100); } } } }
C
#include <stdio.h> typedef struct Car1{ int num; double gas; unsigned int tire : 3; unsigned int roof : 1; unsigned int color : 4; }Car1; typedef struct Car2{ int num; double gas; unsigned int tire; unsigned int roof; unsigned int color; }Car2; int main(void) { printf("ビットフィールドを使った構造体のサイズは%luバイトです.\n", sizeof(Car1)); printf("ビットフィールドを使わない構造体のサイズは%luバイトです.\n", sizeof(Car2)); return 0; }
C
// RUN: %splay %s | lli | FileCheck %s #include <stdio.h> #include <stdlib.h> static int sum(int n) { int i, result = 0; for (i = 1; i <= n; ++i) result += i; return result; } int main(int argc, char **argv) { // CHECK: 15 printf("%d\n", sum(5)); // CHECK: 5050 printf("%d\n", sum(100)); }
C
#define K 4 #define M 10 #define FIRST_PLAYER -1 #include <string.h> #include <stdlib.h> #include <stdio.h> #include <stdbool.h> #include "game_tree.c" const int JOGO_FINALIZADO = 1; const int JOGADA_BEM_SUCEDIDA = 2; const int JOGADA_INVALIDA = 3; struct Node * tree; int currentPlayer = FIRST_PLAYER; char* playerName(int playerNumber) { return playerNumber == -1 ? "PC" : "Humano"; } void switchPlayer() { currentPlayer *= -1; } int storeMove(int removed) { tree = tree->children[removed - 1]; printf("%s tira %d palitos, restam %d\n", playerName(currentPlayer), removed, tree->remaining); if (tree->remaining == 0){ printf("O jogador %s ganhou o jogo!", playerName(currentPlayer)); return JOGO_FINALIZADO; } switchPlayer(); return JOGADA_BEM_SUCEDIDA; } int seekBestPlay() { int minKey, maxKey; int currentMin = 500, currentMax = -500; for(int i=0; i<K && i < tree->remaining;i++) { struct Node *childNode = tree->children[i]; printf("Opção %d com minimax %d\n", i+1, childNode->minimax); if(childNode->minimax < currentMin) { currentMin = childNode->minimax; minKey = i; } if(childNode->minimax > currentMax) { currentMax = childNode->minimax; maxKey = i; } } return (currentPlayer == -1 ? minKey : maxKey) + 1; } int humanInput() { int removed; do{ seekBestPlay(); printf("Quandos palitos deseja tirar? Número: "); scanf("%d", &removed); if (removed > K || removed < 0){ printf("Jogada inválida. Escolha entre 1 e %d palito(s)\n", K); continue; } if (tree->remaining - removed < 0){ printf("Jogada inválida. Restam apenas %d palito(s)\n", tree->remaining); continue; } break; } while (true); return removed; } int main() { printf("Configuração do jogo: jogada máxima %d e número de palitos %d\n\n", K, M); tree = parallel_game_tree(); while (true){ if (storeMove(seekBestPlay()) == JOGO_FINALIZADO) break; if (storeMove(humanInput()) == JOGO_FINALIZADO) break; } }
C
#include"myheader.c" NODE*del(NODE*head) { int r; NODE*temp,*pre; if(head==NULL) { printf("List is empty..\n"); return head; } printf("Enter rol to del..\n"); scanf("%d",&r); temp=head; while(temp) { if(temp->roll!=r) { pre=temp; temp=temp->link; } else break; } if(temp==NULL) { printf("rol not found..\n"); return head; } if(temp==head) { head=head->link; free(temp); printf("Deletion successful...\n"); } else { pre->link=temp->link; free(temp); printf("Deletion successful..\n"); } return head; }
C
#include <stdio.h> #include <stdlib.h> #include "List.h" ListNode* List_Init(void) { printf("Please input your data end by '#':\n"); char c = '\0'; ListNode* head = NULL; ListNode* prev = NULL; while (c = getchar()) { if( '#' == c) break; ListNode* p = (ListNode*)malloc(sizeof(*p)); if(NULL == p) { perror("List_Init failed as malloc failed"); if(NULL != head) List_Destroy(head); prev = p = NULL; exit(OVERFLOW); } p->data = c; p->next = NULL; if(NULL == head) { head = p; prev = head; } else { prev->next = p; prev = p; } p = p->next; } return head; } ListNode* List_ForeInsert(ListNode* head, DataType data) { ListNode* p = (ListNode*)malloc(sizeof(*p)); if(NULL == p) { printf("List_ForeInsert fail as malloc fail.\n"); return head; } p->data = data; p->next = NULL; if(NULL != head) p->next = head; head = p; p = NULL; return head; } Status List_BackInsert(ListNode* head, DataType data) { ListNode* p = (ListNode*)malloc(sizeof(*p)); if(NULL == p) { printf("List_ForeInsert fail as malloc fail.\n"); return ERROR; } p->data = data; p->next = NULL; if(NULL == head) head = p; else { p = head; while(NULL != head->next) head = head->next; head->next = p; } return OK; } Status List_FindElem(ListNode* head, DataType data, DataType* container) { if(NULL == container) { perror("Container does not exist"); return ERROR; } while(NULL != head || data != head->data) head = head->next; if(NULL == head) { container = NULL; return FALSE; } else { *container = head->data; return TRUE; } } void List_Traverse(ListNode* head) { while(NULL != head) { printf("%c\t",head->data); head = head->next; } putchar('\n'); } Status List_DeleteElem(ListNode* head,DataType data) { ListNode* p = head; ListNode* prev = NULL; while( p != NULL || p->data != data) { prev = p; p = p->next; } if(NULL == p) return FALSE; if(head == p) { head = head->next; p->next = NULL; free(p); } else { prev->next = p->next; p->next = NULL; free(p); } return TRUE; } ListNode* List_Reverse(ListNode* head) { ListNode* p = head; if(NULL != p->next) List_Reverse(p->next); head = head->next; head->next = p; p = NULL; } void List_Destory(ListNode* head) { ListNode* next = NULL; ListNode* p = head; if(NULL != p) { next = p->next; free(p); p = p->next; } }
C
#include <stdio.h> void main(){ float peso, altura; int idade, ano_nascimento, dia_nascimento; scanf("%f", &peso); scanf("%f", &altura); scanf("%d", &idade); scanf("%d", &ano_nascimento); scanf("%d", &dia_nascimento); float formula = (((((peso + altura) / idade) + ano_nascimento) * dia_nascimento) - 33) * (idade + 7); printf("%f", formula); }
C
//Project 1 //Author: Carter Mooring //Date: Sept. 11th, 2020 // Implementation of merge sort using a linked mainList. //compile a C program: gcc hello.c //gcc -o hello hello.c //run a C program: ./hello #include <stdio.h> #include <stdlib.h> //Define the link node as a struct struct node{ int data; struct node* next; }; //Prototypes struct node* merge(struct node* head1, struct node* head2); struct node* mergeSort(struct node* head, int size); void printmainList(struct node* node); int getLength(struct node* newmainList); int main(){ struct node* mainList = NULL; struct node* nodeTwo = NULL; struct node* nodeThree = NULL; struct node* nodeFour = NULL; struct node* nodeFive = NULL; struct node* nodeSix = NULL; int mainListSize; //Construct the linked mainList mainList = (struct node*)malloc(sizeof(struct node)); nodeTwo = (struct node*)malloc(sizeof(struct node)); nodeThree = (struct node*)malloc(sizeof(struct node)); nodeFour = (struct node*)malloc(sizeof(struct node)); nodeFive = (struct node*)malloc(sizeof(struct node)); nodeSix = (struct node*)malloc(sizeof(struct node)); mainList->data = 38; mainList->next = nodeTwo; nodeTwo->data = 22; nodeTwo->next = nodeThree; nodeThree->data = 2; nodeThree->next = nodeFour; nodeFour->data = 37; nodeFour->next = nodeFive; nodeFive->data = 5; nodeFive->next = nodeSix; nodeSix->data = 15; nodeSix->next = NULL; mainListSize = getLength(mainList); printf("mainList Unsorted: \n"); printmainList(mainList); printf("mainList Sorted: \n"); printmainList(mergeSort(mainList, mainListSize)); } //Merge takes two pointers as parameters, each pointing to a sorted (sub) mainList, // and returns a new head pointer pointing to the merged mainList. struct node* merge(struct node * head1, struct node * head2){ struct node* result = NULL; if(head1 == NULL){ return (head2); } else if(head2 == NULL){ return (head1); } if (head1->data <= head2->data){ result = head1; result->next = merge(head1->next, head2); }else{ result = head2; result-> next = merge(head1, head2->next); } return (result); } struct node* mergeSort(struct node* head, int size){ struct node* head1 = head; int mid = size / 2; if(head->next == NULL){ return head; } while(mid - 1 > 0){ head1 = head1->next; mid--; } struct node* head2 = head1->next; head1->next = NULL; head1 = head; struct node* h1 = mergeSort(head1, getLength(head1)); struct node* h2 = mergeSort(head2, getLength(head2)); return merge(h1, h2); } //Prints the linked mainLists void printmainList(struct node* node){ while(node != NULL){ printf("%d ", node->data); node = node->next; } printf("\n"); } //Get the lenth of the linked mainList int getLength(struct node* newmainList){ int count = 0; struct node* mainList = newmainList; while(mainList != NULL){ count++; mainList = mainList->next; } return count; }
C
#include <vm_pool.h> #include <page_table.h> #define PAGE_SIZE (4 * 1024) void init_vmpool(struct vmpool *pvmpool, struct pagetable *_pagetable, unsigned int _base_address, unsigned int _size) { pvmpool->ppagetable = _pagetable; pvmpool->base_address = _base_address; pvmpool->size = _size; #if 0 pvmpool->ppagetable->register_vmpool(this); #endif /* alloc a frame for region descriptor * to do this, generate a page fault * at the base address */ pvmpool->pcur_region = (struct region_desc *)(pvmpool->base_address); /* generate a page fault * set the bit[0] with 1 as it is allocated * for region descriptor */ pvmpool->pcur_region->startAddr = pvmpool->base_address; pvmpool->pcur_region->size = PAGE_SIZE; pvmpool->pcur_region->prev = 0; pvmpool->pcur_region->next = 0; pvmpool->region_page_total = PAGE_SIZE; } /* lazy allocator */ unsigned int allocate(struct vmpool *pvmpool, unsigned int _size) { unsigned int pgnum; /* allocate multiple of page, internal fragmentation allowed */ pgnum = (int)(_size/PAGE_SIZE) + (_size%PAGE_SIZE ? 1 : 0); if(!pvmpool->pcur_region) { pvmpool->pcur_region = (struct region_desc *)(pvmpool->base_address); while(pvmpool->pcur_region->next) { pvmpool->pcur_region = pvmpool->pcur_region->next; } } pvmpool->pcur_region->next = pvmpool->pcur_region + 1; pvmpool->pcur_region->next->prev = pvmpool->pcur_region; pvmpool->pcur_region = pvmpool->pcur_region->next; pvmpool->pcur_region->startAddr = pvmpool->base_address + pvmpool->region_page_total; pvmpool->pcur_region->size = _size; pvmpool->pcur_region->next = 0; /* always allocate multiples of page size */ pvmpool->region_page_total += (PAGE_SIZE * pgnum); return pvmpool->pcur_region->startAddr; } void release(struct vmpool *pvmpool, unsigned int _start_address) { int i; unsigned int region_size; unsigned int pgnum; struct region_desc *pcur = (struct region_desc *)(pvmpool->base_address); while(pcur) { if(pcur->startAddr == _start_address) { pcur->prev->next = pcur->next; if(pcur->next) pcur->next->prev = pcur->prev; region_size = pcur->size; pgnum = (int)(region_size/PAGE_SIZE) + (region_size%PAGE_SIZE ? 1 : 0); for(i=0 ; i<pgnum ; i++) { free_page((unsigned int)(_start_address+(PAGE_SIZE*i))); } if(i == pgnum) { /* flushing TLB and reload page table */ load_pagetable(pvmpool->ppagetable); pvmpool->region_page_total -= (pgnum * PAGE_SIZE); } break; } pcur = pcur->next; } if(pvmpool->pcur_region->startAddr == _start_address) { pvmpool->pcur_region = (struct region_desc *)(pvmpool->base_address); while(pvmpool->pcur_region->next) { pvmpool->pcur_region = pvmpool->pcur_region->next; } } } int is_legitimate(struct vmpool *pvmpool, unsigned int _address) { struct region_desc *pcur = (struct region_desc *)(pvmpool->base_address); if(_address == pvmpool->base_address) return 1; pcur = pcur->next; while(pcur) { if(_address >= pcur->startAddr && _address < pcur->startAddr + pcur->size) return 1; else pcur = pcur->next; } return 0; }
C
/********************************************* * * Convert a tree to its mirror tree * *///////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> typedef struct treeNode{ int data; struct treeNode *left; struct treeNode *right; } node; node *create() { int n; node *p; printf("\nEnter data (Enter -1 if no child node)\n"); scanf("%d", &n); if (n == -1) return NULL; p = (node*) malloc(sizeof(node)); p->data = n; printf("\nEnter left child of %d ", n); p->left = create(); printf("\nEnter right child of %d ", n); p->right = create(); return p; } void makeMirror(node *p) { node *temp; if(p) { makeMirror(p->left); makeMirror(p->right); //swapping the left and right child from the end temp = p->left; p->left = p->right; p->right = temp; } } void inOrder(node *p) { if(p) { inOrder(p->left); printf("%d ", p->data); inOrder(p->right); } } void main () { node *root; root = create(); printf("\nInOrder traversal of tree before mirroring : "); inOrder(root); makeMirror(root); printf("\nInOrder traversal of tree after mirroring : "); inOrder(root); }
C
#include <stdio.h> #include "reverse.h" int main(){ char s[100] = "!dlrow ,olleH"; reverse(s); printf("%s\n", s); return 0; }
C
/** ******************************************************************************* * @file brk.c * @author Olli Vanhoja * @brief Change space allocation. * @section LICENSE * Copyright (c) 2014, 2015 Olli Vanhoja <olli.vanhoja@cs.helsinki.fi> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************* */ #define __SYSCALL_DEFS__ #include <syscall.h> #include <errno.h> #include <string.h> #include <unistd.h> static struct _proc_getbreak_args ds_brk; static void * curr_break; static int getbrk(void) { /* * The following syscall just gets the start and stop limits for the brk * functionality. Actual brk operation is solely implemented in * userland. */ if (ds_brk.start == 0) { if (syscall(SYSCALL_PROC_GETBREAK, &ds_brk)) { /* This should never happen unles user is trying to do something * fancy. */ errno = EAGAIN; return -1; } curr_break = ds_brk.start; if (ds_brk.start == 0) return -1; } return 0; } int brk(void * addr) { intptr_t alloc_size; if (getbrk()) return -1; if ((ds_brk.start > addr) || (addr > ds_brk.stop)) { errno = ENOMEM; return -1; } alloc_size = ((intptr_t)addr - (intptr_t)curr_break); if (alloc_size > 0) memset(curr_break, 0, (size_t)alloc_size); curr_break = addr; return 0; } void * sbrk(intptr_t incr) { void * old_break; void * new_break; if (getbrk()) return (void *)-1; old_break = curr_break; new_break = (void *)((char *)curr_break + incr); if ((ds_brk.start > new_break) || (new_break > ds_brk.stop)) { errno = ENOMEM; return (void *)-1; } if (incr > 0) memset(old_break, 0, (size_t)incr); curr_break = new_break; return old_break; }
C
#include <msp430.h> #define STOP_WATCHDOG 0x5A80 // Stop the watchdog timer #define ACLK 0x0100 // Timer ACLK source #define UP 0x0010 // Timer UP mode #define ENABLE_PINS 0xFFFE // Required to use input and outputs #define SLOW 0x00C0 // Slow down ACLK by factor of 8 /** * main.c */ main() { WDTCTL = STOP_WATCHDOG; // stop watchdog timer PM5CTL0 = ENABLE_PINS; // Required to use inputs and outputs P1DIR = BIT0; // Set pin red LED as an output P1OUT = 0x00; // Make sure red LED is off to start TA0CCR0 = 40000; // 40K * 200us ~ 8 second to ISR TA0CTL = ACLK | UP | SLOW;// Set ACLK, UP mode TA0CCTL0 = CCIE; // Enable interrupt for Timer0 _BIS_SR(LPM0_bits | GIE); // Enter Low Power Mode 0 and activate interrupts while(1); } //************************************************************************ // Timer0 Interrupt Service Routine //************************************************************************ #pragma vector=TIMER0_A0_VECTOR __interrupt void Timer0_ISR(void) { if(TA0CCR0 == 40000) // If LED was off for 1 second { TA0CCR0 = 125; // Then turn LED on for short time P1OUT = BIT0; } else // else LED was on for a short time { TA0CCR0 = 40000; // Then turn LED off for long time P1OUT = 0x00; } }
C
#include <stdio.h> #include <stdlib.h> int verifica_input(int valore) { if (valore > 0) { return valore; } else { printf("%d is invalid\n", valore); exit(0); } } int calcola_somma(int n1, int n2) { return n1 + n2; } int main(int argc, char *argv[]) { int a, b, somma; a = verifica_input(atoi(argv[1])); b = verifica_input(atoi(argv[2])); somma = calcola_somma(a, b); printf("la somma è: %d\n", somma); return 0; }
C
#include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <string.h> #include <sys/socket.h> #include <netdb.h> #include <string.h> #include "server.h" int clientContinue = 1; char * commandFind(char* inputString) { char * exitCommand = "@exit"; if(strncmp(exitCommand,inputString,1) != 0) return 0; if(strstr(inputString, exitCommand) != NULL) return EXIT; return 0; } int connect_to_server( const char * server, const char * port ) { int sd; struct addrinfo addrinfo; struct addrinfo * result; char message[256]; addrinfo.ai_flags = 0; addrinfo.ai_family = AF_INET; // IPv4 only addrinfo.ai_socktype = SOCK_STREAM; // Want TCP/IP addrinfo.ai_protocol = 0; // Any protocol addrinfo.ai_addrlen = 0; addrinfo.ai_addr = NULL; addrinfo.ai_canonname = NULL; addrinfo.ai_next = NULL; if ( getaddrinfo( server, port, &addrinfo, &result ) != 0 ) { fprintf( stderr, "\x1b[1;31mgetaddrinfo( %s ) failed. File %s line %d.\x1b[0m\n", server, __FILE__, __LINE__ ); return -1; } else if ( errno = 0, (sd = socket( result->ai_family, result->ai_socktype, result->ai_protocol )) == -1 ) { freeaddrinfo( result ); return -1; } else { do { if ( errno = 0, connect( sd, result->ai_addr, result->ai_addrlen ) == -1 ) { sleep( 1 ); write( 1, message, sprintf( message, "\x1b[2;33mConnecting to server %s ...\x1b[0m\n", server ) ); } else { freeaddrinfo( result ); return sd; // connect() succeeded } } while ( errno == ECONNREFUSED ); freeaddrinfo( result ); return -1; } } int read_chat_thread(void *arg) { char buffer[512]; int sd; sd = *(int *)arg; printf("Now Reading...\n"); while(clientContinue) { if(read( sd, buffer, sizeof(buffer)) == 0 ) // Got message from server / other clients { fprintf( stderr, "\x1b[1;31mServer Disconnect, press enter to exit\x1b[0m\n"); clientContinue = 0; } printf("%s\n",buffer); // print said message memset(buffer,0,sizeof(buffer)); // clear buffer for next string } close(sd); return 0; } char * checkUsername(char* user,char* usernameCheckStatus) { if(strcmp(usernameCheckStatus,FAILURE) == 0) // USERNAME EXISTS { printf("Validation failed, diconnecting...\n\n"); return FAILURE; } else if(strcmp(usernameCheckStatus,NOSPACE) == 0) // CHATROOM FULL { printf("Chatroom is full, disconnecting...\n\n"); return NOSPACE; } else return SUCCESS; } int main( int argc, char ** argv) { int sd; char message[256]; char string[512]; char buffer[512]; char bufferB[512]; char prompt[] = "Enter a string>>"; char output[512]; int len; int count; char c; pthread_t tid; int * sdptr; // Socket Desc. Pointer char usernameInput[512]; char usernameCheckStatus[512]; /* Getting Username */ printf("\n*=============================*\n Chatroom %s\n*=============================*\n",argv[1]); printf("Please enter a username that is less than 100 characters and is not 0 either\n"); printf("Enter username:"); if(fgets(usernameInput,102,stdin) != NULL) // Note the 102. username has max 100, server will see if over 100 { /* cleanup the \n at the end of array from fgets() */ char *pos; if ((pos = strchr(usernameInput, '\n')) != NULL) { *pos = '\0'; } else { while ((c = getchar()) != EOF && c != '\n'); } } /* Getting Username */ if ( argc < 2 ) { fprintf( stderr, "\x1b[1;31mNo host name specified. File %s line %d.\x1b[0m\n", __FILE__, __LINE__ ); exit( 1 ); } else if ( (sd = connect_to_server( argv[1], "3001" )) == -1 ) { write( 1, message, sprintf( message, "\x1b[1;31mCould not connect to server %s errno %s\x1b[0m\n", argv[1], strerror( errno ) ) ); return 1; } else { printf("Username:%s\n",usernameInput); printf("Connection Sucessful, validating username...\n"); /* Sending Username + Validation */ if(write( sd, usernameInput, strlen( usernameInput )+1) == -1) return 0; // Write To server read(sd,usernameCheckStatus,sizeof(usernameCheckStatus)); // Get validation from server if(checkUsername(usernameInput,usernameCheckStatus) != SUCCESS) // Runs through external function { close(sd); return 0; } else { printf("Username created, connecting...\n"); printf("\n=================== Welcome %s ===================\n\n",usernameInput); } /* Sending Username + Validation */ /* The Chatroom (Reading) */ sdptr = (int *)malloc( sizeof(int) ); *sdptr = sd; if ( pthread_create( &tid, 0, read_chat_thread, sdptr ) != 0 ) { printf( "pthread_create() failed in file %s line %d\n", __FILE__, __LINE__ ); return 0; } /* The Chatroom (Reading) */ /* The Chatroom (Writing) */ while (clientContinue) { if(fgets(string,60,stdin) != NULL) { /* cleanup the \n at the end of array from fgets() */ char *pos; if ((pos = strchr(string, '\n')) != NULL) { *pos = '\0'; } else { while ((c = getchar()) != EOF && c != '\n'); } } if(commandFind(string) == EXIT) clientContinue = 0; else { write( sd, string, strlen( string ) + 1 ); // Send message to server } } /* The Chatroom (Writing) */ close( sd ); return 0; } }
C
#ifndef _CLIENT_H_ #define _CLIENT_H_ #include "structs.h" /* Holds all the information relative to a client. */ typedef struct{ pid_t pid; //the calling process pid request_t * request; //pointer to the request made by this client answer_t * answer; //pointer to the answer received by this client int fdRequest; //file descriptor of the fifo where the request is sent int fdAnswer; //file descriptor of the fifo through which the answer will be sent int fd_log; //file descriptor of the file where the main log is kept int fd_book; //file descriptor of the file where the log relative to the seats number is kept char * answer_fifo_name; //the name given to the answer fifo } client_t; /* Creates a new client @return pointer to the new client */ client_t * new_client(); /* Deletes/Frees a client @param client - the client to be deleted */ void free_client(client_t *client); /* Creates the fifo through where the answer will be received @param cluent - the current client */ void createAnswerFifo(client_t *client); /* Opens the request fifo, where the request will be sent. @param client - the current client */ void openRequestFifo(client_t *client); /* Opens the created answer fifo @param client - the current client */ void openAnswerFifo(client_t *client); /* Writes the client log the the correspondent file. @param client */ void writeLog(client_t *client); /* When the request was approved an thus the answer valid, writes a message portraying that in the log file @param client @param pid_msg - a string already containing the pid of the calling process */ void writeValidMessage(client_t *client, char *pid_msg); /* When the request was not approved, writes a message portraying that in the log file @param client @param pid_msg - a string already containing the pid of the calling process */ void writeInvalidMessage(client_t *client, char *pid_msg); /* When the answer does not arrive before the specified timeout, writes a special message to the logfile @param clinet */ void writeTimeOutMessage(client_t *client); /* Converts a string to integer array. Useful for parsing information from the command line arguments. @param pref_list - the string to be converted @param pref_seat_list - the array being created @return the number of elements in the array */ int string_to_array(char *pref_list, int **pref_seat_list); /* Creats a new request with the information passed by the arguments @param client - the client that made the request @param time_out - available waiting time @param num_wanted_seats - the number of seats wanted @param num_pref_seats - the number of preferres seats @param pref_seat_list - an array containing all the preffered seats */ void createRequest(client_t *client, int num_wanted_seats, int num_pref_seats, int *pref_seat_list); /* Sends the request through the request fifo. @param client - the client that made the request */ void sendRequest(client_t *client); /* Waits for the answer to be sent by the server and reads it. @param client - the client waiting for the answer */ void readAnswer(client_t *client); /* Displays the given answer in stdout. Only used for debug purposes. @param client - the clien that made the request */ void displayAnswer(answer_t *answer); #endif
C
#include "electricalcalc.h" void kwtoamps1p(float *realpower, float *powerfactor, int *rmsvoltage) { printf("Enter real power (KW): "); scanf("%f", realpower); printf("Enter powerfactor: "); scanf("%f", powerfactor); printf("Enter RMS voltage: "); scanf("%d", rmsvoltage); } void kwtoamps3p(float *realpower, float *powerfactor, int *llrmsvoltage) { printf("Enter real power (KW): "); scanf("%f", realpower); printf("Enter powerfactor: "); scanf("%f", powerfactor); printf("Enter line-line rms voltage: "); scanf("%d", llrmsvoltage); } float kwtoamps1pconversion(float *realpower, float *powerfactor, int *rmsvoltage) { if (realpower == NULL || powerfactor == NULL || rmsvoltage == NULL) return NULL_ERROR; return (1000 * (*realpower)) / ((*powerfactor) * (*rmsvoltage)); } float kwtoamps3pconversion(float *realpower, float *powerfactor, int *llrmsvoltage) { if (realpower == NULL || powerfactor == NULL || llrmsvoltage == NULL) return NULL_ERROR; return (1000 * (*realpower)) / ((sqrt(3)) * ((*powerfactor) * (*llrmsvoltage))); }
C
#include<stdio.h> #include<unistd.h> #include<stdlib.h> #include<fcntl.h> int main() { int pipefd[2]; char c = 'R'; unsigned int count = 0; if(pipe2(pipefd,O_NONBLOCK) == -1) { perror("pipe"); return (EXIT_FAILURE); } printf("readend = %d\n",pipefd[0]); printf("writeend = %d\n",pipefd[1]); while(write(pipefd[1],&c,1) != -1) { count++; } printf("buffer for pipe = %d\n",count); return (EXIT_SUCCESS); }
C
#include <stdio.h> #include <omp.h> #include <limits.h> int sum = INT_MIN; int main(void) { double start = omp_get_wtime(); #pragma omp parallel for num_threads(4) for(int i=0;i<(INT_MAX>>7);i++) { sum++; } sum+=1; printf("%lf \n", omp_get_wtime()-start); return 0; }
C
///ѧеĽ׳ˣһн׳˺Ľ /*#include<stdio.h> //׼룬ͷļ #include<stdlib.h> //׼ͷļ int fun(int); //һзֵĺ int main(void)//ҽһ { int n; //nںһ printf("׳˵\n"); //ӡʾ scanf_s("%d", &n); //һ printf("%d!=%d", n, fun(x)); //мĽĹеԶ庯 system("pause"); //system()ϵͳpause ͣ return 0; //˳ } int fun(int x) // { if (n == 0 || n == 1) //ifж䣬n01ʱִ { return 1; //ifжеֵΪ1Ϊ01Ľ׳˽Ϊ1 } else //ifжеִ { return n * fun(n - 1); //01õݹ׳˵Ľ } }*/
C
#include <stdio.h> #include <string.h> #include "mpi.h" int main( int argc, char *argv[]) { char message[20]; int myrank, size; MPI_Status status; MPI_Init( &argc, &argv ); MPI_Comm_rank( MPI_COMM_WORLD, &myrank ); MPI_Comm_size( MPI_COMM_WORLD, &size ); if (myrank == 0) /* code for process zero */ { strcpy(message,"Hello, there"); MPI_Send(message, strlen(message)+1, MPI_CHAR, 1, 99, MPI_COMM_WORLD); } else if (myrank == 1) /* code for process one */ { MPI_Recv(message, 20, MPI_CHAR, 0, 99, MPI_COMM_WORLD, &status); printf("Rank %d of %d received :%s\n", myrank, size, message); } MPI_Finalize(); return 0; }
C
#include "hash_tables.h" /** * hash_table_set - This function adds an element to the hash table * @ht: A pointer to the hash table * @key: The key to add to the hash table * @value: The corresponding value to add to the hash table * Return: 1 for success, 0 otherwise */ int hash_table_set(hash_table_t *ht, const char *key, const char *value) { hash_node_t *new_node; unsigned long int idx; if (ht == NULL || key == NULL || value == NULL) return (0); idx = key_index((const unsigned char *)key, ht->size); if (ht->array[idx] != NULL && strcmp(key, ht->array[idx]->key) == 0) { free(ht->array[idx]->value); ht->array[idx]->value = strdup(value); return (1); } new_node = malloc(sizeof(hash_node_t)); if (!new_node) return (0); new_node->key = strdup(key); new_node->value = strdup(value); new_node->next = ht->array[idx]; ht->array[idx] = new_node; return (1); }
C
/* * matrix.c * * Created on: 04/06/2018 * Author: ie714715 */ #include <stdlib.h> #include <stdio.h> int CrearMatriz(int **apuntador, int n, int m); int main(){ setvbuf(stderr, NULL, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0); int **m; //matriz[3][2]; int i,j; m = (int**)malloc(sizeof(int*)*3); for(i = 0; i<3; i++){ m[i] = (int*)malloc(sizeof(int)*2); } for(i = 0; i<3; i++){ for(j =0; j< 2; j++){ m[i][j] = i+1; } } printf("Direccin de m0: %p, m1: %p, m2: %p",m, m++, m+=2); //Direccin de los renglones //printf("Direccin de m[0][0]: %p", *m); for(i = 0; i<3; i++){ //printf("Direccin de m[%d]: %p",i, m[i]); for(j =0; j< 2; j++){ printf("m[%d][%d]: %d\t", i, j, m[i][j]); } printf("\n"); } //Acceder al contenido de la matriz a travs de un apuntador //la matriz acumula direcciones: m almacena los renglones y m* almacena la direccion de las columnas return 0; }
C
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // File name : vector_rce.c // Version : V0.1 // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #include "vector_table.h" #include "debug.h" void DummyHandler(void) { MSG("WARNING: Default dummy interrupt handler entered \n"); } void Misaligned_Access(void) { MSG("WARNING: Unexpected Misaligned Access exception taken \n"); } void Access_Error(void) { asm("bkpt"); MSG("WARNING: Unexpected Access Error exception taken \n"); } void Illegal_Instrn(void) { MSG("WARNING: Unexpected Illegal_Instrn exception taken \n"); } void Breakpoint_Exception(void) { MSG("WARNING: Unexpected Breakpoint exception taken \n"); } void Unrecoverable_Error(void) { MSG("WARNING: Unexpected Unrecoverable_Error exception taken \n"); } extern char _end_text[]; extern char _start_data[]; extern char _end_data[]; extern char _bss_start[]; extern char _bss_end[]; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // __main // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Description: // Copy data section to the right place if necessary. // Initializing bss section // // Input: // None. // // Output: // None. // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ void __main(void) { //need cp to mem char *dst = _start_data; char *src = _end_text; /* if the start of data (dst) is not equal to end of text (src) then copy it, else it's already in the right place */ if( _start_data != _end_text ) { memcpy( dst, src, (_end_data - _start_data)); } /* zero the bss */ if( _bss_end - _bss_start ) { memset( _bss_start, 0x00, ( _bss_end - _bss_start )); } }
C
#include "mapview.h" #include <stdlib.h> #include <stdio.h> int main(int argc, char *argv[]) { int start_sector; int sector_count; if (argc < 4) { printf("Usage: %s [dev] [src_lsn] [# of sectors]\n", argv[0]); return 1; } if (0 != init_mapview(argv[1], 4096)) { printf("Can not init mapview\n"); return 2; } start_sector = atoi(argv[2]); sector_count = atoi(argv[3]); get_map(start_sector, sector_count); return 0; }
C
#include "3-calc.h" /** * main - Performs operation corresponding to math oeprator * @argc: Number of args * @argv: Strings of args * Return: Result of proper operation, or exit if fail */ int main(int argc, char **argv) { int (*operator)(int, int); if (argc != 4) { printf("Error\n"); exit(98); } operator = get_op_func(argv[2]); if (operator == NULL) { printf("Error\n"); exit(99); } if (atoi(argv[3]) == 0 && ((!(strcmp(argv[2], "/"))) || (!(strcmp(argv[2], "%"))))) { printf("Error\n"); exit(100); } printf("%d\n", operator(atoi(argv[1]), atoi(argv[3]))); return (0); }
C
/******************************************************************************* * FILENAME : modules/visual.h * * DESCRIPTION : * Module that contain all of the visual functions. * * NOTES : * - * * */ /** * Exibe o titulo do sistema. * * @return não retorna valores * @author Vitor Santos */ void ShowBanner() { printf("* * * * * * * * * * * * * * * * * * *\n"); printf("* *\n"); printf("* Cifra de Vigenere *\n"); printf("* *\n"); printf("* * * * * * * * * * * * * * * * * * *\n\n"); } /** * Exibe as regras de utilização do sistema. * * @return não retorna valores * @author Vitor Santos */ void ShowRules() { printf("* Orientacoes de uso do programa:\n"); printf("* 1. Utilizar no maximo 128 caracteres, caracteres excedentes serao ignorados.\n"); printf("* 2. Apenas utilizar letras, sem espacamento.\n"); printf("* 3. Acentuacao e numeros tambem sao bloqueados.\n\n"); printf(" Faca bom uso do sistema!\n"); } /** * Exibe o menu para o usuário. * * @return retorna a opção escolhida pelo usuário. * @author Vitor Santos */ bool ShowMenu() { char optionChoosed; printf("* Selecione a opcao desejada.\n"); printf("* 1. Criptografar.\n"); printf("* 2. Descriptografar.\n"); printf("* 3. Sair do programa.\n"); fflush(stdin); fgets(&optionChoosed, 2, stdin); return MenuFunctions(optionChoosed); } /** * Executa a opção escolhida. * * @param optionChoosed Opção escolhida pelo usuário. * @return retorna verdadeiro caso seja uma escolha válida. * @author Vitor Santos */ bool MenuFunctions(char optionChoosed) { switch(optionChoosed) { case '1': { char *textToEncrypt = malloc(sizeof(char) + 128), *encryptKey = malloc(sizeof(char) + 128); GetTextToEncrypt(textToEncrypt); GetTextEncryptKey(encryptKey); printf("Palavra criptografada: %s\n", CryptWord(textToEncrypt, encryptKey)); free(textToEncrypt + 1); free(encryptKey + 1); break; } case '2': { char *encryptText = malloc(sizeof(char) + 128), *encryptKey = malloc(sizeof(char) + 128); GetEncryptText(encryptText); GetTextEncryptKey(encryptKey); printf("Palavra descriptografada: %s\n", DecryptWord(encryptText, encryptKey)); free(encryptText + 1); free(encryptKey + 1); break; } case '3': { QuitProgram(); return false; } default: { printf("Operacao invalida, retornando ao menu principal.\n"); break; } } return true; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "fonctions.h" int main() { char caractere = NULL; char* motSecret = "MARRON"; char *suiteMot = NULL; int i = 0; int nbreLettre = 5; int nbreCoupsRestants = 10; int issue = PERDANT; int longueurMot = strlen(motSecret); printf("Bienvenue dans le Pendu !\n\n"); while(nbreCoupsRestants > 0 || issue == PERDANT) { printf("Il vous reste %d coups a jouer\n", nbreCoupsRestants); printf("Quel est le mot secret \n"); printf("Proposez une lettre : "); caractere = lireCaractere(); devoileLettre(motSecret, caractere); /* printf("@ du premier caractère du mot : %x\n\n", motSecret); printf("Lettre %c\n", motSecret[0]); printf("@ du deuxième caractère du mot : %x\n\n", &motSecret[1]); printf("Lettre %c\n", motSecret[1]); printf("@ du 3ème caractère du mot : %x\n\n", &motSecret[2]); */ } return 0; }
C
#include <omp.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> // export OMP_NUM_THREADS=4 int function(int x) { static int n = 0; n = n + 1; printf("function: (%i) n=%d\n", x, n); fflush(stdout); return 2*x + n; } int function_synchronized(int x) { static int n = 0; #pragma omp atomic n = n + 1; printf("function: (%i) n=%d\n", x, n); fflush(stdout); return 2*x + n; } int main() { int value_private = 10; // The value will never change int counter = 0; int result = 0; // Execute 3*4=12 loops (3 loops per thread). // Access to the function "function" is not synchronized. printf("==========================================================\n"); #pragma omp parallel default(none) private(value_private) shared(counter, result) for (int i=0; i<3; i++) { result = function(i); printf("go [%d] counter:%d result:%d, i:%d\n", omp_get_thread_num(), counter, result, i); counter += 1; } // Example of output: // // function: (0) n=2 // go [0] counter:0 result:3, i:0 // function: (1) n=4 // go [0] counter:1 result:6, i:1 // function: (2) n=5 // go [0] counter:2 result:9, i:2 // function: (0) n=3 // go [2] counter:3 result:5, i:0 // function: (1) n=6 // go [2] counter:4 result:8, i:1 // function: (2) n=7 // go [2] counter:5 result:11, i:2 // function: (0) n=1 // go [3] counter:6 result:7, i:0 // function: (1) n=8 // go [3] counter:7 result:10, i:1 // function: (2) n=9 // go [3] counter:8 result:13, i:2 // function: (0) n=1 // go [1] counter:9 result:9, i:0 // function: (1) n=10 // go [1] counter:10 result:12, i:1 // function: (2) n=11 // go [1] counter:11 result:15, i:2 // counter=12 (expected 12) // // As we can see, 2 threads may execute the function simultaneously: // // go [2] counter:5 result:11, i:2 // function: (0) n=1 // go [3] counter:8 result:13, i:2 // function: (0) n=1 // // Threads 2 and 3 accessed the static variable "n" simultaneously. printf("counter=%d (expected 12)\n", counter); // Execute 3*4=12 loops (3 loops per thread). // Access to the function "function" is synchronized. printf("==========================================================\n"); #pragma omp parallel default(none) private(value_private) shared(counter, result) for (int i=0; i<3; i++) { // Synchronized the access to the function "function". #pragma omp critical result = function(i); printf("go [%d] counter:%d result:%d, i:%d\n", omp_get_thread_num(), counter, result, i); counter += 1; } // Execute 3*4=12 loops (3 loops per thread). // Access to the function "function_synchronized" is not synchronized. // However, "function_synchronized" contains critical sections. printf("==========================================================\n"); #pragma omp parallel default(none) private(value_private) shared(counter, result) for (int i=0; i<3; i++) { // Synchronized the access to the function "function". result = function_synchronized(i); printf("go [%d] counter:%d result:%d, i:%d\n", omp_get_thread_num(), counter, result, i); counter += 1; } printf("==========================================================\n"); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* libft.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jnoreen <jnoreen@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/24 05:52:37 by jnoreen #+# #+# */ /* Updated: 2020/11/24 05:54:21 by jnoreen ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef LIBFT_H # define LIBFT_H # include <stdlib.h> # include <unistd.h> int ft_atoi(const char *str); void *ft_bzero(void *dst, size_t n); void *ft_calloc(size_t num, size_t size); int ft_isalnum(int ch); int ft_isalpha(int ch); int ft_isascii(int ch); int ft_isdigit(int ch); int ft_isprint(int ch); void *ft_memccpy (void *destination, const void *source, int c, size_t n); void *ft_memchr (const void *arr, int c, size_t n); void *ft_memcpy (void *destination, const void *source, size_t n); void *ft_memmove(void *dest, const void *src, size_t n); void *ft_memset (void *destination, int c, size_t n); char *ft_strchr (const char *str, int ch); size_t ft_strlcat(char *dst, const char *src, size_t size); size_t ft_strlcpy (char *dst, const char *src, size_t size); size_t ft_strlen(const char *str); int ft_strncmp(const char *str1, const char *str2, size_t n); char *ft_strrchr(const char *str, int ch); char *ft_strstr(const char *strb, const char *stra); int ft_tolower(int ch); int ft_toupper(int ch); int ft_memcmp(const void *arr1, const void *arr2, size_t n); char *ft_strnstr(const char *big, const char *little, size_t len); char *ft_strdup(const char *str); size_t ft_strlcpy(char *dst, const char *src, size_t size); char *ft_substr(char const *s, unsigned int start, size_t len); char *ft_strjoin(char const *s1, char const *s2); void ft_putchar_fd(char c, int fd); void ft_putstr_fd(char *s, int fd); void ft_putendl_fd(char *s, int fd); void ft_putnbr_fd(int n, int fd); char *ft_strmapi(char const *s, char (*f)(unsigned int, char)); char *ft_itoa(int n); char *ft_strtrim(char const *s1, char const *set); char **ft_split(char const *s, char c); #endif
C
#include <stdio.h> #define SQ_1(y) (y)*(y) #define SQ_2(y) y*y int main() { int a = 0,num_1 = 0,num_2 = 0; scanf("%d",&a); num_1 = SQ_1(a+1); //num_1 = (a+1)*(a+1); num_2 = SQ_2(a+1); //num_2 = a+1*a+1; printf("num_1 = %d\n",num_1); printf("num_2 = %d\n",num_2); return 0; }
C
#include <stdio.h> void quick_sort(int[],int,int); int partition(int[],int,int); int main() { int a[30],n,i; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } quick_sort(a,0,n-1); printf("\nArray after sorting:"); for(i=0;i<n;i++) { printf("%d ",a[i]); } printf("\nMax number:%d\n",a[n-1]); printf("Min number:%d\n",a[0]); return 0; } void quick_sort(int a[],int s,int e) { int j; if(s<e) { j=partition(a,s,e); quick_sort(a,s,j-1); quick_sort(a,j+1,e); } } int partition(int a[],int s,int e) { int p,i,j,temp; p=a[s]; i=s; j=e; while(i<j) { while(a[i]<=p) { i++; } while(a[j]>p) { j--; } if(i<j) { temp=a[i]; a[i]=a[j]; a[j]=temp; } } a[s]=a[j]; a[j]=p; return j; }
C
// Harvard CS50 // vinegere.c #include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int main(int argc, string argv[]) { if(argc !=2) { printf("Invalid entry, try again\n"); // print error for more than 2 entries return 1; } else // continue if tou have 2 entries { string k = argv[1]; // access entry with string k int a = 0; do { if(isalpha(k[a])) a++; else { printf("Only alphabetical entries are allowed, please try again.\n"); return 1; } }while(a < strlen(k)); string P = GetString(); // read plaintext //string k = argv[1]; // store string type entry to k for easier processing int i = 0; for(int j = 0, n = strlen(P); j < n; j++) // use for loop to encript and print Cipertext { int l = (tolower(k[i]) - 97) % 26; // convert key to lower and alphabetical if(isalpha(P[j])) { int Ci; // declare an integer type variable if (isupper(P[j])) // condition to apply on Upper Case Characters stored in the array { // Reduce integer value of character at P[i] by 65 or 'A' according to ASCII table / convert ASCII to Alphabetical Ci = (P[j] + l - 65) % 26; printf("%c", (Ci + 65)); // print Ciphertext while converting back to ASCII values } else if (islower(P[j])) { Ci = (P[j] + l - 97) % 26; // convert ASCII to Alphabetical by reducing by 97 or 'a' for lower case characters printf("%c", (Ci + 97)); // print Ciphertext while converting back to ASCII values } if(i == (strlen(k) - 1)) // check if you need to restart key position { i = 0; // reset key position } else { i++; // increment i by 1 } } else { printf("%c", P[j]); // print anything else that is not alphabetic } } printf("\n"); } return 0; }
C
#include <vector> #include "TF1.h" #include "TFile.h" #include "TGraph.h" #include "TH1D.h" #include "TString.h" #include "Math/Interpolator.h" class MyFunctionObject { public: std::vector<double> X; std::vector<double> Y; TGraph* g; ROOT::Math::Interpolator* eng; // use constructor to customize your function object MyFunctionObject() { } MyFunctionObject(const TGraph* theGraph) { g = (TGraph*)theGraph->Clone("internalGraph"); printf("Graph cloned\n"); int numPoints = g->GetN(); double thisX; double thisY; for(int i=0; i!=numPoints; ++i) { g->GetPoint(i,thisX,thisY); X.push_back(thisX); Y.push_back(thisY); } printf("Vectors set\n"); eng = new ROOT::Math::Interpolator(X,Y); } double operator() (double *x, double *p) { return eng->Eval(x[0]); } private: }; double integrateHistogram(const TH1* h, double fraction) { int nbinsx = h->GetNbinsX(); double histoIntegral = h->Integral(); TGraph* g = new TGraph(nbinsx-1); for(int i=1; i!=nbinsx; ++i) { double inte = h->Integral(i,nbinsx); double frac = inte/histoIntegral; double xpoint = h->GetBinCenter(i); g->SetPoint(i-1,xpoint,frac); } MyFunctionObject* myObj = new MyFunctionObject(g); double minPoint = g->GetX()[0]; double maxPoint = g->GetX()[nbinsx-2]; printf("%g\t%g\t(min and max)\n",minPoint,maxPoint); TF1* myFunc = new TF1("funca",myObj,1.05*minPoint,0.95*maxPoint,0,"MyFunctionObject"); double value = myFunc->GetX(fraction); double xcheck = myFunc->Eval(value); //myFunc->Draw(); printf("Cross check: %g\n",xcheck); return value; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> main() { float id,h,ph,pf; printf("digite um 1 para mulher ou 2 para homem\n"); scanf("%f",&id); printf("digite a altura\n"); scanf("%f",&h); if(id==2) { ph=(72.7*h)-58; printf("peso masculino:%.2f \n",ph); } else { pf=(62.1*h)-44.7; printf("peso feminino:%.2f\n",pf); } system("pause"); }