language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <includes.h> #include "data.h" #include "datadesc.h" #include "fram.h" #include "time.h" #include <stdlib.h> #include <stddef.h> // int GetData(const TDataDescStruct* desc, void* buf, CPU_INT32U index, CPU_INT08U flags) { TVariant32 Val; CPU_INT32U ofst = 0; // . if (desc->IsArray) { if (flags == DATA_FLAG_DIRECT_INDEX) { ofst = (index >= desc->ArraySize) ? desc->ArrayOffset*(desc->ArraySize-1) : desc->ArrayOffset*index; } else { GetData((TDataDescStruct*)desc->ArrayIndex, &ofst, 0, DATA_FLAG_SYSTEM_INDEX); ofst *= desc->ArrayOffset; } } // if (desc->Location == DATA_LOC_RAM) { #if OS_CRITICAL_METHOD == 3 OS_CPU_SR cpu_sr = 0; #endif OS_ENTER_CRITICAL(); memcpy(&Val, (CPU_INT08U*)desc->Data+ofst, sizeof(CPU_INT32U)); OS_EXIT_CRITICAL(); } else if (desc->Location == DATA_LOC_FRAM) { ReadArrayFram((CPU_INT32U)desc->Data+ofst, sizeof(CPU_INT32U), (CPU_INT08U*)&Val); } else return DATA_ERR; // memcpy(buf, &Val, sizeof(CPU_INT32U)); return DATA_OK; } // int SetData(const TDataDescStruct* desc, void* buf, CPU_INT32U index, CPU_INT08U flags) { TVariant32 Val; CPU_INT32U ofst = 0; if (desc->Desc == DATA_DESC_VIEW) return DATA_ERR; // if (desc->RangeValue) { TVariant32 ValMin, ValMax; TRangeValueULONG* RVal = desc->RangeValue; memcpy(&ValMin, &RVal->Min, sizeof(CPU_INT32U)); memcpy(&ValMax, &RVal->Max, sizeof(CPU_INT32U)); memcpy(&Val, buf, sizeof(CPU_INT32U)); if (desc->Type == DATA_TYPE_ULONG) { if ((Val.Val32U > ValMax.Val32U) || (Val.Val32U < ValMin.Val32U)) return DATA_ERR; } else if (desc->Type == DATA_TYPE_SLONG) { if ((Val.Val32S > ValMax.Val32S) || (Val.Val32S < ValMin.Val32S)) return DATA_ERR; } else if (desc->Type == DATA_TYPE_FLOAT) { if ((Val.ValFloat > ValMax.ValFloat) || (Val.ValFloat < ValMin.ValFloat)) return DATA_ERR; } else if (desc->Type == DATA_TYPE_TIME) { } else if (desc->Type == DATA_TYPE_IP_ADDR) { } else if (desc->Type == DATA_TYPE_HOUR_MIN) { if (Val.Val32U >= 24*60) return DATA_ERR; } else return DATA_ERR; } else { memcpy(&Val, buf, sizeof(CPU_INT32U)); } // . if (desc->IsArray) { if (flags == DATA_FLAG_DIRECT_INDEX) { ofst = (index >= desc->ArraySize) ? desc->ArrayOffset*(desc->ArraySize-1) : desc->ArrayOffset*index; } else { GetData((TDataDescStruct*)desc->ArrayIndex, &ofst, 0, DATA_FLAG_SYSTEM_INDEX); ofst *= desc->ArrayOffset; } } // if (desc->Location == DATA_LOC_RAM) { #if OS_CRITICAL_METHOD == 3 OS_CPU_SR cpu_sr = 0; #endif OS_ENTER_CRITICAL(); memcpy((CPU_INT08U*)desc->Data+ofst, &Val, sizeof(CPU_INT32U)); OS_EXIT_CRITICAL(); } else if (desc->Location == DATA_LOC_FRAM) { WriteArrayFram((CPU_INT32U)desc->Data+ofst, sizeof(CPU_INT32U), (CPU_INT08U*)&Val); } else return DATA_ERR; // if (desc->OnchangeFunc) desc->OnchangeFunc(); // return DATA_OK; } // int GetDataMax(const TDataDescStruct* desc, void* buf) { if (desc->RangeValue) { TRangeValueULONG* RVal = desc->RangeValue; memcpy(buf, &RVal->Max, sizeof(CPU_INT32U)); } else { *(CPU_INT32U*)&buf = 0; } return DATA_OK; } // int GetDataMin(const TDataDescStruct* desc, void* buf) { if (desc->RangeValue) { TRangeValueULONG* RVal = desc->RangeValue; memcpy(buf, &RVal->Min, sizeof(CPU_INT32U)); } else { *(CPU_INT32U*)&buf = 0; } return DATA_OK; } // int GetDataStr(const TDataDescStruct* desc, CPU_INT08U* buf, CPU_INT32U index, CPU_INT08U flags) { TVariant32 Val; GetData(desc, &Val, index, flags); if (desc->Type == DATA_TYPE_ULONG) { if (desc->IsIndex) { // if (desc->RangeValue) { TRangeValueULONG* range = (TRangeValueULONG*)desc->RangeValue; if ((Val.Val32U >= range->Min) && (Val.Val32U <= range->Max)) strcpy((char*)buf, (char const*)desc->Items[Val.Val32U]); else {strcpy((char*)buf, ""); return DATA_ERR;} } else if (desc->Desc == DATA_DESC_VIEW) { strcpy((char*)buf, (char const*)desc->Items[Val.Val32U]); } else { strcpy((char*)buf, ""); } } else { sprintf((char*)buf, "%d", Val.Val32U); } } else if (desc->Type == DATA_TYPE_SLONG) { sprintf((char*)buf, "%d", Val.Val32S); } else if (desc->Type == DATA_TYPE_FLOAT) { sprintf((char*)buf, "%0.3f", Val.ValFloat); } else if (desc->Type == DATA_TYPE_TIME) { PrintTimeString((char*)buf, Val.Val32U); } else if (desc->Type == DATA_TYPE_IP_ADDR) { NET_ERR err; NetASCII_IP_to_Str(Val.Val32U, (CPU_CHAR*)buf, DEF_NO, &err); } else if (desc->Type == DATA_TYPE_TIME_COUNT) { PrintSecToBigHourMinSec((char*)buf, Val.Val32U); } else if (desc->Type == DATA_TYPE_HOUR_MIN) { int min_ = Val.Val32U % 60; int hour_ = Val.Val32U / 60; sprintf((char*)buf, "%02d:%02d", hour_, min_); } else return DATA_ERR; return DATA_OK; } // int GetDataFullStr(const TDataDescStruct* desc, CPU_INT08U* buf, CPU_INT32U index, CPU_INT08U flags) { GetDataNameStr(desc, buf); if (desc->Name) { if (desc->IsIndex) strcat((char*)&buf[strlen((char*)buf)], " "); else strcat((char*)&buf[strlen((char*)buf)], "="); } GetDataStr(desc, &buf[strlen((char*)buf)], index, flags); return DATA_OK; } // int GetDataNameStr(const TDataDescStruct* desc, CPU_INT08U* buf) { if (desc->Name) strcpy((char*)buf, (char const*)desc->Name); else strcpy((char*)buf, ""); return DATA_OK; } // int GetDataItem(const TDataDescStruct* desc, CPU_INT08U* buf, CPU_INT32U itemindex) { if (!desc->IsIndex) {buf[0]=0;return DATA_ERR;} if (desc->Type != DATA_TYPE_ULONG) {buf[0]=0;return DATA_ERR;} // if (desc->RangeValue) { TRangeValueULONG* range = (TRangeValueULONG*)desc->RangeValue; if ((itemindex >= range->Min) && (itemindex <= range->Max)) strcpy((char*)buf, (char const*)desc->Items[itemindex]); else return DATA_ERR; } else { strcpy((char*)buf, ""); } return DATA_OK; } // int InitDataByDefault(const TDataDescStruct* desc, CPU_INT32U index) { SetData(desc, (void*)&desc->DefaultValue, index, DATA_FLAG_DIRECT_INDEX); return DATA_OK; } // int InitData(const TDataDescStruct* desc) { return DATA_OK; } // int CheckDataRange(const TDataDescStruct* desc) { TVariant32 ValMin, ValMax, Val; TRangeValueULONG* RVal = desc->RangeValue; if (!desc->RangeValue) return DATA_OK; memcpy(&ValMin, &RVal->Min, sizeof(CPU_INT32U)); memcpy(&ValMax, &RVal->Max, sizeof(CPU_INT32U)); if (desc->IsArray) { for (int i = 0; i < desc->ArraySize; i++) { GetData(desc, &Val, i, DATA_FLAG_DIRECT_INDEX); if (desc->Type == DATA_TYPE_ULONG) { if ((Val.Val32U > ValMax.Val32U) || (Val.Val32U < ValMin.Val32U)) InitDataByDefault(desc, i); } else if (desc->Type == DATA_TYPE_SLONG) { if ((Val.Val32S > ValMax.Val32S) || (Val.Val32S < ValMin.Val32S)) InitDataByDefault(desc, i); } else if (desc->Type == DATA_TYPE_FLOAT) { if ((Val.ValFloat > ValMax.ValFloat) || (Val.ValFloat < ValMin.ValFloat)) InitDataByDefault(desc, i); } else return DATA_ERR; } } else { GetData(desc, &Val, 0, DATA_FLAG_DIRECT_INDEX); if (desc->Type == DATA_TYPE_ULONG) { if ((Val.Val32U > ValMax.Val32U) || (Val.Val32U < ValMin.Val32U)) InitDataByDefault(desc, 0); } else if (desc->Type == DATA_TYPE_SLONG) { if ((Val.Val32S > ValMax.Val32S) || (Val.Val32S < ValMin.Val32S)) InitDataByDefault(desc, 0); } else if (desc->Type == DATA_TYPE_FLOAT) { if ((Val.ValFloat > ValMax.ValFloat) || (Val.ValFloat < ValMin.ValFloat)) InitDataByDefault(desc, 0); } else return DATA_ERR; } return DATA_OK; } // , int InitDescByDefault(const TDataDescStruct* desc) { if (desc->IsArray) { for (int i = 0; i < desc->ArraySize; i++) InitDataByDefault(desc, i); } else { InitDataByDefault(desc, 0); } return DATA_OK; } // int CheckAllData(void) { int i = 0; while (AllDataArray[i].ptr != NULL) { CheckDataRange(AllDataArray[i].ptr); i++; } return DATA_OK; } static char justname[128]; /// void FindDescByName(char* name, TDataDescStruct const** desc, CPU_INT32U *index) { char *name_ptr = name; *index = 0; if (sscanf(name, "%s %d", justname, index) == 2) { name_ptr = justname; } *desc = NULL; int i = 0; while (AllDataArray[i].ptr != NULL) { if (strcmp(AllDataArray[i].name, name_ptr) == 0) { if ((AllDataArray[i].ptr->IsArray) && (*index >= AllDataArray[i].ptr->ArraySize)) { *desc = NULL; } else { *desc = AllDataArray[i].ptr; } break; } i++; } }
C
/* * Maria Deslis * Fall 2014 - Hellman * Linx Programming * Sample 1 */ #include <stdio.h> #include <math.h> #include <cstdlib> void diamondT(int width); void diamondB(int width); void printSpace(int num); int main() { int n; char symbol; printf("%s","Enter a width: "); scanf("%i", &n); // printf("%s","Enter a char: "); // scanf("%s", &symbol); diamondT(n); diamondB(n); return 0; } void diamondT(int width) { int space = width-1; for (int row = 1; row <= width; row++) { printf("%s","|"); printSpace(space); for (int col = 1; col <= (2*row-1); col++) { putchar('*'); } printSpace(space); printf("%s","|\n"); space--; } } void diamondB(int width) { int space = 1; for (int row = 1; row <= width-1; row++) { printf("%s","|"); printSpace(space); for (int col = 0; col < (2*(width-row)-1); col++) { putchar('*'); } printSpace(space); printf("%s","|\n"); space++; } } void printSpace(int num) { if (num > 0) { for (int i = 0; i < num; i++) { putchar(' '); } } }
C
/* * main.c * * Created on: May 11, 2013 * Author: Iulian Gheorghiu (morgoth.creator@gmail.com) */ #include "board_init.h" int main(void) { board_init(); register int CntDelay; while(1) { CntDelay = 8000000; do { if(!CntDelay) break; CntDelay--; } while(1); gpio_out(LED1, 1); gpio_out(LED2, 1); gpio_out(LED3, 1); gpio_out(LED4, 1); UARTprintf(DebugCom, "Str\n"); CntDelay = 8000000; do { if(!CntDelay) break; CntDelay--; } while(1); gpio_out(LED1, 0); gpio_out(LED2, 0); gpio_out(LED3, 0); gpio_out(LED4, 0); UARTprintf(DebugCom, "Rts\n"); } return 0; }
C
#include<stdio.h> int main() { int grade; printf(""); scanf("%d", &grade); grade /= 10; switch (grade) { case 10: case 9:printf("\n");break; case 8:printf("\n");break; case 7:printf("һ\n");break; case 6:printf("\n");break; case 5: case 4: case 3: case 2: case 1:printf("\n");break; default:printf("\n");break; } return 0; }
C
#include "lexer.h" void tokeniseSourcecode( char* filename, tokenStream *s) { FILE* code = fopen(filename,"r"); tokenStream *head = s; tokenStream* curr = head; char* BUF = (char*)calloc(200,1); int linenum = 0; while(!feof(code)){ linenum++; fgets(BUF,200,code); if(strlen(BUF)==0) continue; char *token; token = strtok(BUF, " \t\r\n"); // printf("%d ",linenum); while( token != NULL) { curr->nextToken = calloc(1,sizeof(tokenStream)); curr = curr->nextToken; curr->nextToken = NULL; curr->line_num = linenum; strcpy(curr->lexeme,token); curr->token_name = returnTokenstreamTerminalVal(token); // printf( "%s %d \n",curr->lexeme,curr->token_name); token = strtok(NULL, " \t\r\n"); } // printf("\n"); } curr = head->nextToken; while(curr != NULL) { // printf(" %s %d\n",curr->lexeme,curr->line_num); curr = curr->nextToken; } fclose(code); } terminal returnTokenstreamTerminalVal(char* lex) { if(!strcmp(lex,"program")) return program; else if(!strcmp(lex,"(")) return rb_op; else if(!strcmp(lex,")")) return rb_cl; else if(!strcmp(lex,"{")) return cb_op; else if(!strcmp(lex,"}")) return cb_cl; else if(!strcmp(lex,"declare")) return declare; else if(!strcmp(lex,":")) return col; else if(!strcmp(lex,"list")) return list; else if(!strcmp(lex,"of")) return of; else if(!strcmp(lex,"variables")) return variables; else if(!strcmp(lex,";")) return semicol; else if(!strcmp(lex,"integer")) return integer; else if(!strcmp(lex,"boolean")) return boolean; else if(!strcmp(lex,"real")) return real; else if(!strcmp(lex,"array")) return array; else if(!strcmp(lex,"jagged")) return jagged; else if(!strcmp(lex,"..")) return ddot; else if(!strcmp(lex,"R1")) return r1; else if(!strcmp(lex,"[")) return sq_op; else if(!strcmp(lex,"]")) return sq_cl; else if(!strcmp(lex,"size")) return size; else if(!strcmp(lex,"values")) return values; else if(!strcmp(lex,"+")) return add_op; else if(!strcmp(lex,"-")) return sub_op; else if(!strcmp(lex,"*")) return mul_op; else if(!strcmp(lex,"/")) return div_op; else if(!strcmp(lex,"=")) return eq_op; else if(!strcmp(lex,"|||")) return or_op; else if(!strcmp(lex,"&&&")) return and_op; else if(isalpha(lex[0]) || lex[0] == '_') return id; return num; } non_terminal returnNonTerminalVal(char* lex) { if(!strcmp(lex,"PROGRAM")) return PROGRAM; else if(!strcmp(lex,"STATEMENTS")) return STATEMENTS; else if(!strcmp(lex,"STATEMENT")) return STATEMENT; else if(!strcmp(lex,"DECLARE_STATEMENT")) return DECLARE_STATEMENT; else if(!strcmp(lex,"ASSIGN_STATEMENT")) return ASSIGN_STATEMENT; else if(!strcmp(lex,"SINGLE_DECLARE")) return SINGLE_DECLARE; else if(!strcmp(lex,"MULTI_DECLARE")) return MULTI_DECLARE; else if(!strcmp(lex,"TYPE")) return TYPE; else if(!strcmp(lex,"VAR_LIST")) return VAR_LIST; else if(!strcmp(lex,"PRIM_TYPE")) return PRIM_TYPE; else if(!strcmp(lex,"ARRAY")) return ARRAY; else if(!strcmp(lex,"RECTANGULAR")) return RECTANGULAR; else if(!strcmp(lex,"ASSIGN_STATEMENT")) return ASSIGN_STATEMENT; else if(!strcmp(lex,"JAGGED")) return JAGGED; else if(!strcmp(lex,"JAGGED_INIT_DASH")) return JAGGED_INIT_DASH; else if(!strcmp(lex,"JAGGED_INIT")) return JAGGED_INIT; else if(!strcmp(lex,"TD_INIT")) return TD_INIT; else if(!strcmp(lex,"THD_INIT")) return THD_INIT; else if(!strcmp(lex,"TD_VALS_DASH")) return TD_VALS_DASH; else if(!strcmp(lex,"THD_VALS_DASH")) return THD_VALS_DASH; else if(!strcmp(lex,"TD_VALS")) return TD_VALS; else if(!strcmp(lex,"THD_VALS")) return THD_VALS; else if(!strcmp(lex,"INT_LIST")) return INT_LIST; else if(!strcmp(lex,"INT_LIST_DASH")) return INT_LIST_DASH; else if(!strcmp(lex,"INT_LIST_LIST")) return INT_LIST_LIST; else if(!strcmp(lex,"INT_LIST_LIST_DASH")) return INT_LIST_LIST_DASH; else if(!strcmp(lex,"INT_VAR_LIST")) return INT_VAR_LIST; else if(!strcmp(lex,"INT_VAR_LIST_DASH")) return INT_VAR_LIST_DASH; else if(!strcmp(lex,"ARRAY_RANGE")) return ARRAY_RANGE; else if(!strcmp(lex,"ARRAY_RANGE_DASH")) return ARRAY_RANGE_DASH; else if(!strcmp(lex,"IDX")) return IDX; else if(!strcmp(lex,"MULT_ID")) return MULT_ID; else if(!strcmp(lex,"MULT_ID_DASH")) return MULT_ID_DASH; else if(!strcmp(lex,"EXPR")) return EXPR; else if(!strcmp(lex,"EXPR_DASH")) return EXPR_DASH; else if(!strcmp(lex,"TERM")) return TERM; else if(!strcmp(lex,"TERM_DASH")) return TERM_DASH; else if(!strcmp(lex,"ASO_OP")) return ASO_OP; else if(!strcmp(lex,"MDA_OP")) return MDA_OP; else if(!strcmp(lex,"EPS")) return EPS; else if(!strcmp(lex,"ID1")) return ID1; else if(!strcmp(lex,"IDX1")) return IDX1; else if(!strcmp(lex,"ID_DASH")) return ID_DASH; else if(!strcmp(lex,"IDX_LIST")) return IDX_LIST; } terminal returnTerminalVal(char* lex) { if(!strcmp(lex,"program")) return program; else if(!strcmp(lex,"rb_op")) return rb_op; else if(!strcmp(lex,"rb_cl")) return rb_cl; else if(!strcmp(lex,"cb_op")) return cb_op; else if(!strcmp(lex,"cb_cl")) return cb_cl; else if(!strcmp(lex,"declare")) return declare; else if(!strcmp(lex,"col")) return col; else if(!strcmp(lex,"list")) return list; else if(!strcmp(lex,"of")) return of; else if(!strcmp(lex,"variables")) return variables; else if(!strcmp(lex,"semicol")) return semicol; else if(!strcmp(lex,"integer")) return integer; else if(!strcmp(lex,"boolean")) return boolean; else if(!strcmp(lex,"real")) return real; else if(!strcmp(lex,"array")) return array; else if(!strcmp(lex,"jagged")) return jagged; else if(!strcmp(lex,"ddot")) return ddot; else if(!strcmp(lex,"r1")) return r1; else if(!strcmp(lex,"sq_op")) return sq_op; else if(!strcmp(lex,"sq_cl")) return sq_cl; else if(!strcmp(lex,"size")) return size; else if(!strcmp(lex,"values")) return values; else if(!strcmp(lex,"add_op")) return add_op; else if(!strcmp(lex,"sub_op")) return sub_op; else if(!strcmp(lex,"mul_op")) return mul_op; else if(!strcmp(lex,"div_op")) return div_op; else if(!strcmp(lex,"eq_op")) return eq_op; else if(!strcmp(lex,"eps")) return eps; else if(!strcmp(lex,"or_op")) return or_op; else if(!strcmp(lex,"and_op")) return and_op; else if (!strcmp(lex,"id")) return id; return num; }
C
#include <stdio.h> #include <criterion/criterion.h> #include "../src/baseencode.h" Test(b32_decode_test, b32_all_chars) { baseencode_error_t err; const char *k = "IFCEMRZUGEZSDQVDEQSSMJRIFAXT6XWDU7B2SKS3LURSSLJOFR6DYPRL"; const char *k_dec = "ADFG413!£$%&&((/?^çé*[]#)-.,|<>+"; char *dk = base32_decode(k, strlen(k)+1, &err); cr_expect(strcmp(dk, k_dec) == 0, "Expected %s to be equal to %s", dk, k_dec); free(dk); } Test(b32_decode_test, b32_all_chars_noplusone) { baseencode_error_t err; const char *k = "IFCEMRZUGEZSDQVDEQSSMJRIFAXT6XWDU7B2SKS3LURSSLJOFR6DYPRL"; const char *k_dec = "ADFG413!£$%&&((/?^çé*[]#)-.,|<>+"; char *dk = base32_decode(k, strlen(k), &err); cr_expect(strcmp(dk, k_dec) == 0, "Expected %s to be equal to %s", dk, k_dec); free(dk); } Test(b32_decode_test, b32_rfc4648) { baseencode_error_t err; const char *k[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; const char *k_dec[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; for (int i = 0; i < 7; i++) { char *dk = base32_decode(k[i], strlen(k[i])+1, &err); cr_expect(strcmp(dk, k_dec[i]) == 0, "Expected %s to be equal to %s", dk, k_dec[i]); free(dk); } } Test(b32_decode_test, b32_rfc4648_noplusone) { baseencode_error_t err; const char *k[] = {"", "MY======", "MZXQ====", "MZXW6===", "MZXW6YQ=", "MZXW6YTB", "MZXW6YTBOI======"}; const char *k_dec[] = {"", "f", "fo", "foo", "foob", "fooba", "foobar"}; for (int i = 0; i < 7; i++) { char *dk = base32_decode(k[i], strlen(k[i]), &err); cr_expect(strcmp(dk, k_dec[i]) == 0, "Expected %s to be equal to %s", dk, k_dec[i]); free(dk); } } Test(b32_decode_test, b32_invalid_input) { baseencode_error_t err; const char *k = "£&/(&/"; size_t len = strlen(k); unsigned char *dk = base32_decode(k, len, &err); cr_expect_null(dk, "%s"); cr_expect_eq(err, INVALID_B32_DATA); } Test(b32_decode_test, b32_decode_input_exceeded) { baseencode_error_t err; const char *k = "ASDF"; size_t len = 128*1024*1024; unsigned char *dk = base32_decode(k, len, &err); cr_expect_null(dk, "%s"); cr_expect_eq(err, INPUT_TOO_BIG); } Test(b32_decode_test, b32_decode_input_whitespaces) { baseencode_error_t err; const char *k = "MZ XW 6Y TB"; const char *expected = "fooba"; unsigned char *dk = base32_decode(k, strlen(k), &err); cr_expect_str_eq(dk, expected, "%s"); } Test(b32_decode_test, b32_decode_encode_null) { const char* token = "LLFTSZYMUGKHEDQBAAACAZAMUFKKVFLS"; baseencode_error_t err; unsigned char* binary = base32_decode(token, strlen(token)+1, &err); cr_expect_eq(err, SUCCESS); char* result = base32_encode(binary, 20, &err); cr_expect_eq(err, SUCCESS); cr_expect_str_eq(result, token, "%s"); }
C
#include<stdio.h> void gencard(int ,int, int *, int ); int main() { int card[6]; int i;int val; int u1,l1,u2,l2; // u1 and li for the limits of hypotender u2 and l2 for hypertender int cheker =50; int h; // to select who plays first. the opposite player gets to select the range printf("read whoo plays first \n 0 for hypotender 1 for hyper tender "); scanf("%d",&h); switch(h) { case 0: printf("hypertender please select upper limit og your range 80 to 100 , in a window of 5"); scanf("%d",&u2); l2=u2-5; l1=100-u2; u1=l1+5; break; case 1: printf("hypotender please select lower limit of your range 0 to 20 , in a window of 5"); scanf("%d",&l1); u1=l1+5; u2=100-l1; l2=u2-5; break; default: printf("wrong input"); } printf(" so the wiining windows are\n"); printf("hypotender %d - %d \n",l1,u1); printf("\nhypertender %d - %d \n",l2,u2); if(h==0) printf("*************************************\nhypotender plays first\n****************************************\n"); else printf("\n***********************************\nhypertender playes first\n***************************************\n"); gencard(l1,l2,card,h); int ave1=0,ave2=0; for(i=0;i<6;i++) { if(h==0&&i<3 || h==1&&i>2) { ave1=ave1+card[i]; printf("card hypertender"); cheker=cheker+card[i]; } else if(h==1&&i<3 || h==0&&i>2) { ave2=ave2+card[i]; printf("card hypotender"); cheker=cheker-card[i]; } printf("%d",card[i]); printf(" %d\n",cheker); } printf("HYPERtender card= %d\n",(ave2*3)/5); printf("HYPO tender card= %d\n",(ave1*3)/5); // multiplication card generation int j,k=0,l=0; int mul[20]; mul[0]=u2/(u1+1); for(j=u1+2;j<=45;j++) { val=u2%j; printf("val== %d\n ",val); if(val<5) { val=u2/j; printf("val inside less than 5== %d\n ",val); if(val!=mul[k]) { k++; mul[k]=val; } } } int div[20]; int dk=0; int l11=l1; int rangelower; int rangeupper; if(l1==0){ // avoiding division by zero l11=1; } int divu=50/l11; int divl=50/u1; int intdiv; for(intdiv=2;intdiv<=14;intdiv++) { if(intdiv==divl) { intdiv=divu; } else{ rangelower=intdiv*l11; rangeupper=intdiv*(u1+1)-1; if(rangelower<100) { printf("\n%d ---- lower\n %d -----upper \n",rangelower,rangeupper); div[dk]=intdiv; dk++; } } } /*div[0]=59/u1; for(j=60;j<=l2-1;j++) { val=j/l1; if(val!=div[l]) { l++; div[l]=val; } }*/ printf("***************multiplication**********************\n"); for(j=0;j<=k;j++) // multiplication printf("%d\n",mul[j]); printf("*************division************************\n"); for(j=0;j<dk;j++) // division printf("%d\n",div[j]); /* for division set upper and lower division limits excluding those values from integer 2 calcualte li * integer and u1+1 * integer, this will be range of winning division card holder , among different ranges select a good range good luck */ /* for(j=0;j<=l;j++) // division printf("%d\n",div[j]); */ printf("\n%d not cards just diplaying value %d\n",ave1,ave2); } void gencard(int l1,int l2,int *card,int h) { int u1=l1+5; int u2=l2+5; card[0]=((l2-u1)/2); //+ randomize(2); card[3]=(card[0]*3)/4;// +randomize(1) card[1]=(l2+ 2)- (50 - card[3]); card[4]=(60-u1); // + randomize card[5]=50 - card[4] + card[1] -(l1+3); card[2]=(card[0]*4)/3; }
C
#include<stdio.h> int main() { int num; printf("\nEnter a number:"); scanf("%d", &num); if (num>70) {printf("\nHurray!!You won the lottery");} if (num<70) { printf("oh!you loss"); } return 0; }
C
#ifndef _MFILEHANDLER #define _MFILEHANDLER // maksymalne rozmiary poszczególnych elementów w bazie #define NBAZ 4 #define NTAB 8 #define NREC 32 #define NKOL 8 #define NSIZE 32 #define FBASE "baza.6r" // cała baza zajmuje w pamięci <300 kB typedef struct{ /** NAGŁÓWEK **/ // nazwy poszczególnych elementów w pliku char sbazy[NBAZ][NSIZE]; char stabele[NBAZ*NTAB][NSIZE]; char skolumn[NBAZ*NTAB*NREC][NSIZE]; // uwaga założyliśmy, że rekordy nie potrzebują identyfikatora // ilość poszczególnych elementów w pliku - bardzo ułatwi nawigację short nbazy; // ile baz jest aktualnie w pliku short ntabele[NBAZ]; // ile tabel jest w bazie o danym numerze short nkolumn[NBAZ][NTAB]; // ile kolumn jest w bazie i tabeli o danych numerach short nrekord[NBAZ][NTAB]; // ile rekordów jest w bazie i tabeli o danych numerach /** AKTUALNIE BLOKOWANE REKORDY **/ //short lock[NBAZ][NTAB][NREC]; // tabela ma zawierać same 0 (nieblokowane) i 1 (blokowane) /** ZAWARTOŚĆ PLIKU Z BAZĄ DANYCH **/ char bd [NBAZ][NTAB][NKOL][NREC][NSIZE]; // tu wczytujemy cały plik z bazą }Baza; Baza baza; /*** To są funkcje, które napiszę i będziesz je mógł użyć do obsługi zapytań klienta Standardowo: w funkcjach zwracających int: 0 - sukces, <0 porażka ( ewentualnie kod błędu ) w funkcjach zwracających char* - char[0]='\0' - porażka, wszystko inne to sukces w funkcji zwracającej char* - char[0][0]='\0' - porażka, wszystko inne to sukcess Ty ich po prostu używaj, tym jak będą działać ja się zajmę ;) ***/ /*------------------- FUNKCJE ODNOSZĄCE SIĘ DO BAZ DANYCH W PLIKU --------------------------*/ // tworzy bazę danych o podanej nazwie zwraca jej nr w strukturze, // lub -1 - jeżeli nie da się dodać żadnej więcej bazy, -2 - taka baza już istnieje int add_database(char name[]); // usuwa bazę danych o podanej nazwie, zwraca 0 - jeżeli ok, -1 jeśli nie ma takiej bazy int del_database(int ndb); // zwraca nr bazy o nazwie "name" ze struktury, -1 jak nie ma takiej bazy int get_db(char name[]); // wpisuje do argumentu char* nazwy wszystkich baz danych ze struktury // poszczególne nazwy są oddzielone '\n' np: "Firma\nAdministracja\nZUS" // służy tylko do pokazania baz danych na ekranie ! void pri_database(char*); /*------------------- FUNKCJE ODNOSZĄCE SIĘ DO TABEL W PLIKU --------------------------*/ // dodaje nową tabelę o nazwie name do bazy o numerze ndb ze struktury, // dodatkowo tworzy strukturę tabeli na podstawie nazw kolumn podanych jako // atrybut *kolumny[]. Liczba kolumn musi byż z góry określona za pomocą atrybutu skol. // Przykład użycia: // // char *kol[3]={ "Id", "Imię", "Nazwisko" }; // add_table(0,"Klienci", kol, 3); // zwraca 0 - jeśli udało się utworzyć nową tabelę, // -1 nie można już dodać żadnej nowej tabeli // -2 taka tabela już istnieje // -3 za dużo kolumn int add_table(int ndb, char name[], char kolumny[][NSIZE], int skol); // usuwa tabelę o nazwie name z bazy o numerze ndb ze struktury, zwraca 0 - jeżeli ok, -1 jeśli się nie udało int del_table( int ndb, int ntab ); // zwraca nr tabeli o nazwie "name" przypisanej do bazy o numerze ndb ze struktury, -1 jak nie ma takiej tabeli int get_table(int ndb, char name[]); // zwraca w tabeli char[] nazwy wszystkich tabel z bazy o numerze ndb ze struktury // poszczególne nazwy są oddzielone '\n' np: "Klienci\nSprzedawcy\nDostawcy" // służy tylko do pokazania tabel na ekranie ! void pri_table(int ndb, char *n); /*------------------- FUNKCJE ODNOSZĄCE SIĘ DO REKORDÓW W PLIKU --------------------------*/ // wstawia nowy rekord do tabeli o numerze ntab z bazy o numerze ndb ze struktury // przykład użycia analogiczny jak w przypadku funkcji add_table() // zwraca 0 - jeśli się udało, -1 - jeżeli nie da się już dodać nowych rekordów do tabeli // -2 jeżeli ilość danych zbyt duża, -3 - ilość danych za mała, // W zamierzeniu ma obsługiwać polecenie INSERT int add_record(int ndb, int ntab, char rekord[][NSIZE], int rlen); // usuwa rekord o numerze nrec z tabeli o numerze ntab z bazy o numerze ndb ze struktury // ta funkcja powinna być wywołana przez inne funkcje kasujące: // del_database(), del_table(), rem_record(), user bezpośrednio jej nie używa ! int del_record(int ndb, int ntab, int nrec); // blokuje rekord o numerze nrec z tabeli o numerze ntab z bazy o numerze ndb ze struktury int blk_record(int ndb, int ntab, int nrec); // zmienia rekord o numerze nrec z tabeli o numerze ntab z bazy o numerze ndb ze struktury // zwraca 0 - jeśli się udało, -1 jeżeli ilość danych zbyt duża, -2 - ilość // danych za mała, -3 - jeżeli dany rekord nie istnieje // W zamierzeniu ma obsługiwać polecenie UPDATE int upd_record(int ndb, int ntab, int nrec, char rekord[][NSIZE], int rlen); // usuwa wszystkie rekordy z tabeli ntab z bazy o numerze ndb, w których // kolumna o numerze nkol zawiera wartość text // funkcja obsługuje zapytania typu DELETE ? FROM ? WHERE ? int rem_record(int ndb, int ntab, int nkol, char *text); // Drukowanie wartości wybranych kolumn w rekordzie // nl zależy od nrec, jak nrec=-1 - nl=0 void pri_record(int ndb, int ntab, int nrec, int nkol, int nkolspr, char *phr, char *n, int nl); /*------------------- FUNKCJE ODNOSZĄCE SIĘ DO KOLUMN W PLIKU --------------------------*/ // zwraca nr kolumny o nazwie "name" z tabeli o numerze ntab, przypisanej do bazy o numerze ndb ze struktury int get_column(int ndb, int ntab, char name[]); // zwraca w tabeli char[] wszystkie wartości odczytane // z kolumny o numerze nkol z tabeli o numerze ntab z bazy // o numerze ndb // Ta funkcja ma służyć do obsługi polecenia SELECT void pri_column(int ndb, int ntab, int nkol, char *phr, char *n); // drukuje nagłówki kolumn, potrzebne do SELECT // pzrzyjmuje takie same parametry jak pri_column() void pri_nagl(int ndb, int ntab, int nkol, char *n); /*------------------------------- POZOSTAŁE --------------------------------------------*/ void init_db(void); // jeżeli to pierwsze uruchomienie, zainicjuje strukturę systemu int read_base(void); // odczyt pliku z bazami danych int write_base(void); // zapis pliku void mark_up(char*); // robi podkreślenia pod nagłówkiem tabeli #endif
C
/************************** * Name: Vicky Mohammad * ID: 0895381 **************************/ //import libraries #include <stdlib.h> #include <stdio.h> #include <errno.h> #include <stdbool.h> #include <string.h> #include <ctype.h> #include "hashTable.h" /**Function to point the hash table to the appropriate functions. Allocates memory to the struct and table based on the size given. *@return pointer to the hash table *@param size size of the hash table *@param hashFunction function pointer to a function to hash the data *@param destroyData function pointer to a function to delete a single piece of data from the hash table *@param printNode function pointer to a function that prints out a data element of the table **/ HTable *createTable(size_t size, int (*hashFunction)(size_t tableSize, char* key), void (*destroyData)(void *data), void (*printNode)(void *toBePrinted)){ //create a new table HTable *newTable = malloc(sizeof(HTable)); //init the size newTable->size = size; newTable->table = malloc(sizeof(Node*)*size); newTable->destroyData = destroyData; newTable->hashFunction = hashFunction; newTable->printNode = printNode; //init the table will null to prevent seg fault for(int x=0; x < size; x++){ newTable->table[x] = NULL; }//end for //return the new table return newTable; }//end func /**Function for creating a node for the hash table. *@pre Node must be cast to void pointer before being added. *@post Node is valid and able to be added to the hash table *@param key integer that represents the data (eg 35->"hello") *@param data is a generic pointer to any data type. *@return returns a node for the hash table **/ Node *createNode(char* key, void *data){ //create a new node Node *newNode = malloc(sizeof(Node)); //init the new node newNode->key = key; newNode->data = data; newNode->next = NULL; //return the new node return newNode; }//end func /** Deletes the entire hash table and frees memory of every element. *@pre Hash Table must exist. *@param hashTable pointer to hash table containing elements of data **/ void destroyTable(HTable *hashTable){ //declare variable Node* tempNode = NULL; Node* nodeTobeDeleted = NULL; //if the table is not empty then free the node if(hashTable != NULL){ //check every node for(int x=0; x < hashTable->size; x++){ tempNode = hashTable->table[x]; //go through the table until null while(tempNode != NULL){ nodeTobeDeleted = tempNode; tempNode = tempNode->next; //free the each element on the table and the data hashTable->destroyData(nodeTobeDeleted->data); free(nodeTobeDeleted); }//end while } }else if(hashTable == NULL){ //if the hash table is empty then return return; }//end if //free the table free(hashTable->table); free(hashTable); }//end func /**Inserts a Node in the hash table. *@pre hashTable type must exist and have data allocated to it *@param hashTable pointer to the hash table *@param key integer that represents the data (eg 35->"hello") *@param data pointer to generic data that is to be inserted into the list **/ void insertData(HTable *hashTable, char* key, void *data){ //if its already exist if(lookupData(hashTable, key) != NULL){ printf("The word '%s' already exist.\n", (char*)key); return; }//end if //if the table is empty if(hashTable == NULL){ printf("Hash table is empty.\n"); return; }//end if //if the hash is greater than the table size or smaller than 0 int index = hashNode(hashTable->size, key); if(index < 0 || index > hashTable->size){ printf("The hash index is out of bound.\n"); return; }//end if //input it at the word end of the list at the index if collision happens Node* newNode = createNode(key, data); if(hashTable->table[index] != NULL && hashTable->table[index]->key != key){ //declare a temp node for inserting the new node Node* iterateNode; iterateNode = hashTable->table[index]; //loop until the end of the list while(iterateNode->next != NULL){ iterateNode = iterateNode->next; }//end if //once iterate node is the end of the list, add a new node iterateNode->next = newNode; printf("The word '%s' has been added at index %d.\n", (char*)newNode->data, index); return; }//end if //if nothing is in the list just add it to the new node if(hashTable->table[index] == NULL || hashTable->table[index]->key == key){ //added to the hashtable hashTable->table[index] = newNode; printf("The word '%s' has been added at index %d.\n", (char*)newNode->data, index); return; }//end if }//end func /** THIS FUNCTION IS NOT MANDATORY, users call this function to insert a Node in the hash table. * It's meant as a wrapper for insertData so the users don't need to generate the key when adding. *@pre hashTable type must exist and have data allocated to it *@param hashTable pointer to the hash table *@param data pointer to generic data that is to be inserted into the list **/ void insertDataInMap(HTable *hashTable, void *data){ insertData(hashTable, (char*)data, data); }//end func /**Function to remove a node from the hash table *@pre Hash table must exist and have memory allocated to it *@post Node at key will be removed from the hash table if it exists. *@param hashTable pointer to the hash table struct *@param key integer that represents a piece of data in the table (eg 35->"hello") **/ void removeData(HTable *hashTable, char* key){ //set the varibales int index = hashNode(hashTable->size, key); Node *currentNode = hashTable->table[index]; Node *prevNode = hashTable->table[index]; Node *nextNode = hashTable->table[index]; Node *nodeTobeDeleted; //if its already exist if(lookupData(hashTable, key) == NULL){ printf("The word '%s' doesn't exist.\n", (char*)key); return; }//end if //check if there is something in the list if(hashTable->table[index] != NULL){ //case when the first word is what im looking for if(strcmp(hashTable->table[index]->key, key) == 0){ nextNode = currentNode->next; printf("Removing the word '%s' from dictionary.\n", (char*)currentNode->data); free(currentNode); hashTable->table[index] = nextNode; }else{ //loop until null or find the word while(currentNode != NULL){ //check if its what im looking for if(strcmp(currentNode->key, key) == 0){ //if found delete the data nextNode = currentNode->next; prevNode->next = nextNode; nodeTobeDeleted = currentNode; printf("Removing the word '%s' from dictionary.\n", (char*)nodeTobeDeleted->data); nodeTobeDeleted->data = NULL; nodeTobeDeleted = NULL; free(nodeTobeDeleted); }//end if prevNode = currentNode; currentNode = currentNode->next; }//end while }//end if }else if(hashTable->table[index] == NULL){ //if the list is emppty printf("The index %d is empty.\n", index); }else{ //the key may be out of bound return; }//end if }//end func /**Function to return the data from the key given. *@pre The hash table exists and has memory allocated to it *@param hashTable pointer to the hash table containing data nodes *@param key integer that represents a piece of data in the table (eg 35->"hello") *@return returns a pointer to the data in the hash table. Returns NULL if no match is found. **/ void *lookupData(HTable *hashTable, char* key){ //set the varibales int index = hashNode(hashTable->size, key); Node *iterateNode = hashTable->table[index]; //check if there is something in the list if(hashTable->table[index] != NULL){ while(iterateNode != NULL){ //check if its what im looking for if(strcmp(iterateNode->key, key) == 0){ //if found return return iterateNode->data; }//end if iterateNode = iterateNode->next; }//end while }else{ return NULL; }//end if return NULL; }//end func /** *function of hash the words *@param tableSize for the size of the table *@param key for the word being hashed */ int hashNode(size_t tableSize, char* key){ key = lowerCase(key); //declare variable int total = 0; //loop each character add each of them for(int x=0; x<strlen(key); x++){ total = total + (key[x]*x+strlen(key)); }//end for return total % tableSize; }//end func /** *destroy the data on the node *(to be honest this is just a dummy function to initialize the table) *(im not really using this as it is optional) *@param *data for the data to be destroyed */ void destroyNodeData(void *data){ //free the data free(data); }//end func /** *print the node of the data *@param *toBePrinted the data of node to be printed */ void printNodeData(void *toBePrinted){ printf("%s", (char*)toBePrinted); }//end func /** *print all any available data in the hash table *@param hashTable where you pass the hash table to be printed */ void printList(HTable *hashTable){ printf("Printing list... \n"); //loop through the hash and print each for(int x=0; x < hashTable->size; x++){ //if the hash table is not null then print the element if(hashTable->table[x] != NULL){ //set the starting point Node* tempNode = hashTable->table[x]; //run through the list if(tempNode != NULL) { /*move forward using next pointer*/ while(tempNode != NULL) { //print (tempNode); printf("<%d>:<%s>:<%s>\n", x, (char*)tempNode->key, (char*)tempNode->data); tempNode = tempNode->next; }/*end while*/ }else{ //if the list is null print that its empty printf("The list is empty.\n"); }//end if }//end if }//end for }//end func /** *change to lower case *@param string for the string to change to lowercaser */ char * lowerCase(char * string){ for(int x=0; x <strlen(string);x++){ string[x] = tolower(string[x]); }//end if return string; }//end func
C
#include <stdio.h> #include <stdlib.h> #include <string.h> int main(){ int tam = 0, contIguais = 0, contM = 0, contF = 0, k = 0, x = 0; char caixa[10000], chNum[3]; //Le o n do calcado while(scanf("%s\n", chNum) != EOF){ //Incremento da quantidade de casos x++; //Le o n de cada par que esta na caixa seguido de M ou F fgets(caixa, 9999, stdin); //Recebe o tamanho do vetor tam = strlen(caixa); //Incrementa 1 ao tamanho para considerar o caracter \0 tam += 1; //Faz a contagem da qtde de pares iguais conf. o tipo M ou F while(k <= tam){ if(chNum[0] == caixa[k] && chNum[1] == caixa[k + 1]){ contIguais++; if(caixa[k + 3] == 'M'){ contM++; } else{ contF++; } } k += 5; } //Pula linha apos 2 casos de usos terem sidos digitados if(x != 1){ printf("\n"); } //Impressao dos dados de saida printf("Caso %d:\n", x); printf("Pares Iguais: %d\n", contIguais); printf("F: %d\n", contF); printf("M: %d\n", contM); //Retorno de valores iniciais k = 0; tam = 0; contIguais = 0; contM = 0; contF = 0; } return 0; }
C
typedef struct JsonObject { struct { char *name; JsonValue *value; } *fields; } JsonObject; typedef struct JsonArray { JsonValue *values; } JsonArray; typedef struct JsonValue { enum { JSON_OBJECT, JSON_ARRAY, JSON_STRING, JSON_NUMBER, JSON_BOOLEAN } type; union { JsonObject *object; JsonArray *array; char *string; char *number; unsigned char boolean; }; } JsonValue;
C
#include <stdio.h> #include <conio.h> int main(){ int koltuk[11]={0},count=0,firstClass=5,economy=0,secim,koltukSec; char cevap[2]; printf("------WELCOME TO YARASA REYIS AIRLINES RESERVATION SYSTEM------\n"); while(count<10){ printf("Please type 1 for Economy Class\nPlease type 2 for First Class:"); scanf("%d",&secim); if(secim==1){ printf("Please select your seat assignment(1-5):"); scanf("%d",&koltukSec); if(koltukSec<1||koltukSec>5){ printf("\nWrong selection.\n\n"); } else{ if(!koltuk[koltukSec]&&economy<=5){ printf("\nYour assignment is %d.section %d.seat\n\n",secim,koltukSec); koltuk[koltukSec]=1; count++; economy++; } else if(economy>=5&&firstClass<=10){ printf("\nThe economy class section is full.\n\n"); printf("Would you like to sit in the first class "); printf("Section (Y or N)?"); scanf("%s",cevap); if(toupper(cevap[0])=='Y'){ printf("Please select your seat assignment(6-10):"); scanf("%d",&koltukSec); if(!koltuk[koltukSec]&&firstClass<=10){ printf("\nYour assignment is 2.section %d.seat\n\n",koltukSec); koltuk[koltukSec]=1; count++; firstClass++; } else if(koltuk[koltukSec]==1){ printf("\nThe seat you have selected is already reserved.\n\n"); } } else{ printf("\nNext flight leaves in 3 hours.\n\n"); } } else if(koltuk[koltukSec]==1){ printf("\nThe seat you have selected is already reserved.\n\n"); } else{ printf("\nNext flight leaves in 3 hours.\n\n"); } } } else if(secim==2){ printf("Please select your seat assignment(6-10):"); scanf("%d",&koltukSec); if(koltukSec<6||koltukSec>10){ printf("\nWrong selection.\n\n"); } else{ if(!koltuk[koltukSec]&&firstClass<=10){ printf("\nYour assignment is %d.section %d.seat\n\n",secim,koltukSec); koltuk[koltukSec]=1; count++; firstClass++; } else if(firstClass>=10&&economy<=5){ printf("\nThe First class section is full.\n\n"); printf("Would you like to sit in the economy class "); printf("Section (Y or N)?"); scanf("%s",cevap); if(toupper(cevap[0])=='Y'){ printf("Please select your seat assignment(1-5):"); scanf("%d",&koltukSec); if(!koltuk[koltukSec]&&economy<=5){ printf("\nYour assignment is 1.section %d.seat\n\n",koltukSec); koltuk[koltukSec]=1; count++; economy++; } else if(koltuk[koltukSec]==1){ printf("\nThe seat you have selected is already reserved.\n\n"); } } else{ printf("\nNext flight leaves in 3 hours.\n\n"); } } else if(koltuk[koltukSec]==1){ printf("\nThe seat you have selected is already reserved.\n\n"); } else{ printf("\nNext flight leaves in 3 hours.\n\n"); } } } else{ printf("\nPlease select 1(Economy Class) or 2(First class).\n\n"); } } if(count==10){ printf("\nAll seats are full for this flight...\n\n"); } getch(); return 0; }
C
#include<stdio.h> void main() { int n,res=0,rem,remin; scanf("%d",&n); while(n!=0) { rem=n%10; res=res*10+rem; n=n/10; } while(res!=0) { remin=res%10; printf("%d\t",remin); res=res/10; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_write_o.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: yserhii <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/01/14 15:12:13 by yserhii #+# #+# */ /* Updated: 2019/01/14 15:12:21 by yserhii ### ########.fr */ /* */ /* ************************************************************************** */ #include "libft.h" static long long int ft_len_o(unsigned long long int n, t_mcon *mcon) { int i; int k; i = 0; k = (mcon->con == 'o' ? 8 : 2); if (n == 0) return (1); while (n && ++i) n /= k; return (i); } static void ft_write_o_str(char *tmp, int len, unsigned long long int n, t_mcon *mcon) { int k; k = (mcon->con == 'o' ? 8 : 2); while (n && (tmp[--len] = n % k + '0')) n /= k; while (len > 0) (tmp[--len] = '0'); if (mcon->fl->hesh > 0 && tmp[0] != '0' && (mcon->fl->hesh = 5)) mcon->width--; } static void ft_write_o_prin(t_mcon *mcon, char *tmp, int len) { if (mcon->fl->precis && ft_strcmp(tmp, "0") == 0 && mcon->fl->hesh == 0) { tmp = ""; len = 0; } if (mcon->fl->minus) { if (mcon->fl->hesh == 5) mcon->point = ft_strnjoin(mcon->point, "0", 1); mcon->point = ft_strjoin(mcon->point, tmp); while (len < mcon->width--) mcon->point = ft_strnjoin(mcon->point, " ", 1); return ; } if (mcon->fl->zero && mcon->fl->precis == 0) while (len < mcon->width--) mcon->point = ft_strnjoin(mcon->point, "0", 1); else while (len < mcon->width--) mcon->point = ft_strnjoin(mcon->point, " ", 1); if (mcon->fl->hesh == 5) mcon->point = ft_strnjoin(mcon->point, "0", 1); mcon->point = ft_strjoin(mcon->point, tmp); } void ft_write_o(t_mcon *mcon, unsigned long long n) { char *tmp; int len; len = ft_len_o(n, mcon); while (mcon->num_prec > len && len++) mcon->fl->zero = 0; tmp = ft_strnew(len); ft_write_o_str(tmp, len, n, mcon); ft_write_o_prin(mcon, tmp, len); free(tmp); }
C
#include <stdio.h> #include <stdlib.h> /* sqrt ???????sqrt(a)*sqrt(a)=n ???*/ int dig(long long x){ int c = 0; while(x>0){x/=10;c++;} return c; } int main(void){ long long n,i,j; scanf("%lld",&n); int c=dig(n); for(i=1;i*i<=n;i++){ if(n%i==0){ if(n/i>i)j=n/i; else j=i; int d = dig(j); if(d<c)c=d; } } printf("%d",c); return 0; } ./Main.c: In function main: ./Main.c:12:2: warning: ignoring return value of scanf, declared with attribute warn_unused_result [-Wunused-result] scanf("%lld",&n); ^
C
#include <stdio.h> int main(void) { int a = 123; if(a >= 0 && a < 10) { printf("weishu: 1\n"); } if(a >= 10 && a < 100) { printf("weishu: 2\n"); } if ( a >= 100 && a<1000) { printf("weishu: 3\n"); } if ( a >= 1000 && a<10000) { printf("weishu: 4\n"); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* type_p.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lramos-r <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/03/10 13:25:33 by lramos-r #+# #+# */ /* Updated: 2020/03/10 15:12:37 by lramos-r ### ########.fr */ /* */ /* ************************************************************************** */ #include "printf.h" static char *precision_p(char *src, t_fields *f) { char *prec; int len; len = (int)ft_strlen(src); if (f->precision <= len) { prec = ft_strnew(len + 2); ft_memmove(prec, "0x", 2); ft_memmove(&prec[2], src, len); } else { prec = ft_strnew(f->precision + 2); ft_memmove(prec, "0x", 2); ft_memset(&prec[2], '0', f->precision - len); ft_memmove(&prec[2 + f->precision - len], src, len); } return (prec); } static int aux_width_p(t_fields *f, int len, char *src, char *wid) { if (f->flag == '-') { ft_memmove(wid, src, len); ft_memset(&wid[len], ' ', f->width - len); } else if (f->flag == '0') { ft_memmove(wid, src, len); ft_memset(&wid[len], '0', f->width - len); } else { ft_memset(wid, ' ', f->width - len); ft_memmove(&wid[f->width - len], src, len); } return (0); } static char *width_p(char *src, t_fields *f) { char *wid; int len; len = (int)ft_strlen(src); if (f->width <= len) wid = ft_strdup(src); else { wid = ft_strnew(f->width); aux_width_p(f, len, src, wid); } return (wid); } int type_p(t_fields *f, unsigned long long int arg) { char *p; char *prec; char *w; int len; if (f->precision > -1 && arg == '\0') p = ft_strdup(""); else if (arg == '\0') p = ft_itoa_base(0, 16); else p = ft_itoa_base(arg, 16); prec = precision_p(p, f); w = width_p(prec, f); len = (int)ft_strlen(w); ft_putstr(w); free(prec); free(p); free(w); return (len); }
C
#include <stdio.h> int main (void) { int x , b , v[6] , dabriel , guarte ; scanf("%d", &x); while( x != 0 ){ scanf("%d",&b); scanf("%d %d %d", &v[0], &v[1] ,&v[2]); scanf("%d %d %d", &v[3], &v[4] ,&v[5]); if( v[2] % 2 == 0 ) dabriel = (v[0]+v[1])/2 + b; else dabriel = (v[0]+v[1])/2; if ( v[5] % 2 == 0 ) guarte = (v[3]+v[4])/2 + b; else guarte = (v[3]+v[4])/2; if(dabriel > guarte) printf("Dabriel\n"); else if (guarte > dabriel) printf("Guarte\n"); else printf("Empate\n"); x--; } return 0; }
C
#include <stdio.h> #include <stdlib.h> char inverte(char s[], int n) { char resposta[n]; for(int i=0; i<n; i++){ resposta[i] = s[n-1-i]; printf("%c", resposta[i]); } printf("\n"); } int lenght(char s[]) { int i = 0; while(s[i]!='\0') i++; return i; } int main() { int n; char entrada[255]; fgets(entrada, 255, stdin); n = lenght(entrada); printf("%d\n", n); inverte(entrada, n); return 0; }
C
//Author: LinusDev //overworld 0-1 //nether 2.0 //end 3.0 float dimension(in sampler2D source, float nightDay){ vec3 topLeftLight = texture2D(source, vec2(0.0, 0.0)).rgb; vec3 bottomLeftLight = texture2D(source, vec2(0.0, 1.0)).rgb; #ifdef UNDER_WATER //End's and Nether's TopLeftCorner and BottomLeftCorner are equal, but the Nether has more Red //Water cannot be placed in the Nether if(topLeftLight.r == bottomLeftLight.r){ return 3.0; } return nightDay; #else if(topLeftLight.r == bottomLeftLight.r && topLeftLight.g == bottomLeftLight.g){ return 3.0; //End } if(pow(topLeftLight.r, 1.0) > 0.3){ return 2.0; //Nether } return nightDay; #endif }
C
/* ** EPITECH PROJECT, 2018 ** my_rpg_2017 ** File description: ** object disp */ #include "../../../include/rpg.h" int disp_objects(sfRenderWindow *wd, map_t *map) { list_t *objs = map->objects; object_t *obj = NULL; for (; objs != NULL; objs = objs->next) { obj = (object_t*)objs->data; if (obj->sprite != NULL) disp_sprite_at(wd, map, obj->sprite, obj->pos); } return (0); }
C
#include <stdio.h> #include <stdint.h> #include <assert.h> #include "instance.h" #include "sortarray.h" #include "game_srv.h" int enter_instance(ROLE *role, INSTANCE *instance) { int ret; IDX idx_role; assert(instance); assert(role); assert(role->instance.p == NULL); if (instance->role_num >= MAX_ROLE_PER_INSTANCE) { return (-1); } idx_role.idx = GET_IDX(role); idx_role.p = role; ret = array_insert(&idx_role, &instance->role[0], (int *)&instance->role_num, sizeof(IDX), 1, comp_idx); if (ret < 0) { log4c_category_log(mycat, LOG4C_PRIORITY_INFO, "%s %d: role[%u] already in instance[%d]", __FUNCTION__, __LINE__, idx_role.idx, instance->id); return (-10); } role->instance.idx = GET_IDX(instance); role->instance.p = instance; role->instance_dice = 0; log4c_category_log(mycat, LOG4C_PRIORITY_DEBUG, "%s: role[%lu] enter instance[%d]", __FUNCTION__, role->role_id, instance->id); return (0); } int leave_instance(ROLE *role, INSTANCE *instance) { int ret; IDX idx_role; assert(instance); assert(role); idx_role.idx = GET_IDX(role); idx_role.p = role; ret = array_delete(&idx_role, &instance->role[0], (int *)&instance->role_num, sizeof(IDX), comp_idx); if (ret < 0) { log4c_category_log(mycat, LOG4C_PRIORITY_INFO, "%s %d: role[%u] not in instance[%d]", __FUNCTION__, __LINE__, idx_role.idx, instance->id); return (-10); } role->instance.idx = MAX_IDX; role->instance.p = NULL; log4c_category_log(mycat, LOG4C_PRIORITY_DEBUG, "%s: role[%lu] leave instance[%d]", __FUNCTION__, role->role_id, instance->id); if (instance->role_num == 0) { log4c_category_log(mycat, LOG4C_PRIORITY_DEBUG, "%s: destory instance[%d]", __FUNCTION__, role->role_id, instance->id); destory_instance(instance); } return (0); } INSTANCE *new_instance(uint16_t id) { INSTANCE *ret = create_instance(); if (!ret) { log4c_category_log(mycat, LOG4C_PRIORITY_INFO, "%s %d: create_instance failed"); return (NULL); } ret->id = id; ret->role_num = 0; return (ret); } void init_instance_data(INSTANCE *instance) { assert(instance); instance->role_num = 0; } int resume_instance_data(INSTANCE *instance) { int i; assert(instance); for (i = 0; i < instance->role_num; ++i) { instance->role[i].p = (void *)get_role_byidx(instance->role[i].idx); if (!instance->role[i].p) { log4c_category_log(mycat, LOG4C_PRIORITY_ERROR, "%s: fail", __FUNCTION__); return (-1); } } return (0); }
C
/* ** make_team_tab.c for Project-Master in /home/nathalie/rendu/network/PSU_2016_ ** ** Made by Nathalie CAI ** Login <nathalie.cai@epitech.eu> ** ** Started on Mon Jun 26 17:52:26 2017 Nathalie CAI ** Last update Sat Jul 1 15:12:36 2017 Baptiste Veyssiere */ #include <stdlib.h> #include <string.h> #include "server.h" static int is_in_tab(char **tab, char *target) { int i; i = 0; while (tab != NULL && tab[i] != NULL) { if (strcmp(tab[i], target) == 0) return (1); i++; } return (0); } static char **default_team(void) { char **tab; if (!(tab = malloc(sizeof(char*) * 5))) return (NULL); tab[0] = "team1"; tab[1] = "team2"; tab[2] = "team3"; tab[3] = "team4"; tab[4] = NULL; return (tab); } char **team_tab(int ac, char **av) { int i; int j; char **tab; i = 0; while (i < ac && strcmp(av[i], "-n") != 0) i++; tab = NULL; j = 0; while (++i < ac && strncmp(av[i], "-", 1) != 0) { if (is_in_tab(tab, av[i]) == 0) { if ((tab = realloc(tab, sizeof(char *) * (j + 2))) == NULL) return (NULL); tab[j] = av[i]; tab[j + 1] = NULL; } j++; } i = -1; while (tab && tab[++i]); if (i < 1) return (default_team()); return (tab); }
C
#include <stdio.h> int main(void) { puts(" A"); puts(" B B"); puts(" C C"); puts(" D D"); puts(" E E"); puts(" D D"); puts(" C C"); puts(" B B"); puts(" A"); return 0; }
C
/* ** quaternion.c for Recalage in /goinfre/recalage/src ** ** Made by thomas moulard ** Login <moular_t@epita.fr> ** ** Started on Wed Dec 14 21:11:02 2005 thomas moulard ** Last update Fri Dec 23 01:52:57 2005 thomas moulard */ #include <stdio.h> #include <assert.h> #include "recalage.h" /** ** Initialize a quaternion. */ void init_quaternion(struct s_quaternion *q) { q->s = q->vec.x = q->vec.y = q->vec.z = 0.0; } /** ** q = q2 * q3 */ void mult_quaternion(struct s_quaternion *q, struct s_quaternion *q2, struct s_quaternion *q3) { q->s = ((q2->s * q3->s) - (q2->vec.x * q3->vec.x) - (q2->vec.y * q3->vec.y) - (q2->vec.z * q3->vec.z)); q->vec.x = ((q2->vec.x * q3->s) + (q2->s * q3->vec.x) + (q2->vec.y * q3->vec.z) - (q2->vec.z * q3->vec.y)); q->vec.y = ((q2->vec.y * q3->s) + (q2->s * q3->vec.y) + (q2->vec.z * q3->vec.x) - (q2->vec.x * q3->vec.z)); q->vec.z = ((q2->vec.z * q3->s) + (q2->s * q3->vec.z) + (q2->vec.x * q3->vec.y) - (q2->vec.y * q3->vec.x)); } /** ** Computes the opposite of a quaternion */ void opp_quaternion(struct s_quaternion *q, struct s_quaternion *q2) { q->s = q2->s; q->vec.x = -q2->vec.x; q->vec.y = -q2->vec.y; q->vec.z = -q2->vec.z; } /** ** Convert a 4x1 matrix to a quaternion */ void matrice2quaternion(struct s_quaternion *q, struct s_matrice *m) { assert((m->w == 1) && (m->h == 4)); q->s = m->data[0]; q->vec.x = m->data[1]; q->vec.y = m->data[2]; q->vec.z = m->data[3]; } /** ** Print the quaternion on the standard output. */ void aff_quaternion(struct s_quaternion *q, char *str) { fprintf(stderr, "-----\n%s\n", str); fprintf(stderr, "w: %f\n", q->s); fprintf(stderr, "x: %f\n", q->vec.x); fprintf(stderr, "y: %f\n", q->vec.y); fprintf(stderr, "z: %f\n", q->vec.z); fprintf(stderr, "-----\n"); }
C
#ifndef GAMEPADEVENTHANDLER_H #define GAMEPADEVENTHANDLER_H #include <errno.h> #include <mqueue.h> #include <unistd.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #define JS_EVENT_BUTTON 0x01 /* button pressed/released */ #define JS_EVENT_AXIS 0x02 /* joystick moved */ #define JS_EVENT_INIT 0x80 /* initial state of device */ #define JS_BUTTON_A 0x00 #define JS_BUTTON_B 0x01 #define JS_BUTTON_X 0x02 #define JS_BUTTON_Y 0x03 #define JS_BUTTON_LB 0x04 #define JS_BUTTON_RB 0x05 #define JS_BUTTON_SELECT 0x06 #define JS_BUTTON_START 0x07 #define JS_AXIS_X1 0x00 #define JS_AXIS_Y1 0x01 #define JS_AXIS_X2 0x02 #define JS_AXIS_Y2 0x03 #define TRUE 1 #define FALSE 0 typedef struct args_t { mqd_t *mq; char *devPath; int *runningFlag; }args_t; struct js_event { unsigned int time; /* event timestamp in milliseconds */ short value; /* value */ unsigned char type; /* event type */ unsigned char number; /* axis/button number */ }; typedef struct js_attr_t{ char button_cnt; char axis_cnt; int version; char identifier[16]; char dev_name[16]; }js_attr_t; typedef enum buttonName{ BUTTON_A = JS_BUTTON_A, BUTTON_B = JS_BUTTON_B, BUTTON_X = JS_BUTTON_X, BUTTON_Y = JS_BUTTON_Y, BUTTON_LB = JS_BUTTON_LB, BUTTON_RB = JS_BUTTON_RB, BUTTON_SELECT = JS_BUTTON_SELECT, BUTTON_START = JS_BUTTON_START, AXIS_X1, AXIS_Y1, AXIS_X2, AXIS_Y2 }buttonName; typedef enum buttonType{ AXIS = JS_EVENT_AXIS, BUTTON = JS_EVENT_BUTTON }buttonType; typedef struct { unsigned int timestamp; buttonName name; buttonType type; short value; }button_event_t; void gamepadEventHandler(void *args); #endif
C
// // Created by Christop Reek on 2019-05-12. // #include "libft.h" #include "ft_ls.h" static void ft_rbtforeach_pre(t_rbtree *root, void (*f)(t_rbtree *elem)) { if (root->content) f(root); if (root->left->content) ft_rbtforeach_pre(root->left, f); if (root->right->content) ft_rbtforeach_pre(root->right, f); } static void ft_rbtforeach_in(t_rbtree *root, void (*f)(t_rbtree *elem)) { if (root->left->content) ft_rbtforeach_in(root->left, f); if (root->content) f(root); if (root->right->content) ft_rbtforeach_in(root->right, f); } static void ft_rbtforeach_post(t_rbtree *root, void (*f)(t_rbtree *elem)) { if (root->left->content) ft_rbtforeach_post(root->left, f); if (root->right->content) ft_rbtforeach_post(root->right, f); if (root->content) f(root); } void ft_rbtforeach(t_rbtree *root, void (*f)(t_rbtree *elem), int order) { if (!root || !f) { printf("o nihuya %p %p\n", root, f); return; } if (order == PREFIX) { ft_rbtforeach_pre(root, f); } else if (order == INFIX) { ft_rbtforeach_in(root, f); } else if (order == POSTFIX) { ft_rbtforeach_post(root, f); } } static void ft_rbtforeach_pre_two(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length)) { if (root->content) f(root, str_length); if (root->left->content) ft_rbtforeach_pre_two(root->left, str_length, f); if (root->right->content) ft_rbtforeach_pre_two(root->right, str_length, f); } static void ft_rbtforeach_in_two(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length)) { if (root->left->content) ft_rbtforeach_in_two(root->left, str_length, f); if (root->content) f(root, str_length); if (root->right->content) ft_rbtforeach_in_two(root->right, str_length, f); } static void ft_rbtforeach_post_two(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length)) { if (root->left->content) ft_rbtforeach_post_two(root->left, str_length, f); if (root->right->content) ft_rbtforeach_post_two(root->right, str_length, f); if (root->content) f(root, str_length); } void ft_rbtforeach_two(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length), int order) { if (!root || !f) { printf("o nihuya %p %p\n", root, f); return; } if (order == PREFIX) { ft_rbtforeach_pre_two(root, str_length, f); } else if (order == INFIX) { ft_rbtforeach_in_two(root, str_length, f); } else if (order == POSTFIX) { ft_rbtforeach_post_two(root, str_length, f); } } static void ft_rbtforeach_pre_three(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length, char *str), char *str) { if (root->content) f(root, str_length, str); if (root->left->content) ft_rbtforeach_pre_three(root->left, str_length, f, str); if (root->right->content) ft_rbtforeach_pre_two(root->right, str_length, f3); } static void ft_rbtforeach_in_three(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length, char *str), char *str) { if (root->left->content) ft_rbtforeach_in_three(root->left, str_length, f, str); if (root->content) f(root, str_length, str); if (root->right->content) ft_rbtforeach_in_three(root->right, str_length, f, str); } static void ft_rbtforeach_post_three(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length, char *str), char *str) { if (root->left->content) ft_rbtforeach_post_three(root->left, str_length, f, str); if (root->right->content) ft_rbtforeach_post_three(root->right, str_length, f, str); if (root->content) f(root, str_length, str); } void ft_rbtforeach_three(t_rbtree *root, t_length *str_length, void (*f)(t_rbtree *elem, t_length *str_length, char *str), int order, char *str) { if (!root || !f) { printf("no root or no func %p %p\n", root, f); return; } if (order == PREFIX) { ft_rbtforeach_pre_three(root, str_length, f, str); } else if (order == INFIX) { ft_rbtforeach_in_three(root, str_length, f, str); } else if (order == POSTFIX) { ft_rbtforeach_post_three(root, str_length, f, str); } }
C
#include <stdio.h> #define taille (8) void montreTableau(int tableau[taille]); int main() { int tableau[taille] = {3, 2, 4, -1, 6, 0, -5, 18}; int permute = 0, i, temp, compteurBoucles = 0, permutations = 0; do { montreTableau(tableau); permute = 0; compteurBoucles++; for (i = 0; i < (taille - 1); i++) { if (tableau[i + 1] < tableau[i]) { temp = tableau[i + 1]; tableau[i + 1] = tableau[i]; tableau[i] = temp; permutations++; permute = 1; } } } while (permute == 1); printf("FIN\n"); montreTableau(tableau); printf("Nb Boucles : %d avec %d permutations.\n", compteurBoucles, permutations); } void montreTableau(int tableau[taille]) { int i; printf("[ "); for (i = 0; i < taille; i++) { printf("%d, ", tableau[i]); } printf(" ]\n"); }
C
/** * Handles the logs by sending the printw statements to a pop up window * * This is terrible code, but relies on v_init() in view.c to be called first * to work. * Todo: Refactor this into the view.c */ #include <ncurses.h> #include "logger.h" #include "view.h" static WINDOW *log_win; /** Prints the log level and the message */ void l_log(enum LogLevel log_level, char *msg) { char *str_log_level; switch(log_level) /* I'm sorry */ { case DEBUG: str_log_level = "DEBUG"; break; case INFO: str_log_level = "INFO"; break; case WARN: str_log_level = "WARN"; break; case ERROR: str_log_level = "ERROR"; break; default: str_log_level = "UNKOWN"; } v_display_log(str_log_level, msg); }
C
#include <stdio.h> int main() { int a,b,c,i,j,k,l,r,p; int sa,m,d,day,hr,mi,sec; char cd[5],cd2[5],e[4],f[4],g[4],h[4]; scanf("%s %d",&cd ,&a); scanf("%d %s %d %s %d", &l, &e, &c, &f,&d); scanf("%s %d",&cd2 ,&b); scanf("%d %s %d %s %d", &i, &g, &j, &h ,&k); r = (a*24*60*60) + (l*60*60) + (c*60) + d; sa = (b*24*60*60) + (i*60*60) + (j*60) + k; p = sa - r; day = p/86400; hr = (p - (day*86400))/3600; mi = (p - (day*86400) - (hr*3600) )/60; sec = p - (day*86400) - (hr*3600) - (mi*60); printf("%d dia(s)\n",day); printf("%d hora(s)\n",hr); printf("%d minuto(s)\n",mi); printf("%d segundo(s)\n",sec); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <getopt.h> #include <sys/resource.h> #include "entradaSaida.h" Arquivos* argumentosEntrada(int argc, char* argv[]){ Arquivos* arq = malloc(sizeof(Arquivos)); // armazena os ponteiros dos arquivos int opcao; arq->flag = 1; // passados por linha de comando em uma struct if (argc < 5){ fprintf(stderr, "Use: ./tp4 -i [ARQUIVO DE ENTRADA DE DADOS] -o [ARQUIVO DE SAIDA]\n"); arq->flag = 0; return arq; } while((opcao = getopt(argc, argv, "i:o:"))!= -1) { // recebe-se os argumentos por meio // da funcao getopt() switch(opcao) { case 'i': if(!(arq->entrada = fopen(optarg, "r"))) { fprintf(stderr, "Erro na abertura do arquivo.\n"); arq->flag = 0; return arq; } break; case 'o': if(!(arq->saida = fopen(optarg, "w"))) { fprintf(stderr, "Erro na abertura do arquivo.\n"); arq->flag = 0; return arq; } } } return arq; } void contaTempoProcessador(double *utime, double *stime){ struct rusage resources; getrusage(RUSAGE_SELF, &resources); *utime = (double) resources.ru_utime.tv_sec + 1.e-6 * (double) resources.ru_utime.tv_usec; *stime = (double) resources.ru_stime.tv_sec + 1.e-6 * (double) resources.ru_stime.tv_usec; } void calculaTamanhoStrings(int* tamanhoPadrao, int* tamanhoTexto, FILE* arq){ while (fgetc(arq) != '\n') (*tamanhoPadrao)++; while (fgetc(arq) != EOF) (*tamanhoTexto)++; rewind(arq); } char* AlocaString(int tamanho){ char *str = malloc(sizeof(char)*tamanho); return str; } void liberaStrings(char* padrao, char* texto){ free(padrao); free(texto); } int verificaArqVazio(FILE* arq){ int tamanho_arq; fseek (arq, 0, SEEK_END); // aponta para o fim do arquivo com fseek() if((tamanho_arq = ftell (arq)) == 0){ // retorna o valor da posição do ponteiro com ftell() fprintf(stderr, "O arquivo de entrada está vazio!\n"); return 0; } rewind(arq); // retorna o ponteiro para o inicio do arquivo, para os proximos return 1; // procedimentos } void imprimeTempo(double user_time, double system_time, FILE* arq){ fprintf(arq, "Tempo de execução:\n"); fprintf(arq, "%fs (tempo de usuário) + %fs (tempo de sistema) = %fs (tempo total)\n\n", user_time, system_time, user_time+system_time); } void imprimeCasamento(int pos, FILE* arq){ if (pos != 0) fprintf(arq, "Casamento na posicao: %d\n", pos); else fprintf(arq, "Não há casamento.\n"); } void liberaArquivos(Arquivos *arq){ fclose(arq->entrada); fclose(arq->saida); free(arq); }
C
void Index(void) { printf("\n1.Input record\n2.Calculate total and average score of every course\n" "3.Calculate total and average score of every student\n" "4.Sort in descending order by total score of every student\n" "5.Sort in ascending order by total score of every student\n" "6.Sort in ascending order by number\n" "7.Sort in dictionary order by name\n" "8.Search by number\n""9.Search by name\n" "10.Statistic analysis for every course\n11.List record\n" "12.Write to a file\n""13.Read from a file\n""0.Exit\n"); }
C
#include<stdio.h> int main(){ int var= 20; int *ip; *ip = &var; printf("Address of variable var : %p\n", &var); printf("Value stored in pointer *ip : %p\n", ip); printf("Value of *ip variable : %d\n", *ip); return 0; }
C
#include <stdio.h> #include <stdlib.h> /* Structura unei liste simplu inlantuite*/ struct node { int data; struct node *next; } *LLOne, *LLTwo, *unionLL; void initialize(){ LLOne = LLTwo = NULL; } void insert(struct node **head, int num) { /* Se creaza un nou nod */ struct node* newNode = (struct node*) malloc(sizeof(struct node)); newNode->data = num; /* Urmatorul poinet al noului nod */ newNode->next = *head; *head = newNode; } /* Se cauta un element in lista prin traversarea liniara a acesteia de la cap la coada */ int search(struct node *head, int num) { while (head != NULL) { if (head->data == num){ return 1; } head = head->next; } return 0; } /* Returneaza uniunea celor doua liste */ struct node* findunion(struct node *LLOne, struct node *LLTwo) { unionLL = NULL; /* Adauga toate nodurile din prima lista */ struct node *temp = LLOne; while(temp != NULL){ insert(&unionLL, temp->data); temp = temp->next; } /* Se insereaza toata nodurile din a doua lista ce nu se afla in prima*/ while(LLTwo != NULL){ if(!search(LLOne, LLTwo->data)){ insert(&unionLL, LLTwo->data); } LLTwo = LLTwo->next; } return unionLL; } /* Afisarea listei de la cap la coada */ void printLinkedList(struct node *nodePtr) { while (nodePtr != NULL) { printf("%d", nodePtr->data); nodePtr = nodePtr->next; if(nodePtr != NULL) printf("-->"); } } /*Returneaza cel mai mare element*/ int getMaxNode(struct node *stnode){ if(stnode == NULL){ printf(" User message : Invalid Input !!!\n"); return 0; } int max = stnode->data; while(stnode != NULL){ if(stnode->data > max){ max = stnode->data; } stnode = stnode->next; } return max; } /*Returneaza cel mai mic element*/ int getMinNode(struct node *stnode){ if(stnode == NULL){ printf(" User message : Invalid Input !!!\n"); return 0; } int min=stnode->data; while(stnode!=NULL){ if(stnode->data<min){ min=stnode->data; } stnode=stnode->next; } return min; } int main() { int i, LLOneCount, LLTwoCount, temp; initialize(); /*Se creaza prima lista*/ printf("Enter number of nodes in first Linked List\n"); scanf("%d", &LLOneCount); printf("Enter %d integers\n", LLOneCount); for(i=0; i<LLOneCount; i++){ scanf("%d", &temp); insert(&LLOne, temp); } printLinkedList(LLOne); /*Se creaza a doua lista*/ printf("\nEnter number of nodes in second Linked List\n"); scanf("%d", &LLTwoCount); printf("Enter %d integers\n", LLTwoCount); for(i=0; i<LLTwoCount; i++){ scanf("%d", &temp); insert(&LLTwo, temp); } printLinkedList(LLTwo); /* Afisarea uniunii celor doua liste */ findunion(LLOne, LLTwo); printf("\nUnion Linked List\n"); printLinkedList(unionLL); printf("\n"); printf("Biggest element in the union: %d\n",getMaxNode(unionLL)); printf("Smallest element in the union: %d\n",getMinNode(unionLL)); return 0; }
C
#include <stdio.h> #include <stdlib.h> void handler1(void) { printf("Executing exit handler 1\n"); } void handler2(void) { printf("Executing exit handler 2\n"); } int main(void) { atexit(&handler2); atexit(&handler1); printf("Main done!\n"); exit(0); }
C
#include <stdio.h> #include <stdlib.h> int main() { char sex; float height,age,weight; printf("Input sex initial: "); scanf("%c",&sex); printf("\nInput height: "); scanf("%f",&height); printf("\nInput age: "); scanf("%f",&age); weight=50+0.75*(height-150)+(age-20)/4; if(sex=='m' || sex=='M')printf("%f",weight); if(sex=='f' || sex=='F')printf("%f",weight-10); return 0; }
C
#include<stdlib.h> void lost_memory(); int* get_size( int s ); int main(){ lost_memory(); int* i = get_size(4); } void lost_memory(){ int* i = malloc(sizeof(int)); } int* get_size( int s ){ int* i = malloc(sizeof(int)*s); return i; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include "uci.h" #include "search.h" #include "movegen.h" int parseMove(Board* board, char *move_string) { MoveList move_list[1]; generateMoves(board, move_list); int source_square = (move_string[0] - 'a') + (8 - (move_string[1] - '0')) * 8; int target_square = (move_string[2] - 'a') + (8 - (move_string[3] - '0')) * 8; for (int move_count = 0; move_count < move_list->count; move_count++) { int move = move_list->moves[move_count]; if (source_square == getMoveSource(move) && target_square == getMoveTarget(move)) { int promoted_piece = getMovePromoted(move); if (promoted_piece) { if ((promoted_piece == Q || promoted_piece == q) && move_string[4] == 'q') return move; else if ((promoted_piece == R || promoted_piece == r) && move_string[4] == 'r') return move; else if ((promoted_piece == B || promoted_piece == b) && move_string[4] == 'b') return move; else if ((promoted_piece == N || promoted_piece == n) && move_string[4] == 'n') return move; continue; } return move; } } return 0; } void parsePosition(Board* board, char *command) { command += 9; char *current_char = command; if (strncmp(command, "startpos", 8) == 0) parseFen(board, startPosition); else { current_char = strstr(command, "fen"); if (current_char == NULL) parseFen(board, startPosition); else { current_char += 4; parseFen(board, current_char); } } current_char = strstr(command, "moves"); if (current_char != NULL) { current_char += 6; while(*current_char) { int move = parseMove(board, current_char); if (move == 0) break; board->repTable[++board->repIndex] = board->hashKey; makeMove(board, move); while (*current_char && *current_char != ' ') current_char++; current_char++; } } printBoard(board); } void parseGo(Board* board, SearchInfo* info, char *command) { info->quit = 0; info->movestogo = 30; info->movetime = -1; info->time = -1; info->inc = 0; info->starttime = 0; info->stoptime = 0; info->timeset = 0; info->stopped = 0; int depth = -1; char *argument = NULL; if ((argument = strstr(command,"infinite"))) {} if ((argument = strstr(command,"binc")) && board->side == BLACK) info->inc = atoi(argument + 5); if ((argument = strstr(command,"winc")) && board->side == WHITE) info->inc = atoi(argument + 5); if ((argument = strstr(command,"wtime")) && board->side == WHITE) info->time = atoi(argument + 6); if ((argument = strstr(command,"btime")) && board->side == BLACK) info->time = atoi(argument + 6); if ((argument = strstr(command,"movestogo"))) info->movestogo = atoi(argument + 10); if ((argument = strstr(command,"movetime"))) info->movetime = atoi(argument + 9); if ((argument = strstr(command,"depth"))) depth = atoi(argument + 6); if(info->movetime != -1) { info->time = info->movetime; info->movestogo = 1; } info->starttime = getTimeMS(); depth = depth; if(info->time != -1) { info->timeset = 1; info->time /= info->movestogo; if (info->time > 1500) info->time -= 50; info->stoptime = info->starttime + info->time + info->inc; if (info->time < 1500 && info->inc && depth == 64) info->stoptime = info->starttime + info->inc - 50; } if(depth == -1) depth = 64; printf("time: %d start: %u stop: %u depth: %d timeset:%d\n", info->time, info->starttime, info->stoptime, depth, info->timeset); searchPosition(board, info, depth); } void uciLoop(Board* board, SearchInfo* info) { setbuf(stdin, NULL); setbuf(stdout, NULL); char input[2000]; printf("id name Gizmo\n"); printf("id author Lancer\n"); printf("uciok\n"); while (1) { memset(input, 0, sizeof(input)); fflush(stdout); if (!fgets(input, 2000, stdin)) continue; if (input[0] == '\n') continue; if (strncmp(input, "isready", 7) == 0) { printf("readyok\n"); continue; } else if (strncmp(input, "position", 8) == 0) { parsePosition(board, input); clearHashTable(); } else if (strncmp(input, "ucinewgame", 10) == 0) { parsePosition(board, "position startpos"); clearHashTable(); } else if (strncmp(input, "go", 2) == 0) parseGo(board, info, input); else if (strncmp(input, "quit", 4) == 0) break; else if (strncmp(input, "uci", 3) == 0) { printf("id name Gizmo\n"); printf("id author Lancer\n"); printf("uciok\n"); } } } int input_waiting() { #ifndef WIN32 fd_set readfds; struct timeval tv; FD_ZERO (&readfds); FD_SET (fileno(stdin), &readfds); tv.tv_sec=0; tv.tv_usec=0; select(16, &readfds, 0, 0, &tv); return (FD_ISSET(fileno(stdin), &readfds)); #else static int init = 0, pipe; static HANDLE inh; DWORD dw; if (!init) { init = 1; inh = GetStdHandle(STD_INPUT_HANDLE); pipe = !GetConsoleMode(inh, &dw); if (!pipe) { SetConsoleMode(inh, dw & ~(ENABLE_MOUSE_INPUT|ENABLE_WINDOW_INPUT)); FlushConsoleInputBuffer(inh); } } if (pipe) { if (!PeekNamedPipe(inh, NULL, 0, NULL, &dw, NULL)) return 1; return dw; } else { GetNumberOfConsoleInputEvents(inh, &dw); return dw <= 1 ? 0 : dw; } #endif } // read GUI/user input void read_input(Board* board, SearchInfo* info) { int bytes; char input[256] = "", * endc; if (input_waiting()) { info->stopped = 1; do bytes = read(fileno(stdin), input, 256); while (bytes < 0); endc = strchr(input, '\n'); if (endc) *endc = 0; if (strlen(input) > 0) { if (!strncmp(input, "quit", 4)) info->quit = 1; else if (!strncmp(input, "stop", 4)) info->quit = 1; } } } void communicate(Board* board, SearchInfo* info) { if (info->timeset == 1 && getTimeMS() > info->stoptime) { info->stopped = 1; } read_input(board, info); }
C
#pragma once #include <math.h> #include <stdint.h> #include <algorithm> #include <assert.h> __global__ void scan_kernel( const unsigned int num_samples_per_thread, const unsigned int *const bin_count, unsigned int *const prefix_idx, unsigned int *const block_sum) { const unsigned int tid = (blockIdx.x*blockDim.x) + threadIdx.x; const unsigned int tid_offset = tid*num_samples_per_thread; unsigned int prefix_sum; if (tid == 0) prefix_sum = 0; else prefix_sum = bin_count[tid_offset-1]; for (unsigned int i = 0; i < num_samples_per_thread; i++) { prefix_idx[i+tid_offset] = prefix_sum; prefix_sum += bin_count[i+tid_offset]; } // store the block prefixsum as the value from the last element block_sum[tid] = prefix_idx[(num_samples_per_thread-1) + tid_offset]; } __global__ void add_scan_total_kernel( unsigned int *const prefix_idx, const unsigned int *const total_count) { const unsigned int tid = (blockIdx.x * blockDim.x) + threadIdx.x; prefix_idx[tid] += total_count[blockIdx.x]; } __global__ void scan_kernel_single( const unsigned int num_sample, const unsigned int *const bin_count, unsigned int *const dest_bin_idx) { unsigned int prefix_sum = 0; for (unsigned int i = 0; i < num_sample; i++) { dest_bin_idx[i] = prefix_sum; prefix_sum += bin_count[i]; } }
C
/* * Preparation for lecture. * Rewrote the code in the lecture video to get a better understanding of it. */ #include <stdio.h> int main(void) { /* Initialization of variable */ int grade; printf("Please enter the danish grade to be translated: "); scanf("%d", &grade); printf("The corresponding ECTS grade is: "); /* Switch */ switch (grade) { case 12: printf("A"); break; case 10: printf("B"); break; case 7: printf("C"); break; case 4: printf("D"); break; case 2: printf("E"); break; case 0: printf("Fx"); break; case -3: printf("F"); break; default: printf("Please input a correct Danish 7 step grade."); break; } printf("\n"); return 0; }
C
#include <stdio.h> #include <pthread.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> typedef struct Goods { int data; struct Good *next; } Goods; Goods *head = NULL; pthread_mutex_t headlock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t hasgood = PTHREAD_COND_INITIALIZER; void *producer(void *arg) { Goods *ng; while (1) { ng=(Goods *)malloc(sizeof(Goods)); ng->data=rand()%100; pthread_mutex_lock(&headlock); ng->next = head; head = ng; pthread_mutex_unlock(&headlock); pthread_cond_signal(&hasgood); printf("producer %d\n", ng->data); sleep(rand()%3); } return 0; } void *consumer(void *arg) { Goods *k; while (1) { pthread_mutex_lock(&headlock); if(!head) { pthread_cond_wait(&hasgood, &headlock); } k=head; head=head->next; pthread_mutex_unlock(&headlock); printf("consumer %d\n", k->data); free(k); sleep(rand()%3); } return 0; } int main() { pthread_t ptid, ctid; pthread_create(&ptid, NULL, producer, NULL); pthread_create(&ctid, NULL, consumer, NULL); pthread_join(ptid, NULL); pthread_join(ctid, NULL); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> typedef unsigned char u8; /* Board Width */ static const u8 BOARDWIDTH = 10; #define SQR(x) ((x) * (x)) /* Symbol Definition */ static const char BOAT_SYM = 'b'; static const char HIT_SYM = 'x'; static const char MISS_SYM = '0'; static const char WATER_SYM = '.'; /* Rendering */ void draw_screen(u8 *player, u8 *enemy); void draw_seperator(u8 length); void draw_board(u8 *buf); void clear_screen(); #define TABLE_ALL (0xFF) #define TABLE_CARRIER (0x1 << 0) #define TABLE_BATTLESHIP (0x1 << 1) #define TABLE_CRUISER (0x1 << 2) #define TABLE_SUBMARINE (0x1 << 3) #define TABLE_DESTROYER (0x1 << 4) void draw_boat_table(u8 ships); /* Boad Setup */ void create_board(u8 *buf); void pick_positions(u8 *buf); int place_boat(u8 *buf, u8 id, char row, u8 col, char dir); int main(int argc, char* argv[]) { /* Create and initialise player board */ u8 player[SQR(BOARDWIDTH)]; create_board(player); /* Create and initialise enemy board */ u8 enemy[SQR(BOARDWIDTH)]; create_board(enemy); /* Display game screen*/ draw_screen(player, enemy); /* Select positions */ pick_positions(player); return 0; } /* Initialise a given board to be empty, full of water */ void create_board(u8 *buf) { memset(buf, WATER_SYM, SQR(BOARDWIDTH)); } void pick_positions(u8 *buf) { u8 picking_positions = TABLE_ALL; while (picking_positions) { //clear_screen(); draw_board(buf); draw_boat_table(picking_positions); printf("Please input a position to place a boat in the format of \ <id><coordinate><direction> e.g. 1A3D for a Carrier \ starting at A3 facing downward.\n> "); char row, dir; u8 id, col; scanf("%hhd%c%hhd%c", &id, &row, &col, &dir); /* Place boat */ place_boat(buf, id, row, col, dir); } } /* Abstraction for drawing both the players and enemies * boards with a seperator. Enemy board is displayed first. */ void draw_screen(u8 *player, u8 *enemy) { clear_screen(); draw_board(enemy); draw_seperator(BOARDWIDTH * 2 + 2); draw_board(player); } /* Draws a line of `=` of given length */ void draw_seperator(u8 length) { while ((length--) > 0) { printf("="); } printf("\n"); } /* Draws a given board with the coordinates displayed * on top and on the sides, with letters for the vertical * axis. */ void draw_board(u8 *buf) { for (u8 y = 0; y <= BOARDWIDTH; ++y) { /* Write verticle axis coordinates*/ if (!y) printf(" "); else printf("%c ", 65 + (y - 1)); /* Draw Row */ for (u8 x = 0; x < BOARDWIDTH; ++x) { /* If top row, draw horizontal axis coordinates*/ if (!y) printf("%d ", x + 1); else printf("%c ", buf[(y - 1) * BOARDWIDTH + x]); } printf("\n"); } } void draw_boat_table(u8 ships) { printf("| Number | Boat | Size |\n"); printf("| ------ | ---------- | ---- |\n"); /* Print Carrier State*/ if (ships | TABLE_CARRIER) printf("| 1 | Carrier | 5 |\n"); else printf("| 1 | \e[9mCarrier\e[0m | 5 |\n"); /* Print Battleship State*/ if (ships | TABLE_BATTLESHIP) printf("| 2 | Battleship | 4 |\n"); else printf("| 2 | \e[9mBattleship\e[9m | 4 |\n"); /* Print Cruiser State*/ if (ships | TABLE_CRUISER) printf("| 3 | Cruiser | 3 |\n"); else printf("| 3 | \e[9mCruiser\e[0m | 3 |\n"); /* Print Submarine State*/ if (ships | TABLE_SUBMARINE) printf("| 4 | Submarine | 3 |\n"); else printf("| 4 | \e[9mSubmarine\e[0m | 3 |\n"); /* Print Destroyer State*/ if (ships | TABLE_DESTROYER) printf("| 5 | Destroyer | 2 |\n"); else printf("| 5 | \e[9mDestroyer\e[0m | 2 |\n"); } void clear_screen() { printf("\e[1;1H\e[2J"); } int place_boat(u8 *buf, u8 id, char row, u8 col, char dir) { if (id == 0 || id > 5) return 1; /* Invalid Boat */ if (row - 65 < 0 || row - 65 >= BOARDWIDTH) return 1; /* Invalid Row */ if (col > BOARDWIDTH >= BOARDWIDTH) return 1; /* Invalid Col */ if (dir != 'D' && dir != 'R') return 1; /* Invalid Direction*/ const u8 lengths[] = { 5, 4, 3, 3, 2 }; u8 len = lengths[id - 1]; u8 x = col - 1, y = row - 65; if (dir == 'D' && y + len >= BOARDWIDTH) return 1; /* Out of bounds */ if (dir == 'R' && x + len >= BOARDWIDTH) return 1; /* Out of bounds */ /* Draw downwards or right */ u8 index = 0; for (u8 i = 0; i < len; ++i) { index = (dir == 'D') ? (y + i) * BOARDWIDTH + x : y * BOARDWIDTH + (x + i); buf[index] = BOAT_SYM; } return 0; }
C
#include "main.h" /* To save battery, this firmare is always racing to sleep. On an interrupt (button press or timeout), the ARM core executes the small routine associated with the current mode and interrupt source then goes back to sleep. */ static MachineState state; #ifdef ENABLE_SERIAL_DGB char DBG_BUFFER[50]; #endif const uint16 tones[5] = { 1234, // Red 400, // Green 600, // Blue 800, // Yellow 0 // NoColor }; void errorExit(uint8 count, Color color) { DBG("EXITING BECAUSE OF ERROR: %d %d\n", count, color); // Display error code for (uint32 i = 0; i < count; i++) { setLed(color, 0); CyDelay(400); setLed(color, 1); CyDelay(200); } powerOff(); } int main(void) { setupPeripherals(); if (!isBatteryGood()) { //errorExit(Yellow, 2); } DBG("\n\nStarting Serial Debug.\n"); setupInterrupts(); setMode(Menu); setTimeout(1000); for(;;) { DBG("Sleeping...\n"); STATUS(0); CySysPmSleep(); } } // Executed on every button press by the ISR void dispatchButtonPressed(Color color) { uint8 s = CyEnterCriticalSection(); STATUS(1); seedColors(state.nbRounds, state.colors); if (switchDebounce(color)) { DBG("Button press: %d\n", color); switch (state.mode) { case Menu: Menu_buttonPressed(color, &state); break; case Playback: Playback_buttonPressed(color, &state); break; case Listening: Listening_buttonPressed(color, &state); break; case Ending: Ending_buttonPressed(color, &state); break; } } CyExitCriticalSection(s); } // Executed on main timer timeout void dispatchTimeout() { uint8 s = CyEnterCriticalSection(); seedColors(state.nbRounds, state.colors); STATUS(1); DBG("Woken up from main timer.\n"); switch (state.mode) { case Menu: Menu_timeout(&state); break; case Playback: Playback_timeout(&state); break; case Listening: Listening_timeout(&state); break; case Ending: Ending_timeout(&state); break; } CyExitCriticalSection(s); } void setMode(Mode mode) { DBG("Setting mode to %d\n", mode); state.mode = mode; state.currentRound = 0; setTimeout(1); }
C
#include <assert.h> #include <ctype.h> #include <limits.h> #include <math.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <stdlib.h> #include <string.h> char* readline(); char* ltrim(char*); char* rtrim(char*); char** split_string(char*); int parse_int(char*); /* * Complete the 'twoPluses' function below. * * The function is expected to return an INTEGER. * The function accepts STRING_ARRAY grid as parameter. */ typedef struct NODE { int x; int count; int r; int c; struct NODE* next; }NODE; NODE* node = NULL; int LIMIT = 1; int checkpluses(char**, int, int, int, int, int, int); NODE* add_to_node(int, int, int, int, NODE*); void isort_llist_desc(NODE*); void markpluses(NODE*, char**); int check_pluses(int, int, char**, int); void free_node(NODE*); int allpluses(int, char**, int); int twoPluses(int grid_count, char** grid) { int max = allpluses(grid_count, grid, 0); int limit = LIMIT - 4, temp; while(limit > 0) { temp = allpluses(grid_count, grid, limit); if (temp > max) max = temp; limit = limit - 4; } free_node(node); node = NULL; return max; } int allpluses(int grid_count, char**grid, int limit) { int rows = grid_count, max = 0, temp; int columns = strlen(grid[0]); for (int r = 1; r < rows; r++) for (int c = 1; c < columns; c++) if (grid[r][c] == 'G') checkpluses(grid, rows, columns, r, c, 1, limit); if (node) { isort_llist_desc(node); NODE* n = NULL; for (n = node; n != NULL; n = (*n).next) { markpluses(n, grid); temp = check_pluses(rows, columns, grid, limit); temp = temp * ((*n).count); if (max <= temp) max = temp; markpluses(n, grid); } LIMIT = (*node).count; } if (max == 0) return 1; else return max; } int checkpluses(char** grid, int rows, int columns, int r, int c, int check, int limit) { int x = 1, count = 1; while(((c+x) < columns) && ((c-x) >= 0) && ((r+x) < rows) && ((r-x) >= 0)) { if (grid[r+x][c] == 'B' || grid[r-x][c] == 'B' || grid[r][c+x] == 'B' || grid[r][c-x] == 'B') break; else count += 4; x++; if (count == limit) break; } if (count > 1 && check) node = add_to_node(x, count, r, c, node); return count; } int check_pluses(int rows, int columns, char** grid, int limit) { int max = 0, x; for (int r = 1; r < rows; r++) for (int c = 1; c < columns; c++) if (grid[r][c] == 'G') { x = checkpluses(grid, rows, columns, r, c, 0, limit); if (max < x) max = x; } return max; } NODE* add_to_node(int x, int count, int r, int c, NODE* head) { NODE* n = malloc(sizeof(NODE)); (*n).c = c; (*n).x = x; (*n).count = count; (*n).r = r; if (head == NULL) (*n).next = NULL; else (*n).next = head; return n; } void isort_llist_desc(NODE* head) { if (!head || (*head).next == NULL) return; NODE* c, *d; int temp_c, temp_x, temp_r, temp_count; for (c = head; c != NULL; c = (*c).next) { for (d = (*c).next; d != NULL; d = (*d).next) { if ((*c).count < (*d).count) { temp_c = (*c).c; temp_count = (*c).count; temp_r = (*c).r; temp_x = (*c).x; (*c).count = (*d).count; (*c).x = (*d).x; (*c).r = (*d).r; (*c).c = (*d).c; (*d).x = temp_x; (*d).count = temp_count; (*d).r = temp_r; (*d).c = temp_c; } } } return; } void markpluses(NODE* head, char** grid) { int row = (*head).r; int column = (*head).c; for (int c = 1; c < (*head).x; c++) { if (grid[row+c][column] == 'G') grid[row+c][column] = 'B'; else grid[row+c][column] = 'G'; if (grid[row-c][column] == 'G') grid[row-c][column] = 'B'; else grid[row-c][column] = 'G'; if (grid[row][column+c] == 'G') grid[row][column+c] = 'B'; else grid[row][column+c] = 'G'; if (grid[row][column-c] == 'G') grid[row][column-c] = 'B'; else grid[row][column-c] = 'G'; } if (grid[row][column] == 'G') grid[row][column] = 'B'; else grid[row][column] = 'G'; return; } void free_node(NODE* head) { NODE* temp; while(head) { temp = head; head = (*head).next; free(temp); } return; } int main() { FILE* fptr = fopen(getenv("OUTPUT_PATH"), "w"); char** first_multiple_input = split_string(rtrim(readline())); int n = parse_int(*(first_multiple_input + 0)); int m = parse_int(*(first_multiple_input + 1)); char** grid = malloc(n * sizeof(char*)); for (int i = 0; i < n; i++) { char* grid_item = readline(); *(grid + i) = grid_item; } int result = twoPluses(n, grid); fprintf(fptr, "%d\n", result); fclose(fptr); return 0; } char* readline() { size_t alloc_length = 1024; size_t data_length = 0; char* data = malloc(alloc_length); while (true) { char* cursor = data + data_length; char* line = fgets(cursor, alloc_length - data_length, stdin); if (!line) { break; } data_length += strlen(cursor); if (data_length < alloc_length - 1 || data[data_length - 1] == '\n') { break; } alloc_length <<= 1; data = realloc(data, alloc_length); if (!data) { data = '\0'; break; } } if (data[data_length - 1] == '\n') { data[data_length - 1] = '\0'; data = realloc(data, data_length); if (!data) { data = '\0'; } } else { data = realloc(data, data_length + 1); if (!data) { data = '\0'; } else { data[data_length] = '\0'; } } return data; } char* ltrim(char* str) { if (!str) { return '\0'; } if (!*str) { return str; } while (*str != '\0' && isspace(*str)) { str++; } return str; } char* rtrim(char* str) { if (!str) { return '\0'; } if (!*str) { return str; } char* end = str + strlen(str) - 1; while (end >= str && isspace(*end)) { end--; } *(end + 1) = '\0'; return str; } char** split_string(char* str) { char** splits = NULL; char* token = strtok(str, " "); int spaces = 0; while (token) { splits = realloc(splits, sizeof(char*) * ++spaces); if (!splits) { return splits; } splits[spaces - 1] = token; token = strtok(NULL, " "); } return splits; } int parse_int(char* str) { char* endptr; int value = strtol(str, &endptr, 10); if (endptr == str || *endptr != '\0') { exit(EXIT_FAILURE); } return value; }
C
#include <avr/pgmspace.h> #include <avr/eeprom.h> #include <avr/io.h> // PORTC #include <util/crc16.h> #include <stdio.h> // sprintf_P #include <stdlib.h> // strtol #include <errno.h> // errno #include <limits.h> // LONG_MIN #include <ctype.h> // isalnum #include <string.h> // strlen #include "setup.h" #include "usart.h" #define EEPROM_START_ADDRESS ((uint8_t*)(8)) /*****************************************************************************/ void setup_send( const char* s) { for (; *s != 0; ++s) { uart3_PutChar(*s); } } /*****************************************************************************/ void setup_send_P( PGM_P s) { PORTC = PORTC ^ 0x40; for (;;) { const char c = pgm_read_byte(s++); if (c==0) { break; } setup_send_char(c); } } /*****************************************************************************/ static uint8_t hexchar_of_int( const uint8_t ii) { return ii<10 ? ii + '0' : ii + 'A' - 10; } /*****************************************************************************/ void setup_send_hex( const uint8_t x) { setup_send_char(hexchar_of_int(x>>4)); setup_send_char(hexchar_of_int(x&0x0F)); } /*****************************************************************************/ void setup_send_newline() { setup_send_P(PSTR("\r\n")); } /*****************************************************************************/ void setup_send_integer( PGM_P name, const int32_t i, PGM_P unit) { char xbuf[14]; setup_send_P(name); setup_send_P(PSTR(" = ")); sprintf_P(xbuf, PSTR("%ld"), i); setup_send(xbuf); setup_send_P(unit); setup_send_newline(); } /*****************************************************************************/ void setup_send_integer_x10( PGM_P name, const int32_t i, PGM_P unit) { const int32_t i_mod = i % 10; char xbuf[20]; setup_send_P(name); setup_send_P(PSTR(" = ")); sprintf_P(xbuf, PSTR("%ld.%ld"), i/10, (i_mod<0 ? -i_mod : i_mod)); setup_send(xbuf); setup_send_P(unit); setup_send_newline(); } /*****************************************************************************/ void setup_send_boolean( PGM_P name, const bool b) { setup_send_P(name); setup_send_P(PSTR(" = ")); if (b) { setup_send_P(PSTR("true")); } else { setup_send_P(PSTR("false")); } setup_send_newline(); } /*****************************************************************************/ void setup_send_string( PGM_P name, const char* s) { setup_send_P(name); setup_send_P(PSTR(" = ")); setup_send(s); setup_send_newline(); } /*****************************************************************************/ uint8_t setup_crc(const SETUP* setup) { uint8_t r = 0; uint8_t i; for (i=0; i<sizeof(*setup); ++i) { r = _crc_ibutton_update(r, ((const uint8_t*)setup)[i]); } return r; } /*****************************************************************************/ static void setup_print(const SETUP* setup) { setup_send_P( PSTR("N NAME VALUE\r\n")); setup_send_integer_x10(PSTR("0: Compass offset"), setup->compass_offset_x10, PSTR(" deg.")); setup_send_P(PSTR("Set new values as follows: N VALUE\r\n")); setup_send_P(PSTR("For example, set offset 3.3deg with the following command:\r\n")); setup_send_P(PSTR("0 33")); } /*****************************************************************************/ bool setup_load_from_nvram(SETUP* setup) { // 1. Read from eeprom. const uint8_t crc2 = eeprom_read_byte((uint8_t*)(EEPROM_START_ADDRESS)); eeprom_read_block( (uint8_t*)(setup), (void*)(EEPROM_START_ADDRESS+1), sizeof(*setup)); // 2. Check CRC. if (setup_crc(setup) == crc2) { setup_print(setup); return true; } else { setup->compass_offset_x10 = 0; setup_print(setup); return false; } } /*****************************************************************************/ void setup_store_to_nvram(const SETUP* setup) { // 2. Write to the eeprom. eeprom_write_byte(((uint8_t*)(EEPROM_START_ADDRESS)), setup_crc(setup)); eeprom_write_block( (const uint8_t*)(setup), (void*)(EEPROM_START_ADDRESS+1), sizeof(*setup)); } /*****************************************************************************/ static int32_t parse_integer_in_range( char* s, const int32_t min_value, const int32_t max_value, const int32_t old_value, PGM_P name, PGM_P unit) { char xbuf[128]; int32_t new_value; char* endptr = s; errno = 0; new_value = strtol(s, &endptr, 10); if (errno==0 && endptr!=s) { if (new_value >= min_value && new_value<=max_value) { setup_send_P(name); sprintf_P(xbuf, PSTR(" is now %ld"), new_value); setup_send(xbuf); setup_send_char(' '); setup_send_P(unit); setup_send_P(PSTR(".\r\n")); return new_value; } else { setup_send_P(name); sprintf_P(xbuf, PSTR(" %ld"), new_value); setup_send(xbuf); sprintf_P(xbuf, PSTR(" is out of the range %ld .. %ld \r\n"), min_value, max_value); setup_send(xbuf); return old_value; } } else { setup_send_P(PSTR("Invalid integer specified.\r\n")); return old_value; } } /*****************************************************************************/ static unsigned int input_length = 0; static char input_buffer[64]; void setup_handle_input( const char c, SETUP* setup) { if (c == '\r') { setup_send_char('\n'); input_buffer[input_length] = 0; // Look what we've got. if (input_length>0) { const char cmd = input_buffer[0]; if (cmd == '?') { setup_print(setup); } else if (input_length>2) { switch (cmd) { case '0': setup->compass_offset_x10 = parse_integer_in_range( input_buffer + 2, -3600, 3600, setup->compass_offset_x10, PSTR("Compass offset"), PSTR("x 0.1deg")); setup_store_to_nvram(setup); break; } } } // Print prompt. setup_send_P(PSTR("\r\n>")); input_length = 0; } else if (c == 0x08) { // it is nice to handle backspace. if (input_length>0) { --input_length; } } else if (c!='\r' && c!='\n') { if (input_length+1<sizeof(input_buffer)) { input_buffer[input_length] = c; ++input_length; } else { input_length = 0; } } }
C
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct ThreadArg_tag { int i; char* fileName; } ThreadArg; void* doWork(ThreadArg* arg) { free(arg->fileName); free(arg); return NULL; } void readString(char* buf,size_t sz) { char* end = buf + sz; char ch; while((ch=getchar()) != EOF && ch != '\n' && buf < end) *buf++ = ch; *buf = 0; } int main(int argc,char* argv[]) { int i; int nbThreads = atoi(argv[1]); char buf[128]; pthread_t minion[nbThreads]; for(i=0;i < nbThreads;i++) { printf("give a filename: "); readString(buf,sizeof(buf)-1); printf("Got [%s]\n",buf); ThreadArg* arg = calloc(1, sizeof(ThreadArg)); arg->i = i; arg->fileName = calloc(128, sizeof(char)); strncpy(arg->fileName,buf,sizeof(buf)-1); pthread_create(minion+i,NULL,(void*(*)(void*))doWork,arg); } for(i=0;i < nbThreads;i++) pthread_join(minion[i],NULL); return 0; }
C
#include <stdio.h> #include "LibFS.h" void usage(char *prog) { fprintf(stderr, "usage: %s <disk image file>\n", prog); exit(1); } int main(int argc, char *argv[]) { if (argc != 2) { usage(argv[0]); } char *path = argv[1]; FS_Boot(path); FS_Sync(); char buffer[100]; Dir_Create("/a"); Dir_Create("/b"); File_Create("/abc.txt"); int x = File_Open("/abc.txt"); File_Write(x, "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ip", 570); File_Write(x, "abcdefghijklmnopqrst", 20); File_Seek(x,6); int y = File_Read(x, buffer, 590); print_bitmaps(); printf("\n%d\n", y); return 0; }
C
#include "lists.h" dlistint_t *ad_node(const int n, dlistint_t *next, dlistint_t *prev); /** * insert_dnodeint_at_index - insert a node at given index * @h: header of double linked list * @idx: index to insert the node * @n: int data to insert * Return: size of the printed double list */ dlistint_t *insert_dnodeint_at_index(dlistint_t **h, unsigned int idx, int n) { unsigned int i = 0; dlistint_t *new_node = NULL; void *init_value; if (h == NULL) return (NULL); if ((*h) == NULL && idx == 0) return (add_dnodeint(h, n)); else if (*h == NULL) return (NULL); while ((*h)->prev != NULL)/*check start of list*/ { (*h) = (*h)->prev; } init_value = *h; for (i = 0; (*h) != NULL; i++) { if (idx == i) break; (*h) = (*h)->next; } if (idx == i && *h == NULL) { (*h) = init_value; return (add_dnodeint_end(h, n)); } if (*h == NULL) { (*h) = init_value; return (NULL); } new_node = ad_node(n, (*h), (*h)->prev); if ((*h)->prev != NULL) (*h)->prev->next = new_node; (*h)->prev = new_node; while ((*h)->prev != NULL)/*check start of list*/ (*h) = (*h)->prev; return (new_node); } /** * ad_node - creates a new node * @n: data for the new node * @next: struct next address position * @prev: struct prev address position * Return: pointer to the new node */ dlistint_t *ad_node(const int n, dlistint_t *next, dlistint_t *prev) { dlistint_t *new_node = NULL; new_node = malloc(sizeof(dlistint_t)); if (new_node == NULL) return (NULL); new_node->prev = prev; new_node->n = n; new_node->next = next; return (new_node); }
C
#include<stdio.h> #include<string.h> int main() { char str_1[10],str_2[10]; int i,n,tot=0,j,sum,num,a,t,on; scanf("%d",&t); getchar(); while(t--){ gets(str_1); if(strcmp(str_1,"report")==0){on=1;} else{ n=strlen(str_1); printf("n--%d\n",n); sum=0; a=1; for(i=n-1;i>=7;i--) { printf("%c\n",str_1[i]); num = str_1[i]-'0'; printf("num--%d\n",num); sum=sum + num*a; a=a*10; } printf("%d\n",sum); if(on){ printf("tot=%d\n",tot); } else {} } } return 0; }
C
// This is just a mock server that I will create on the local network, just to test the actual client server that I must make #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <string.h> #define bufsize 1024 #define RECVDMSG "Received Message" int main(){ // variables int sock, rval, port, mysock; struct sockaddr_in server; char buf[bufsize]; port = 5000; // create socket sock = socket(AF_INET, SOCK_STREAM, 0); if (sock < 0){ perror("Error creating socket\n"); return(-1); } server.sin_family = AF_INET; server.sin_port = htons(port); inet_aton("127.0.0.1", &server.sin_addr.s_addr); // bind the socket if (bind(sock, (struct sockaddr *)&server, sizeof(server))){ perror("Error binding the socket\n"); return(-1); } // listen for socket(s) listen(sock, 5); // upto 5 connections // to have multiple sockets, we will need to create an array of sockets int sockets[5]; // accept a connection mysock = accept(sock, (struct sockaddr *) 0, 0); if (mysock < 0){ perror("ERROR: connecting the sock\n"); return(-1); } // read a message from the socket bzero(buf, bufsize+1); rval = read(mysock, buf, bufsize); if (rval < 0){ perror("ERROR: reading from socket\n"); return(-1); } // now we have the message, display on the server printf("Received MSG: %s\n",buf); // return an acknowledgement to the socket rval = write(mysock, RECVDMSG, sizeof(RECVDMSG)); if (rval < 0){ perror("ERROR: writing to socket\n"); return(-1); } // exit and close sock close(sock); return(0); }
C
#include <stdio.h> #include <stdlib.h> #include "getEntries.c" char chaine[MAX_SIZE]; typedef struct cellule { int id; struct cellule *suivant; }; void desallocation(struct cellule *cellule, int i); void affichage(struct cellule *cellule, int i); void creation(struct cellule *cellule, int i); int main() { int i; struct cellule cellule; i=0; creation(&cellule,i); i=0; affichage(&cellule,i); i =0; desallocation(&cellule,i); } void affichage(struct cellule *cellule, int i) { if(i<10) { printf("%d ",cellule->id); affichage(cellule->suivant,i+1); } else { printf("\n"); printf("Fin\n"); } } void creation(struct cellule *cellule, int i) { int entier; if(i<10) { printf("Rentrez un entier : "); entier=(int)getNumber(chaine); cellule->id=entier; cellule->suivant=(struct cellule *)malloc(sizeof(struct cellule)); creation(cellule->suivant,i+1); } } void desallocation(struct cellule *cellule, int i) { if(i<10) { free(cellule->suivant); desallocation(cellule->suivant,i+1); } }
C
#include "holberton.h" /** *reverse_array - reverse a array of the integers *@a: Parameter *@n: legenth of array *Return: Always void */ void reverse_array(int *a, int n) { int *start, *end, c, i, j; start = a; end = a; j = n - 1; for (i = 0; i < n / 2; i++) { c = start[i]; start[i] = end[j]; end[j] = c; j--; } }
C
#include <stdio.h> #include <stdlib.h> #include "TAD_BufferSaida.h" #include "big_file.h" //Cria buffer saida e seta seus valores BUFFER* BufferSaida_Criar(int n_reg_b_s) { BUFFER* buffer = malloc(sizeof(BUFFER)); ITEM_VENDA* iv = malloc(sizeof(ITEM_VENDA) * n_reg_b_s); for(int i = 0; i < n_reg_b_s; i++){ iv[i].id = 0; iv[i].id_venda = 0; iv[i].desconto = 0; iv[i].data = 0; iv[i].obs[0] = '\0'; } buffer->n_reg_max = n_reg_b_s; buffer->iv = iv; buffer->bloco = 0; buffer->ocupado = 0; buffer->buffer_pk = "saida.dat"; return buffer; } void BufferSaida_Inserir(BUFFER* buffer, ITEM_VENDA iv_saida){ buffer->iv[buffer->ocupado+1] = iv_saida; buffer->ocupado++; } //Joga no arquivo saido o buffer void BufferSaida_Despejar(BUFFER* buffer, int *flag){ FILE* arq = fopen(buffer->buffer_pk, "wb"); fseek(arq, buffer->bloco*sizeof(ITEM_VENDA)*buffer->n_reg_max, SEEK_SET); if(buffer->ocupado < buffer->n_reg_max){ fwrite(buffer->iv, sizeof(ITEM_VENDA), buffer->ocupado, arq); *flag = 1; } else fwrite(buffer->iv, sizeof(ITEM_VENDA), buffer->n_reg_max, arq); buffer->bloco++; buffer->ocupado = 0; fclose(arq); } void BufferSaida_Destruir(BUFFER* buffer){ free(buffer->iv); free(buffer); }
C
#include <stdio.h> int main() { int x[5] = {1,200,3,4,5}; int *ptrX = &x[0]; *(ptrX+2) = 300; printf("x[0]: %d\n", *(ptrX) ); printf("x[1]: %d\n", *(ptrX+1) ); printf("x[2]: %d\n", *(ptrX+2) ); printf("x[3]: %d\n", *(ptrX+3) ); printf("x[4]: %d\n", *(ptrX+4) ); return 0; }
C
/* * queue.h * * Created on: May 30, 2018 * Author: houxd */ #ifndef QUEUE_H_ #define QUEUE_H_ #include "rtos_wrapper.h" struct Queue_t { uint32_t item_size; uint8_t *buffer_beg; uint8_t *buffer_end; uint8_t *head; uint8_t *tail; int empty; }; /** * @param buffer queue data buffer, the size must be equals param buffersize * @param buffersize equals with param buffer size * @param itemsize ensure buffersize%itemsize=0. the item count calc from * buffersize/itemsize. */ extern void queue_create(struct Queue_t* q, void *buffer, uint32_t buffer_size, uint32_t item_size); /** * @param pdat the item structure instance pointer that want push to it. * @return 0 is success, -1 is full queue. */ extern int queue_push(struct Queue_t* q, const void *pdat); extern int queue_pop(struct Queue_t* q, void *pdat); extern void queue_reset(struct Queue_t* q); extern uint32_t queue_size(struct Queue_t* q); #endif /* QUEUE_H_ */
C
#ifndef BINTREE_H #define BINTREE_H typedef struct Tnode { char *word; int cnt; struct Tnode *left; struct Tnode *right; } Tnode; // when 'word' not in tree, add a 'word' node // else, ++cnt of the node Tnode *addtree(Tnode *pn, char *word); Tnode *freetree(Tnode *pn); void printtree(Tnode *pn); // see words with the same first n char as a group void printgroup(Tnode *pn, int n); #endif
C
#include<stdio.h> int gre(int a); int gre(int a) { int b[10],i,l; printf("Enter the elements"); for(i=0;i<a;i++) { scanf("%d",&b[i]); } l=b[0]; for(i=1;i<a;i++) { if(l<b[i]) { l=b[i]; } } return l; } void main() { int x,y; printf("Enter the limit"); scanf("%d",&x); y=gre(x); printf("largest %d",y); }
C
#include <msp430g2553.h> int main(void) { WDTCTL = WDTPW + WDTHOLD; //Disable the Watchdog timer for our convenience. P1DIR |= BIT2; //Set pin 1.2 to the output direction. P1SEL |= BIT2;//Select pin 1.2 as our PWM output. P1REN |= BIT3;//enable pull up/down reg P1OUT |= BIT3;//p1.3 is set as output P1IE |= BIT3; // interrupt enable on p1.3 PWM(130,60); //Give input PWM(frequency,pulse_width) TA0CTL = TASSEL_2 + MC_1; //TASSEL_2 selects SMCLK as the clock source, and MC_1 tells it to count up to the value in TA0CCR0. __enable_interrupt(); __bis_SR_register(LPM0_bits); //Switch to low power mode 0. while(1) { } } // Port 1 interrupt service routine #pragma vector=PORT1_VECTOR __interrupt void Port_1(void) { __delay_cycles(500000); P1SEL &= ~BIT2; //turn off p1.2 P1IFG &= ~BIT3; //clear interrupt flag on p1.3 } void PWM(int f,int PW) { TA0CCR0 = 1000000 / f; //Set the period in the Timer A0 Capture/Compare 0 register to given frequency value. TA0CCTL1 = OUTMOD_7;/* PWM output mode: 7 - PWM reset/set */ TA0CCR1 = PW; //The period in microseconds that the power is ON. }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* bitwise.h :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ukelly <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/13 18:50:08 by ukelly #+# #+# */ /* Updated: 2021/03/13 18:50:10 by ukelly ### ########.fr */ /* */ /* ************************************************************************** */ #ifndef BITWISE_H # define BITWISE_H # include <stddef.h> /* ** @defgroup bitwise Bitwise ** @brief Bits manipulation functions ** @details bitwise desc here!//FIXME ** @{ */ /* ** @file operations.c */ size_t and(size_t x, size_t y); size_t or(size_t x, size_t y); size_t xor(size_t x, size_t y); size_t not(size_t x); /* ** @file shift.c */ size_t rshift(size_t x, size_t shift); size_t lshift(size_t x, size_t shift); size_t circular_lshift(size_t x, size_t shift); size_t circular_rshift(size_t x, size_t shift); /* ** @file hasbyte.c */ int has_zero_byte(size_t word); int has_byte(size_t word, unsigned char byte); int has_byte_more(size_t word, unsigned char byte); int has_byte_less(size_t word, unsigned char byte); /* ** @file mask.c */ size_t get_mask(unsigned char masked); /* ** }@ */ #endif
C
#include <stdio.h> int main(void) { int no,rem,count=0; printf("enter the number"); scanf("%d",&no); while(no!=0) { rem=no%10; count++; no=no/10; } printf("the number of digits in a number is %d",count); return 0; }
C
#include <stdio.h> #define square(x) ((x)*(x)) int main() { int n; printf("enter a number between 1 and 7\n"); scanf("%d", &n); switch(n) { case 1: printf("Sunday\n"); break; case 2: printf("Monnday\n"); break; case 3: printf("Tuesday\n"); break; case 4: printf("Wednesday\n"); break; case 5: printf("Thursday\n"); break; case 6: printf("Friday\n"); break; case 7: printf("Saturday\n"); break; default: printf("wrong number\n"); break; } return 0; }
C
/* ----------- * project2.c * Project for CSCI 2021, Fall 2018, Professor Chris Dovolis * Written by Ry Wiese * This program will get the interger value from the user then change to the binary version and store it. * operate a variety of bitwise operations such as add, subtraction, and, or, not, left shift, and right shift. * Kyeongtak Han * x500: han00127 * ---------- */ #include <stdio.h> #include <stdlib.h> #define LEN 16 typedef char* reg; void add(reg reg1, reg reg2, reg result_reg); void subtract(reg reg1, reg reg2, reg result_reg); void and(reg reg1, reg reg2, reg result_reg); void or(reg reg1, reg reg2, reg result_reg); void not(reg reg1, reg result_reg); void logical_left_shift(reg reg1, int n, reg result_reg); void arithmetic_right_shift(reg reg1, int n, reg result_reg); int str_len(char* s); int power(int x, int n); void itoreg(int a, reg r); short int regtoi(reg r); void print_status(reg rega, reg regb, reg regc, reg regd); void run_tests(reg rega, reg regb, reg regc, reg regd); int main(int argc, char** argv) { //check for correct number of command line arguments if(argc != 3) { printf("Please enter exactly 2 integers as command line arguments.\n"); printf("You entered %d integers.\n", argc - 1); exit(0); } //assign command line arguments to short ints short int a = atoi(argv[1]); short int b = atoi(argv[2]); short int c = 0; short int d = 0; //create four 16 bit registers reg rega = malloc((LEN + 1) * sizeof(char)); reg regb = malloc((LEN + 1) * sizeof(char)); reg regc = malloc((LEN + 1) * sizeof(char)); reg regd = malloc((LEN + 1) * sizeof(char)); //initialze the registers with the ints provided by the command line args itoreg(a, rega); itoreg(b, regb); itoreg(c, regc); itoreg(d, regd); print_status(rega, regb, regc, regd); printf("\n"); run_tests(rega, regb, regc, regd); //always free malloced memory free(rega); free(regb); free(regc); free(regd); return 0; } // This is method that operate the add function. It will access each index then compare the value then store the correct value in result_reg. // There are three cases that will occur. '0'&& '0', '0' && '1' or vice versa, '1' && '1' void add(reg reg1, reg reg2, reg result_reg) { int carry = 0; //This will check out the case of '1' + '1'. If so carry will be added to next one. for(int i = LEN -1; i >= 0; i--){ // first case '0' and '0' if(reg1[i] == '0' && reg2[i] == '0'){ if(carry == 1){ result_reg[i] = '1'; carry = 0; }else{ result_reg[i] = '0'; carry = 0; } } // second case '1' and '1' else if(reg1[i] == '1' && reg2[i] == '1'){ if(carry == 1){ result_reg[i] = '1'; carry =1; }else{ result_reg[i] = '0'; carry = 1; } } // third case '0' and '1' or '1' or '0' else{ if(carry == 1){ result_reg[i] = '0'; carry = 1; }else{ result_reg[i] = '1'; carry = 0; } } } result_reg[LEN] = '\0'; } /* The method that operates the subtraction using just bitwise operator and my another method of which add, not and the property of itoreg method. To preserve the original binary value, I used the two temps, temp and temp2. 1. Take not function into reg2 then stored that value in temp2 (Inverting) 2. Using the properity of Integer to Register method 3. Add 1's complement and binary 1 to make 2's complement. 4. Adding the result of 2's complement and reg1. */ void subtract(reg reg1, reg reg2, reg result_reg) { reg temp = malloc((LEN + 1) * sizeof(char)); // To presever the original value reg temp2 = malloc((LEN + 1) * sizeof(char)); // To presever the original value not(reg2, temp2); //1's comlement of reg2 then store the value in temp2 itoreg(1, temp); // 0000000000000001 add(temp2, temp, temp2); // add temp2(not reg2) and 0000000000000001 for 2's complement add(reg1,temp2,result_reg); // add the reg1 and temp2(2's complement of not reg2) then store it in the result_reg } // The method that do bitwise operation, and. If '1' and '1' -> '1' else '0'. Store the value in result_reg. void and(reg reg1, reg reg2, reg result_reg) { int i; for(i = LEN -1; i>= 0; i--){ if(reg1[i] == '1' && reg2[i] == '1'){result_reg[i] = '1';} else{result_reg[i] ='0';} } result_reg[LEN] = '\0'; } // The method that do bitwise operation, or. '0' and '0' is the only case that can result in '0'. Otherwise '1'. Store the value in result_reg. void or(reg reg1, reg reg2, reg result_reg) { int i; for(i = LEN -1; i>= 0; i--){ if(reg1[i] == '0' && reg2[i] == '0'){result_reg[i] = '0';} else{result_reg[i] ='1';} } result_reg[LEN] = '\0'; } // The method that do bitwise operation, not. If it's '1' --> '0'. Otherwise '0'. Store the value in result_reg. void not(reg reg1, reg result_reg) { int i; for(i = LEN-1; i>= 0; i--){ if(reg1[i] == '1'){result_reg[i] ='0';} else{result_reg[i] = '1';} } result_reg[LEN] = '\0'; } /* The method that do logical left shift ex) 11001010 --> 1001 0100 then stores the value in result_reg. -pre n=0 result_reg equal to reg1. */ void logical_left_shift(reg reg1, int n, reg result_reg) { int i; int j = 0; // Control part in order to decide the place to put the 0's. // copy the register1 for(i = LEN-1; i >= 0; i --){ result_reg[i] = reg1[i]; } // It will iterate the same amount as the int n (parameter) while(n > 0){ for(i=0; i < LEN-1 - j; i++){ // passing from the last index of the binary result_reg[i] = result_reg[i +1]; } result_reg[LEN-1-j] = '0'; // Put the zero at the end. It also keep moving to left n--; // Control the how many times it will iterate. j++; // Skip the place. } result_reg[LEN] = '\0'; } /* The method that do logical right shift ex) 11001010 --> 11100101 then stores the value in result_reg. -pre n=0 result_reg equal to reg1. */ void arithmetic_right_shift(reg reg1, int n, reg result_reg) { int i; int j = 0; // Copy the register1. for(i = LEN-1; i >= 0; i --){ result_reg[i] = reg1[i]; } // if the first is '1' --> It will keep the value '1'. because it need to keep the minus. if(reg1[0] == '1'){ while(n > 0){ for(i = LEN -2; i > 0; i--){ result_reg[i] = result_reg[i -1]; // assgined the previous value to current place. left to right. } result_reg[0] = '1'; // Keep push the '1' in the first place of binary. n--; j++; } } else{ // This will be iterated exactly same times as the int n. while(n > 0){ for(i=LEN-2; i > 0; i--){ result_reg[i] = result_reg[i - 1]; } result_reg[j] = '0'; n--; // Control the how many times while loop will iterate. j++; // Skip the place. } } result_reg[LEN] = '\0'; } //finds the length of s int str_len(char* s) { int l = 0; while(s[l] != '\0') l++; return l-1; } //returns x^n int power(int x, int n) { if(n <= 0) return 1; else return x * power(x, n-1); } //short for integer to register //stores the 2s complement version of a in r void itoreg(int a, reg r) { int i = 0; int p = LEN - 1; //handle whether a is positive or negative if(a >= 0) { r[i] = '0'; } else { r[i] = '1'; a += power(2, p); } i++; p--; //fill in the rest of the register while(i < LEN) { if(a/power(2, p)) { r[i] = '1'; a -= power(2, p); } else { r[i] = '0'; } i++; p--; } r[LEN] = '\0'; } //short for register to integer //returns the integer version of r short int regtoi(reg r) { int p = LEN - 1; int i = 0; int a = -1 * (r[i] - 48) * power(2, p); i++; p--; while(i < LEN) { a += (r[i] - 48) * power(2, p); i++; p--; } return a; } //prints the values in the registers void print_status(reg rega, reg regb, reg regc, reg regd) { printf("Register status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", regtoi(rega), regtoi(regb), regtoi(regc), regtoi(regd)); printf("rega: %s\nregb: %s\nregc: %s\nregd: %s\n", rega, regb, regc, regd); } //run a series of tests to see if your functions work properly void run_tests(reg rega, reg regb, reg regc, reg regd) { signed short int a, b, c, d; //Test add(rega, regb, regc) printf("Adding rega to regb and storing the result in regc...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); add(rega, regb, regc); c = a + b; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test add(rega, regb, regb) printf("Adding rega to regb and storing the result in regb...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); add(rega, regb, regb); b = a + b; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test add(rega, regc, rega) printf("Adding rega to regc and storing the result in rega...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); add(rega, regc, rega); a = a + c; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test subtract(regb, rega, regd) printf("Subtracting rega from regb and storing the result in regd...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); subtract(regb, rega, regd); d = b - a; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test subtract(regd, regb, regb) printf("Subtracting regb from regd and storing the result in regb...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); subtract(regd, regb, regb); b = d - b; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test subtract(rega, regc, rega) subtract(rega, regc, rega); a= a-c printf("Subtracting regc from rega and storing the result in rega...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); subtract(rega, regc, rega); a = a - c; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test and(rega, regc, regd) printf("Bitwise and-ing rega and regc and storing the result in regd...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); and(rega, regc, regd); d = a & c; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test and(regc, regd, rega) printf("Bitwise and-ing regc and regd and storing the result in rega...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); and(regc, regd, rega); a = c & d; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test and(rega, regb, rega) printf("Bitwise and-ing rega and regb and storing the result in rega...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); and(rega, regb, rega); a = a & b; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test or(rega, regb, regd) printf("Bitwise or-ing rega and regb and storing the result in regd...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); or(rega, regb, regd); d = a | b; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test or(regc, rega, rega) printf("Bitwise or-ing regc and rega and storing the result in rega...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); or(regc, rega, rega); a = c | a; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test or(regb, regc, regb) printf("Bitwise or-ing regb and regc and storing the result in regb...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); or(regb, regc, regb); b = b | c; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test not(regb, rega) printf("Bitwise not-ing regb and storing the result in rega...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); not(regb, rega); a = ~b; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test not(regd, regd) printf("Bitwise not-ing regd and storing the result in regd...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); not(regd, regd); d = ~d; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test logical_left_shift(rega, 4, regc) printf("Logical left shifting rega by 4 and storing the result in regc...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); logical_left_shift(rega, 4, regc); c = a << 4; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test logical_left_shift(regb, 6, regb) printf("Logical left shifting regb by 6 and storing the result in regb...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); logical_left_shift(regb, 6, regb); b = b << 6; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test arithmetic_right_shift(regc, 2, regb) printf("Arithmetic right shifting regc by 2 and storing the result in regb...\n"); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); arithmetic_right_shift(regc, 2, regb); b = c >> 2; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); //Test arithmetic_right_shift(rega, 7, rega) printf("Arithmetic right shifting rega by 7 using a negative number and storing the result in rega...\n"); itoreg(-3945, rega); a = regtoi(rega); b = regtoi(regb); c = regtoi(regc); d = regtoi(regd); arithmetic_right_shift(rega, 7, rega); a = a >> 7; printf("Expected status:\n"); printf("rega: %d\nregb: %d\nregc: %d\nregd: %d\n", a, b, c, d); print_status(rega, regb, regc, regd); if(regtoi(rega)==a && regtoi(regb)==b && regtoi(regc)==c && regtoi(regd)==d) printf("Correct!\n\n"); else printf("Wrong!\n\n"); }
C
#include <stdio.h> #define MAXIDLEN 63 /** FUNCTION: skipspaces * INPUT: FILE* * OUTPUT: void * DESCRIPTION: skipspaces advances the file pointer * to the first non-space char **/ void skipspaces(FILE *tape); /** FUNCTION: gettoken * INPUT: FILE* * OUTPUT: int (token) * DESCRIPTION: gettoken will read the tape * trying to classify a substring as one of the tokens * using functions that abstract automatas **/ int gettoken(FILE *tape); /** FUNCTION: isID * INPUT: FILE* * OUTPUT:int (token) * DESCRIPTION: if the substring read in the input tape * matches the following regular expression, return the * ID token defined in tokens.h * REGEX: [a-zA-Z][a-zA-Z0-9_]* **/ int isID(FILE *tape); /** FUNCTION: isNUM * INPUT: FILE* * OUTPUT:int (token) * DESCRIPTION: if the substring read in the input tape * matches one of the following regular expressions, * return the appropriate token defined in tokens.h * REGEX: **/ int isNUM(FILE *tape); /** FUNCTION: chk_Exp * INPUT:FILE *, int * OUTPUT: int * DESCRIPTION: if the substring read in the input * matches the exp regex it will return the new position for * lexeme, otherwise it returns the old position * REGEX:[Ee][/+/-]?[0-9]+ **/ int chk_Exp(FILE* tape, int i0); /** Function: clearLexeme * INPUT: void * OUTPUT:void * DESCRIPTION: this function makes all chars in lexeme * turn to 0 **/ void clearLexeme(void);
C
#include <stdio.h> void replace(char str[]) { int i=0; int length =0; while(str[i]!='\0') { if(str[i]==' ') { str[i] = '-'; } i++; length++; } printf("String replaced with - is : "); for(i=0;i<length;i++) { printf("%c", str[i]); } return; } int main() { char str[20]; printf("Enter the string: \n"); scanf("%[^\n]", str); replace(str); return 0; }
C
#pragma once #include "lib.h" // List.h #define ELLIPSE_TYPE 0 #define BRICK_TYPE 1 #define TETRAHEDRON_TYPE 2 #define LIGHT_TYPE 3 typedef struct Element_ { char type; double *object; struct Element_ *next; } Element; typedef struct List_ { Element *head; double nbElement; } List; //Initialises the list List * initList(); // Adds an element in the list void addElementList(Element * e, List * L); // Deletes the last element of the list void deleteElementList(List * list); // Brick.h typedef struct Brick_ { Point a; Point b; Point c; Point d; Point e; Point f; Point g; Point h; Rgb color; } Brick; // checks if the brick could exist int DoesBrickExist(Brick B); // Gives the point of contact between a line and a brick Point contactBrickWithLine(Brick B, Line L); // Encodes a brick as an array double * encodeBrick(Brick B); // Encodes a brick's array as a brick structure Brick decodeBrick(double * brick); // Checks if there is a direct path between the point and light int testIfLightCutsBrick(double *object,Light Li,Point C); // Creates a "brick" element to be added in a chained list Element * createElementBrick(double * B); // Ellipse.h typedef struct Ellipse_ { //radii of the ellipsoid double a; double b; double c; // x y z coordinates of the center point double x; double y; double z; Rgb color; } Ellipse; //Gives the point of contact between a line and an ellipse Point contactEllipseWithLine(Ellipse E, Line L); // Encodes an array as an ellipse structure Ellipse decodeEllipse(double * ellipse); //Encodes an ellipse as an array double * encodeEllipse(Ellipse E); //Tests line of sight with light int testIfLightCutsEllipse(double *object, Light Li, Point C); // Gives the tangente plane of a intersection point between a plane and an ellipse Plane tangentPlaneEllipse(Ellipse E, Line L); // Creates an "ellipse" element to be added in a chained list Element * createElementEllipse(double * E); // Tetrahedron.h typedef struct Tetrahedron_ { Point a; Point b; Point c; Point d; Rgb color; } Tetrahedron; // Gives the point of contact between a line and a tetrahedron Point contactTetrahedronWithLine(Tetrahedron T, Line L); //Encodes a tetrahedron as an array double * encodeTetrahedron(Tetrahedron T); //Encodes a tetrahedron's array as a tetrahedron structure Tetrahedron decodeTetrahedron(double *tetrahedron); // Checks if there is a direct path between the point and light int testIfLightCutsTetrahedron(double *object, Light Li, Point C); // Creates a "tetrahedron" element to be added in a chained list Element * createElementTetrahedron(double * T); // Light.h // Encodes a light's array as a light structure Light decodeLight(double * light); // Encodes a light as an array double * encodeLight(Light L); // Creates a light element for the list Element * createElementLight(double * L); // Tests if two points are equals int arePointsEqual(Point O, Point I); // Gives a vector in a plane Vector vectorInPlane(Point O, Plane P); // Gets intersection point beteween two lines Point pointIntersectionLineAndLine(Line L, Line D); // Gets intersection point beteween a line and a segment Point pointIntersectionLineAndSegment(Point A, Point B, Line L); // Checks if a point is in a polyogon int isOnPolygon(Point *list, double numberOfPoint, Point test); // Checks if a point is in polygon int isOnPolygonAngleMethod(Point *list, double numberOfPoint, Point I); // Checks if a point is in polygon // Comes from "L’hélicoptère aux 52 orteils de Moldavie" and adapted to our libs int isOnPolygonLilianMethod(Point *list, double numberOfPoint, Point I);
C
// 合理利用数组,既可以节省变量,又方便循环 /* 1058 A+B in Hogwarts (20)(20 分) If you are a fan of Harry Potter, you would know the world of magic has its own currency system -- as Hagrid explained it to Harry, "Seventeen silver Sickles to a Galleon and twenty-nine Knuts to a Sickle, it's easy enough." Your job is to write a program to compute A+B where A and B are given in the standard form of "Galleon.Sickle.Knut" (Galleon is an integer in [0, 10^7^], Sickle is an integer in [0, 17), and Knut is an integer in [0, 29)). Input Specification: Each input file contains one test case which occupies a line with A and B in the standard form, separated by one space. Output Specification: For each test case you should output the sum of A and B in one line, with the same format as the input. Sample Input: 3.2.1 10.16.27 Sample Output: 14.1.28 */ #include<stdio.h> int main() { int a[3], b[3], c[3], d[3] = {1<<30, 17, 29}; scanf("%d.%d.%d%d.%d.%d", a, a+1, a+2, b, b+1, b+2); int i, carry = 0; for(i=2; i>=0; i--){ c[i] = (a[i] + b[i] + carry) % d[i]; carry = (a[i] + b[i] + carry) / d[i]; } printf("%d.%d.%d", c[0], c[1], c[2]); }
C
//Jovani de Souza & Davi Pegoraro //roteamento com UDP #include "roteador.h" tabela_roteamento linhas[LINHAS];//vetor de linhas//cria a tabela de roteamento int count_table=0; roteador roteadores[NROTEADORES];//vetor de roteadores, usa paenas o ID, mas instancia um vetor para facilitar a leitura do arquivo int op=-1, msg_control=0, msg_control_rec=0; mensagem msgs_env[NMENSAGEM];//CRIA VETOR DE MENSAGENS, funciona como uma caixa de mensagens enviadas mensagem msgs_rec[NMENSAGEM];//CRIA VETOR DE MENSAGENS, funciona como uma caixa de entrada struct sockaddr_in si_me, si_other; int sock; int argvID; pthread_t recebe_id; //função main - vai receber por linha de comando o ID do roteador de vai variar de 0 a 5 int main(int argc, char *argv[]){ int x; int grafo[NROTEADORES][NROTEADORES];//grafo que sera usado para gerar a tabela de roteamento prenchegrafo(grafo);//função deixa a matriz preenchida com -1 e a diagonal com 0 inicializa_topologia(grafo);//função que inicializa a topologia da rede baseada no arquivo de entrada enlaces.config //test(grafo);//teste de impressão prenche_tabela(grafo); argvID=toint(argv[1]);///cast //trata erro no ID passado pelo terminal if(argvID<0 || argvID >= NROTEADORES){ die("Numero de roteador invalido\n");//garante que o id do roteador seja de 0 a 5 } if(argc<2){ die("insira o ID do roteador\n");//se não for passado o ID }else if(argc>2){ die("insira apenas o ID do roteador 'de 0 a 5'");//se for passado mais que 1 parametro } memset((char *) &si_other, 0, sizeof(si_other));//zera a estrutura si_other.sin_family = AF_INET; //Familia ipv4 si_other.sin_addr.s_addr = htonl(INADDR_ANY); //Atribui o ip criar_roteador(argvID); pthread_create(&recebe_id, NULL, recebe, NULL); //Cria a thread receptora sleep(2); while(1){//loop menu, usado pra mandar e ler mensagens system("clear"); system("clear"); if(op == -1){ printf("ROTEADOR %d\n", argvID); printf("---------------------------------------------\n"); printf("0 - Atualizar\n"); printf("1 - Checar Mensagens\n"); printf("2 - Enviar Mensagem\n"); printf("3 - Sair\n\n"); printf("---------------------------------------------\n"); scanf("%d", &op); }else if(op==0){ op=-1; }else if(op==1){ for(x=0; x<=msg_control_rec; x++){ if(x<msg_control_rec){ printf("Mensagem %d recebida de %d\n",msgs_rec[x].num, msgs_rec[x].origem); } printf("%s\n", msgs_rec[x].msg); } sleep(10); op=-1; }else if(op==2){ envia(argvID); }else if(op==3){ exit(1); }else{ op=-1; } } } void * recebe(void * nada){//recebe mensagens e retransmite se necessário int slen=sizeof(si_other);//si_me int next,i; while(1){ if((recvfrom(sock, &msgs_rec[msg_control_rec], sizeof(msgs_rec[msg_control_rec]), 0, (struct sockaddr*) &si_me, &slen)) == -1){ printf("Erro ao receber mensagem\n"); msg_control_rec--; }else{ } if(msgs_rec[msg_control_rec].destino== argvID){//checa se é pra mim printf("Mensagem recebida do roteador %d\n", msgs_rec[msg_control_rec].origem); msg_control_rec++; }else{ //reenvia msgs_env[msg_control]=msgs_rec[msg_control_rec];//atribui a mensagem recebida como uma mensagem de envio for(i=0; i<NROTEADORES; i++){//procura na rota o indice atual, entao atrivui o rpximo para next if(msgs_env[msg_control].rota[i]==argvID){ next=msgs_env[msg_control].rota[i+1]; } } printf("\nRetransmitindo de %d para %d\n",msgs_rec[msg_control_rec].origem, next); send_next(next);//reenvia a mensagem para o destino } } } void envia(int argvID){//envia mensagens, faz busca e fornece rota para o pacote int i=1,dest,next; printf("Digite o roteador destino\n"); scanf("%d", &dest);//destino da mensagem if(dest>5 || dest<0){ die("Esse roteador nao existe\n");//trata erro na inserção do destino op=-1; } seta_rota(argvID, dest);//com orig & dest, busca o vetor rota para a mesagem[msg_control] printf("Escreva a mensagem que quer enviar para %d\n", dest); getchar(); fgets(msgs_env[msg_control].msg, MENSAGEM_SIZE, stdin);//mensagem no vetor de msgs_env// pega do teclado e guarda a msg na caixa msgs_env[msg_control].num=msg_control;//seta id da mensagem msgs_env[msg_control].origem= argvID; msgs_env[msg_control].destino= dest; //até aqui// pega destino, pega msg e seta a rota para a mensagem//msg prota para enviar next=msgs_env[msg_control].rota[1];//next recebe o segundo valor do vetor rota, pois a posição 0 contem o proprio roteador send_next(next); op=-1; } void send_next(int next){ printf("Enviando mensagem para %d\n", next); sleep(2); si_other.sin_port= htons(roteadores[next].porta); if(inet_aton(roteadores[next].ip , &si_other.sin_addr) == 0){//se tiver erro no endereço die("Falha ao obter ip do destino\n"); }else{ if(sendto(sock, &msgs_env[msg_control],sizeof(msgs_env[msg_control]), 0,(struct sockaddr*) &si_other, sizeof(si_other)) ==-1){ die("Falha no envio da mensagem\n");//se tiver erro na mensagem }else{ printf("Roteador %d enviando Mensagem %d para %d\n", argvID, msgs_env[msg_control].num, roteadores[next].id); } } } void seta_rota(int origem, int destino){//recebe uma origem e um destino, retorna m vetor com a rota int i,j,a,b; msg_control++; a=origem; b=destino; for(i=0; i<LINHAS; i++){//faz uma busca na tabela de roteamento if(linhas[i].origem==a && linhas[i].destino==b){//se encontrar origem e destino compativeis, então for(j=0; j<NROTEADORES; j++){ msgs_env[msg_control].rota[j]=linhas[i].caminho[j];//atribui o caminho encontrado, para a rota da mensagem //printf("%d\n", msgs_env[msg_control].rota[j]); } } } sleep(1); op=-1; } void criar_roteador(int argvID){ int i,id; id=argvID; //abre o arquivo e carrega as informações do roteador FILE *r = fopen("roteador.config", "r"); if(!r) die("Erro ao abrir o arquivo roteadores.config\n"); for(i = 0; fscanf(r, "%d %d %s\n", &roteadores[i].id, &roteadores[i].porta, roteadores[i].ip) != EOF; i++); //le arquivo de configuração dos roteadores, e atribui para todos os ids, usa apena o id informado pelo terminal printf("%d %d %s\n", roteadores[id].id, roteadores[id].porta, roteadores[id].ip); fclose(r); //Cria o socket if((sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == -1){ die("Erro ao criar Socket\n"); } //Zera a estrutura memset((char *) &si_me, 0, sizeof(si_me)); si_me.sin_family = AF_INET; //Familia si_me.sin_port = htons(roteadores[id].porta); //Porta em ordem de bytes de rede si_me.sin_addr.s_addr = htonl(INADDR_ANY); //Atribui o ip //si_me.sin_addr.s_addr = inet_addr(roteadores[id].ip); //Atribui o socket //bind socket a porta if( bind(sock , (struct sockaddr*)&si_me, sizeof(si_me) ) == -1){ die("erro no bind"); } //printf("%s\n", ID); } void prenche_tabela(int grafo[NROTEADORES][NROTEADORES]){ int i,j,count=0; for(i=0; i<NROTEADORES; i++){//prenche a tabela de roteamento com as origens e destinos for(j=0; j<NROTEADORES; j++){ linhas[count].origem=i; linhas[count].destino=j; count++; } } for(i=0; i<NROTEADORES; i++){ dijkstra(grafo, i); } //sleep(500); } void inicializa_topologia(int grafo[NROTEADORES][NROTEADORES]){ int x,y,custo; FILE *p = fopen("enlaces.config", "r");//abre o arquivo enlaces em modo leitura if(!p){ die("Erro ao abrir arquivo enlaces.config\n"); } while(fscanf(p, "%d %d %d\n", &x, &y, &custo) != EOF){//enquanto a leitura do arquivo não chega ao fim grafo[x][y]=custo; grafo[y][x]=custo; } fclose(p); } void prenchegrafo(int grafo[NROTEADORES][NROTEADORES]){//recebe um grafo NxN e preenche a diagona principal com 0 e o restante com -1 int i,j; //memset(grafo, -1, sizeof(grafo)); for(i=0; i<NROTEADORES; i++){//preenche o grafo com -1 for(j=0; j<NROTEADORES; j++){ grafo[i][j]=-1; } } for(i=0, j=0; i< NROTEADORES; i++, j++){//zera a diagonal grafo[i][j]=0; } } void die(char *s){//função pra imprimir erros na tela perror(s); //exit(1); } void test(int grafo[NROTEADORES][NROTEADORES]){ int i,j; for(i=0; i<NROTEADORES; i++){//preenche o grafo com -1 for(j=0; j<NROTEADORES; j++){ printf("%d\t", grafo[i][j]); } printf("\n"); } } ////////////////////////////////////////////////////////////////////// int verifica(int * vetor, int valor){//função que verifica a existencia de um valor no vetor de vertices abertos int a; //retorna 1 se encontrar o valor e retorna 0 se não encontrar for(a = 0; a < 6; a++){ if(vetor[a]== valor) return 1; } return 0; } void removevetor(int * vetor, int valor){// função que verifica um valor no vetor, se encontrar o valor, substitui por 0, usado para liberar o vetor de abertos int a; for(a = 0; a < 6; a++){ if(vetor[a] == valor) vetor[a] = 0; } } int achamenor(int * vetor, int * v_aberto){ int a, b=0, menor = 1000; for(a = 0; a < 6; a++) if(vetor[a]!=0 && vetor[a] < menor && verifica(v_aberto, a)){//se o valor for diferente de 0, se o valor sor menor que 1000 e se o valor estiver no vetor de abertos menor = vetor[a]; //então menor recebe o novo valor b = a; } //no fim a função retorna esse menor valor return b; } void dijkstra(int grafo[NROTEADORES][NROTEADORES], int v_inicial){ int v_aberto[NROTEADORES], i,a=v_inicial,b,controle=NROTEADORES; int vertices[NROTEADORES]; int anterior[NROTEADORES]; int distancia[NROTEADORES]; int origem=v_inicial; for(i=0; i<NROTEADORES; i++){//atribui os valores dos nós para o vetor vertices[i]=i; v_aberto[i]=i; anterior[i]=i; distancia[i]=1000;//custos ficam em 1000 } distancia[v_inicial]=0;//custo de vertici inicial fica 0 while(controle >= 0){//calcula o dijkstra for(b = 0; b < NROTEADORES; b++){ if(grafo[a][b]>0 && verifica(v_aberto,b) && (distancia[b] > (grafo[a][b]+distancia[a]))){// se o valor atual for diferente de 0 e o valor de b estiver no vetor de abertos e se o custo é menor que 1000 distancia[b] = grafo[a][b] +distancia[a];// assume novo custo anterior[b] = a;//guarda vertice anterior } } removevetor(v_aberto, a);//remove o vertice do vetor de abertos controle--; a = achamenor(distancia, v_aberto);//a recebe o valor do menor vizinho } backtracking(origem, anterior); } void backtracking(int origem, int anterior[NROTEADORES]){ int a, x=0,y=0, v_rota[NROTEADORES],aux=0,destino=6; while(aux<=5){ a=aux; while(destino != origem){// usa v_rota para salvar o caminho de tras pra frente fazendo o backtracking destino = a; v_rota[x] = destino; x++; a = anterior[destino]; } //printf("%d %d ", linhas[count_table].origem, linhas[count_table].destino); for(a = x-1,y=0; a >=0 ; a--){ linhas[count_table].caminho[y]=v_rota[a];//guarda o valor do caminho no vetor da estrutura da tabela //printf(" %d ",linhas[count_table].caminho[y] ); y++; } //printf("\n"); // sleep(1); count_table++; x=0; aux++; destino=aux; } // printf("\n"); } int toint(char *str){//converte pra int//função da internet int i, pot, ans; ans = 0; for(i = strlen(str) - 1, pot = 1; i >= 0; i--, pot *= 10) ans += pot * (str[i] - '0'); return ans; }
C
#include<stdio.h> int main() { int i; printf("һλʮ"); scanf("%d",&i); printf("%d,ΪʮΪ%X",i,i); getch(); return 0; }
C
/* ** EPITECH PROJECT, 2020 ** MUL_game ** File description: ** display_text.c */ #include "my.h" #include "gui.h" void display_texts(sfRenderWindow *window, sfText **texts) { if (texts && window) for (size_t a = 0; texts[a]; a++) { sfRenderWindow_drawText(window, texts[a], NULL); } } void display_one_text(sfRenderWindow *window, sfText *text) { if (text && window) sfRenderWindow_drawText(window, text, NULL); }
C
#include <stdio.h> #include <stdlib.h> #include "biblioteca.h" #include <string.h> #include <ctype.h> #include <windows.h> /// @brief pide al usuario ingresar caracteres y de forma segura se guardan en una variable. /// /// @param cadena - es el vector char en la cual se guarda lo que el usuario ingreso /// @param tam - es el tamao del vector char, usado para que no desborde el vector /// @return int myGets(char* cadena,int tam){ fflush(stdin); fgets(cadena,tam,stdin); cadena[strlen(cadena)-1]='\0'; return 0; } /// @brief pide al usuario ingresar caracteres, los lee y checkea que que tenga un formato numero ENTERO /// /// @param pResultado - el puntero por el cual devuelve el entero ingresado y validado. /// @return - retorna 1 si el si lo que ingreso el usuario es convertible a int, sino retorna 0 int getInt(int* pResultado){ int retorno=1; char buffer[4096]; if(myGets(buffer,sizeof(buffer))==0&&esNumericaInt(buffer)&&strlen(buffer)>0){ retorno=0; *pResultado=atoi(buffer); } return retorno; } /// @brief pide al usuario ingresar caracteres, los lee y checkea que que tenga un formato de numero FLOAT /// /// @param pResultado - el puntero por el cual devuelve el float ingresado y validado. /// @return - retorna 1 si el si lo que ingreso el usuario es convertible a float, sino retorna 0 int getFloat(float* pResultado){ int retorno=1; char buffer[4096]; if(myGets(buffer,sizeof(buffer))==0&&esNumericaFloat(buffer)&&strlen(buffer)>0){ retorno=0; *pResultado=atof(buffer); } return retorno; } /// @brief Usa lo ingresado por el usuario y checkea si es "texto basico", aceptando solo: ESPACIOS, a-z,A-Z,-. /// /// @param pResultado - el puntero por el cual devuelve el vector char ingresado y validado. /// @param tam - es el tamao del vector char, usado para que no desborde el vector /// @return retorna 0 si algun caracter no es "basico", y 1 si todos los todos los caracteres son basicos. int getChar(char* pResultado, int tam){ int retorno=0; char buffer[4096]; if(myGets(buffer,tam)==0&&esTextoBasico(buffer)==1&&strlen(buffer)>0){ retorno=1; strncpy(pResultado,buffer,tam); } return retorno; } /// @brief toma una cadena de caracteres y checkea que sea numerica del tipo Int /// /// @param cadena - la cadena de caracteres a checkear /// @return - retorna 1 si la cadena es numerica del tipo int y 0 si algun caracter no es valido para una variable int. int esNumericaInt(char* cadena){ int retorno= 1; int i=0; if(cadena[0]=='-'){ i=1; } for(;cadena[i]!='\0';i++){ if(cadena[i]<'0'||cadena[i]>'9'){ retorno=0; break; } } return retorno; } /// @brief toma una cadena de caracteres y checkea que sea numerica del tipo float /// /// @param cadena - la cadena de caracteres a checkear /// @return - retorna 1 si la cadena es numerica del tipo float y 0 si algun caracter no es valido para una variable float. int esNumericaFloat(char* cadena){ int retorno= 1; int i=0;//inicializo la variable i aca para modificarla en el if de abajo, y no le meto nada en ese sector del for int contadorPunto=0; int esNegativo=0; if(cadena[0]=='-'){//checkeo si la poss 0 es un "-", si es asi, el for comienza desde 1 y no desde 0 i=1; //ya que la unica posicion valida para un menos en el la poss 0 esNegativo=1;//pongo una vandera de que el numero es negativo } for(;cadena[i]!='\0';i++){//dejo vacio el primer argumento, por q ya esta definido arriba if(cadena[i]<'.'||(cadena[i]>'.'&&cadena[i]<'0')||cadena[i]>'9'){//ya descartado el "-" solo filtro numeros y punto //para entender el if este tenes q mirar el ascii retorno=0;//devuelve 0 si se encontro algo que no va y rompe break; } else{//si no es caracter invalido va a saltear el if y entrar aca if(cadena[i]=='.'){//aca le pregunto espesificamente si es un punto, y si es q lo cuente contadorPunto++; if(contadorPunto>1||(esNegativo==0&&i==0)||(esNegativo==1&&i==1)){//aca filtro el punto si hay mas de uno retorno=0;//y tambien la posicion que tiene en la cadena, no puede estar adelante de todo break;//si esta adelante de todo o hay mas de un punto retorno 0(error) y break. } } } } return retorno; } /// @brief checkea si es "texto basico", aceptando solo: ESPACIOS, a-z,A-Z,-. /// /// @param cadena - la cadena de caracteres a checkear /// @return retorna 1 si la cadena es denominada como "texto basico" sino retorna 0. int esTextoBasico(char* cadena){ int retorno= 1; int i; for(i=0;cadena[i]!='\0';i++){ if(cadena[i]<32||(cadena[i]>32&&cadena[i]<65)||(cadena[i]>90&&cadena[i]<97)||(cadena[i]>122&&cadena[i]<164)||cadena[i]>165){ retorno=0; break; } } return retorno; } /// @brief funcion final para pedir un entero, utilizando varias funciones que le dan seguridad y otros agregando parametros como Rango y Reintentos. /// /// @param pResultado - puntero donde se guardara el numero ingresado por el usuario /// @param mensaje - mensaje en pantalla antes de pedir al usuario ingresar el numero. /// @param mensajeError - mensaje de error por si el usuario no ingresa un numero valido. /// @param minimo - el minimo valor aceptado. /// @param maximo - el maximo valor aceptado /// @param reintentos - la cantidad de reintentos por si falla constantemente. void utn_getIntRango(int* pResultado, char* mensaje,char* mensajeError,int minimo, int maximo, int reintentos){ int buffer; if(pResultado!=NULL&&mensaje!=NULL&&mensajeError!=NULL&&minimo<=maximo&&reintentos>=0){ do{ printf("%s",mensaje); if(getInt(&buffer)==0&&buffer>=minimo&&buffer<=maximo){ *pResultado=buffer; break; } printf("%s",mensajeError); reintentos--; }while(reintentos>=0); } } /// @brief funcion final para pedir un Nombre o Apellido, utilizando varias funciones que le dan seguridad y otros agregando parametros como mensaje, mensaje de error y Reintentos. /// /// @param pResultado - el puntero donde se guarde lo ingresado por el usuario /// @param tam - tamao del puntero, para asegurarnos de no desbordar el vector. /// @param mensaje mensaje que vera el usuario antes de pedirle que ingrese datos /// @param mensajeError - el mensaje que se mostrara si el usuario no ingresa datos validos. /// @param reintentos - la cantidad de reintentos por si falla constantemente. void utn_getCharNombre(char*pResultado,int tam, char* mensaje,char* mensajeError, int reintentos){ char buffer[4096]; if(pResultado!=NULL&&mensaje!=NULL&&mensajeError!=NULL&&reintentos>=0){ do{ printf("%s",mensaje); if(getChar(buffer,tam)==1){ PrimerasLetrasMayuscula(buffer); strncpy(pResultado,buffer,tam); break; } printf("%s",mensajeError); reintentos--; }while(reintentos>=0); } } /// @brief toma una cadena de caracteres y devuelve la misma cadena con la primer letra de cada palabra mayuscula /// /// @param mensaje - el vector char que se modificara /// @return int PrimerasLetrasMayuscula(char*mensaje){ int i; mensaje[0]=toupper(mensaje[0]); for(i=1;mensaje[i]!='\0';i++){ mensaje[i]=tolower(mensaje[i]); if(mensaje[i-1]==32){ mensaje[i]=toupper(mensaje[i]); } } return 1; } /// @brief funcion final para pedir un numero int, utilizando varias funciones que le dan seguridad y otros agregando parametros como mensaje, mensaje de error y Reintentos. /// /// /// @param pResultado - puntero que devuelve el numero ingresado /// @param mensaje - mensaje que se le muestra al usuario antes de pedirle un numero /// @param mensajeError - mensaje de error que se le muestra al usuario si ingresa algun caracter fuera de los permitidos /// @param reintentos - cuantos intentos tiene el usuario de poder llegar a ingresar un numero correctamente void utn_getInt(int*pResultado, char*mensaje,char*mensajeError, int reintentos){ int buffer; if(pResultado!=NULL&&mensaje!=NULL&&mensajeError!=NULL&&reintentos>=0){ do{ printf("%s",mensaje); if(getInt(&buffer)==0){ *pResultado=buffer; break; } printf("%s",mensajeError); reintentos--; }while(reintentos>=0); } } /// @brief funcion final para pedir un numero float, utilizando varias funciones que le dan seguridad y otros agregando parametros como mensaje, mensaje de error y Reintentos. /// /// /// @param pResultado - puntero que devuelve el numero ingresado /// @param mensaje - mensaje que se le muestra al usuario antes de pedirle un numero /// @param mensajeError - mensaje de error que se le muestra al usuario si ingresa algun caracter fuera de los permitidos /// @param reintentos - cuantos intentos tiene el usuario de poder llegar a ingresar un numero correctamente void utn_getFloat(float*pResultado,char*mensaje,char*mensajeError, int reintentos){ float buffer; if(pResultado!=NULL&&mensaje!=NULL&&mensajeError!=NULL&&reintentos>=0){ do{ printf("%s",mensaje); if(getFloat(&buffer)==0){ *pResultado=buffer; break; } printf("%s",mensajeError); reintentos--; }while(reintentos>=0); } } /// @brief funcion final para pedir un Nombre o Apellido, utilizando varias funciones que le dan seguridad y otros agregando parametros como mensaje, mensaje de error y Reintentos. /// /// @param pResultado - el puntero donde se guarde lo ingresado por el usuario /// @param tam - tamao del puntero, para asegurarnos de no desbordar el vector. /// @param mensaje mensaje que vera el usuario antes de pedirle que ingrese datos /// @param mensajeError - el mensaje que se mostrara si el usuario no ingresa datos validos. /// @param reintentos - la cantidad de reintentos por si falla constantemente. int utn_getCharSorN(char SorN[],char* mensaje,char* mensajeError){ char buffer[3]; int bandera=0; if(mensaje!=NULL&&mensajeError!=NULL){ do{ printf("%s",mensaje); if(getChar(buffer,3)==1){ buffer[0]=toupper(buffer[0]); } if(buffer[0]=='S'|| buffer[0]=='N'){ bandera=1; strncpy(SorN,buffer,3); break; } printf("%s",mensajeError); }while(bandera==0); } return bandera; } //FIRMA void Firma(void){ printf("========================================DANIEL MANRESA========================================\n"); printf("|| :::::::: :::::::::: :::::::::: ::::::::: :::::::::: ::::::::: :::::::: ::: ::: ||\n"); printf("|| :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: :+: ||\n"); printf("|| +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ +:+ ||\n"); printf("|| +#+ +:+ :#::+::# :#::+::# +#++:++#+ +#++:++# +#++:++#: +#+ +#++: ||\n"); printf("|| +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ +#+ ||\n"); printf("|| #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# #+# ||\n"); printf("|| ######## ### ### ### ########## ### ### ######## ### ||\n"); printf("========================================DANIEL MANRESA========================================\n"); Sleep(5000); }
C
#include "killer.h" #include "move_generation.h" #include "utils.h" #define MAX_KILLERS 8 typedef struct Killers { int count; int next; Move killer[MAX_KILLERS]; } Killers; Killers killers_at_ply[16]; void clear_killers() { for (int ply = 0; ply < 16; ply++) { Killers killers = {}; killers_at_ply[ply] = killers; } } int add_killers(Position position, Move current_move, int ply, Move moves[]) { int count = 0; Killers killers = killers_at_ply[ply]; for (int i = 0; i < killers.count; i++) { Move killer = killers.killer[i]; if (killer.step_count > position.steps && is_legal(position, killer)) { for (int step_number = 0; step_number < current_move.step_count; step_number++) { killer.steps.step[step_number] = current_move.steps.step[step_number]; } moves[count++] = killer; } } return count; } void save_killer(Move move, int ply) { Killers killers = killers_at_ply[ply]; killers.killer[killers.next] = move; killers.next = (killers.next+1) % MAX_KILLERS; killers.count = min(killers.count+1, MAX_KILLERS); killers_at_ply[ply] = killers; }
C
#include <stdio.h> // Count spaces, tabs, and newlines. int main() { long count = 0; int c; while ((c = getchar()) != EOF) { if (c == ' ' || c == '\t' || c == '\n') { count += 1; } } printf("Spaces, tabs, or newlines: %ld\n", count); }
C
/*! \file flood_fill.c \author MMteam \brief This file contains the implementation of the different MM brain function such as flood fill algorithm. \see flood_fill.h \date 2020 */ #include <flood_fill.h> /* Fill a case of the maze with a color */ void fill(struct Maze maze, int16_t OX, int16_t OY, int16_t color) { int16_t size = maze.size; if((OX < 0 || OX >= size) || (OY < 0 || OY >= size)) { printf("fill:invalide file entering %s %d\n", __FUNCTION__, __LINE__); exit(0); } maze.maze[OY * size + OX].value = color; } /* Push the destination boxs of the maze to the queue */ void pushDestinationBoxs(Queue_XY* queue, int16_t OX, int16_t OY) { struct oddpair_XY XY; if(queue == NULL) { printf("floodFill:invalide file entering %s %d\n", __FUNCTION__, __LINE__); exit(0); } XY = createOddpair_XY(OX, OY, 0); pushQueue_XY(queue, XY); } /*---- The FloodFill algorithm ----*/ /* Imagine you pour water into the destination of the maze( which is the four center cells surrounded by 7 walls). The water will first flow to the cell immediately outside the destination cells. And then to it’s immediately accessible neighboring cells. Similarly, water will flow along the paths in the maze, eventually reaching the starting position of the mouse. */ /* Flood fill algorithm */ void floodFill(struct Maze maze, int16_t OX, int16_t OY) { struct oddpair_XY XY; initFFMaze(maze); struct Box* boxs = maze.maze; int16_t size = maze.size; if(boxs == NULL) { printf("floodFill:invalide file entering %s %d\n", __FUNCTION__, __LINE__); exit(0); } int16_t colorMaze = 0; Queue_XY queue = initQueue_XY(); pushDestinationBoxs(&queue, OX, OY); uint8_t sign = 0; while(!emptyQueue_XY(queue)) { XY = summitQueue_XY(queue); popQueue_XY(&queue); if(XY.sign != sign) { sign = XY.sign; colorMaze++; } fill(maze, XY.OX, XY.OY, colorMaze); //Top neighbour, check if ther is no wall if(GET_TOP(boxs[(XY.OY)*size + XY.OX].wallIndicator) == 0 && boxs[(XY.OY - 1)*size + XY.OX].value == -1 && boxs[(XY.OY - 1)*size + XY.OX].value != -2) { pushQueue_XY(&queue, createOddpair_XY(XY.OX, XY.OY - 1, 1 - XY.sign)); boxs[(XY.OY - 1)*size + XY.OX].value = -2; } //Bottom neighbour, check if ther is no wall if(GET_BOTTOM(boxs[(XY.OY)*size + XY.OX].wallIndicator) == 0 && boxs[(XY.OY + 1)*size + XY.OX].value == -1 && boxs[(XY.OY + 1)*size + XY.OX].value != -2) { pushQueue_XY(&queue, createOddpair_XY(XY.OX, XY.OY + 1, 1 - XY.sign)); boxs[(XY.OY + 1)*size + XY.OX].value = -2; } //Left neighbour, check if ther is no wall if(GET_LEFT(boxs[XY.OY * size + (XY.OX)].wallIndicator) == 0 && boxs[XY.OY * size + (XY.OX - 1)].value == -1 && boxs[XY.OY * size + (XY.OX - 1)].value != -2) { pushQueue_XY(&queue, createOddpair_XY(XY.OX - 1, XY.OY, 1 - XY.sign)); boxs[XY.OY * size + (XY.OX - 1)].value = -2; } //Right neighbour, check if ther is no wall if(GET_RIGHT(boxs[XY.OY * size + (XY.OX)].wallIndicator) == 0 && boxs[XY.OY * size + (XY.OX + 1)].value == -1 && boxs[XY.OY * size + (XY.OX + 1)].value != -2) { pushQueue_XY(&queue, createOddpair_XY(XY.OX + 1, XY.OY, 1 - XY.sign)); boxs[XY.OY * size + (XY.OX + 1)].value = -2; } } freeQueue_XY(&queue); } /* Backward flood fill algorithm */ Queue_XY backwardFloodFill(struct Maze maze, int16_t OX, int16_t OY) { struct Box* boxs = maze.maze; int16_t size = maze.size; if(boxs == NULL) { printf("floodFill:invalide file entering %s %d\n", __FUNCTION__, __LINE__); exit(0); } Queue_XY queue = initQueue_XY(); struct Box box = boxs[OY * size + OX]; pushQueue_XY(&queue, createOddpair_XY(OX, OY, 1)); while (box.value != 0) { box = minValueNeighbour(maze, OX, OY); if(box.value == INT16_MAX) { break; } pushQueue_XY(&queue, createOddpair_XY(box.OX, box.OY, 1)); OX = box.OX; OY = box.OY; } return queue; }
C
#include <stdio.h> #include <stdlib.h> /* concatenate two integer arrays */ int *intarrayadd(int *a, int asize, int *b, int bsize) { int *c,larger,smaller,x; /* allocate for the larger array */ larger = asize > bsize ? asize : bsize; /* and get the smaller size as well */ smaller = larger > asize ? asize : bsize; /* allocate storage for new array */ c = malloc( sizeof(int) * (larger) ); /* add if the allocate in successfull */ if( c!=NULL ) { /* copy up to the size of the smaller array */ for( x=0; x<smaller; x++ ) *(c+x) = *(a+x) + *(b+x); /* just copy over the remaining values from the larger array */ if( asize==larger ) { /* use existing value of x */ /* array 'a' is larger */ for( ; x<larger; x++ ) *(c+x) = *(a+x); } else { /* array 'b' is larger */ for( ; x<larger; x++ ) *(c+x) = *(b+x); } } return(c); } int main() { int a[] = { 11, 22, 33, 44, 55 }; int b[] = { 89, 78, 67, 56, 45, 1, 2, 3 }; int as,bs,x,*add,larger; /* obtain array sizes */ as = sizeof(a)/sizeof(int); bs = sizeof(b)/sizeof(int); /* show array a */ printf("Array 'a':"); for( x=0; x<as; x++ ) printf(" %d",a[x]); putchar('\n'); /* show array b */ printf("Array 'b':"); for( x=0; x<bs; x++ ) printf(" %d",b[x]); putchar('\n'); /* add the two arrays */ add = intarrayadd(a,as,b,bs); if( add!=NULL ) { larger = as > bs ? as : bs; printf("Result: "); for( x=0; x<larger; x++ ) printf(" %d",*(add+x)); putchar('\n'); } else { puts("Array manipulation error"); } return(0); }
C
#include<stdio.h> #include<stdlib.h> #include<math.h> /* Método de Romberg: - Método de los trapezios 1. Dividir el intervalo [a,b] en 2**i partes iguales en cada paso i 2. Aplicar la fórmula de los trapezios 3. Parar cuando se llege a una precisión o se evalue num veces. - Método de extrapolación de Richardson: 1. */ double i(double args); int main(void){ x = malloc(sizeof(double)*(n)); free(x); }
C
#include <stdio.h> #include <stdlib.h> #include <linux/i2c-dev.h> #include <fcntl.h> #include <string.h> #include <sys/ioctl.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <sys/ipc.h> #include <sys/shm.h> #include <errno.h> #include <wiringPiSPI.h> #include "misc.h" #include <sys/types.h> #include <dirent.h> #include <string.h> #include <stdarg.h> #define MAX_RECENT 10 struct TRecentPacket RecentPackets[4][MAX_RECENT]; char Hex(char Character) { char HexTable[] = "0123456789ABCDEF"; return HexTable[Character]; } void WriteLog(char *FileName, char *Buffer) { FILE *fp; if ((fp = fopen(FileName, "at")) != NULL) { fputs(Buffer, fp); fclose(fp); } } int GetBoardType(void) { FILE *cpuFd ; char line [120] ; char *c ; static int boardRev = -1; if (boardRev < 0) { if ((cpuFd = fopen ("/proc/cpuinfo", "r")) != NULL) { while (fgets (line, 120, cpuFd) != NULL) { if (strncmp (line, "Hardware", 8) == 0) { printf ("RPi %s", line); if (strstr (line, "BCM2709") != NULL) { boardRev = 2; } } if (strncmp (line, "Revision", 8) == 0) { if (boardRev < 0) { printf ("RPi %s", line); if ((strstr(line, "0015") != NULL) || (strstr(line, "0010") != NULL) || (strstr(line, "0012") != NULL) || (strstr(line, "0013") != NULL)) { // B+ or A+ boardRev = 1; } else if ((strstr(line, "900092") != NULL) || (strstr(line, "920092") != NULL) || (strstr(line, "900093") != NULL)) { // Zero boardRev = 3; } } } } fclose (cpuFd) ; } } return boardRev; } short open_i2c(int address) { short fd; char i2c_dev[16]; sprintf(i2c_dev, "/dev/i2c-%d", piBoardRev()-1); if ((fd = open(i2c_dev, O_RDWR)) < 0) { // Open port for reading and writing printf("Failed to open i2c port\n"); return 0; } if (ioctl(fd, I2C_SLAVE, address) < 0) // Set the port options and set the address of the device we wish to speak to { printf("Unable to get bus access to talk to slave on address %02Xh\n", address); return 0; } return fd; } int FileExists(char *filename) { struct stat st; return stat(filename, &st) == 0; } void StartNewFileIfNeeded(int Channel) { if (Config.Channels[Channel].ImageFP) { // At end of file ? if (Config.Channels[Channel].SSDVPacketNumber >= (Config.Channels[Channel].SSDVNumberOfPackets-1)) { fclose(Config.Channels[Channel].ImageFP); Config.Channels[Channel].ImageFP = NULL; } } if (Config.Channels[Channel].ImageFP == NULL) { // Not currently sending a file. Test to see if SSDV file has been marked as complete if (FileExists(Config.Channels[Channel].ssdv_done)) { // New file should be ready now FILE *fp; printf("File %s found\n", Config.Channels[Channel].ssdv_done); // Zap the "done" file and the previous SSDV file remove(Config.Channels[Channel].ssdv_done); // remove(Config.Channels[Channel].current_ssdv); // Rename new file to replace that one // rename(Config.Channels[Channel].next_ssdv, Config.Channels[Channel].current_ssdv); if ((fp = fopen(Config.Channels[Channel].ssdv_filename, "rb")) != NULL) { char filename[100]; int RecordCount, i; printf("File %s opened\n", Config.Channels[Channel].ssdv_filename); // That worked so let's get the file size so we can monitor progress fseek(fp, 0L, SEEK_END); RecordCount = ftell(fp) / 256; // SSDV records are 256 bytes fclose(fp); // Now fill in list of un-sent packets for (i=0; i<RecordCount; i++) { // Config.Channels[Channel].SSDVPackets[0].Packets[i] = ((i & 63)<10) || ((i & 63)>30); Config.Channels[Channel].SSDVPackets[0].Packets[i] = 1; } Config.Channels[Channel].SSDVPackets[0].NumberOfPackets = RecordCount; Config.Channels[Channel].SSDVPackets[0].ImageNumber = Config.Channels[Channel].SSDVFileNumber; Config.Channels[Channel].NumberOfPacketsInImage[Config.Channels[Channel].SSDVFileNumber] = RecordCount; // fseek(Config.Channels[Channel].ImageFP, 0L, SEEK_SET); // Set record counter back to zero // Config.Channels[Channel].SSDVRecordNumber = 0; // And clear the flag so that the script can be recreated later // Config.Channels[Channel].NextSSDVFileReady = 0; sprintf(filename, "ssdv_done_%d", Channel); remove(filename); } } } } int FindNextUnsentImagePacket(int Channel, int *ImageNumber, int *PacketNumber, int *NumberOfPackets) { int i, j, PacketType; // for (i=0; i<3; i++) for (i=2; i>=0; i--) { if (Config.Channels[Channel].SSDVPackets[i].ImageNumber >= 0) { for (j=0; j<Config.Channels[Channel].SSDVPackets[i].NumberOfPackets; j++) { PacketType = Config.Channels[Channel].SSDVPackets[i].Packets[j]; if (PacketType) { *ImageNumber = Config.Channels[Channel].SSDVPackets[i].ImageNumber; *PacketNumber = j; *NumberOfPackets = Config.Channels[Channel].SSDVPackets[i].NumberOfPackets; Config.Channels[Channel].SSDVPackets[i].Packets[j] = 0; // printf("Channel %d Image %d Packet %d of %d\n", Channel, *ImageNumber, *PacketNumber + 1, *NumberOfPackets); return (PacketType == 2); } } // This line unused now Config.Channels[Channel].SSDVPackets[i].ImageNumber = -1; } } // printf("Channel %d no packets\n", Channel); *ImageNumber = -1; *PacketNumber = -1; *NumberOfPackets = 0; return 0; } int ChooseImagePacketToSend(int Channel) { int Index, ImageNumber, PacketNumber, NumberOfPackets, ResentPacket; ResentPacket = FindNextUnsentImagePacket(Channel, &ImageNumber, &PacketNumber, &NumberOfPackets); // Different image to existing ? if (ImageNumber != Config.Channels[Channel].SSDVImageNumber) { // No longer using the same file, so close if necessary if (Config.Channels[Channel].ImageFP) { fclose(Config.Channels[Channel].ImageFP); Config.Channels[Channel].ImageFP = NULL; } // Open file, if we have a packet to send if (ImageNumber >= 0) { char FileName[100]; sprintf(FileName, "ssdv_%d_%d.bin", Channel, ImageNumber); printf(">>>> Switching to SSDV file %s\n", FileName); Config.Channels[Channel].ImageFP = fopen(FileName, "rb"); } // Note image and packet numbers for next call Config.Channels[Channel].SSDVImageNumber = ImageNumber; Config.Channels[Channel].SSDVPacketNumber = -1; } // Different packet to existing if (Config.Channels[Channel].ImageFP) { if (PacketNumber != (Config.Channels[Channel].SSDVPacketNumber+1)) { // Not the next packet after the last one, in the same file // So we need to seek first // fseek(Config.Channels[Channel].ImageFP, (unsigned long)PacketNumber * 256L, SEEK_SET); } fseek(Config.Channels[Channel].ImageFP, (unsigned long)PacketNumber * 256L, SEEK_SET); // Remember packet number for next time Config.Channels[Channel].SSDVPacketNumber = PacketNumber; } Config.Channels[Channel].SSDVNumberOfPackets = NumberOfPackets; return ResentPacket; } int FindImageInList(int Channel, int ImageNumber) { int i; // First pass - look for this image number for (i=0; i<3; i++) { if (Config.Channels[Channel].SSDVPackets[i].ImageNumber == ImageNumber) { return i; } } // Second pass - look for unused line for (i=0; i<3; i++) { struct TSSDVPackets ZeroPacket = {0}; if (Config.Channels[Channel].SSDVPackets[i].ImageNumber < 0) { Config.Channels[Channel].SSDVPackets[i] = ZeroPacket; Config.Channels[Channel].SSDVPackets[i].ImageNumber = ImageNumber; Config.Channels[Channel].SSDVPackets[i].NumberOfPackets = Config.Channels[Channel].NumberOfPacketsInImage[ImageNumber]; return i; } } // Not found and already full printf("FindImageInList - NOT FOUND\n"); return -1; } void AddImagePacketToRecentList(int Channel, int ImageNumber, int PacketNumber) { int i; // shift them along for (i=0; i<(MAX_RECENT-1); i++) { RecentPackets[Channel][i] = RecentPackets[Channel][i+1]; } RecentPackets[Channel][MAX_RECENT-1].ImageNumber = ImageNumber; RecentPackets[Channel][MAX_RECENT-1].PacketNumber = PacketNumber; // printf("Added channel %d image %d packet %d to list\n", Channel, ImageNumber, PacketNumber); } int ImagePacketRecentlySent(int Channel, int ImageNumber, int PacketNumber) { int i; for (i=0; i<MAX_RECENT; i++) { if ((RecentPackets[Channel][i].ImageNumber == ImageNumber) && (RecentPackets[Channel][i].PacketNumber == PacketNumber)) { return 1; } } return 0; } void MarkMissingPacketsBeyond(int Channel, int ImageNumber, int HighestReceived) { int Index; printf("MarkMissingPacketsBeyond(%d, %d, %d)\n", Channel, ImageNumber, HighestReceived); if ((Index = FindImageInList(Channel, ImageNumber)) >= 0) { int i; for (i=HighestReceived+1; i<Config.Channels[Channel].NumberOfPacketsInImage[ImageNumber]; i++) { if (!Config.Channels[Channel].SSDVPackets[Index].Packets[i]) { if (!ImagePacketRecentlySent(Channel, ImageNumber, i)) { // printf("Marking image %d index %d packet %d channel %d\n", ImageNumber, Index, i, Channel); Config.Channels[Channel].SSDVPackets[Index].Packets[i] = 2; } } } } } void MarkMissingPackets(int Channel, int ImageNumber, int FirstMissingPacket, int LastMissingPacket) { int Index, i; printf("MarkMissingPackets(%d, %d, %d, %d)\n", Channel, ImageNumber, FirstMissingPacket, LastMissingPacket); if ((Index = FindImageInList(Channel, ImageNumber)) >= 0) { printf("Index = %d\n", Index); for (i=FirstMissingPacket; i<=LastMissingPacket; i++) { if (!Config.Channels[Channel].SSDVPackets[Index].Packets[i]) { if (!ImagePacketRecentlySent(Channel, ImageNumber, i)) { // printf("Marking image %d index %d packet %d channel %d\n", ImageNumber, Index, i, Channel); Config.Channels[Channel].SSDVPackets[Index].Packets[i] = 2; } } } } } void ProcessSMSUplinkMessage(int LoRaChannel, unsigned char *Message) { // Process uplink message (e.g. for Astro Pi scrolling LED) // Message is like "#001,Hello Dave!\n" // or "#001,First Message\nSecond Message\n" char FileName[32], *Token; int MessageNumber; FILE *fp; Token = strtok(Message+1, ","); MessageNumber = atoi(Token); sprintf(FileName, "Uplink_%d.sms", MessageNumber); Token = strtok(NULL, "\n"); if ((fp = fopen(FileName, "wt")) != NULL) { fputs(Token, fp); fclose(fp); Config.LoRaDevices[LoRaChannel].MessageCount++; Config.LoRaDevices[LoRaChannel].LastMessageNumber = MessageNumber; } } void ProcessSSDVUplinkMessage(int Channel, unsigned char *Message) { int Value, Image, RangeStart; char Temp[8], *ptr; // !1:256=10-30,74-94,104,113,116,119,138-161,180,182,192,199,201-222,2:69=10-30 printf("Uplink: %s\n", Message); ptr = Temp; Message++; // Skip ! at start RangeStart = -1; Temp[0] = '\0'; while (*Message) { if (isdigit(*Message)) { *ptr++ = *Message; *ptr = '\0'; } else { if (Temp[0]) { Value = atoi(Temp); Temp[0] = '\0'; ptr = Temp; if (*Message == ':') { // Image number Image = Value; } else if (*Message == '=') { // Highest received packet number MarkMissingPacketsBeyond(Channel, Image, Value); } else if (*Message == '-') { // Start of range of missing packets RangeStart = Value; } else { // Missing packet number if (RangeStart >= 0) { MarkMissingPackets(Channel, Image, RangeStart, Value); RangeStart = -1; } else { MarkMissingPackets(Channel, Image, Value, Value); } } } } Message++; } } void ReadString(FILE *fp, char *keyword, int Channel, char *Result, int Length, int NeedValue) { char line[100], FullKeyWord[64], *token, *value; if (Channel >= 0) { sprintf(FullKeyWord, "%s_%d", keyword, Channel); } else { strcpy(FullKeyWord, keyword); } fseek(fp, 0, SEEK_SET); *Result = '\0'; while (fgets(line, sizeof(line), fp) != NULL) { line[strcspn(line, "\r")] = '\0'; // Ignore any CR (in case someone has edited the file from Windows with notepad) token = strtok(line, "="); if (strcasecmp(FullKeyWord, token) == 0) { value = strtok(NULL, "\n"); strncpy(Result, value, Length); if (Length) Result[Length-1] = '\0'; return; } } if (NeedValue) { printf("Missing value for '%s' in configuration file\n", keyword); exit(1); } } double ReadFloat(FILE *fp, char *keyword, int Channel, int NeedValue, double DefaultValue) { char Temp[64]; ReadString(fp, keyword, Channel, Temp, sizeof(Temp), NeedValue); if (Temp[0]) { return atof(Temp); } return DefaultValue; } int ReadInteger(FILE *fp, char *keyword, int Channel, int NeedValue, int DefaultValue) { char Temp[64]; ReadString(fp, keyword, Channel, Temp, sizeof(Temp), NeedValue); if (Temp[0]) { return atoi(Temp); } return DefaultValue; } int ReadCameraType(FILE *fp, char *keyword) { char Temp[64]; ReadString(fp, keyword, -1, Temp, sizeof(Temp), 0); if ((*Temp == '1') || (*Temp == 'Y') || (*Temp == 'y') || (*Temp == 't') || (*Temp == 'T')) { return 1; // CSI (raspistill) Camera } if ((*Temp == 'F') || (*Temp == 'f') || (*Temp == 'U') || (*Temp == 'u')) { return 2; // USB (fswebcam) Camera } return 0; } int ReadBoolean(FILE *fp, char *keyword, int Channel, int NeedValue, int *Result) { char Temp[32]; ReadString(fp, keyword, Channel, Temp, sizeof(Temp), NeedValue); if (*Temp) { *Result = (*Temp == '1') || (*Temp == 'Y') || (*Temp == 'y') || (*Temp == 't') || (*Temp == 'T'); } else { *Result = 0; } return *Temp; } int ReadBooleanFromString(FILE *fp, char *keyword, char *searchword) { char Temp[100]; ReadString(fp, keyword, -1, Temp, sizeof(Temp), 0); if (strcasestr(Temp, searchword)) return 1; else return 0; } void AppendCRC(char *Temp) { int i, j, Count; unsigned int CRC, xPolynomial; Count = strlen(Temp); // Config->PredictionID CRC = 0xffff; // Seed xPolynomial = 0x1021; for (i = 2; i < Count; i++) { // For speed, repeat calculation instead of looping for each bit CRC ^= (((unsigned int)Temp[i]) << 8); for (j=0; j<8; j++) { if (CRC & 0x8000) CRC = (CRC << 1) ^ 0x1021; else CRC <<= 1; } } Temp[Count++] = '*'; Temp[Count++] = Hex((CRC >> 12) & 15); Temp[Count++] = Hex((CRC >> 8) & 15); Temp[Count++] = Hex((CRC >> 4) & 15); Temp[Count++] = Hex(CRC & 15); Temp[Count++] = '\n'; Temp[Count++] = '\0'; } int prog_count(char* name) { DIR* dir; struct dirent* ent; char buf[512]; long pid; char pname[100] = {0,}; char state; FILE *fp=NULL; int Count=0; if (!(dir = opendir("/proc"))) { perror("can't open /proc"); return 0; } while((ent = readdir(dir)) != NULL) { long lpid = atol(ent->d_name); if (lpid < 0) continue; snprintf(buf, sizeof(buf), "/proc/%ld/stat", lpid); fp = fopen(buf, "r"); if (fp) { if ((fscanf(fp, "%ld (%[^)]) %c", &pid, pname, &state)) != 3 ) { printf("fscanf failed \n"); fclose(fp); closedir(dir); return 0; } if (!strcmp(pname, name)) { Count++; } fclose(fp); } } closedir(dir); return Count; } void LogMessage(const char *format, ...) { char Buffer[200]; va_list args; va_start(args, format); vsprintf(Buffer, format, args); va_end(args); if (strlen(Buffer) > 79) { Buffer[77] = '.'; Buffer[78] = '.'; Buffer[79] = 0; } if (Buffer[strlen(Buffer)-1] == '\n') { Buffer[strlen(Buffer)-1] = '\0'; } puts(Buffer); } int devicetree(void) { struct stat statBuf ; return stat ("/proc/device-tree", &statBuf) == 0; }
C
#include <stdio.h> int f(int m,int n) { if(m<n||m<1||n<1) return 0; if(n==1) return m; if(m==n) return 1; return f(m-1,n)+f(m-1,n-1); } int main() { int m,n,y; scanf("%d %d",&m,&n); y=f(m,n); printf("%d",y); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* print_board.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: pheilbro <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2019/08/01 21:58:36 by pheilbro #+# #+# */ /* Updated: 2019/08/02 15:02:44 by pheilbro ### ########.fr */ /* */ /* ************************************************************************** */ #include <unistd.h> #include "fillit.h" void empty_board(char (*board)[16][16], int size) { int i; int j; i = 0; while (i < size) { j = 0; while (j < size) (*board)[i][j++] = '.'; i++; } } void make_char_board(char (*board)[16][16], t_piece *tets, int len) { int i; int blocks_placed; int j; i = 0; while (i < len) { blocks_placed = 0; j = 0; while (blocks_placed < 4 && j < 16) { if (tets[i].char_tet[j] == '#') { (*board)[tets[i].pos.y + j / 4][tets[i].pos.x + j % 4] = 'A' + i; blocks_placed++; } j++; } i++; } } void print_board(t_piece *tets, int len, int size) { char char_board[16][16]; int y; y = 0; empty_board(&char_board, size); make_char_board(&char_board, tets, len); while (y < size) { write(1, char_board[y], size); write(1, "\n", 1); y++; } }
C
#include <stdio.h> int main() { float R,pi,b; scanf("%f",&R); pi=3.14159; b=4.0/3*pi*R*R*R; { printf("VOLUME = %.3f\n",b); } return 0; }
C
#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int i=5; //Ps-incremento i++ printf("Pos-increemento: %d",i++); printf("\ni: %d",i); i = 5; printf("\nReiniciado i: %d",i); //Pr-increemento ++i; printf("\nPre-increemento: %d",++i); //Quebra de linha printf("\n"); //Pos-decreemento i-- printf("\nPos-increemento: %d",i--); printf("\ni: %d",i); //Pr-decreemento --i; printf("\nPre-increemento: %d",--i); return 0; }
C
//LU Decomposition //Siddhartha #include<stdio.h> #include<gsl/gsl_linalg.h> #include<gsl/gsl_matrix.h> int main() { float a[3][3]={{1, 0.67, 0.33}, {0.45, 1, 0.55},{0.67, 0.33, 1}}, U[3][3], L[3][3], P[3][3]; gsl_matrix *A = gsl_matrix_alloc(3,3); gsl_permutation *p = gsl_permutation_alloc(3); int i, j; printf("A: \n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%.3f ",a[i][j]); } printf("\n"); } for(i=0;i<3;i++) { for(j=0;j<3;j++) { gsl_matrix_set(A,i,j,a[i][j]); } } int n; gsl_linalg_LU_decomp(A, p, &n); //Doing the LU decomposition /***Getting U***/ for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(j<i) { U[i][j]=0.0; } else { U[i][j]=gsl_matrix_get(A,i,j); } } } /*Getting L*/ for(i=0;i<3;i++) { for(j=0;j<3;j++) { if(j>i) { L[i][j]=0.0; } else if(i==j) { L[i][j]=1.0; } else { L[i][j]=gsl_matrix_get(A,i,j); } } printf("\n"); } /*Getting P*/ gsl_matrix *Unit=gsl_matrix_alloc(3,3); gsl_matrix_set_identity(Unit); for(i=0;i<3;i++) { for(j=0;j<3;j++) { P[i][j]=gsl_matrix_get(Unit, i, gsl_permutation_get(p,j)); } } /********PRINTING**********/ printf("U:\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%.3f ",U[i][j]); } printf("\n"); } printf("\nL:\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%.3f\t",L[i][j]); } printf("\n"); } printf("\nP:\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%.3f\t",P[i][j]); } printf("\n"); } /************CHECKING THE DECOMPOSITION************************/ float Pa[3][3], LU[3][3]; int k=0; for(i=0;i<3;i++) { for(j=0;j<3;j++) { Pa[i][j]=0; LU[i][j]=0; for(k=0;k<3;k++) { Pa[i][j]+=P[i][k]*a[k][j]; LU[i][j]+=L[i][k]*U[k][j]; } } } printf("\nPA:\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%.3f\t",Pa[i][j]); } printf("\n"); } printf("\nLU:\n"); for(i=0;i<3;i++) { for(j=0;j<3;j++) { printf("%.3f\t",LU[i][j]); } printf("\n"); } gsl_permutation_free(p); gsl_matrix_free(A); return 0; }
C
#include<stdio.h> #include<conio.h> void displayarray(int arr[3][3]); int main() { int arr[3][3],i,j; clrscr(); for(i=0;i<3;i++) { for(j=0;j<3;j++) { scanf("%d",&arr[i][j]); } } displayarray(arr); getch(); return 0; } void displayarray(int arr[3][3]) { int i,j; for(i=0;i<3;i++) { printf("\n"); for(j=0;j<3;j++) { printf("%d",arr[i][j]); printf(" "); } } }
C
#include "headers.h" //no 0 indexing for value and suit system because they make calculating card values more confusing while writing code //value system is 3 as 1, 4 as 2 ... A as 12, 2 as 13 //suit system is diamonds as 1, clubs as 2, ... //(PART 1) INIIALIZING THE DECK //purpose: inputs information into a card //parameters: value and suit of an individual card (refer to comments on top of the file) void initialize_card(int value, int suit){ int ranking = (4 * (value - 1)) + suit; //ex: 3 of diamond would be card 1, 3 of club would be card 2, etc deck[ranking].value = value; deck[ranking].suit = suit; deck[ranking].rank = ranking; //ex: 5 of clubs (value: 3, suit: 2) -> ranking is (4 * (3-1)) + 2 = 10 } //purpose: through the deck array to initialize each card's info... //this sets up the deck in order of increasing value //parameters: none void initialize_deck(){ int card = 1, value = 1, suit = 1; while (card < 53){ while (suit < 5){ initialize_card(value, suit); card++; suit++; } value++; suit = 1; } } //(PART 2) DISPLAYING CARDS, DEALING THEM OUT, AND SORTING THE HAND //purpose: print out a card's value and suit (ex: A of Spades) based on ranking //this is ugly but necessary for easier testing //parameters: card's ranking from 1-52 void display_card_ranking(int ranking){ int card_value = deck[ranking].value; int card_suit = deck[ranking].suit; char s1[16]; //value char s2[16]; //suit if (card_value == 1){strcpy(s1, "3 of "); } if (card_value == 2){strcpy(s1, "4 of "); } if (card_value == 3){strcpy(s1, "5 of "); } if (card_value == 4){strcpy(s1, "6 of "); } if (card_value == 5){strcpy(s1, "7 of "); } if (card_value == 6){strcpy(s1, "8 of "); } if (card_value == 7){strcpy(s1, "9 of "); } if (card_value == 8){strcpy(s1, "10 of "); } if (card_value == 9){strcpy(s1, "J of "); } if (card_value == 10){strcpy(s1, "Q of "); } if (card_value == 11){strcpy(s1, "K of "); } if (card_value == 12){strcpy(s1, "A of "); } if (card_value == 13){strcpy(s1, "2 of "); } if (card_suit == 1){strcpy(s2, "Diamonds"); } if (card_suit == 2){strcpy(s2, "Clubs"); } if (card_suit == 3){strcpy(s2, "Hearts"); } if (card_suit == 4){strcpy(s2, "Spades"); } strcat(s1, s2); printf("%s \n", s1); } //purpose: print out a card's value and suit based on a struct card //parameters: a card struct from the deck array void display_card(struct card my_card){ int card_value = my_card.value; int card_suit = my_card.suit; int ranking = (4 * (card_value - 1)) + card_suit; display_card_ranking(ranking); } char * get_card_name(struct card to_name){ char * name; name = malloc( sizeof(char) * 256 ); sprintf(name, "%d", to_name.rank); strcat(name, ": "); char s1[16]; //value char s2[16]; //suit if (to_name.value == 1){strcpy(s1, "3 of "); } if (to_name.value == 2){strcpy(s1, "4 of "); } if (to_name.value == 3){strcpy(s1, "5 of "); } if (to_name.value == 4){strcpy(s1, "6 of "); } if (to_name.value == 5){strcpy(s1, "7 of "); } if (to_name.value == 6){strcpy(s1, "8 of "); } if (to_name.value == 7){strcpy(s1, "9 of "); } if (to_name.value == 8){strcpy(s1, "10 of "); } if (to_name.value == 9){strcpy(s1, "J of "); } if (to_name.value == 10){strcpy(s1, "Q of "); } if (to_name.value == 11){strcpy(s1, "K of "); } if (to_name.value == 12){strcpy(s1, "A of "); } if (to_name.value == 13){strcpy(s1, "2 of "); } if (to_name.suit == 1){strcpy(s2, "Diamonds\n"); } if (to_name.suit == 2){strcpy(s2, "Clubs\n"); } if (to_name.suit == 3){strcpy(s2, "Hearts\n"); } if (to_name.suit == 4){strcpy(s2, "Spades\n"); } strcat(s1, s2); strcat(name, s1); return name; } //purpose: returns the hand in string form to be displayed to the user //parameters: specified hand array, the number of cards in the hand char * get_hand(struct card hand[], int num_cards){ char * to_ret = (char *)malloc( sizeof(char) * 256 ); int i=0; strcat(to_ret, "Your hand:\n"); while(i < num_cards){ char * card_name = get_card_name(hand[i]); strcat(to_ret, card_name); free(card_name); i++; } return to_ret; } //purpose: should return the corresponding card struct when calling a rank // should return the suit and value // try modding and dividng the rankings to arrive at the value and suit struct card get_card(int rank){ struct card ret; if (rank % 4 == 0 ){ ret.suit = 4; } else { ret.suit = rank % 4; } ret.value = ( rank - ret.suit ) / 4 + 1; ret.rank = rank; return ret; } //purpose: there are 4 hand arrays (represents each player) initialized in the header file //this inserts a card into a specificed hand array //parameters: specified hand array, specified index of hand array (1 of 13 cards in the hand), //and ranking of the card to be inserted into the hand void set_hand(struct card hand[], int ranking, int index){ int card_value = deck[ranking].value; int card_suit = deck[ranking].suit; hand[index].value = card_value; hand[index].suit = card_suit; hand[index].rank = ranking; } //purpose: there are 4 int arrays initialized in the header meant to store random ints //each random int distributed to each array corresponds to a card's ranking from 1-52 //parameters: none void deal_random_ints(){ int a = 0; while (a < 52){ random_ints[a] = a+1; a++; } int i = 0; srand(time(NULL)); while (i < 52){ int temp = random_ints[i]; int r = rand() % 52; //random index random_ints[i] = random_ints[r]; random_ints[r] = temp; i ++; } /* for testing purposes only int k; for (k = 0; k< 52; k++){ printf("%d ", random_ints[k]); } */ } //QUICKSORT FUNCTIONS BELOW //purpose: used old quicksort hw from AP CS //this is to display a dealt hand in increasing order of ranking void swap(int* a, int* b){ int temp = *a; *a = *b; *b = temp; } int part (int array[], int min, int max){ int pivot = array[max]; int i = (min-1); int j = min; while (j <= max-1){ if (array[j] <= pivot){ i++; swap(&array[i], &array[j]); } j++; } swap(&array[i+1], &array[max]); return (i+1); } void quicksort(int array[], int min, int max){ if (min < max){ int position = part(array, min, max); quicksort(array, min, position-1); quicksort(array, position+1, max); } } void sort_hand(int hand[]){ quicksort(hand, 0, 12); } //purpose: to distribute the random ints (representing card rankings) to each hand //then this function converts each int to the corresponding card on the card struct array used for gameplay //parameters: none void deal_hands(){ deal_random_ints(); //distribute random ints to each of the 4 "hand" arrays int i = 0, r = 0; while (i < 13){ rand_hand_one[i] = random_ints[r]; r++; rand_hand_two[i] = random_ints[r]; r++; rand_hand_three[i] = random_ints[r]; r++; rand_hand_four[i] = random_ints[r]; r++; i++; } sort_hand(rand_hand_one); sort_hand(rand_hand_two); sort_hand(rand_hand_three); sort_hand(rand_hand_four); //this below sorts the hands! int j = 0, k = 0; while (j < 13){ set_hand(hand_one, rand_hand_one[k], j); set_hand(hand_two, rand_hand_two[k], j); set_hand(hand_three, rand_hand_three[k], j); set_hand(hand_four, rand_hand_four[k], j); k++; j++; } } //purpose: once the deck is shuffled and each hand receieves its cards //this function displays the cards in each hand, which are in sorted order to make gameplay convenient void display_hand(struct card hand[]){ int i = 0; while (i < 13){ display_card(hand[i]); i++; } } //purpose: the three of diamonds will allow a player to start the game //returns: the id of the player whose turn it now is int check_start(){ if (hand_one[0].rank == 1){ current_turn = 1; //1 indicates that it is currently that player's turn printf("\nPlayer 1 will begin the game! \n"); return 1; } if (hand_two[0].rank == 1){ current_turn = 2; printf("\nPlayer 2 will begin the game! \n"); return 2; } if (hand_three[0].rank == 1){ current_turn = 3; printf("\nPlayer 3 will begin the game! \n"); return 3; } if (hand_four[0].rank == 1){ current_turn = 4; printf("\nPlayer 4 will begin the game! \n"); return 4; } return -1; } /** //purpose: once a hand is left with no cards, the player wins //this function checks if the hand array is empty. Then it will end the game with a print message. Return 1 to end the game. Return 0 will continue the game. //we want to check if each index of an array is empty. The hand is not shuffled when the player uses cards from whatever index. int check_win_condition(struct card hand[]){ for(int i; i < 13; i++){ //remember to add function to remove cards from hands if (hand[i] == NULL){ return 1; win_condition = 1; printf("Congratulations"); } else{ return 0; } } } */ //purpose: take a player's input as to what kind of cards he wants to play on his free // void process_input_free(char * line){ // if (strncmp(line, "single", sizeof(line)) == 0){ // card_type = 0; // printf("\nCard type set as single until next free\n"); } // else{ // if (strncmp(line, "double", sizeof(line)) == 0){ // card_type = 1; // printf("\nCard type set as double until next free\n"); } // else{ // if (strncmp(line, "combo", sizeof(line)) == 0){ // card_type = 2; // printf("\nCard type set as combo until next free\n"); } // else{ // printf("\nInvalid card type played, please enter: single, double, or combo\n"); } // } // } // } /* int main(){ initialize_deck(); printf("testing shuffling and dealing hands \n"); deal_hands(); // char input[1024]; // while (1){ // printf("Anthony and William's Excellent Shell:" ); // fgets(input, 1024, stdin); // // //insert terminating null into end of command // *strchr(input, '\n') = 0; // // if (strncmp(input, "exit", sizeof(input)) != 0){ // process_input_free(input); } // else{ // exit(0); //exit the shell if user typed in exit // } // } printf("\nHere is hand one: \n"); display_hand(hand_one); printf("\nHere is hand two: \n"); display_hand(hand_two); printf("\nHere is hand three: \n"); display_hand(hand_three); printf("\nHere is hand four: \n"); display_hand(hand_four); //note: input card ranking into array index (ex: 3 of diamonds is deck[1]) //random testing, here is the format to check and compare combos printf("checking valid straight (should be 1) %d \n", check_straight(deck[1], deck[6], deck[12], deck[15], deck[17]) ); printf("checking invalid straight (should be 0) %d \n", check_straight(deck[1], deck[2], deck[7], deck[11], deck[17]) ); printf("checking valid flush (should be 1) %d \n", check_flush(deck[3], deck[11], deck[15], deck[23], deck[31]) ); printf("checking invalid flush (should be 0) %d \n", check_flush(deck[3], deck[4], deck[11], deck[15], deck[19]) ); printf("checking valid house (should be 1) %d \n", check_house(deck[50], deck[51], deck[52], deck[1], deck[4]) ); printf("checking invalid house (should be 0) %d \n", check_house(deck[1], deck[6], deck[12], deck[15], deck[17]) ); printf("checking valid bomb (should be 1) %d \n", check_bomb(deck[49], deck[50], deck[51], deck[52], deck[1]) ); printf("checking invalid bomb (should be 0) %d \n", check_bomb(deck[1], deck[6], deck[12], deck[15], deck[17]) ); printf("checking valid straight flush (should be 1) %d \n", check_straight_flush(deck[1], deck[5], deck[9], deck[13], deck[17]) ); printf("checking invalid straight flush (should be 0) %d \n", check_straight_flush(deck[1], deck[2], deck[7], deck[11], deck[17]) ); printf("comparing two straights (should be -1) %d \n", compare_straight(deck[1], deck[6], deck[9], deck[14], deck[19], deck[2], deck[5], deck[10], deck[13], deck[20]) ); printf("comparing two flushes of different suit (should be 1) %d \n", compare_flush(deck[2], deck[6], deck[10], deck[14], deck[22], deck[1], deck[5], deck[9], deck[13], deck[49]) ); printf("comparing two flushes of same suit (should be 1) %d \n", compare_flush(deck[1], deck[37], deck[41], deck[45], deck[49], deck[5], deck[9], deck[13], deck[17], deck[25]) ); printf("comparing two houses (should be -1) %d \n", compare_house(deck[1], deck[2], deck[3], deck[5], deck[6], deck[9], deck[10], deck[11], deck[13], deck[14]) ); printf("comparing two bombs (should be 1) %d \n", compare_bomb(deck[49], deck[50], deck[51], deck[52], deck[48], deck[1], deck[2], deck[3], deck[4], deck[5]) ); printf("comparing two straight flushes of same suit (should be -1) %d \n", compare_straight_flush(deck[1], deck[5], deck[9], deck[13], deck[17], deck[33], deck[37], deck[41], deck[45], deck[49]) ); printf("comparing two straight flushes of different suit (should be -1) %d \n", compare_straight_flush(deck[33], deck[37], deck[41], deck[45], deck[49], deck[2], deck[6], deck[10], deck[14], deck[18]) ); printf("now testing two combos of different type.. (should be 1) %d \n", compare_combo(deck[1], deck[37], deck[41], deck[45], deck[49], deck[1], deck[6], deck[9], deck[14], deck[19])); printf("now testing two combos of same type.. (should be 1) %d \n", compare_combo(deck[1], deck[37], deck[41], deck[45], deck[49], deck[5], deck[9], deck[13], deck[17], deck[25]) ); printf("now testing to see if function catches invalid combo played (should be 0) %d \n", compare_combo(deck[1], deck[37], deck[41], deck[45], deck[49], deck[3], deck[4], deck[5], deck[6], deck[52]) ); return 0; } */ /* int main(int argc, char const *argv[]) { struct card test = get_card(10); printf("value: %d\nsuit: %d\n", test.value, test.suit); char * name = get_card_name(test); printf("%s\n", name ); free(name); printf("\n\n"); initialize_deck(); deal_hands(); char * hand = get_hand( hand_one, 13 ); printf("%s\n", hand); free(hand); return 0; } */
C
//Write a recursive program which accept number from user and return summation of its digits //Input: 879 //Output:24 #include<stdio.h> int Sum(int iNo) { static int iSum=0; int iDigit=0; if(iNo>0) { iDigit=iNo%10; iNo=iNo/10; iSum=iSum+iDigit; Sum(iNo); } return iSum; } int main() { int iValue=0,iRet=0; printf("Enter number\n"); scanf("%d",&iValue); iRet=Sum(iValue); printf("Addition of digits are: %d\n",iRet); return 0; }
C
#include <stdio.h> #include <sys/param.h> #include <signal.h> #include <string.h> #include <zconf.h> #include <sys/wait.h> #include <stdlib.h> #include <errno.h> /**************************************************** * * * Operating Systems (0368-2162) * * Mini Shell Assignment * * * *****************************************************/ int perform_piping(char** arglist, int seperator); int perform_foreground_process(char** arglist); int perform_background_process(char** arglist); void zombies_handler(); void allow_SIGINT(); void ignore_SIGINT(); void SIGCHLD_handler(int sig); /* After finishes, the parent (shell) should not terminate upon SIGINT * * prevent zombies and remove them as fast as possible */ int prepare(void){ zombies_handler(); ignore_SIGINT(); return 0; } /* Changing the action taken by the process on receipt of a SIGINT signal */ void ignore_SIGINT(){ struct sigaction sa; sa.sa_handler = SIG_IGN; sa.sa_flags = SA_RESTART; if (sigaction(SIGINT, &sa, 0) == -1) { fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } } /* Changing the action taken by the process on receipt of a SIGINT signal */ void allow_SIGINT(){ struct sigaction sa; sa.sa_handler = SIG_DFL; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_NOCLDSTOP; if (sigaction(SIGINT, &sa, 0) == -1) { perror(0); exit(1); } } /* Changing the action taken by the process on receipt of a SIGCHLD signal */ void zombies_handler(){ struct sigaction sa; sa.sa_handler = &SIGCHLD_handler; sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART | SA_NOCLDSTOP; if (sigaction(SIGCHLD, &sa, 0) == -1) { fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } } /* Defining an action to be taken by the process on receipt of a SIGCHLD signal */ void SIGCHLD_handler(int sig) { int saved_errno = errno; while (waitpid((pid_t)(-1), 0, WNOHANG) > 0) {} errno = saved_errno; } /* Commands specified in the arglist executed via execvp() as a child process using fork() */ int process_arglist(int count, char** arglist){ /* If the last non-NULL word in arglist is "&" (a single ampersand), run the child process in the background */ if (!strcmp(arglist[count-1],"&")){ arglist[count-1] = NULL; perform_background_process(arglist); return 1; } /* If arglist contains the word "|" (a single pipe symbol), run two child processes * * with the output (stdout) of the first process piped to the input (stdin) of the second process */ for (int i = 0; i < count; ++i) { if (!strcmp(arglist[i],"|")){ perform_piping(arglist,i); return 1; } } /* Run the child process in the Foreground */ perform_foreground_process(arglist); return 1; } /* The shell executes the command and waits until it completes before accepting another command */ int perform_foreground_process(char** arglist){ int pid = fork(); if (pid < 0){ fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } else if (0 == pid) { allow_SIGINT(); /* Foreground child processes (regular commands or parts of a pipe) should terminate upon SIGINT */ execvp(arglist[0], arglist); exit(1); } waitpid(pid, NULL, 0); return 1; } /* The shell executes the command but does not wait for its completion before accepting another command */ int perform_background_process(char** arglist){ int pid = fork(); if (pid < 0){ fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } else if (0 == pid) { execvp(arglist[0], arglist); exit(1); } return 1; } /* The shell executes both commands concurrently, piping the standard output of the first command to the standard input of the second command * * The shell waits until both commands complete before accepting another command */ int perform_piping(char** arglist, int seperator){ int fd[2]; /* Creating the pipe */ if (pipe(fd) == -1){ fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } /* First child process */ int pid1 = fork(); if (pid1 < 0){ fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } else if (0 == pid1){ arglist[seperator] = NULL; allow_SIGINT(); /* Foreground child processes (regular commands or parts of a pipe) should terminate upon SIGINT */ dup2(fd[1],STDOUT_FILENO); /* Writing STDOUT to the pipe */ close(fd[0]); close(fd[1]); execvp(arglist[0],arglist); } /* Second child process */ int pid2 = fork(); if(pid2 < 0){ fprintf(stderr, "An error occurred while using my shell: %s\n", strerror( errno )); exit(1); } else if (0 == pid2){ allow_SIGINT(); /* Foreground child processes (regular commands or parts of a pipe) should terminate upon SIGINT */ dup2(fd[0],STDIN_FILENO); /* Reading STDIN from the pipe */ close(fd[0]); close(fd[1]); execvp(arglist[seperator + 1],arglist + seperator + 1); } close(fd[0]); close(fd[1]); waitpid(pid1, NULL, 0); waitpid(pid2, NULL, 0); return 1; } /* The skeleton calls this function before exiting */ int finalize(void){ return 0; }
C
#include <stdio.h> #include <stdlib.h> //----------------------------------------------------------------------------- int main(void) { int OuterIndex; int Index; for (OuterIndex = 0; OuterIndex < 3; OuterIndex++) { int Index; printf("Outer index is %d\n",OuterIndex); for (Index = 0; Index < 3; Index++) { printf("Index is %d\n",Index); } } printf("\n"); for (Index = 0; Index < 3; Index++) { int Index; for (Index = 0; Index < 3; Index++) { printf("Index is %d\n",Index); } } return(EXIT_SUCCESS); } //-----------------------------------------------------------------------------
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <limits.h> #define STACK_LENGTH 5 #define EMPTY (-1) #define STACK_FULL (STACK_LENGTH-1) #define STACK_EMPTY INT_MIN // = -2147483648 typedef struct { int stackValues[STACK_LENGTH]; int top; }stack; bool push(stack* mystack, int value) { if (mystack->top >= STACK_FULL) { printf("There's no space in the stack!\n"); return false; } else { (mystack->top)++; mystack->stackValues[mystack->top] = value; return true; } } int pop(stack* mystack) { if (mystack->top == EMPTY) { printf("Nothing to take from stack!\n"); return STACK_EMPTY; } else { int result = mystack->stackValues[mystack->top]; (mystack->top)--; return result; } } int peek(stack* mystack) { if (mystack->top == EMPTY) { printf("Nothing to take from stack!\n"); return STACK_EMPTY; } else { int result = mystack->stackValues[mystack->top]; return result; } } int main(int argc, char* argv[]) { stack s1; s1.top = EMPTY; stack s2; s2.top = EMPTY; push(&s1,1); push(&s1,2); push(&s1,3); push(&s2,4); push(&s2,5); push(&s2,6); int r; printf("\n"); while ((r=pop(&s1)) != STACK_EMPTY) { printf("Result = %d\n",r); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_diu_parse.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: jtambra <talya_1998@mail.ru> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/02/14 00:02:44 by jtambra #+# #+# */ /* Updated: 2021/02/14 01:09:57 by jtambra ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/ft_printf.h" char *ft_itoa_base(long long nb, int base) { char *str; size_t len; len = ft_len_base(nb, base); if (!(str = (char *)malloc(sizeof(char) * (len + 1)))) return (NULL); str[len] = '\0'; if (nb < 0) nb = nb * -1; if (nb == 0) str[0] = '0'; while (nb > 0) { if (nb % base >= 10) str[len - 1] = nb % base + 87; else str[len - 1] = nb % base + 48; nb = nb / base; len--; } return (str); } int ft_di_parse(t_spec value, va_list arg, int base) { char *str; int i; int count; int len; long long num; count = 0; i = 0; if ((num = va_arg(arg, int)) < 0) value.sign_num = 1; if ((str = ft_itoa_base(num, base)) == NULL) return (-1); len = ft_strlen(str); if (value.dot < 0 || value.dot <= len) count = ft_no_dot(value, str, count); if (value.dot != -1 && value.dot > len) count = ft_dot_exist(value, str, count, i); if (str) free(str); return (count); } int ft_u_parse(t_spec value, va_list arg, int base) { char *str; int i; int count; int len; long long num; i = 0; count = 0; num = va_arg(arg, int); if (num < 0) { num = num * -1; num = (4294967295 - num) + 1; } if ((str = ft_itoa_base(num, base)) == NULL) return (-1); len = ft_strlen(str); if (value.dot < 0 || value.dot <= len) count = ft_no_dot(value, str, count); if (value.dot != -1 && value.dot > len) count = ft_dot_exist(value, str, count, i); if (str) free(str); return (count); }
C
#include <stdio.h> int main() { int i = -3, j = 2 , k = 0, m; m = j || i && k; printf("m = %d, i = %d, j = %d, k = %d\n", m, i, j , k); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* i_aff.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: dbauduin <dbauduin@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/10/21 16:23:18 by dbauduin #+# #+# */ /* Updated: 2018/11/13 01:22:41 by dbauduin ### ########.fr */ /* */ /* ************************************************************************** */ #include "vm.h" /* ************************************************************************** */ /* The opcode is 16. There is a parameter encoding byte, which is a register, */ /* whose contents are interpreted as the ASCII value of a character to be */ /* displayed on the standard output. This code is modulo 256. */ /* ************************************************************************** */ void i_aff(t_proc *processus, t_env *env) { t_var v; char aff; int pc; env->op = 16; pc = set_pc(processus->pc + 1); if (MASK(env->a[MODA(pc)].hex) == 64 && (is_reg_valid(v.p1 = (char)env->a[MODA(pc + 1)].hex))) { pc = set_pc(pc + 1); v.p2 = processus->reg[v.p1 - 1]; aff = v.p2 % 256; if (env->aff == 1) ft_print(1, "Player %d aff: %c\n", processus->player->nbr, aff); processus->pc = set_pc(pc + 1); } else processus->pc = set_pc(processus->pc + 3); }
C
#include <stdio.h> #include<string.h> #include <unisd.h> /** * main - run all function * * Return: Return 1 and exit */ int main(void) { int l; l =strln("and that piece of art is useful\" - Dora Korpar, 2015-10-19"); write(2 ,"and that piece of art is useful\" - Dora korpar, 2015-10-19\n",l); return (1); }
C
//c program to swap two integers with using a third variable. #include<stdio.h> void main() { int a,b,temp; printf("enter two no.s to be swapped: "); scanf("%d %d",&a,&b); printf("before swap,\n a=%d and b=%d",a,b); temp = a; a=b; b=temp; printf("\nafter swap,\n a=%d and b=%d",a,b); }
C
#define rule 30 extern void bputs(char *state, int count); extern void shift(char *state, int count); void _main() { char state[20] = {0}; state[10] = 4; for(int i = 0; i<75; i++) { bputs(&state, 20); eval(&state, 20); } } void eval(char *state, int count) { char news[129] = {0}; char tmp = 0; for(int i = 0; i<8*count; i++) { shift(state, count); tmp = state[0] & 7; news[0] |= ((rule >> tmp) & 1) << 2; shift(&news, count); } for(int i = 0; i<count; i++) { tmp = news[i]; state[i] = tmp; } }
C
#include <stdio.h> #include <conio.h> #define SIZE 10 void readValues(double arr[], int size) { for (size_t i = 0; i < size; i++) { printf("Enter Value %d: ", i + 1); scanf("%lf", &arr[i]); } return arr; } void displayValues(double arr[], int size) { for (size_t i = 0; i < size; i++) { printf("%lf\n", arr[i]); } } double getAverageValue(double arr[], int size) { double sum = 0.0; double average = 0.0; for (size_t i = 0; i < size; i++) { sum += arr[i]; average = sum / size; } return average; } void main() { double value[SIZE]; readValues(value, SIZE); printf("\n"); displayValues(value, SIZE); printf("\n"); double average = getAverageValue(value, SIZE); printf("Average = %lf\n", average); getch(); }
C
#include <ltrace.h> #include <signal.h> #include <errno.h> /* * POSIX signal set operations * sigaddset() add signal signum from set. * return 0 on success and -1 on error. */ int sigaddset(sigset_t *set, int signo) { TRACE if (signo < 0 || signo > 31) { errno = EINVAL; return -1; } *set |= 1 << signo; return 0; }
C
/****************************************************************************** * unittest3.c * David Adams * CS 362 * Spring 2015 * Assignment 3 * This file has been added for Assignment 3 in order to provide unit tests * for the gainCard() function within the dominion.c file. ******************************************************************************/ #include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include <string.h> #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { int totalFail = 0; int totalPass = 0; int seed = -1; struct gameState G; int k[10] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy}; int NUM_TEST_CARDS = 3; int testCards[NUM_TEST_CARDS]; int i, x; int priorSupply, postSupply; int priorHand, postHand; int priorDeck, postDeck; int priorDiscard, postDiscard; SelectStream(1); PutSeed(-1); Random(); for (i = 0; i < NUM_TEST_CARDS; i++) { testCards[i] = k[(int)floor(Random() * 10)]; } initializeGame(2, k, seed, &G); //Begin testing-------------------------------------------------------------- printf("------------------------------------------------------------\n"); printf("-----------------BEGIN TESTING FOR gainCard()---------------\n"); printf("------------------------------------------------------------\n"); //Test out of bounds input for card to get ie. card that does not exist if (gainCard(treasure_map + 2, &G, 0, 0) == -1) { printf("gainCard(): PASS -> handles non existent card.\n\n"); totalPass++; } else { printf("gainCard(): FAIL -> does not handle non existent card.\n\n"); totalFail++; } //test empty supply pile ie. all cards are gone of that type G.supplyCount[curse] = 0; if (gainCard(curse, &G, 0, 0) == -1) { printf("gainCard(): PASS -> handles empty supply pile.\n\n"); totalPass++; } else { printf("gainCard(): FAIL -> does not handle empty supply pile.\n\n"); totalFail++; } //Test for out of bounds player if (gainCard(copper, &G, 0, MAX_PLAYERS + 1) == -1) { printf("gainCard(): PASS -> handles out of bounds player.\n\n"); totalPass++; } else { printf("gainCard(): FAIL -> does not exit on out of bounds player.\n\n"); totalFail++; } //Test to make sure anything other than 1 or 2 adds card to discard pile priorSupply = G.supplyCount[copper]; priorDiscard = G.discardCount[0]; gainCard(copper, &G, 3, 0); postSupply = G.supplyCount[copper]; postDiscard = G.discardCount[0]; if (postSupply == (priorSupply - 1)) { printf("gainCard(): PASS -> decrements supply count on flag not equal to 1 or 2.\n\n"); totalPass++; } else { printf("gainCard(): FAIL -> does not decrement supply count on flag not equal to 1 or 2.\n\n"); totalFail++; } if ( postDiscard == (priorDiscard + 1) && G.discard[0][postDiscard - 1] == copper ) { printf("gainCard(): PASS -> correctly discards card on flag not equal to 1 or 2.\n\n"); totalPass++; } else { printf("gainCard(): FAIL -> did not discard card on flag not equal to 1 or 2.\n\n"); totalFail++; } //Test scenario of adding card to the discard pile //test scenario of adding card to the deck //test scenario of adding card to the hand //The following uses NUM_TEST_CARDS number of random cards to test to make //sure that the cards are gained in either the discard, deck or hand for (x = 0; x < NUM_TEST_CARDS; x++) { //testing gaining card x and adding it to the deck priorSupply = G.supplyCount[testCards[x]]; priorDeck = G.deckCount[0]; gainCard(testCards[x], &G, 1, 0); //add card to deck postSupply = G.supplyCount[testCards[x]]; postDeck = G.deckCount[0]; if ( postDeck == (priorDeck + 1) ) { if ( G.deck[0][postDeck - 1] == testCards[x] ) { printf("gainCard(): PASS -> Test card %d gained correctly to deck.\n\n", testCards[x]); totalPass++; } else { printf("gainCard(): FAIL -> Test card %d incremented deck count but was not correctly added to deck.\n\n", testCards[x]); totalFail++; } } else { if ( G.deck[0][postDeck - 1] == testCards[x] ) { printf("gainCard(): FAIL -> Test card %d was added to deck but did not increment deck count.\n\n", testCards[x]); totalFail++; } else { printf("gainCard(): FAIL -> Test card %d was not added to deck and did not increment deck count.\n\n", testCards[x]); totalFail++; } } if ( postSupply == (priorSupply - 1) ) { printf("gainCard(): PASS -> Test card %d decreased supply pile after added to deck.\n\n", testCards[x]); totalPass++; } else { printf("gainCard(): FAIL -> Test card %d did not decrease supply pile after added to deck.\n\n", testCards[x]); totalFail++; } //testing gaining card x and adding it to the hand priorSupply = G.supplyCount[testCards[x]]; priorHand = G.handCount[0]; gainCard(testCards[x], &G, 2, 0); //add card to hand postSupply = G.supplyCount[testCards[x]]; postHand = G.handCount[0]; if ( postHand == (priorHand + 1) ) { if ( G.hand[0][postHand - 1] == testCards[x] ) { printf("gainCard(): PASS -> Test card %d gained correctly to hand.\n\n", testCards[x]); totalPass++; } else { printf("gainCard(): FAIL -> Test card %d incremented hand count but was not correctly added to hand.\n\n", testCards[x]); totalFail++; } } else { if ( G.hand[0][postHand - 1] == testCards[x] ) { printf("gainCard(): FAIL -> Test card %d was added to hand but did not increment hand count.\n\n", testCards[x]); totalFail++; } else { printf("gainCard(): FAIL -> Test card %d was not added to hand and did not increment hand count.\n\n", testCards[x]); totalFail++; } } if ( postSupply == (priorSupply - 1) ) { printf("gainCard(): PASS -> Test card %d decreased supply pile after added to hand.\n\n", testCards[x]); totalPass++; } else { printf("gainCard(): FAIL -> Test card %d did not decrease supply pile after added to deck.\n\n", testCards[x]); totalFail++; } //testing gaining card x and adding it to discard priorSupply = G.supplyCount[testCards[x]]; priorDiscard = G.discardCount[0]; gainCard(testCards[x], &G, 0, 0); //add card to discard postSupply = G.supplyCount[testCards[x]]; postDiscard = G.discardCount[0]; if ( postDiscard == (priorDiscard + 1) ) { if ( G.discard[0][postDiscard - 1] == testCards[x] ) { printf("gainCard(): PASS -> Test card %d gained correctly to discard.\n\n", testCards[x]); totalPass++; } else { printf("gainCard(): FAIL -> Test card %d incremented discard count but was not correctly added to discard.\n\n", testCards[x]); totalFail++; } } else { if ( G.discard[0][postDiscard - 1] == testCards[x] ) { printf("gainCard(): FAIL -> Test card %d was added to discard but did not increment discard count.\n\n", testCards[x]); totalFail++; } else { printf("gainCard(): FAIL -> Test card %d was not added to discard and did not increment discard count.\n\n", testCards[x]); totalFail++; } } if ( postSupply == (priorSupply - 1) ) { printf("gainCard(): PASS -> Test card %d decreased supply pile after added to discard.\n\n", testCards[x]); totalPass++; } else { printf("gainCard(): FAIL -> Test card %d did not decrease supply pile after added to deck.\n\n", testCards[x]); totalFail++; } } printf("------------------------------------------------------------\n"); printf("----------------RESULTS of gainCard() testing---------------\n"); printf("Tests Passed: %d\tTests Failed: %d\n", totalPass, totalFail); printf("------------------------------------------------------------\n"); return 0; }
C
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /* * File: main.c * Author: nderouelle * * Created on 10 septembre 2019, 11:36 */ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <string.h> /* * */ typedef struct{ unsigned char jour; unsigned char mois; unsigned short int annee; char jourDeLaSemaine[10]; // le jour en toute lettre }datePerso; int main(int argc, char** argv) { int socketServer; struct sockaddr_in informationsServeur; int monEntier; int entierDuClient; int retourSendto; int retourRecvfrom; int tailleAdr; socketServer=socket(PF_INET,SOCK_DGRAM,IPPROTO_TCP); if(socketServer==-1){ printf("pb socket : %s\n",strerror(errno)); exit errno; } // init de informationsServeur avec les infos du serveur // IP, port, type informationsServeur.sin_family = AF_INET; informationsServeur.sin_port = ntohs (55555); informationsServeur.sin_addr.s_addr = inet_addr("172.18.58.134"); memset(informationsServeur.sin_zero,0,sizeof(informationsServeur.sin_zero)) ; tailleAdr=sizeof(informationsServeur); // recevoir l'entier en provenance du serveur retourRecvfrom = recvfrom(socketServer, (struct sockaddr*)&entierDuClient, sizeof(monEntier), 0, (struct sockaddr*)&informationsServeur, sizeof(informationsServeur)); if(retourRecvfrom){ } printf("Reponse du serveur : %d\n",entierDuClient); monEntier=12; // envoyer monEntier au serveur retourSendto = sendto(socketServer, (struct sockaddr*)&monEntier, sizeof(monEntier), 0, (struct sockaddr*)&informationsServeur, sizeof(informationsServeur)); if(retourSendto){ } return (EXIT_SUCCESS); }
C
/************************************************** * Happy C64 * * ---------------------------------------------- * * Peek et Poke * * ---------------------------------------------- * * Lire et écrire dans la mémoire du c64 * **************************************************/ // =================== // * Fichier include * // =================== #include <happyc64.h> // ============================= // * Declaration des variables * // ============================= unsigned char v1,octet_1,octet_2; unsigned int v2; // ====================== // * La fonction main() * // ====================== void main() { // -------------------------------- // * Desactiver l'affichage video * // -------------------------------- SCREEN_OFF; // ---------------------------------- // * Deplacement du VIC II en $8000 * // ---------------------------------- set_vic_bank(VIC_BANK_2); // ------------------------------------------------------- // * Deplacement sur screen memory a l'offet 0 du vic II * // ------------------------------------------------------- set_adresse_screen_memory(SM_0); // ------------------------------------------------------------------ // * Deplacement du pointeur de tiles après le screen memory : $800 * // ------------------------------------------------------------------ set_location_character(2); // ---------------------------------- // * Effacer l'ecran avec le tile 0 * // ---------------------------------- cls(0); // ------------------------------------------ // * Modifier le fond avec la couleur noire * // ------------------------------------------ set_color_background (C_BLACK); // ------------------------------------------- // * Modifier le cadre avec la couleur grise * // ------------------------------------------- set_color_border(C_GREY); // ------------------------ // * Chargement des fonts * // ------------------------ load_file("c64,s",(void*)0x8800,8); // --------------------------------------- // * Initiation du text engine en tile 0 * // --------------------------------------- set_text_pointer(0); // ------------------------ // * Activation du VIC II * // ------------------------ SCREEN_ON; // ====================== // * Valeur sur 1 octet * // ====================== /* PEEK et POKE permet de travailler sur 1 octet. (8 bits) */ // -------------------------------- // * Entrer une valeur en mémoire * // -------------------------------- POKE(0x400,69); // POKE(Adresse,value) // ---------------------------------- // * Memoriser la valeur en mémoire * // ---------------------------------- v1 = PEEK(0x400); // PEEK(adresse) // ------------------------------ // * Afficher le contenue de v1 * // ------------------------------ draw_text(1,1,"Valeur de V1 (1 octet) (unsigned char)",C_RED,0); draw_text_value_8(1,2,v1,C_YELLOW); // ============================= // * Valeur sur 2 octets (int) * // ============================= /* POKEW et PEEKW permet de travailler sur un mots (ou word) donc 2 octets (16 bits) sur commodore 64) */ // -------------------------------- // * Entrer une valeur en mémoire * // -------------------------------- POKEW(0x400,28000); // ---------------------------------- // * Memoriser la valeur en mémoire * // ---------------------------------- v2 = PEEKW(0x400); // PEEK(adresse) // ------------------------------ // * Afficher le contenue de v2 * // ------------------------------ draw_text(1,4,"Valeur de V2 (2 octets) (unsigned int)",C_RED,0); draw_text_value_16(1,5,v2,C_YELLOW); // =================================================== // * Affichage des deux octets qui représente le int * // =================================================== /* Pour recomposer la valeur sur 16 bits : - (octet_2 * 256) + octet_1 */ octet_1 = PEEK(0x400); octet_2 = PEEK(0x401); draw_text(1,7,"octet 1 et octet 2 sur le unsigned int",C_RED,0); draw_text_value_8(1,8,octet_1,C_YELLOW); draw_text_value_8(1,9,octet_2,C_YELLOW); draw_text(1,11,"Formule :",C_RED,0); draw_text(1,12,"(octet_2 * 256) + octet_1",C_RED,0); // ------------------------------------------ // * Boucle infini pour voir le résultat ! * // ------------------------------------------ while(1) { wait_vbl(); // on attend le début du Vblank. } // end while } // end main
C
#include<stdio.h> int main() { int n,a[10],i,j,temp,flag; scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); } for(i=1;i<n;i++) { flag=0; for(j=0;j<=n-i-1;j++) { if(a[j]>a[j+1]) { temp=a[j]; a[j]=a[j+1]; a[j+1]=temp; flag=1; } } if(flag==0) break; } for(i=0;i<n;i++) printf("\n%d",a[i]); }