language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include <stdio.h> #include<stdlib.h> #include"lib_dados.h" /*-------------LISTA------------*/ int lista_vazia(t_listaG *l) { return l->quant == 0; } int inicializa_listaGeral (t_listaG *l, int vel) { t_nodo *s1, *s2; s1 = (t_nodo*) malloc (sizeof(t_nodo)); s2 = (t_nodo*) malloc (sizeof(t_nodo)); if((s1 == NULL) || (s2==NULL)) return 0; /*faz a ligacao entre os sentinelas*/ s1->prox = s2; s1->prev = NULL; s2->prox = NULL; s2->prev = s1; s1->posX = 0; s1->posY = 0; s2->posX = 0; s2->posY = 0; /*inicia a lista*/ l->ini = s1; l->fim = s2; l->atual = NULL; l->quant = 0; l->velocidade = vel; return 1; } int inicializa_listaAlien (t_alien *l, int vel) { nodoAlien_t *s1, *s2; s1 = (nodoAlien_t*) malloc (sizeof(nodoAlien_t)); s2 = (nodoAlien_t*) malloc (sizeof(nodoAlien_t)); if((s1 == NULL) || (s2==NULL)) return 0; /*faz a ligacao entre os sentinelas*/ s1->prox = s2; s1->prev = NULL; s2->prox = NULL; s2->prev = s1; s1->posX = 0; s1->posY = 0; s2->posX = 0; s2->posY = 0; /*inicia a lista*/ l->ini = s1; l->fim = s2; l->atual = NULL; l->quant = 0; l->velocidade = vel; l->direcao = 0; return 1; } int inicia_atual(t_listaG *l) { if (l->quant == 0) return 0; l->atual = l->ini->prox; return 1; } int inicia_atualAlien(t_alien *l) { if (l->quant == 0) return 0; l->atual = l->ini->prox; return 1; } /* Insere o elemento item no final da lista. Retorna 1 se a operação foi bem sucedida e zero caso contrário. */ int insereObjeto(int posX, int posY, t_listaG *l) { t_nodo *new; new = (t_nodo *) malloc(sizeof(t_nodo)); if (new == NULL) return 0; /*insere no fim da lista*/ new->posX = posX; new->posY = posY; new->prox = l->fim; new->prev = l->fim->prev; l->fim->prev->prox = new; l->fim->prev = new; l->quant = l->quant + 1; return 1; } int insereAlien(int posX, int posY, int tipo, t_jogo *jg) { nodoAlien_t *new; new = (nodoAlien_t *) malloc(sizeof(nodoAlien_t)); if (new == NULL) return 0; t_alien *l; l = &(jg->aliens); new->posX = posX; new->posY = posY; new->tipo = tipo; new->estado = 1; new->prox = l->fim; new->prev = l->fim->prev; l->fim->prev->prox = new; l->fim->prev = new; l->quant++; return 1; } int apagaObjeto(int posX, int posY, t_listaG *l) { t_nodo *p; /*coloca chave nas sentinelas*/ l->ini->posX = posX; l->ini->posY = posY; l->fim->posX = posX; l->fim->posY = posY; /*percorre a lista a partir do primeiro elemento a partir da sentinela*/ p = l->ini->prox; while((p->posX != posX) || (p->posY != posY)) p = p->prox; /*verifica se o elemento encontrado eh as sentinelas*/ if((p->prox == NULL) || (p->prev == NULL)) return 0; /*retira elemento da lista*/ p->prev->prox = p->prox; p->prox->prev = p->prev; free(p); l->quant--; return 1; } int apagaAlien(int posX, int posY, t_jogo *jg) { t_alien *l; l = &(jg->aliens); nodoAlien_t *p; /*coloca chave nas sentinelas*/ l->ini->posX = posX; l->ini->posY = posY; l->fim->posX = posX; l->fim->posY = posY; /*percorre a lista a partir do primeiro elemento a partir da sentinela*/ p = l->ini->prox; while((p->posX != posX) || (p->posY != posY)) p = p->prox; /*verifica se o elemento encontrado eh as sentinelas*/ if((p->prox == NULL) || (p->prev == NULL)) return 0; /*retira elemento da lista*/ p->prev->prox = p->prox; p->prox->prev = p->prev; free(p); l->quant--; return 1; } int busca_objeto(int posX, int posY, t_listaG *l) { t_nodo *p; /*coloca chave nas sentinelas*/ l->ini->posX = posX; l->ini->posY = posY; l->fim->posX = posX; l->fim->posY = posY; p = l->ini->prox; while((p->posX != posX) || (p->posY != posY)) p = p->prox; /*verifica se o elemento encontrado eh as sentinelas*/ if((p->prox == NULL) || (p->prev == NULL)) return 0; /*se nao eh as sentinelas retorna 1*/ return 1; } void dados_atual(int *posX, int *posY, t_listaG *l) { if(l->atual->prox == NULL) return; *posX = l->atual->posX; *posY = l->atual->posY; } void dados_atualAlien(int *posX, int *posY, t_alien *l) { if(l->atual->prox == NULL) return; *posX = l->atual->posX; *posY = l->atual->posY; } void outros_dadosAlien(int *estado, int *tipo, t_alien *l) { if(l->atual->prox == NULL) return; *estado = l->atual->estado; *tipo = l->atual->tipo; } int velocidade_Alien(t_alien *aliens) { return aliens->velocidade; } int velocidade_Objeto(t_listaG *l) { return l->velocidade; } void quantidadeObjetos(int *quant, t_listaG *l) { *quant = l->quant; } void quantidadeAliens(int *quant, t_alien *l) { *quant = l->quant; } int direcao_alien(t_alien *aliens) { return aliens->direcao; } void altera_atual(int posX, int posY, t_listaG *l) { l->atual->posX = posX; l->atual->posY = posY; } int altera_estadoAlien(int posX, int posY, t_jogo *jg) { t_alien *l; l = &(jg->aliens); nodoAlien_t *p; /*coloca chave nas sentinelas*/ l->ini->posX = posX; l->ini->posY = posY; l->fim->posX = posX; l->fim->posY = posY; /*percorre a lista a partir do primeiro elemento a partir da sentinela*/ p = l->ini->prox; while((p->posX != posX) || (p->posY != posY)) p = p->prox; /*verifica se o elemento encontrado eh as sentinelas*/ if((p->prox == NULL) || (p->prev == NULL)) return 0; p->estado = 2; return 1; } void altera_velocidade(int velocidade, t_alien *aliens) { aliens->velocidade = velocidade; } void incrementa_atual(t_listaG *l) { if(l->atual->prox == NULL) return; l->atual = l->atual->prox; } int incrementa_atualAlien(t_alien *l) { if(l->atual->prox == NULL) return 0; l->atual = l->atual->prox; return 1; } void destroi_lista(t_listaG *l) { t_nodo *p, *r; p=l->ini; while(p->prox != NULL) { r = p; p = p->prox; free(r); } free(p); l->ini = NULL; l->fim = NULL; l->atual = NULL; l->quant = 0; } /*-------------OUTRAS------------*//*-------------OUTRAS------------*//*-------------OUTRAS------------*//*-------------OUTRAS------------*/ int iniciaDados(t_jogo *jg) { /*inicializa as listas*/ if(! inicializa_listaGeral(&(jg->tiro), VELOCIDADE_TIRO)) return 0; if(! inicializa_listaGeral(&(jg->bomba), VELOCIDADE_BOMBA)) return 0; if(! inicializa_listaAlien(&(jg->aliens), VELOCIDADE_ALIENS)) return 0; if(! inicializa_listaGeral(&(jg->naveMae), VELOCIDADE_NVMAE)) return 0; if(! inicializa_listaGeral(&(jg->canhao), VELOCIDADE_CANHAO)) return 0; int i, j, k,posX, posY; /*cria canhao*/ insereObjeto(POS_INI_CANHAO_X, POS_INI_CANHAO_Y, &(jg->canhao)); /*cria nave mae*/ insereObjeto(POS_INI_NVMAE_X, POS_INI_NVMAE_Y, &(jg->naveMae)); /*inicializa a barreira*/ if(! inicializa_listaGeral(&(jg->barreira0), 0)) return 0; if(! inicializa_listaGeral(&(jg->barreira1), 0)) return 0; if(! inicializa_listaGeral(&(jg->barreira2), 0)) return 0; if(! inicializa_listaGeral(&(jg->barreira3), 0)) return 0; posY = LINHA_BARREIRA; for(j = 0; j < LARG_BARREIRA; j++) { for(k = 0; k < ALT_BARREIRA; k++) { /*constroi o bloco da barreira*/ posX = MARGEM_BARREIRA; insereObjeto( posX+j , posY+k , &(jg->barreira0)); posX = MARGEM_BARREIRA + DIST_BARREIRA + LARG_BARREIRA; insereObjeto( posX+j , posY+k , &(jg->barreira1)); posX = MARGEM_BARREIRA + 2*(DIST_BARREIRA + LARG_BARREIRA); insereObjeto( posX+j , posY+k , &(jg->barreira2)); posX = MARGEM_BARREIRA + 3*(DIST_BARREIRA + LARG_BARREIRA); insereObjeto( posX+j , posY+k , &(jg->barreira3)); } } /*configura aliens*/ for (i = 0; i < QUANT_ALIENS_Y; i++) { for(j = 0; j < QUANT_ALIENS_X; j++) { /*calcula a posicao do alien*/ posX = j*(LARG_ALIEN+DIST_ALIEN)+POS_INI_ALIENSX; posY = i*(COMP_ALIEN+DIST_ALIEN)+POS_INI_ALIENSY; /*insere o alien na lista de aliens *todas as outras configuracoes do alien(tipo, estado), sera feita na funcao*/ if(i==0) insereAlien(posX, posY, 0, jg); else if((i>0) &&(i<3)) insereAlien(posX, posY, 1, jg); else if((i>=3) &&(i<QUANT_ALIENS_Y)) insereAlien(posX, posY, 2, jg); } } return 1; } void inicia_pontos_vida(t_jogo *jogo) { jogo->pontuacao = 0; jogo->vidas = 3; } void limpa_Alien(t_jogo *jg) { t_alien*l; l = &(jg->aliens); nodoAlien_t *p; p = l->ini->prox; while(p->prox != NULL) { if(p->estado == 2) apagaAlien(p->posX, p->posY, jg); p = p->prox; } } int apaga_jogo(t_jogo *jg) { destroi_lista(&(jg->barreira3)); destroi_lista(&(jg->barreira2)); destroi_lista(&(jg->barreira1)); destroi_lista(&(jg->barreira0)); destroi_lista(&(jg->naveMae)); destroi_lista(&(jg->canhao)); destroi_lista(&(jg->tiro)); destroi_lista(&(jg->bomba)); return 1; } void extremosAlien(int *esquerda, int *direitas, t_jogo *jg) { t_alien*l; l = &(jg->aliens); int esq, dir; nodoAlien_t *p; p = l->ini->prox; esq = l->ini->prox->posX; dir = l->ini->prox->posX; while(p->prox != NULL) { if(p->posX > dir) dir = p->posX; if(p->posX < esq) esq = p->posX; p = p->prox; } *esquerda = esq; *direitas = dir + LARG_ALIEN; } void alturaInferiorAlien(int *altAlien, t_jogo *jg) { t_alien*l; l = &(jg->aliens); int menor; nodoAlien_t *p; p = l->ini->prox; menor = l->ini->prox->posY; while(p->prox != NULL) { if(p->posY > menor) menor = p->posY; p = p->prox; } *altAlien = menor+COMP_ALIEN - 1; } void altera_posCanhao(t_listaG *canhao, int dir) { t_nodo *p; p = canhao->ini->prox; if(dir == 1) p->posX = p->posX+1; else p->posX = p->posX-1; } void altera_posAlien(t_alien *aliens, int dir) { nodoAlien_t *p; p = aliens->ini->prox; while(p->prox != NULL) { if(dir == 3) p->posY = p->posY+1; else if (dir == 1) p->posX = p->posX-1; else if (dir == 0) p->posX = p->posX+1; p = p->prox; } if (dir == 3) { if(aliens->direcao == 0) aliens->direcao = 1; else aliens->direcao = 0; } } void inverte_estadoAlien(t_alien *l) { nodoAlien_t *p; p = l->ini->prox; while(p->prox != NULL) { if(p->estado != 2) p->estado = p->estado * -1; p = p->prox; } } void incrementa_pontuacao(t_jogo *jg, int pont) { jg->pontuacao = jg->pontuacao + pont; } int decrementa_vida(t_jogo *jg) { jg->vidas = jg->vidas - 1; if (jg->vidas > 0) return 1; return 0; }
C
#include "wav_fun.h" #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> enum errors_t load_WAV(const char *filename, struct WAVE_file_t **wav_file_ptr) { enum errors_t error = success; if (!filename || !wav_file_ptr) return incorrect_args; FILE *file = fopen(filename, "rb"); if (!file) return file_not_found; if (!(*wav_file_ptr = (struct WAVE_file_t *)malloc(sizeof(struct WAVE_file_t)))) { fclose(file); return allocation_error; } struct WAVE_file_t *wav_file = *wav_file_ptr; //loading riff header from .wav file if ((error = load_riff(&(wav_file->RIFF_header), file))) { fclose(file); free(wav_file); return error; } //loading fmt header from .wav file if ((error = load_fmt(&(wav_file->WAVE_fmt), file))) { fclose(file); free(wav_file); return error; } //reading WAVE data header if ((error = load_data(&(wav_file->WAVE_data), file))) { fclose(file); free(wav_file); return error; } fclose(file); return success; } void destroy_WAV(struct WAVE_file_t *wav_file) { free(wav_file->WAVE_data.audioData); free(wav_file); } const char *error_handle(enum errors_t errorNumber) { switch (errorNumber) { case success: return "Success\n"; case incorrect_args: return "Incorrect arguments passed to function!\n"; case file_not_found: return "Incorrect filename. File not found!\n"; case file_corrupted: return "File corrupted. Can not read file! \n"; case incorrect_file_type: return "Incorrect file type. File contains incorrect data! \n"; case allocation_error: return "Allocation error. Couldn't alocate memory! \n"; case file_already_exists: return "File already exists. Rename your file!\n"; case file_write_error: return "File write error. Could not write data to file!\n"; default: return "Unrecognized error number\n "; } return ""; } uint32_t littleEndian32Convert(uint32_t val) { union uint32_convert_t temp = {.value = val}; uint8_t tempByte = temp.byte[0]; temp.byte[0] = temp.byte[3]; temp.byte[3] = tempByte; tempByte = temp.byte[1]; temp.byte[1] = temp.byte[2]; temp.byte[2] = tempByte; return temp.value; } uint16_t littleEndian16Convert(uint16_t val) { union uint16_convert_t temp = {.value = val}; uint8_t tempByte = temp.byte[0]; temp.byte[0] = temp.byte[1]; temp.byte[1] = tempByte; return temp.value; } enum errors_t load_riff(struct RIFF_header_t *riff, FILE *file) { if (!riff || !file) return incorrect_args; //reading RIFF header if (!fread(riff, sizeof(struct RIFF_header_t), 1, file)) { return file_corrupted; } //converting loaded data into little endian riff->chunkID = littleEndian32Convert(riff->chunkID); riff->format = littleEndian32Convert(riff->format); //validating file type if (riff->chunkID != RIFF_ID || riff->format != WAVE_ID) { return incorrect_file_type; } return success; } enum errors_t load_fmt(struct WAVE_fmt_t *fmt, FILE *file) { if (!fmt || !file) return incorrect_args; //loading fmt header from .wav file //reading WAVE fmt header if (!fread(fmt, sizeof(struct WAVE_fmt_t), 1, file)) { return file_corrupted; } //convert fmt header from big_endian to little_endian fmt->chunkID = littleEndian32Convert(fmt->chunkID); //validating WAVE fmt header if (fmt->chunkID != FMT_ID || fmt->chunkSize != 16 || fmt->audioFormat != 1) { printf("FMT"); // printf(" 0x%x 0x%x 0x%x", fmt->chunkID, fmt->chunkSize, fmt->audioFormat); return incorrect_file_type; } return success; } enum errors_t load_data(struct WAVE_data_t *waveData, FILE *file) { if (!waveData || !file) return incorrect_args; //reading WAVE data header if (!fread(waveData, sizeof(uint32_t), 2, file)) { return file_corrupted; } //convert data from big endian to little endian waveData->chunkID = littleEndian32Convert(waveData->chunkID); //validating WAVE data header if (waveData->chunkID != WAVE_DATA_ID || waveData->chunkSize == 0) { return incorrect_file_type; } uint8_t *data = (uint8_t *)malloc(sizeof(uint8_t) * waveData->chunkSize); if (!data) { return allocation_error; } waveData->audioData = data; if (!fread(waveData->audioData, sizeof(uint8_t), waveData->chunkSize, file)) { free(data); printf("DATA"); return file_corrupted; } return success; } enum errors_t save_WAV(const char *filename, struct WAVE_file_t *wav_file) { if (!filename || !wav_file) { return incorrect_args; } //check if file already exists FILE *f = fopen(filename, "rb"); if (f) { fclose(f); return file_already_exists; } FILE *file = fopen(filename, "wb"); //writing RIFF header uint32_t convert_temp = littleEndian32Convert(wav_file->RIFF_header.chunkID); if (!fwrite(&convert_temp, sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } if (!fwrite(&(wav_file->RIFF_header.chunkSize), sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } convert_temp = littleEndian32Convert(wav_file->RIFF_header.format); if (!fwrite(&convert_temp, sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } //writing fmt header convert_temp = littleEndian32Convert(wav_file->WAVE_fmt.chunkID); if (!fwrite(&convert_temp, sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } if (!fwrite((void *)((intptr_t) & (wav_file->WAVE_fmt) + sizeof(uint32_t)), sizeof(struct WAVE_fmt_t) - sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } //writing wave data convert_temp = littleEndian32Convert(wav_file->WAVE_data.chunkID); if (!fwrite(&convert_temp, sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } if (!fwrite(&(wav_file->WAVE_data.chunkSize), sizeof(uint32_t), 1, file)) { fclose(file); return file_write_error; } if (!fwrite(wav_file->WAVE_data.audioData, wav_file->WAVE_data.chunkSize, 1, file)) { fclose(file); return file_write_error; } fclose(file); return success; } void print_WAV_info(struct WAVE_file_t *wav_file) { if (!wav_file) return; printf("WAVE file info:\n"); printf("\t[RIFF header]\n"); printf("### ChunkID: 0x%x\n", wav_file->RIFF_header.chunkID); printf("### ChunkSize: %d\n", wav_file->RIFF_header.chunkSize); printf("### Format: 0x%x\n", wav_file->RIFF_header.format); printf("\t[fmt header]\n"); printf("### ChunkID: 0x%x\n", wav_file->WAVE_fmt.chunkID); printf("### ChunkSize: %d\n", wav_file->WAVE_fmt.chunkSize); printf("### AudioFormat: %d\n", wav_file->WAVE_fmt.audioFormat); printf("### Chunnels: %d\n", wav_file->WAVE_fmt.channels); printf("### SampleRate: %d\n", wav_file->WAVE_fmt.sampleRate); printf("### ByteRate: %d\n", wav_file->WAVE_fmt.byteRate); printf("### BlockAlign: %d\n", wav_file->WAVE_fmt.blockAlign); printf("### BitsPerSample: %d\n", wav_file->WAVE_fmt.bitsPerSample); printf("\tTotal sound data size: %d\n\n", wav_file->WAVE_data.chunkSize); } enum errors_t generate_WAV_header(struct WAVE_file_t **wav_file_ptr, uint16_t channels, uint32_t SampleRate, uint16_t BitsPerSample) { if (!wav_file_ptr) return incorrect_args; if (!(*wav_file_ptr = (struct WAVE_file_t *)malloc(sizeof(struct WAVE_file_t)))) { return allocation_error; } struct WAVE_file_t *wav_file = *wav_file_ptr; //RIFF header wav_file->RIFF_header.chunkID = RIFF_ID; wav_file->RIFF_header.chunkSize = 36; wav_file->RIFF_header.format = WAVE_ID; //FMT header wav_file->WAVE_fmt.chunkID = FMT_ID; wav_file->WAVE_fmt.chunkSize = 16; wav_file->WAVE_fmt.audioFormat = 1; wav_file->WAVE_fmt.channels = channels; wav_file->WAVE_fmt.sampleRate = SampleRate; wav_file->WAVE_fmt.bitsPerSample = BitsPerSample; wav_file->WAVE_fmt.byteRate = SampleRate * channels * BitsPerSample / 8; wav_file->WAVE_fmt.blockAlign = channels * BitsPerSample / 8; //wave data header wav_file->WAVE_data.chunkID = WAVE_DATA_ID; wav_file->WAVE_data.chunkSize = 0; return success; } enum errors_t WAV_add_data(struct WAVE_file_t *wav_file, uint8_t *data, int buffer_size) { if (!wav_file || !data || buffer_size <= 0) { return incorrect_args; } wav_file->WAVE_data.chunkSize = buffer_size; wav_file->RIFF_header.chunkSize += buffer_size; wav_file->WAVE_data.audioData = data; return success; } enum errors_t generate_sound(struct WAVE_file_t *wav_file, int time, uint16_t (*generate_signal)(double, double, uint16_t), double frequency, uint16_t Amplitude) { if (!wav_file || time <= 0 || !generate_signal) return incorrect_args; uint8_t *data = (uint8_t *)malloc(sizeof(uint8_t) * time * wav_file->WAVE_fmt.sampleRate * wav_file->WAVE_fmt.blockAlign); if (!data) return allocation_error; uint16_t *temp_array = (uint16_t *)data; double timeStep = 0.0; for (int i = 0; i < time * wav_file->WAVE_fmt.sampleRate; i++) { double temp = generate_signal(frequency, timeStep, Amplitude); *(temp_array + i) = temp; timeStep += 1.0 / (wav_file->WAVE_fmt.sampleRate); } enum errors_t error = WAV_add_data(wav_file, data, time * wav_file->WAVE_fmt.sampleRate * wav_file->WAVE_fmt.blockAlign); if (error) return error; return success; } uint16_t generate_sinus(double frequency, double time, uint16_t Amplitude) { if (Amplitude > 100) Amplitude = 100; return Amplitude * (100 * sin(time * frequency * 2 * 3.1415) + 100); } uint16_t generate_white_noise(double frequency, double time, uint16_t Amplitude) { if (Amplitude > 100) Amplitude = 100; srand(clock()); double result = Amplitude * (rand() % 100); return result; } uint16_t generate_sinus2(double frequency, double time, uint16_t Amplitude) { if (Amplitude > 100) Amplitude = 100; return Amplitude * (100 * sin(time * frequency * 2 * 3.1415) + 100) * ((25 * sin(time * 5 * frequency * 2 * 3.1415) + 100)); } uint16_t generate_square(double frequency, double time, uint16_t Amplitude) { if (Amplitude > 100) Amplitude = 100; double sin_res = sin(time * frequency * 2 * 3.1415); sin_res = (sin_res > 0 ? 3 : 1); return Amplitude * 100 * sin_res; } uint16_t generate_saw(double frequency, double time, uint16_t Amplitude) { if (Amplitude > 100) Amplitude = 100; return Amplitude * (100 * (frequency * 3.1415 * fmod(time, 1.0 / frequency) - (3.1415 / 2))); }
C
int emptyStack(OperandStack *top) { return top == NULL ; } int countSlots(OperandStack* p1,int argNumber) { OperandStack* p2; Operand operand; int i, slots = 0; stackInit(&p2); for (i = 0; i < argNumber; i++, slots++) { operand = popOperand(&p1); pushOperand(&p2, operand); if (operand.type32_64 == CAT2) slots++; } for (i = 0; i < argNumber; i++) { pushOperand(&p1, popOperand(&p2)); } return slots; } void pushOperand(OperandStack **topAddress, Operand operandToPush) { OperandStack *p1; p1 = malloc(sizeof(OperandStack)); p1->operand = operandToPush; p1->nextOperand = *topAddress; *topAddress = p1; } void stackInit(OperandStack **stackAddress) { *stackAddress = NULL; } Operand popOperand(OperandStack **topAddress) { OperandStack *p1; Operand operand; if (!emptyStack(*topAddress)) { operand = (*topAddress)->operand; p1 = *topAddress *topAddress = (*topAddress)->nextOperand; free(p1); } else { printf("A pilha esta vazia\n"); exit(1); } return operand; } int emptyStackFrame(StackFrame *topFrame) { return topFrame == NULL ; } void frameStackInit(StackFrame **topFrame) { *topFrame = NULL; } void pushFrame(StackFrame **topFrameAddress) { StackFrame *p1; p1 = malloc(sizeof(StackFrame)); p1->nextFrame = *topFrameAddress; *topFrameAddress = p1; } void popFrame(StackFrame **topFrameAddress) { StackFrame *p1; if (!emptyStackFrame(*topFrameAddress)) { p1 = *topFrameAddress; *topFrameAddress = (*topFrameAddress)->nextFrame; free(p1); } else { printf("A pilha esta vazia\n"); exit(1); } } void frameInit(ClassList *init, ClassFile classfile, StackFrame *stackFrame, char* methodName, char* descriptor) { ClassFile* classfile_aux; MethodInfo* method; AttributeInfo methodCode; u2 superClassIndex; char superClassName[100]; int i; method = NULL; classfile_aux = &classfile; superClassIndex = classfile_aux->super_class; /* Procura o metodo pelo nome e se no encontrar, procura na super classe */ while (classfile_aux != NULL && (method = getMethodByName(*classfile_aux, methodName, descriptor)) == NULL && superClassIndex != 0) { superClassName = getUTF8(classfile_aux->constant_pool, classfile_aux->constant_pool[superClassIndex].info.classInfo.nameIndex)); classfile_aux = getClassFileByName(init, superClassName); if (classfile_aux != NULL ) { superClassIndex = classfile_aux->super_class; } } if (method == NULL ) { printf("Metodo nao encontrado >> %s %s\n", methodName, descriptor); exit(1); } for (i = 0; i < method->attributesCount; i++) { if (strcmp(getUTF8(classfile_aux->constant_pool, method->attributes[i].attributeNameIndex), "Code") == 0) { methodCode = method->attributes[i]; break; } } /* belongingClass do frame recebe o constant_pool do classFile */ stackFrame->frame->execEnvir->belongingClass = classfile_aux->constant_pool; /* inicializa a pilha de operandos */ stackInit(&(stackFrame->frame->topOperand)); /* seta o opcode do mtodo que vai ser executado */ stackFrame->frame->execEnvir->currOpcode = methodCode.tipoInfo.code.code; /* inicializa vetor de variveis locais */ stackFrame->localVarArray = malloc(methodCode.tipoInfo.code.maxLocals * sizeof(int)); /* seta o pc */ stackFrame->execEnvir->pc = stackFrame->frame->execEnvir->currOpcode; }
C
// // Root Macro to plot spectra for energy Loss per micron ("dE/dX") spectra from foldtest.for // for various silicon thicknesses as an illustration why "dE/dX" is a dubious concept (which implies // scalable behavior at any thickness), as Hans Bichsel always complained. // // Utility to read in spectrum data from one file // int ReadSpec(string* Fname, float Eval[], float Hval[], float Hint[]) { FILE* infile = fopen(Fname->c_str(), "rb"); if (!infile) { printf ("Cannot open %s'\n", Fname->c_str() ); return 1; } else { printf ("Input file = %s'\n", Fname->c_str() ); } int ind = 0; int n=6; int L; float E, adc, H, asp, ass; while(n==6) { n = fscanf(infile, "%i %f %f %f %f %f", &L, &E, &adc, &H, &asp, &ass); if(n==6) { Eval[ind] = E; Hval[ind] = H; Hint[ind] = asp; ind++; } } printf("Read %i lines from %s\n",ind,Fname->c_str()); fclose(infile); return ind; } // // Main plotting routine // void dEdX() { // // Plot inititializations // gStyle->SetMarkerStyle(1); gStyle->SetMarkerColor(kCyan); gStyle->SetTitleSize(0.06,"xyz"); gStyle->SetLabelSize(0.04,"xyz"); gStyle->SetPadTopMargin(0.08); gStyle->SetPadLeftMargin(0.13); gStyle->SetPadRightMargin(0.1); gStyle->SetPadBottomMargin(0.12); gStyle->SetOptStat(0); gStyle->SetTitleFontSize(0.06); gStyle->SetPadGridY(0); gStyle->SetPadGridX(0); const int nFiles = 4; const std::string specFile[nFiles] = { "results/foldspec_muon_1000mev_1micron.dat", "results/foldspec_muon_1000mev_5micron.dat", "results/foldspec_muon_1000mev_20micron.dat", "results/foldspec_muon_1000mev_300micron.dat" }; TCanvas *c2 = new TCanvas("c2","Bichsel dE/dx Spectra",100,10,900,600); TGraph* gr[nFiles]; int color[nFiles] = { 1, 7, 4, 2 }; int thmu[nFiles] = { 1, 5, 20, 300 }; // // Loop through the files // float EeV[400]; // Input E-loss bin value (eV) float Hdat[400]; // Input E-loss spectrum probability (/eV) float Hintegral[400]; // Input E-loss spectrum probability integral(/eV) float Electron[400]; // E-loss in number of electrons float Hscale[400]; // E-loss spectrum probability const float Emax = 120.; const float eHole = 3.70; // <Eloss> in eV per e/hole pair at 0 degree C c2->cd(1); TLegend* leg = new TLegend(0.65,0.65,0.85,0.87); for(int i=0; i<nFiles; i++) { string Ftemp = specFile[i]; int nLine = ReadSpec(&Ftemp,EeV,Hdat,Hintegral); for(int j=0; j<nLine; j++) { Electron[j] = EeV[j]/eHole/thmu[i]; // No. of electrons per micron Hscale[j] = eHole*Hdat[j]*thmu[i]; // Prob(E) } int nPlot = 0 ; for(int j=0; j<nLine; j++) { if(Electron[j]<Emax) nPlot++; } gr[i] = new TGraph(nPlot,Electron,Hscale); gr[i]->SetMarkerStyle(1); gr[i]->SetMarkerColor(color[i]); gr[i]->SetLineColor(color[i]); if(i==0) { gr[i]->SetTitle("dE/dx spectrum"); gr[i]->GetXaxis()->SetTitle("E Loss (electrons)/micron"); gr[i]->GetYaxis()->SetTitle("Prob(E)"); gr[i]->GetYaxis()->SetTitleOffset(0.9); gr[i]->SetMinimum(0); gr[i]->Draw("AL"); } else { gr[i]->Draw("LSAME"); } char thickness[20]; sprintf(thickness,"%2i micron\n",thmu[i]); leg->AddEntry(gr[i],thickness,"L"); } leg->Draw(); TText* t1=new TText(30.,0.04,"1 GeV muon"); t1->Draw(); }
C
#include<stdio.h> #include<string.h> int main() { int i,j,k; int t; int col; int mat[200][200]; scanf("%d",&t); int c; int count; int dir; char str[250]; int level; for(i=0;i<t;i++) { scanf("%d",&c); scanf("%s",str); count=0; dir=1; level=0; for(j=0;j<strlen(str);j++) { mat[level][count]=str[j]; if(dir==1) { if(count==c-1) { dir=0; level++; } else { count++; } } else { if(count==0) { dir=1; level++; } else { count--; } } } printf("\n"); for(j=0;j<c;j++) { for(k=0;k<level;k++) { printf("%c",mat[k][j]); } } } return 0; }
C
//program to opendir, readdir and closedir #include<stdio.h> #include<dirent.h> #include<sys/types.h> #include<sys/stat.h> #include<unistd.h> int main() { DIR *dp; struct dirent *dptr; mkdir("Arun",0777); dp = opendir("Arun"); while((dptr = readdir(dp)) != NULL) { printf("%s/\n",dptr->d_name); printf("%d\n",dptr->d_type); printf("%llu\n",dptr->d_ino); } closedir(dp); }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <stdlib.h> #include <sys/wait.h> #include <sys/mman.h> #include <string.h> #define MAP_SIZE 512 int main() { char *mapped_area; if((mapped_area = (mmap(NULL, MAP_SIZE, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0))) == MAP_FAILED) { printf("[mmap == MAP_FAILED]\n"); return -1; } char *s = "Hello, mmap!"; pid_t pid = fork(); if(pid == -1) { // borked printf("[pid == -1]\n"); return -1; } else if(pid == 0) { // child sprintf(mapped_area, "%s", s); } else { // parent wait(NULL); printf("%s\n",mapped_area); } return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* flags.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: fhamel <fhamel@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/01/22 11:17:54 by fhamel #+# #+# */ /* Updated: 2020/03/10 12:31:53 by fhamel ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_printf.h" void init_flags(t_flags *flags) { flags->percent = 0; flags->rev = 0; flags->zero = 0; flags->nb1 = 0; flags->dot = 0; flags->nb2 = 0; } int get_nb_convert(char *str, va_list args) { int i; i = 0; if ('0' <= str[i] && str[i] <= '9') return (ft_atoi(&str[i])); else if (str[i] == '*') return (va_arg(args, int)); return (0); } void fill_flags(char *str, t_flags *flags, va_list args) { int i; i = 0; if (str[i] == '-' || str[i] == '0') { flags->rev = (str[i] == '-' ? 1 : 0); flags->zero = (str[i] == '0' ? 1 : 0); i++; } while (str[i] == '-' || str[i] == '0') i++; flags->nb1 = get_nb_convert(&str[i], args); while (!is_convert(str[i]) && str[i] != '.') i++; if (str[i] == '.') { flags->dot = 1; i++; flags->nb2 = get_nb_convert(&str[i], args); } }
C
/* * Compile: gcc put.c -o put */ #define _GNU_SOURCE #include <stdio.h> #include <sys/socket.h> #include <netdb.h> #include <sys/socket.h> #include <sys/types.h> #include <netinet/in.h> #include <arpa/inet.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <time.h> int main(int argc, char *argv[]) { struct hostent *he; struct sockaddr_in addr_in; int socket_fd = -1; int port; char *content, *payload = NULL; int length; char utc[100]; time_t now; /* check parameter count */ if (argc < 3) { fprintf(stderr, "not enough parameters\n"); return 1; } /* get port and resolve address */ port = atoi(argv[2]); if (port < 1 || port > 65535) { fprintf(stderr, "invalid port\n"); return 1; } he = gethostbyname(argv[1]); if (!he) { fprintf(stderr, "unable to resolve given host\n"); return 1; } /* connect */ socket_fd = socket(AF_INET, SOCK_STREAM, 0); if (socket_fd < 0) { fprintf(stderr, "unable to open socket\n"); return 1; } memset(&addr_in, 0, sizeof(addr_in)); addr_in.sin_family = AF_INET; memcpy(&addr_in.sin_addr.s_addr, he->h_addr, he->h_length); addr_in.sin_port = htons(port); if (connect(socket_fd, (struct sockaddr *)&addr_in, sizeof(addr_in)) < 0) { fprintf(stderr, "failed to connect\n"); return 1; } /* create payload */ now = time(NULL); strftime(utc, sizeof(utc), "%FT%TZ", gmtime(&now)); length = asprintf(&content, "{\"time\":\"%s\"}", utc); asprintf(&payload, "PUT /time/ HTTP/1.1\r\nContent-Length: %d\r\n\r\n%s", length, content); /* send */ write(socket_fd, payload, strlen(payload)); /* free resources */ close(socket_fd); free(content); free(payload); return 0; }
C
#include <stdio.h> #include <inttypes.h> #include "decode_png.h" #include "pngle.h" #include "esp_log.h" void png_init(pngle_t *pngle, uint32_t w, uint32_t h) { ESP_LOGD(__FUNCTION__, "png_init w=%"PRIu32" h=%"PRIu32, w, h); ESP_LOGD(__FUNCTION__, "screenWidth=%d screenHeight=%d", pngle->screenWidth, pngle->screenHeight); pngle->imageWidth = w; pngle->imageHeight = h; pngle->reduction = false; pngle->scale_factor = 1.0; // Calculate Reduction if (pngle->screenWidth < pngle->imageWidth || pngle->screenHeight < pngle->imageHeight) { pngle->reduction = true; double factorWidth = (double)pngle->screenWidth / (double)pngle->imageWidth; double factorHeight = (double)pngle->screenHeight / (double)pngle->imageHeight; pngle->scale_factor = factorWidth; if (factorHeight < factorWidth) pngle->scale_factor = factorHeight; pngle->imageWidth = pngle->imageWidth * pngle->scale_factor; pngle->imageHeight = pngle->imageHeight * pngle->scale_factor; } ESP_LOGD(__FUNCTION__, "reduction=%d scale_factor=%f", pngle->reduction, pngle->scale_factor); ESP_LOGD(__FUNCTION__, "imageWidth=%d imageHeight=%d", pngle->imageWidth, pngle->imageHeight); } #define rgb565(r, g, b) (((r & 0xF8) << 8) | ((g & 0xFC) << 3) | (b >> 3)) void png_draw(pngle_t *pngle, uint32_t x, uint32_t y, uint32_t w, uint32_t h, uint8_t rgba[4]) { ESP_LOGD(__FUNCTION__, "png_draw x=%"PRIu32" y=%"PRIu32" w=%"PRIu32" h=%"PRIu32, x,y,w,h); #if 0 uint8_t r = rgba[0]; uint8_t g = rgba[1]; uint8_t b = rgba[2]; #endif // image reduction uint32_t _x = x; uint32_t _y = y; if (pngle->reduction) { _x = x * pngle->scale_factor; _y = y * pngle->scale_factor; } if (_y < pngle->screenHeight && _x < pngle->screenWidth) { #if 0 pngle->pixels[_y][_x].red = rgba[0]; pngle->pixels[_y][_x].green = rgba[1]; pngle->pixels[_y][_x].blue = rgba[2]; #endif pngle->pixels[_y][_x] = rgb565(rgba[0], rgba[1], rgba[2]); } } void png_finish(pngle_t *pngle) { ESP_LOGD(__FUNCTION__, "png_finish"); }
C
#include <stdio.h> #include <stdlib.h> #include "game.h" #include <string.h> #include <time.h> #define SIZE 4 void print_bullscows(int bulls, int cows) { printf("Кол-во 'Быков' = %d\n", bulls); printf("Кол-во 'Коров' = %d\n", cows); } void string_to_int(int *digitmas) { int i = 0; char *str = (char*)malloc(sizeof(char)); printf("Введите четырёхзначное число, или 'q' для выхода:"); fgets(str, 15, stdin); if (str[0] == 'q' && strlen(str) == 2) { exit(0); } else { if ((digit_check(str)) && (repeat_digits(str))) { for (i = 0; i < SIZE; i++) { digitmas[i] = str[i] - 48; } } else { string_to_int(digitmas); } } } void print_result(int bulls, int *arr, int attempts) { int i = 0; if (bulls != 4) { printf("Вы проиграли!Загаднное число: "); for (i = 0; i < 4; i++) { printf("%d", arr[i]); } printf("\n"); } else { printf("Поздравляю, вы угадали число с %d попытки!\n", attempts); } } int getrand(int range_min, int range_max) { return range_min + rand() % (range_max - range_min + 1); } void randomizer(int *mas) { int range[10]; int size = 10; int n; for (int i = 0; i < 10; i++) { range[i] = i; } srand(time(NULL)); for (int i = 0; i < SIZE; i++) { n = getrand(0, size - 1); mas[i] = range[n]; if (mas[0] == 0) { randomizer(mas); } range[n] = range[size - 1]; size--; } } int bulls_counter(int *array_b, int *player_num) { int b = 0, i = 0; for (i = 3; i >= 0; i--) { if ((array_b[i]) == (player_num[i])) { b++; } } return b; } int cows_counter(int *array_c, int *player_n) { int c = 0, j = 0, i = 0; for (i = 3; i >= 0; i--) { for (j = 3; j >= 0; j--) { if ((array_c[j]) == (player_n[i])) { c++; } } } return c; } int digit_check(const char *str) { int i = 0; for (i = 0; i < strlen(str); i++) { if ((str[i] >= '0') && (str[i] <= '9') && (atoi(str) > 1000) && (str[4] == 10)) { return 1; } } printf("Неверный ввод,попробуйте ещё раз.\n"); return 0; } int startup_options_check(int argc, char **argv) { int n = 0; if (argc == 1 || atoi(argv[2]) == 0) { n = 10; } else { n = atoi(argv[2]); } return n; } int repeat_digits(const char *num) { int i, j; for (i = 0; i < strlen(num) - 1; i++) { for (j = i + 1; j < strlen(num); j++) { if (num[j] == num[i]) { printf("Неверный ввод, попробуйте ещё раз.\n"); return 0; } } } return 1; }
C
/* * vector_splat.h * * Created on: 8.2.2010 * Author: Lukáš Křivský */ #ifndef VECTOR_SPLAT_H_ #define VECTOR_SPLAT_H_ #include "vector_struct.h" //! Vector Splat /*! * Each element of the result is component b of a. * \param a Input vector * \param element Number of selected element * * \return It returns vector with selected component. */ __inline vector_t vector_splat_float (vector_t a, int element) { float temp; element = element & 3; temp = a.vf[element]; a.vf[0] = temp; a.vf[1] = temp; a.vf[2] = temp; a.vf[3] = temp; return a; } //! Vector Splat /*! * Each element of the result is component b of a. * \param a Input vector * \param element Number of selected element * * \return It returns vector with selected component. */ __inline vector_t vector_splat_sint (vector_t a, int element) { int temp; element = element & 3; temp = a.vsi[element]; a.vsi[0] = temp; a.vsi[1] = temp; a.vsi[2] = temp; a.vsi[3] = temp; return a; } //! Vector Splat /*! * Each element of the result is component b of a. * \param a Input vector * \param element Number of selected element * * \return It returns vector with selected component. */ __inline vector_t vector_splat_uint (vector_t a, int element) { unsigned int temp; element = element & 3; temp = a.vui[element]; a.vui[0] = temp; a.vui[1] = temp; a.vui[2] = temp; a.vui[3] = temp; return a; } //! Vector Splat /*! * Each element of the result is component b of a. * \param a Input vector * \param element Number of selected element * * \return It returns vector with selected component. */ __inline vector_t vector_splat_char (vector_t a, int element) { char temp; element = element & 0x0f; temp = a.vchar[element]; a.vchar[0] = temp; a.vchar[1] = temp; a.vchar[2] = temp; a.vchar[3] = temp; a.vchar[4] = temp; a.vchar[5] = temp; a.vchar[6] = temp; a.vchar[7] = temp; a.vchar[8] = temp; a.vchar[9] = temp; a.vchar[10] = temp; a.vchar[11] = temp; a.vchar[12] = temp; a.vchar[13] = temp; a.vchar[14] = temp; a.vchar[15] = temp; return a; } #endif /* VECTOR_SPLAT_H_ */
C
#include <include/dag.h> /* This example demonstrates a technique to create a DAG (directed acyclic graph). * The graph will build a tree with players, platoons, regions and units: * * - A unit belongs to a platoon (a platoon can have 0-n units) * - A platoon is in a region (a region can have 0-n platoons) * - A platoon is controlled by a player (a player can control 0-n platoons) * * After the DAG is constructed, a method is demonstrated to create extremely * fast intersections of the collection of units, subdivided by platoon, region and * and player. * * Because of the way the DAG is constructed, units are organized in tables that * are subdivided by platoon, and platoons are organized in tables that are * subdivided by player and region. The only thing a system has to do in order * to determine whether a table has entities containing to a parent, is checking * whether the the parent is part of the table components. * * This is an O(n) check where n is the number of components. N is typically * a very low number, especially when compared to the number of entities in a * table. */ /* Units have a Position and Health */ typedef struct Position { int32_t x; int32_t y; } Position; typedef int32_t Health; /* Add parents as components to child entities. This will split up entities * across different tables, which allows for making quick intersections based * on player, region or platoon */ static void adopt(EcsWorld *world, EcsEntity object, EcsEntity parent) { ecs_add(world, object, parent); } /* Create entities with the EcsContainer component. This allows entities to be * added to other entities just like normal components- with the exception that * they don't add data. */ static EcsEntity create(EcsWorld *world, EcsEntity parent, const char *id, EcsEntity type) { EcsEntity result = ecs_new(world, type); ecs_stage_add(world, result, EcsContainer_h); if (parent) ecs_stage_add(world, result, parent); ecs_set(world, result, EcsId, {id}); ecs_commit(world, result); return result; } static void ListUnits(EcsRows *rows) { EcsWorld *world = rows->world; void *row; for (row = rows->first; row < rows->last; row = ecs_next(rows, row)) { EcsEntity entity = ecs_entity(rows, row, ECS_ROW_ENTITY); EcsEntity platoon = ecs_entity(rows, row, 0); Position *p = ecs_data(rows, row, 1); Health *h = ecs_data(rows, row, 2); printf("Unit %llu, %s, position (%d,%d), health %d\n", entity, ecs_id(world, platoon), p->x, p->y, *h); } } static void ListPlatoons(EcsRows *rows) { EcsWorld *world = rows->world; EcsEntity ListUnits_h = ecs_component(rows, 3); void *row; for (row = rows->first; row < rows->last; row = ecs_next(rows, row)) { EcsEntity entity = ecs_entity(rows, row, ECS_ROW_ENTITY); EcsEntity player = ecs_entity(rows, row, 0); EcsEntity region = ecs_entity(rows, row, 1); printf("%s, %s, %s:\n", ecs_id(world, entity), ecs_id(world, region), ecs_id(world, player)); ecs_run(world, ListUnits_h, rows->delta_time, entity, NULL); } } int main(int argc, char *argv[]) { /* An EcsWorld contains all our entities, components and systems */ EcsWorld *world = ecs_init(); /* Register components */ ECS_COMPONENT(world, Position); ECS_COMPONENT(world, Health); /* Register tags for players, platoons and regions */ ECS_TAG(world, Player); ECS_TAG(world, Region); ECS_TAG(world, Platoon); /* Override all components from prefab in Unit family. The prefab is just * used here to provide default values for unit components. */ ECS_PREFAB(world, UnitPrefab, Position, Health); ECS_FAMILY(world, Unit, UnitPrefab, Position, Health); ecs_set(world, UnitPrefab_h, Position, {0, 0}); ecs_set(world, UnitPrefab_h, Health, {100}); /* On-demand system that lists all units. In addition to Position and Health * which are the "normal" components found on a unit, units also have the * Platoon entity. With CONTAINER.Platoon, we select the "Platoon" component * from this platoon entity. Since "Platoon" is a TAG and not a CONTAINER * it does not contain any data. The reason we still add it to the signature * is so we get access to the platoon entity. * * We can get access to the platoon entity with ecs_source in the system * callback, which gives us the entity on which the Platoon component was * found, which in this case is the platoon to which the unit belongs. */ ECS_SYSTEM(world, ListUnits, EcsOnDemand, CONTAINER.Platoon, Position, Health); /* On-demand system that lists all platoons. This system selects all * entities that have the "Platoon" tag. In addition, it references the * Player and Region TAGs in the same way ListUnit does for platoons. This * gives the system access to the player and region the platoon belongs to. * * Additionally, the ListUnits handle is passed to the system, so it can * invoke the ListUnits on-demand system to list the entities that match * with the platoon. */ ECS_SYSTEM(world, ListPlatoons, EcsOnDemand, CONTAINER.Player, CONTAINER.Region, Platoon, ID.ListUnits); /* Create players, platoons and regions */ EcsEntity player1 = create(world, 0, "Player 1", Player_h); EcsEntity player2 = create(world, 0, "Player 2", Player_h); EcsEntity region1 = create(world, 0, "Region 1", Region_h); EcsEntity region2 = create(world, 0, "Region 2", Region_h); EcsEntity platoon1 = create(world, player1, "Platoon 1", Platoon_h); EcsEntity platoon2 = create(world, player1, "Platoon 2", Platoon_h); EcsEntity platoon3 = create(world, player2, "Platoon 3", Platoon_h); /* Add platoons to regions, in addition to players */ adopt(world, platoon1, region1); adopt(world, platoon2, region2); adopt(world, platoon3, region2); /* Create units in platoons */ int i; for (i = 0; i < 5; i ++) create(world, platoon1, NULL, Unit_h); for (i = 0; i < 5; i ++) create(world, platoon2, NULL, Unit_h); for (i = 0; i < 5; i ++) create(world, platoon3, NULL, Unit_h); /* List all units */ printf("-- All units\n"); ecs_run(world, ListUnits_h, 1.0, 0, NULL); /* Only list units for platoon 2 */ printf("\n-- Platoon 2 filter\n"); ecs_run(world, ListUnits_h, 1.0, platoon2, NULL); /* Only list units/platoons for player 1 */ printf("\n-- Player 1 filter\n"); ecs_run(world, ListPlatoons_h, 1.0, player1, NULL); /* Only list units/platoons for region 2 */ printf("\n-- Region 2 filter\n"); ecs_run(world, ListPlatoons_h, 1.0, region2, NULL); /* Cleanup the world. */ return ecs_fini(world); }
C
#include "c1.h" #include<stdio.h> #include<string.h> #include<stdlib.h> unsigned int originalsize=0; //used in header stored in the beginning of compressed file. Gives number of characters in file. int usedchar = 0; //Gives the number of characters that are present in sentence int *freqarr = NULL; //Will be called ahead to create an array that'll store frequency and index of character node *nodes = NULL; //Will store the characters used and their frequency in sorted order int numnodes=0; //will store currennt index of node int arrofcodes[256][100]={}; //Will store the huffman codes for each of the 256 characters void initcode(treenode* root); //Function to initialize code of array void savecodes(treenode* root, int arr[], int top); //Function to get codes from traversing huffman tree and save it into array int flushbuffer(FILE *f); //Function for emptying buffer out completely unsigned char buffer[1]; //Buffer to keep bits(codes) int bitsinbuffer = 0; //Keeps track of bits already filled int stack[100]; //Will store the code of character to be encoded int huffman(char * ipfile, char * opfile){ FILE * fin; FILE * fout; if ((fin = fopen(ipfile, "rb")) == NULL){ perror("Failed to open input file"); return -1; } if ((fout = fopen(opfile, "wb")) == NULL) { perror("Failed to open output file"); return -1; } findfreq(fin); nodes=(node*)malloc(256 *(sizeof(node))); addleaves(); writeheader(fout); buildhuffmancomptree(); fseek(fin, 0, SEEK_SET); int c; while ((c = fgetc(fin)) != EOF){ encodealphabet(fout, c); } flushbuffer(fout); fclose(fin); fclose(fout); return 0; } void findfreq(FILE * f){ freqarr=(int *)malloc(256 * (sizeof(int))); int ch; while (1) { ch = fgetc(f); if (ch == EOF) break; freqarr[ch]++; originalsize++; } for(ch=0;ch<256;ch++){ if (freqarr[ch] > 0) usedchar++; } } void addleaves() { int i, freq; for (i = 0; i < 256; ++i) { freq = freqarr[i]; if (freq > 0) addnode(i, freq); } } void addnode(char index, int weight) { int i = numnodes; while (i > 0 && nodes[i-1].weight > weight) { memcpy(&nodes[i], &nodes[i-1], sizeof(node)); i--; } nodes[i].index = index; nodes[i].weight = weight; numnodes++; } int writeheader(FILE *f) { int i, j, byte = 0, size = sizeof(unsigned int) + sizeof(int) + (usedchar * (1 + sizeof(int))); unsigned int weight; char *buffer = (char *)malloc(size* (sizeof(char))); if (buffer == NULL) return -1; j = sizeof(int); while (j--){ buffer[byte++] =(originalsize >> (j << 3)) & 0xff; //Will store last 8 bits of integer byte. Little Endian } j=sizeof(int); while(j--){ buffer[byte++]=(usedchar >> (j<< 3)) & 0xff; } for (i = 0; i < usedchar; ++i) { weight = nodes[i].weight; buffer[byte++] =nodes[i].index; j = sizeof(int); while (j--){ buffer[byte++] = (weight >> (j << 3)) & 0xff; //Will store weight also according to little endian } } fwrite(buffer, 1, size, f); free(buffer); return 0; } void buildhuffmancomptree(){ int i; char * arr=(char *)malloc(usedchar * (sizeof(char))); int * freq=(int *)malloc(usedchar * (sizeof(int))); for(i=0;i<usedchar;i++){ arr[i]=nodes[i].index; freq[i]=nodes[i].weight; } int size = usedchar; treenode* root = buildHuffmanTree(arr, freq, size); initcode(root); } void initcode(treenode* root){ int i,j; for(i=0;i<256;i++){ arrofcodes[i][0]=-1; } int arr1[100], top = 0; savecodes(root, arr1, top); } void savecodes(treenode* root, int arr[], int top){ if (root->left) { arr[top] = 0; savecodes(root->left, arr, top + 1); } if (root->right){ arr[top] = 1; savecodes(root->right, arr, top + 1); } if (!(root->left) && !(root->right)) { int i; for (i = 0; i < top; ++i){ arrofcodes[root->data][i]=arr[i]; } arrofcodes[root->data][i]=-1; } } void encodealphabet(FILE *fout, int character) { int stackidx = 0,i; for(i=0;i<100;i++){ if(arrofcodes[character][i]!=-1){ stack[i]=arrofcodes[character][i]; } else{ break; } } while (stackidx<i){ writebit(fout, stack[stackidx]); stackidx++; } } int writebit(FILE *f, int bit) { if (bitsinbuffer == 8) { fwrite(buffer, 1, 1, f); bitsinbuffer = 0; memset(buffer, 0, 1); } if (bit) buffer[0] |= 1 << (7-bitsinbuffer); bitsinbuffer++; return 0; } int flushbuffer(FILE *f) { if (bitsinbuffer) { fwrite(buffer, 1, 1, f); bitsinbuffer = 0; } return 0; } treenode* newNode(char data, unsigned freq){ treenode* temp = (treenode*)malloc(sizeof(treenode)); temp->left = temp->right = NULL; temp->data = data; temp->freq = freq; return temp; } tree* createtree(unsigned capacity){ tree* hufftree = (tree*)malloc(sizeof(tree)); hufftree->size = 0; hufftree->array = (treenode**)malloc(capacity * sizeof(treenode*)); return hufftree; } void minHeapify(tree* hufftree, int idx){ int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < hufftree->size && hufftree->array[left]-> freq < hufftree->array[smallest]->freq) smallest = left; if (right < hufftree->size && hufftree->array[right]->freq < hufftree->array[smallest]->freq) smallest = right; if (smallest != idx){ treenode* temp=hufftree->array[smallest]; hufftree->array[smallest]=hufftree->array[idx]; hufftree->array[idx]=temp; minHeapify(hufftree, smallest); } } treenode* extractMin(tree* hufftree) { treenode* temp = hufftree->array[0]; hufftree->array[0] = hufftree->array[hufftree->size - 1]; --hufftree->size; minHeapify(hufftree, 0); return temp; } void inserttree(tree* hufftree,treenode* hufftreenode){ hufftree->size++; int i = hufftree->size - 1; while (i && hufftreenode->freq < hufftree->array[(i - 1) / 2]->freq) { hufftree->array[i] = hufftree->array[(i - 1) / 2]; i = (i - 1) / 2; } hufftree->array[i] = hufftreenode; } tree* createAndBuildtree(char data[], int freq[], int size){ tree* hufftree = createtree(size); for (int i = 0; i < size; ++i){ hufftree->array[i] = newNode(data[i], freq[i]); } hufftree->size = size; return hufftree; } treenode* buildHuffmanTree(char data[], int freq[], int size) { treenode *left, *right, *top; tree* hufftree = createAndBuildtree(data, freq, size); while (!(hufftree->size==1)) { left = extractMin(hufftree); right = extractMin(hufftree); top = newNode('$', left->freq + right->freq); // '$' is a special value for internal nodes, not used top->left = left; top->right = right; inserttree(hufftree, top); } return extractMin(hufftree); }
C
#include<stdio.h> #include<stdlib.h> typedef struct node{ int coeff; int exp; struct node *next; }*NODE; NODE insertsort(NODE l,int c,int e){ NODE n=(NODE)malloc(sizeof(struct node)); n->coeff=c; n->exp=e; n->next=NULL; if(l==NULL){ return n; } if(e<=l->exp){ n->next=l; return n; } NODE prev,curr=l; while(curr!=NULL && e>curr->exp){ prev=curr; curr=curr->next; } prev->next=n; n->next=curr; return l; } void display(NODE f) { NODE t=f; printf("\nLIST ELEMENTS: "); while(t->next!=NULL) { if((t->next)->coeff>=0) printf("%dX^%d+",t->coeff,t->exp); else printf("%dX^%d",t->coeff,t->exp); t=t->next; } printf("%dX^%d\n",t->coeff,t->exp); } void subtract(NODE l1,NODE l2){ int c; int diff; NODE l3=NULL; while(l1!=NULL && l2!=NULL){ if(l1->exp==l2->exp)c=0; else if(l1->exp<l2->exp)c=1; else c=2; switch(c){ case 0: diff=l1->exp-l2->exp; if(diff){ l3=insertsort(l3,diff,l1->exp); } l1=l1->next; l2=l2->next; break; case 1: l3=insertsort(l3,l1->coeff,l1->exp); l1=l1->next; break; case 2: l3=insertsort(l3,l1->coeff,l1->exp); l1=l1->next; break; } } while(l1!=NULL){ l3=insertsort(l3,l1->coeff,l1->exp); l1=l1->next; } while(l2!=NULL){ l3=insertsort(l3,l2->coeff,l2->exp); l2=l2->next; } display(l3); } NODE multiply(NODE poly1,NODE poly2,NODE poly3){ NODE ptr1, ptr2; ptr1 = poly1; ptr2 = poly2; while (ptr1 != NULL) { while (ptr2 != NULL) { int coeff, power; // Multiply the coefficient of both // polynomials and store it in coeff coeff = ptr1->coeff * ptr2->coeff; // Add the powerer of both polynomials // and store it in power power = ptr1->exp + ptr2->exp; // Invoke addnode function to create // a newnode by passing three parameters poly3 = insertsort(poly3, coeff, power); // move the pointer of 2nd polynomial // two get its next term ptr2 = ptr2->next; } // Move the 2nd pointer to the // starting point of 2nd polynomial ptr2 = poly2; // move the pointer of 1st polynomial ptr1 = ptr1->next; } // this function will be invoke to add // the coefficient of the elements // having same powerer from the resultant linked list removedup(poly3); return poly3; } void removedup(NODE poly3){ NODE curr=poly3; while(curr!=NULL && curr ->next!=NULL) { if(curr->exp==curr->next->exp){ NODE dup=curr->next; curr->coeff=curr->coeff+dup->coeff; curr->next=dup->next; free(dup); } else{ curr=curr->next; } } } int main() { NODE f=NULL; NODE s=NULL; int ch; int c; int e; printf("INPUT THE FIRST LIST:"); do { printf("\nINPUT YOUR CHOICE\n"); printf("1.PUSH\t2.EXIT AND INPUT NEW LIST\n"); scanf("%d",&ch); switch(ch) { case 1: printf("INPUT COEFFICIENT AND EXPONENT:\n"); scanf("%d%d",&c,&e); f=insertsort(f,c,e); break; case 2: printf("\nINPUT SECOND LIST:"); break; } }while(ch!=2); do { printf("\nINPUT YOUR CHOICE\n"); printf("1.PUSH\t2.EXIT AND INPUT NEW LIST\n"); scanf("%d",&ch); switch(ch) { case 1: printf("INPUT COEFFICIENT AND EXPONENT:\n"); scanf("%d%d",&c,&e); s=insertsort(s,c,e); break; case 2: printf("\nDISPLAYING GIVEN LISTS:\n"); break; } }while(ch!=2); display(f); display(s); printf("\nAFTER SUBTRACTION:"); subtract(f,s); printf("\nAFTER MULTIPLICATION:"); NODE l3=NULL; l3=multiply(f,s,l3); display(l3); return 0; }
C
#include <assert.h> #include "linked_list_api.h" void test_create_node() { int a = 5; node_t *node_a = create_node(&a); /* SO link about casting: * https://stackoverflow.com/questions/16016920/type-casting-integer-to-void */ assert(*((int *)node_a->data) == a); char c = 'q'; node_t *node_c = create_node(&c); assert(*((char *)node_c->data) == c); char *str_b = "b"; node_t *node_b = create_node(str_b); assert(*((char *)node_b->data) == *str_b); printf("test_create_node done!\n"); } void test_add_prev() { int a = 5; int b = 7; char c = 'q'; node_t *head = create_node(&a); add_prev(head, create_node(&c)); assert(*((char *)head->prev->data) == 'q'); add_prev(head, create_node(&b)); assert(*((int *)head->prev->data) == 7); assert(head->prev->prev->prev == NULL); printf("test_add_prev done!\n"); } void test_add_to_end(){ node_t *head = NULL; int a = 3; add_to_end(&head, create_node(&a)); assert( *((int *)head->data) == 3); assert(head->prev == NULL); int b = 1; add_to_end(&head, create_node(&b)); assert( *((int *)head->data) == 3); assert(*((int *)head->next->data) == 1); printf("test_add_to_end done!\n"); } void test_find_node() { int a = 5; int b = 7; char c = 'c'; char *sz = "szStr"; double d = 2.3; int not_in_list = 123; node_t *head = NULL; assert(find_node(&head,create_node(&a)) == NULL); add_to_end(&head, create_node(&a)); add_to_end(&head, create_node(&c)); add_to_end(&head, create_node(&b)); add_to_end(&head, create_node(sz)); add_to_end(&head, create_node(&d)); assert(*((int *)find_node(&head,&b)->data) == b); assert(find_node(&head, create_node(&not_in_list)) == NULL); puts("test_find_node done!"); } int main(void) { test_create_node(); test_add_prev(); test_add_to_end(); test_find_node(); }
C
/* Nikola Kilibarda and Matthew Mabrey CSC-345-01 Operating Systems Dr. Yoon Project 3 */ #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <stdbool.h> #define PAGE_SIZE 256 #define BUFFER_SIZE 10 #define NUMBER_OF_FRAMES 256 #define PAGE_TABLE_SIZE 256 #define BLOCK 256 #define TLB_SIZE 16 #define FRAME_SIZE 128 struct TlbEntry { int frame_num; int pg_num; int isValid; }; /*file declaration*/ FILE *backing_store_bin; FILE *address_file; FILE *out1; FILE *out2; FILE *out3; typedef struct TlbEntry TlbEntry_t; signed char physical_memory[FRAME_SIZE][PAGE_SIZE]; /* a char array read into logical addresses from the file*/ char input_address[BUFFER_SIZE]; int phys_addr; int logc_addr; int frame_num; int pg_num; int offset; int val = 0; int TlbHits = 0; int pg_faults = 0; int nxt_open_tlb_indx = 1; int nxt_open_frame = 0; int frame_cnt = 0; int nxt_frame = 0; bool foundFlg = false; int pg_no_indx = 0; int page_table[PAGE_TABLE_SIZE]; int frame_table[128]; TlbEntry_t table[TLB_SIZE]; /* an array to read the frame from the backing store */ signed char frame_tmp[PAGE_SIZE]; int get_page_number(int logc_addr); int get_offset(int logc_addr); void initialize_page_table(); void initTlb(); int checkTlb(int pg_num); int check_page_table(int pg_num); int main(int argc, char *argv[]) { /* Check for user input */ if(argc < 2){ printf("You must enter the name of an input file!\n"); return 1; } /*open the address file for reading*/ address_file = fopen(argv[1], "rt"); /*open the backing store binary file*/ backing_store_bin = fopen("BACKING_STORE.bin", "rb"); /*open the file write the logical addressess*/ out1 = fopen("out1.txt", "wt"); /*open the file to write the physical addressess*/ out2 = fopen("out2.txt", "wt"); /*open the file to write the vals*/ out3 = fopen("out3.txt", "wt"); if (address_file == NULL) { printf("Cannot open file addresses.txt"); return -1; } if (backing_store_bin == NULL) { printf("Cannot open file BACKING_STORE.bin"); return -1; } /*reset TLB*/ initTlb(); /*reset/init the page table*/ initialize_page_table(); while (fgets(input_address, BUFFER_SIZE, address_file) != NULL) { logc_addr = atoi(input_address); pg_num = get_page_number(logc_addr); /*First check TLB*/ frame_num = checkTlb(pg_num); offset = get_offset(logc_addr); /*then check the page table*/ if (frame_num == -1) { frame_num = check_page_table(pg_num); } /*construct the physical address for the frame number and offset*/ phys_addr = (frame_num << 8) | offset; val = physical_memory[frame_num][offset]; /*write to the files*/ fprintf(out1, "%d\n", logc_addr); fprintf(out2,"%d\n", phys_addr); fprintf(out3, "%d\n", val); } printf("Page faults = %d / 1000, %.3f\n", pg_faults, ((double)pg_faults/1000)); printf("TLB hits = %d / 1000, %.3f\n", TlbHits, ((double)TlbHits/1000)); /*closing the files after finished writting*/ fclose(out1); fclose(out2); fclose(out3); fclose(address_file); fclose(backing_store_bin); return 0; } void initialize_page_table() { int k=0; while ( k < PAGE_TABLE_SIZE) { page_table[k] = -1; k++; } } int get_offset(int logc_addr) { return (logc_addr & 255); } int get_page_number(int logc_addr) { return (logc_addr & 65280) >> 8; } int checkTlb(int pg_num) { int frame_num = -1; int k = 0; while ( k < TLB_SIZE) { if ((table[k].pg_num == pg_num) && (table[k].isValid == 1)){ frame_num = table[k].frame_num; TlbHits++; break; } k++; } return frame_num; } void initTlb() { int k=0; while (k < TLB_SIZE) { table[k].frame_num = -1; table[k].pg_num = -1; table[k].isValid = -1; k++; } } int check_page_table(int pg_num) { foundFlg=false; frame_num = page_table[pg_num]; int k = 0; // if frame not in page table get from the backing store if (frame_num == -1) { //count page faults ++pg_faults; //get the info from the backing store fseek(backing_store_bin, pg_num * PAGE_SIZE, SEEK_SET); fread(frame_tmp, sizeof(signed char), PAGE_SIZE, backing_store_bin); while (k < PAGE_SIZE) { physical_memory[nxt_frame][k] = frame_tmp[k]; k++; } // page replacement due to max_frame = 128 if (!(FRAME_SIZE > frame_cnt)) { //since the frame will be overwritten, search for page in page table and set to -1 for (k = 0; k < PAGE_TABLE_SIZE; k++) { if (page_table[k] == nxt_frame) { page_table[k] = -1; pg_no_indx = k; break; } } } //get frame from the page_table[page_num] FIFO page_table[pg_num] = nxt_frame; frame_num = page_table[pg_num]; nxt_frame = (nxt_frame + 1) % FRAME_SIZE; frame_cnt++; } // in case that overwritten page exist in the tlb, find the frame in tlb and update the page. for (k = 0; k < TLB_SIZE; k++) { if (frame_num == table[k].frame_num) { table[k].pg_num = pg_num; foundFlg = true; } } //if frame not in tlb in the TLB update it. if (!foundFlg) { table[nxt_open_tlb_indx].frame_num = frame_num; table[nxt_open_tlb_indx].pg_num = pg_num; table[nxt_open_tlb_indx].isValid = true; /*FIFO*/ nxt_open_tlb_indx = (nxt_open_tlb_indx + 1) % TLB_SIZE; } return frame_num; }
C
/* Nome: Aula 5 - Estrutura IF-ELSE Copyright: ESAMC - Francisco Author: Elton Date: 23/03/2020 - 20:22 Description: Exerccio 10 - INSS alquota */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main () { float sal, INSS, saldev; //pega trs variveis printf("Digite o seu salary: "); //Pede para digitar o seu salrio scanf("%f", &sal); //Voc digita o salrio na varivel sal if (sal < 1174.86) //Se o salrio for menor que esse... { INSS = 0.08; //o INSS ser 8% printf("seu INSS deu 8 por cento \n"); //dir isso saldev = sal * INSS; //far conta com o salrio dado printf("E seu salary que deve is: %.2f", saldev); //e falar qual a quantia que ele deve } else if (sal >= 1174.86 && sal <= 1958.10) { INSS = 0.09; //o INSS ser 9% printf("seu INSS deu 9 por cento \n"); //dir isso saldev = sal * INSS; //far conta com o salrio dado printf("E seu salary que deve is: %.2f", saldev); //e falar qual a quantia que ele deve } else if (sal >= 1958.10 && sal <= 3916.20) { INSS = 0.11; //o INSS ser 11% printf("seu INSS deu 11 por cento \n"); //dir isso saldev = sal * INSS; //far conta com o salrio dado printf("E seu salary que deve is: %.2f", saldev); //e falar qual a quantia que ele deve } else { saldev = 430.78; //J dar a quantia que ele deve printf("E seu salary que deve is: R$%.2f ", saldev); //E falar isso... } }
C
// daca o dau in bara iar cu git-ul sa-mi spui te rog ^^' #include <stdio.h> #include <stdlib.h> #include "ListGraph.h" #include "MatrixGraph.h" #include "Queue.h" #include "Stack.h" #define MAX_NODES 10 static int time; // generez un graf cu 5 noduri si 5 muchii pt teste: // 0: 1 2 3 // 1: 0 2 // 2: 0 1 4 // 3: 0 // 4: 2 void generate_lg_graph(list_graph_t* lg, int *numbers) { lg_add_edge(lg, numbers[0], numbers[1]); lg_add_edge(lg, numbers[0], numbers[2]); lg_add_edge(lg, numbers[0], numbers[3]); lg_add_edge(lg, numbers[1], numbers[2]); lg_add_edge(lg, numbers[2], numbers[4]); } void generate_mg_graph(matrix_graph_t* mg, int *numbers) { mg_add_edge(mg, numbers[0], numbers[1]); mg_add_edge(mg, numbers[0], numbers[2]); mg_add_edge(mg, numbers[0], numbers[3]); mg_add_edge(mg, numbers[1], numbers[2]); mg_add_edge(mg, numbers[2], numbers[4]); } void print_matrix_graph(matrix_graph_t* mg) { for(int i = 0; i < mg->nodes; i++) { for(int j = 0; j < mg->nodes; j++) { printf("%d ", mg->matrix[i][j]); } printf("\n"); } } void print_list_graph(list_graph_t* lg) { for(int i = 0; i < lg->nodes; i++) { // are vecini if(lg->neighbors[i]->size) { printf("%d: ", i); ll_print_int(lg->neighbors[i]); } } } void dfs_list_graph_recursive(list_graph_t* lg, int node, int* visited, int* t_desc, int* t_fin) { visited[node] = 1; t_desc[node] = time++; printf("%d ", node); ll_node_t *current = lg->neighbors[node]->head; while(current != NULL) { // daca nodul nu a fost vizitat pana acum if(!visited[*(int *)current->data]) { dfs_list_graph_recursive(lg, *(int *)current->data, visited, t_desc, t_fin); } current = current->next; } t_fin[node] = time++; } void dfs_list_graph_iterative(list_graph_t* lg, int node, int* visited, int* t_desc, int* t_fin) { for(int i = 0; i < lg->nodes; i++) { visited[i] = 0; } stack_t *st = st_create(sizeof(int)); visited[node] = 1; st_push(st, &node); while(!st_is_empty(st)) { node = *(int *)st_peek(st); st_pop(st); t_fin[node]++; printf("%d ", node); ll_node_t *current = lg->neighbors[node]->head; while(current != NULL) { // daca nodul nu a fost vizitat pana acum if(!visited[*(int *)current->data]) { visited[*(int *)current->data] = 1; t_desc[*(int *)current->data]++; st_push(st, current->data); } current = current->next; } } printf("\n"); st_free(st); } void dfs_matrix_graph(matrix_graph_t* mg, int node, int* visited, int* t_desc, int* t_fin) { visited[node] = 1; t_desc[node] = time++; printf("%d ", node); for(int j = 0; j < mg->nodes; j++) { // exista muchie si nodul n-a fost inca vizitat if(mg->matrix[node][j] == 1 && visited[j] == 0) { dfs_matrix_graph(mg, j, visited, t_desc, t_fin); } } t_fin[node] = time++; } void bfs_list_graph(list_graph_t* lg, int* visited, int* parent) { int node; for(int i = 0; i < lg->nodes; i++) { visited[i] = 0; } queue_t *q = q_create(sizeof(int), lg->nodes); // incep parcurgerea de la parent visited[*parent] = 1; q_enqueue(q, parent); while(!q_is_empty(q)) { node = *(int *)q_front(q); printf("%d ", node); q_dequeue(q); ll_node_t *current = lg->neighbors[node]->head; while(current != NULL) { // daca nodul nu a fost vizitat pana acum if(!visited[*(int *)current->data]) { visited[*(int *)current->data] = 1; q_enqueue(q, current->data); } current = current->next; } } printf("\n"); q_free(q); } void bfs_matrix_graph(matrix_graph_t* mg, int* visited, int* parent) { int nodes[mg->nodes]; for(int i = 0; i < mg->nodes; i++) { nodes[i] = -1; visited[i] = 0; } // nodes[] -> nodurile parcurse // visited[] -> tin evidenta parcurgerii nodes[0] = *parent; visited[*parent] = 1; int index_node = 0, index_vis = 0; // index_node > index_vis => nu mai am nicio alta muchie si ma opresc while(index_node <= index_vis) { for(int k = 0; k < mg->nodes; k++) { // exista muchie si nodul n-a fost inca vizitat if(mg->matrix[*parent][k] == 1 && visited[k] == 0) { index_vis++; nodes[index_vis] = k; visited[k] = 1; } } index_node++; *parent = nodes[index_node]; } for(int i = 0; i < mg->nodes; i++) { if(nodes[i] != -1) { printf("%d ", nodes[i]); } } printf("\n"); } void bfs_matrix_graph_queue(matrix_graph_t* mg, int* visited, int* parent) { int node; for(int i = 0; i < mg->nodes; i++) { visited[i] = 0; } queue_t *q = q_create(sizeof(int), mg->nodes); // incep parcurgerea de la parent visited[*parent] = 1; q_enqueue(q, parent); while(!q_is_empty(q)) { node = *(int *)q_front(q); printf("%d ", node); q_dequeue(q); for(int i = 0; i < mg->nodes; i++) { if(mg_has_edge(mg, node, i) && !visited[i]) { visited[i] = 1; q_enqueue(q, &i); } } } printf("\n"); } void floyd_warshall(matrix_graph_t* mg) { /* TODO BONUS */ } int main() { int nodes, edges; int x[MAX_NODES], y[MAX_NODES]; int visited[MAX_NODES], t_desc[MAX_NODES], t_fin[MAX_NODES]; list_graph_t* lg = lg_create(MAX_NODES); matrix_graph_t* mg = mg_create(MAX_NODES); int numbers[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; printf("-------------------------------- Test ListGraph " "--------------------------------\n"); // Test add_edge_list_graph has_edge_list_graph lg_add_edge(lg, numbers[0], numbers[1]); lg_add_edge(lg, numbers[3], numbers[2]); printf("#1:\nOutput: %d\nOutput asteptat: 1\n", lg_has_edge(lg, numbers[0], numbers[1])); printf("#2:\nOutput: %d\nOutput asteptat: 1\n", lg_has_edge(lg, numbers[3], numbers[2])); printf("#3:\nOutput: %d\nOutput asteptat: 0\n", lg_has_edge(lg, numbers[2], numbers[4])); // Test remove_edge_list_graph lg_remove_edge(lg, numbers[0], numbers[1]); printf("#4:\nOutput: %d\nOutput asteptat: 0\n", lg_has_edge(lg, numbers[0], numbers[1])); /* Test get_neighbours_list_graph */ lg_add_edge(lg, numbers[0], numbers[1]); lg_add_edge(lg, numbers[0], numbers[2]); lg_add_edge(lg, numbers[0], numbers[3]); lg_add_edge(lg, numbers[0], numbers[4]); linked_list_t* l = lg_get_neighbours(lg, numbers[0]); printf("#5:\n"); printf("Output: "); ll_print_int(l); printf("Output asteptat: 1 2 3 4\n"); printf("-------------------------------- Test MatrixGraph " "--------------------------------\n"); /* test add edge_matrix_graph has_edge_matrix_graph */ mg_add_edge(mg, numbers[0], numbers[1]); mg_add_edge(mg, numbers[3], numbers[2]); printf("#1:\nOutput: %d\nOutput asteptat: 1\n", mg_has_edge(mg, numbers[0], numbers[1])); printf("#2:\nOutput: %d\nOutput asteptat: 1\n", mg_has_edge(mg, numbers[3], numbers[2])); printf("#3:\nOutput: %d\nOutput asteptat: 0\n", mg_has_edge(mg, numbers[2], numbers[4])); /* test remove_edge_matrix_graph */ mg_remove_edge(mg, numbers[0], numbers[1]); printf("#4:\nOutput: %d\nOutput asteptat: 0\n", mg_has_edge(mg, numbers[0], numbers[1])); lg_free(lg); mg_free(mg); printf("-------------------------------- Test BFS_ListGraph " "--------------------------------\n"); lg = lg_create(MAX_NODES); generate_lg_graph(lg, numbers); printf("#1:\nOutput: "); bfs_list_graph(lg, visited, &numbers[2]); printf("Output asteptat: 2 0 1 4 3\n"); printf("#2:\nOutput: "); bfs_list_graph(lg, visited, &numbers[1]); printf("Output asteptat: 1 0 2 3 4\n"); printf("-------------------------------- Test DFS_Recursive_ListGraph " "--------------------------------\n"); for(int i = 0; i < lg->nodes; i++) { visited[i] = 0; } printf("#1:\nOutput: "); dfs_list_graph_recursive(lg, numbers[0], visited, t_desc, t_fin); printf("\nOutput asteptat: 0 1 2 4 3\n"); for(int i = 0; i < lg->nodes; i++) { visited[i] = 0; } printf("#2:\nOutput: "); dfs_list_graph_recursive(lg, numbers[3], visited, t_desc, t_fin); printf("\nOutput asteptat: 3 0 1 2 4\n"); printf("-------------------------------- Test DFS_Iterative_ListGraph " "--------------------------------\n"); printf("#1:\nOutput: "); dfs_list_graph_iterative(lg, numbers[0], visited, t_desc, t_fin); printf("Output asteptat: 0 3 2 4 1\n"); printf("#2:\nOutput: "); dfs_list_graph_iterative(lg, numbers[1], visited, t_desc, t_fin); printf("Output asteptat: 1 2 4 0 3\n"); lg_free(lg); printf("-------------------------------- Test BFS_MatrixGraph " "--------------------------------\n"); mg = mg_create(MAX_NODES); generate_mg_graph(mg, numbers); printf("#1:\nOutput: "); bfs_matrix_graph(mg, visited, &numbers[2]); printf("Output asteptat: 2 0 1 4 3\n"); printf("#2:\nOutput: "); bfs_matrix_graph_queue(mg, visited, &numbers[4]); printf("Output asteptat: 4 2 0 1 3\n"); printf("-------------------------------- Test DFS_MatrixGraph " "--------------------------------\n"); for(int i = 0; i < mg->nodes; i++) { visited[i] = 0; } printf("#1:\nOutput: "); dfs_matrix_graph(mg, numbers[3], visited, t_desc, t_fin); printf("\nOutput asteptat: 3 0 1 2 4\n"); for(int i = 0; i < mg->nodes; i++) { visited[i] = 0; } printf("#2:\nOutput: "); dfs_matrix_graph(mg, numbers[1], visited, t_desc, t_fin); printf("\nOutput asteptat: 1 0 2 4 3\n"); mg_free(mg); return 0; }
C
#include<stdio.h> #include<pthread.h> #include<stdlib.h> #include<signal.h> #include<unistd.h> #include<sys/types.h> #include<termios.h> #include <sys/stat.h> #include <fcntl.h> #include<malloc.h> #define ITERATIONS_TO_CHECK 10000 int THREADS_NUM = 0; int flag = 0; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_barrier_t barrier; int max_iter = 0; void quit_handler(int sign) { // signal(sign, SIG_IGN); // if(sign == SIGINT) { printf("flag is true\n"); // pthread_mutex_lock(&mutex); flag = 1; // pthread_mutex_unlock(&mutex); // } } struct Param { int offset; double result; }; void* execute_thread(void* args) { struct sigaction action; struct sigaction ign; // action.sa_flags = SA_SIGINFO; // action.sa_sigaction = quit_handler; // ign.sa_flags = SA_SIGINFO; // ign.sa_sigaction = SIG_IGN; // if (sigaction(SIGINT, &action, NULL) == -1) { // perror("sigusr: sigaction"); // _exit(1); // } double pi = 0.0; struct Param* param = (struct Param*)args; int i; int iter = 0; while(1) { printf("%d\n", param->offset); for(i = iter*10000 + param->offset; i < (iter+1)*10000; i+=THREADS_NUM) { pi += 1.0/(i*4.0 + 1.0); pi -= 1.0/(i*4.0 + 3.0); } // if(flag != 1) { // if (sigaction(SIGINT, &ign, NULL) == -1) { // perror("sigusr: sigaction"); // _exit(1); // } // pthread_mutex_lock(&mutex); // pthread_mutex_unlock(&mutex); pthread_barrier_wait(&barrier); // if (sigaction(SIGINT, &action, NULL) == -1) { // perror("sigusr: sigaction"); // _exit(1); // } // } pthread_mutex_lock(&mutex); if((flag == 1)) { pthread_mutex_unlock(&mutex); printf("thread-%d result=%f\n", param->offset, pi); ((struct Param*)args)->result = pi; // pthread_exit(args); break; } else { iter++; if(iter<max_iter) max_iter = iter; } pthread_mutex_unlock(&mutex); } pthread_exit(args); } int main(int argc, char* argv[]) { if(argc != 2) { printf("bad arguments number"); return 0; } THREADS_NUM = atoi(argv[1]); if(pthread_barrier_init(&barrier, NULL, THREADS_NUM) != 0) { printf("barrirer init\n"); exit(-1); } signal( SIGINT, quit_handler); signal( SIGTERM, quit_handler); pthread_t thread[THREADS_NUM]; int status; int status_addr, i, j; struct Param* params; params = (struct Param*)malloc(sizeof(struct Param)*THREADS_NUM); for(i = 0; i < THREADS_NUM; i++) { params[i].offset = i; status = pthread_create(&thread[i], NULL, execute_thread, &(params[i])); if(status != 0) fprintf(stderr, "Error creating thread\n"); } double result = 0.0; for(i = 0; i < THREADS_NUM; i++) { struct Param* res; status = pthread_join(thread[i], (void**)&res); result += res->result; } result = result * 4.0; printf("pi done - %.15g \n", result); pthread_barrier_destroy(&barrier); free(params); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* parser.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: seruiz <seruiz@student.42lyon.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/02 13:18:34 by seruiz #+# #+# */ /* Updated: 2021/03/15 14:17:07 by seruiz ### ########lyon.fr */ /* */ /* ************************************************************************** */ #include "minishell_parser.h" int ft_cat(char *dest, char *s, int j) { int i; i = 0; while (s[i]) { dest[j] = s[i]; i++; j++; } return (j); } char *ft_strjoin_free(char *s1, char *s2) { char *str; int j; size_t str1_lenght; size_t str2_lenght; j = 0; str1_lenght = ft_strlen(s1); str2_lenght = ft_strlen(s2); str = ft_managed_malloc(sizeof(char) * (str1_lenght + str2_lenght + 1)); str[str1_lenght + str2_lenght] = '\0'; j = ft_cat(str, s1, 0); j = ft_cat(str, s2, j); ft_managed_free(s1); ft_managed_free(s2); return (str); } void ft_fill_mask(char *mask, char c, int len, t_shell_command *str_struct) { while (len >= 0) { mask[len] = c; len--; } if (str_struct->command_mask == NULL) str_struct->command_mask = mask; else str_struct->command_mask = ft_strjoin_free(str_struct->command_mask, mask); } void ft_fill_str(char *line, int j, int len, t_shell_command *str_struct) { char *s; int x; x = 0; s = ft_managed_malloc(sizeof(char) * len + 1); s[len] = '\0'; while (x < len) { s[x] = line[j]; x++; j++; } if (str_struct->command_string == NULL) str_struct->command_string = s; else str_struct->command_string = ft_strjoin_free(str_struct->command_string, s); } int ft_single_quote(char *line, int j, t_shell_command *str_struct) { int ret; char *mask; ret = j + 1; while (line[ret] && line[ret] != '\'') ret++; mask = ft_managed_malloc(sizeof(char) * (ret - j)); mask[ret - j - 1] = '\0'; ft_fill_mask(mask, '1', ret - j - 2, str_struct); ft_fill_str(line, j + 1, ret - j - 1, str_struct); if (line[ret] != '\'') return (ret); return (ret + 1); } int ft_double_quote(char *line, int j, t_shell_command *str_struct) { int ret; char *mask; ret = j + 1; while ((line[ret] && (line[ret] != '\"' && ret - 1 >= 0)) || line[ret - 1] == '\\') ret++; mask = ft_managed_malloc(sizeof(char) * (ret - j)); mask[ret - j - 1] = '\0'; ft_fill_mask(mask, '2', ret - j - 2, str_struct); ft_fill_str(line, j + 1, ret - j - 1, str_struct); if (line[ret] != '\"') return (ret); return (ret + 1); } t_shell_separator *ft_set_sep(char *line, int j) { t_shell_separator *sep; sep = ft_managed_malloc(sizeof(t_shell_separator)); if (line[j] == '&' && line[j + 1] == '&') sep->instruction_type = SHELL_SEPARATOR_TYPE_AND; else if (line[j] == '|' && line[j + 1] == '|') sep->instruction_type = SHELL_SEPARATOR_TYPE_OR; else if (line[j] == ';') sep->instruction_type = SHELL_SEPARATOR_TYPE_END; else if (line[j] == '|') sep->instruction_type = SHELL_SEPARATOR_TYPE_PIPE; return (sep); } t_shell_command *ft_new_str_struct(void) { t_shell_command *str_struct; str_struct = ft_managed_malloc(sizeof(t_shell_command)); str_struct->instruction_type = SHELL_INSTRUCTION_COMMAND; str_struct->command_mask = NULL; str_struct->command_string = NULL; return (str_struct); } int ft_separator(char *line, t_node_binary **root, int j, t_shell_command **str_root) { t_node_binary *new_node; t_shell_separator *sep; sep = ft_set_sep(line, j); if ((*root)->value == NULL) { (*root)->value = sep; (*root)->left = ft_binarytree_node_create(*str_root); } else { new_node = ft_binarytree_node_create(sep); (*root)->right = ft_binarytree_node_create(*str_root); new_node->left = *root; *root = new_node; } *str_root = ft_new_str_struct(); if (sep->instruction_type == SHELL_SEPARATOR_TYPE_END || sep->instruction_type == SHELL_SEPARATOR_TYPE_PIPE) return (j + 1); return (j + 2); } int ft_is_separator(char *line, int j) { if (line[j] == '&' && line[j + 1] == '&') return (1); else if (line[j] && (line[j] == ';' || line[j] == '|')) return (1); else return (0); } int ft_no_quote(char *line, int j, t_shell_command *str_struct) { int ret; char *mask; ret = j; while (line[ret] && line[ret] != '\"' && line[ret] != '\'' && ft_is_separator(line, ret) == 0) { if (line[ret] == '\\') ret++; ret++; } mask = ft_managed_malloc(sizeof(char) * (ret - j + 1)); mask[ret - j] = '\0'; ft_fill_mask(mask, '0', ret - j - 1, str_struct); ft_fill_str(line, j, ret - j, str_struct); return (ret); } int ft_show_tree(t_node_binary *root) { char node_type; t_node_binary **buff; printf("\n\nSHOW TREE :\n\n"); buff = &root; while (buff[0] != NULL) { node_type = *((char*)(buff[0]->value)); printf("\nNodetype = %d\n", *((char*)(buff[0]->value))); if (*((char*)(buff[0]->value)) == 0) printf("\nNode str = %s\n", (((t_shell_command *)(buff[0]->value))->command_string)); if (buff[0]->left != NULL) { printf("\nLeft_Nodetype = %d\n", *((char*)(buff[0]->left->value))); printf("\nRight_Nodetype = %d\n", *((char*)(buff[0]->right->value))); if (*((char*)(buff[0]->left->value)) == 0) printf("\nstr left = %s\n", (((t_shell_command *)(buff[0]->left->value))->command_string)); if (*((char*)(buff[0]->right->value)) == 0) printf("\nstr right= %s\n", (((t_shell_command *)(buff[0]->right->value))->command_string)); buff = &buff[0]->left; } else buff[0] = NULL; } return (0); } t_parse_struct *ft_setup_parse_struct(void) { t_parse_struct *ret; ret = ft_managed_malloc(sizeof(t_parse_struct)); ret->str_struct = ft_managed_malloc(sizeof(t_shell_command)); ret->str_struct->instruction_type = SHELL_INSTRUCTION_COMMAND; ret->str_struct->command_mask = NULL; ret->str_struct->command_string = NULL; ret->root = ft_managed_malloc(sizeof(t_node_binary *)); ret->str_root = ft_managed_malloc(sizeof(t_shell_command *)); ret->node = ft_binarytree_node_create(NULL); ret->str_root[0] = ret->str_struct; ret->root[0] = ret->node; return (ret); } t_node_binary *ft_treat_line(char *line) { int i; int j; t_parse_struct *s; s = ft_setup_parse_struct(); i = ft_strlen(line); j = 0; while (line[j]) { if (ft_is_separator(line, j) == 1) j = ft_separator(line, s->root, j, s->str_root); if (line[j] != '\'' && line[j] != '\"') j = ft_no_quote(line, j, s->str_root[0]); else if (line[j] == '\'') j = ft_single_quote(line, j, s->str_root[0]); else if (line[j] == '\"') j = ft_double_quote(line, j, s->str_root[0]); } if ((s->root[0])->value == NULL) (s->root[0])->value = (s->str_root[0]); else if ((s->root[0])->right == NULL) (s->root[0])->right = ft_binarytree_node_create((s->str_root[0])); return (s->root[0]); } // int main(void) // { // char *line; // char *prompt; // int ret; // t_node_binary *root; // ret = 0; // prompt = ft_managed_malloc(sizeof(char) * 12); // if (line == NULL || prompt == NULL) // return (0); // prompt = "\e[1;1H\e[2J"; // write(1, prompt, 11); // prompt = "Minishell ~ "; // while (ret >= 0) // { // write(1, prompt, 12); // ret = get_next_line(0, &line); // root = ft_treat_line(line); // ft_show_tree(root); // free(line); // } // return (1); // }
C
#include<stdio.h> int z=0; int f(int x,int y,int *m) { int static kk=9; x=x+2; y=y+3; z=z+y+1+*m; kk=kk+x; *m=kk; printf("%d %d %d %d %d \n", x,y,kk,z,*m); return x+y; } int main() { int k=3,m=5,r=0; printf("%d %d %d %d\n",k,m,r,z); z=f(k,m,&r); printf("%d %d %d %d\n",k,m,r,z); z=f(m,k,&r); printf("%d %d %d %d",k,m,r,z); return 0; }
C
#include <stdio.h> #include <stdlib.h> int number[11]={0,12,16,24,35,47,59,62,73,88,99};//待查表,第一个元素是哨兵位而不是待查数据,待查数据从下标1(第二个元素)开始 int Sequential_Search(int *a,int n,int key) { int i; for(i=1;i<=n;i++) { if(a[i]==key) return i;//返回查找到的下标 } return 0;//返回0代表查找失败 } int Sequential_Search2(int *a,int n,int key) { int i; a[0]=key;//设置哨兵 i=n; while(a[i]!=key) { i--; } return i;//返回0则查找失败 } int Binary_Search(int *a,int n,int key) { int low,high,mid; low=1; high=n; while(low<=high) { mid=(low+high)/2; if(key<a[mid]) high=mid-1; else if(key>a[mid]) low=mid+1; else return mid; } return 0; } int Interpolation_Search(int *a,int n,int key)//插值查找 { int low,high,mid; low=1; high=n; while(low<=high) { mid=low+(high-low)*(key-a[low])/(a[high]-a[low]); if(key<a[mid]) high=mid-1; else if(key>a[mid]) low=mid+1; else return mid; } return 0; } int main() { int position; position = Binary_Search(number,10,47); printf("Position is %d\n",position); return 0; }
C
/************************************************************************* * File Name: wait4Check.c * Author: JohnMiller * Mail: jfmcs_0211@126.com * Created Time: Wed 30 Aug 2017 12:11:50 AM CST *************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <sys/resource.h> #include <unistd.h> #include <stdarg.h> void waitchildren(int signum); void h_exit(int status); int main() { pid_t pid; int status; if((pid =fork()) < 0) { printf("fork error!\n"); exit(0); } else if(pid == 0) { printf("Hello from the child process%4d!\n",getpid()); setenv("PS1","CHILD\\$",1); printf("Process%4d: I'm calling exec. \n",getpid()); execl("/bin/sh","/bin/sh","execlCheck.sh",NULL); printf("Process%4d: You should never see this because the child is already gone.\n",getpid()); } else if(pid!= -1) { printf("Hello from the parent process%4d!\n",getpid()); printf("Process%4d: The parent has forked process%d. \n",getpid(),pid); printf("Process%4d: The parent is waiting for the child to exit.\n",getpid()); wait4(pid,&status,0,NULL); h_exit(status); } return 0; } void h_exit(int status) { if(WIFEXITED(status)) printf("normal termination,exit status=%d. \n",WEXITSTATUS(status)); else if(WIFSIGNALED(status)) printf("abnormal termination,exit status=%d. \n",WTERMSIG(status)); }
C
#include <string.h> #include <stdlib.h> #include <stdio.h> #include "QuickSort.h" #include "Compare.h" #include "sort_file.h" void QuickSort(char *data,int size,int wall,int pivot,int m,char type,int length,void *pivot_value){ if(wall >= pivot){ return; } int r = partition(data,size,wall,pivot,m,type,length,pivot_value); QuickSort(data,size,wall,r-1,m,type,length,pivot_value); QuickSort(data,size,r+1,pivot,m,type,length,pivot_value); } int partition(char *data,int size,int wall,int pivot,int m,char type,int length,void *pivot_value){ memcpy(pivot_value,&data[sizeof(int)+size*pivot+m],length); for(int i=wall;i<pivot;i++){ if(!compare(&(data[sizeof(int)+size*i+m]),&(data[sizeof(int)+size*pivot+m]),type,length)){ if(i>wall){ swap(data,size,i,wall); } wall++; } } swap(data,size,wall,pivot); return wall; } void swap(char *data,int size,int i,int j){ Record record; memcpy(&(record.id),&(data[sizeof(int)+size*i]),sizeof(int)); memcpy(&(record.name),&(data[2*sizeof(int)+size*i]),sizeof(record.name)); memcpy(&(record.surname),&(data[2*sizeof(int)+size*i+sizeof(record.name)]),sizeof(record.surname)); memcpy(&(record.city),&(data[2*sizeof(int)+size*i+sizeof(record.name)+sizeof(record.surname)]),sizeof(record.city)); memcpy(&(data[sizeof(int)+size*i]),&(data[sizeof(int)+size*j]),sizeof(int)); memcpy(&(data[2*sizeof(int)+size*i]),&(data[2*sizeof(int)+size*j]),sizeof(record.name)); memcpy(&(data[2*sizeof(int)+size*i+sizeof(record.name)]),&(data[2*sizeof(int)+size*j+sizeof(record.name)]),sizeof(record.surname)); memcpy(&(data[2*sizeof(int)+size*i+sizeof(record.name)+sizeof(record.surname)]),&(data[2*sizeof(int)+size*j+sizeof(record.name)+sizeof(record.surname)]),sizeof(record.city)); memcpy(&(data[sizeof(int)+size*j]),&(record.id),sizeof(int)); memcpy(&(data[2*sizeof(int)+size*j]),&(record.name),sizeof(record.name)); memcpy(&(data[2*sizeof(int)+size*j+sizeof(record.name)]),&(record.surname),sizeof(record.surname)); memcpy(&(data[2*sizeof(int)+size*j+sizeof(record.name)+sizeof(record.surname)]),&(record.city),sizeof(record.city)); }
C
#include<stdio.h> int main() { for(int i=5;i>0;i--) { char c=97; for(int j=i;j>0;j--) { if(c=='a') { printf("%c ",c-32); } else printf("%c ",c); c++; } printf("\n");} }
C
#include <unistd.h> void ft_putchar(char c) { write(1, &c, 1); } void ft_display(int *range) { int i; i = 0; while (range[i] != '\0') ft_putchar(range[i++]); } void ft_display_char(void) { ft_putchar(','); ft_putchar(' '); } void ft_print_comb(void) { int range[4]; range[0] = 48; while (range[0] < 58) { range[1] = range[0] + 1; while (range[1] < 58) { range[2] = range[1] + 1; while (range[2] < 58) { ft_display(range); if (!(range[0] == 55 && range[1] == 56 && range[2] == 57)) ft_display_char(); range[2]++; } range[1]++; } range[0]++; } ft_putchar('\n'); }
C
/* | PC-LISP (C) 1984-1989 Peter J.Ashwood-Smith */ #include <stdio.h> #include <math.h> #include "lisp.h" /************************************************************************* ** intexpt(x,y) compute x^y where x & y are both integers. We use a ** ** a very simplistic doubling algorithm. If asked for x^0 return 1, ** ** if asked for x^y where y < 0 return 0 because 1/(y^x) is in range ** ** 0..1. If asked for x^y where y > 0 we loop checking if y is odd, if ** ** it is we form the product z by just multiplying it by x once and ** ** decrementing the exponent, however if the exponent y is even, it is ** ** safe to double x and divide y by 2 and maintain the same result, by ** ** doubling and halving we make the algorithm O(lg(n)) intead of O(n). ** *************************************************************************/ long intexpt(x,y) long x,y; { long z; if (y < 0) return(0L); /* neg exponent ans=0 */ z = 1L; /* x^0 = 1 = z */ while(y > 0) if (y&1){z*=x;y--;} else {y>>= 1;x*=x;}; /* accumulate z */ return(z); } /************************************************************************* ** buexpt: (expt x y) Will return the result x^y. If the numbers are ** ** both fixnums we call intexpt to compute the result using a quick ** ** doubling algorithm. If however one of the args is a double we call ** ** on the IEE floating point power function 'pow' to do the work for us** ** It probably uses x^y = e^(y*log(x)). ** *************************************************************************/ struct conscell *buexpt(form) struct conscell *form; { struct conscell *p1,*p2; double fop1,fop2; if (form != NULL) { p1 = form->carp; form = form->cdrp; if ((form != NULL)&&(form->cdrp == NULL)) { p2 = form->carp; if ((p1!=NULL)&&(p2!=NULL)) { if ( (p1->celltype == FIXATOM) && (p2->celltype == FIXATOM) ) return( newintop( intexpt( FIX(p1)->atom, FIX(p2)->atom ) ) ); if ( GetFloat(p1, &fop1) && GetFloat(p2, &fop2) ) return( newrealop( pow( fop1, fop2 ) ) ); } } } ierror("expt"); /* doesn't return */ return NULL; /* keep compiler happy */ }
C
#include <stdio.h> int main(){ char str[30] = "BANGLA", str_new[30]; int i, j; for(i=5,j=0; i>=0;i--){ str_new[j] = str[i]; j++; } str_new[j] = '\0'; printf("%s", str_new); return 0; }
C
/** * Embedded Systems Interfacing * PIC24FJ128GA010 * Write SPI * Wilson Woods * 11.2.2020 */ #include "mcc_generated_files/system.h" void usDelay( int time ) { T1CON = 0x8000; // 1:1 pre-scale, 16MHz clock TMR1 = 0; // clear TMR1 while ( TMR1 < time * 16 ); // count input time as microseconds } void msDelay( int N ) { T1CON = 0x8030; // 1:256 pre-scale, 16MHz clock TMR1 = 0; // clear TMR1 while ( TMR1 < N * 62.5 ); // count input N as milliseconds } void SPI1Init( void ) { SPI1CON1 = 0x0120; SPI1STAT = 0x8000; // enable SPI peripheral } unsigned char writeSPI1( unsigned char j ) { while ( SPI1STATbits.SPITBF ); SPI1BUF = j; // write byte to SPI1BUF while ( !SPI1STATbits.SPIRBF ); // wait if receive not complete return SPI1BUF; // read the received value } int main( void ) { SYSTEM_Initialize(); SPI1Init(); TRISB = 0x0000; // PORTB as output since RB0 is our SS PORTBbits.RB0 = 1; // SS active low writeSPI1( 0x76 ); // reset cursor int k; while ( 1 ) { PORTBbits.RB0 = 0; // set SS low writeSPI1( 0x76 ); // reset cursor usDelay( 500 ); // delay to spread out waveform for ( k = 1; k < 16; k++ ) { PORTBbits.RB0 = 0; // set SS low writeSPI1( k ); // write 1 to 1st position to begin usDelay( 500 ); writeSPI1( k + 1 ); // write 2 to 2nd position to begin usDelay( 500 ); writeSPI1( k + 2 ); // write 3 to 3rd position to begin usDelay( 500 ); writeSPI1( k + 3 ); // write 4 to 4th position to begin usDelay( 500 ); PORTBbits.RB0 = 1; // set SS high msDelay( 500 ); } } return 1; }
C
#include <stdio.h> #include <stdlib.h> #include <signal.h> #include <unistd.h> #include <setjmp.h> #include <pthread.h> static jmp_buf env_alrm; void sig_handler(int arg) { printf("%lu %s\n", pthread_self(), __FUNCTION__); longjmp(env_alrm, 1); printf("sig_handler end\n"); } unsigned int sleep1(unsigned int seconds) { printf("%lu %s\n", pthread_self(), __FUNCTION__); if (SIG_ERR == signal(SIGALRM, sig_handler)) { printf("signal failed!\n"); return seconds; } alarm(seconds); pause(); return (alarm(0)); } unsigned int sleep2(unsigned int seconds) { printf("%lu %s\n", pthread_self(), __FUNCTION__); if (SIG_ERR == signal(SIGALRM, sig_handler)) { printf("signal failed\n"); return seconds; } if (setjmp(env_alrm) == 0) { alarm(seconds); pause(); } return alarm(0); } void sig_int(int sig) { printf("%lu %s\n", pthread_self(), __FUNCTION__); int i, j; int k; printf("sig_int start\n"); for (i = 0; i != 300000; ++i) { for (j = 0; j != 40000; ++j) k += i * j; } printf("sig_int end\n"); } int main(int argc, char const *argv[]) { printf("%lu %s\n", pthread_self(), __FUNCTION__); printf("%d\n", SIGINT); if (SIG_ERR == signal(SIGINT, sig_int)) { printf("signal interrupt failed!\n"); } sleep2(5); return 0; }
C
//ʵstrcat #include<stdio.h> #include<Windows.h> #include<assert.h> #pragma warning(disable:4996) char *strcat(char *str1, const char *str2) { assert(str1 != NULL&&str2!=NULL); char *temp = str1; while (*temp != '\0') { temp++; } while ((*temp++ = *str2++) != '\0');//ַstr2еַƵstr1 return str1; } int main() { char str1[20] = "abc"; char str2[] = "efg"; char *str3 = strcat(str1, str2); printf("str1=%s\n", str1); printf("str2=%s\n", str2); printf("str3=%s\n", str3); system("pause"); return 0; }
C
/* reads the tss.log created by silvercheetah and gives advice. * * Reads your workout history and data from tss.log generated by silvercheetah * and calculates the TSS that is needed day-by-day to achieve optimal fitness * while remaining under a given freshness threshold. * * Also, uses a formula which correlates TSS with time, speed, and FTP during a * workout. With this, it can recommend how long you need to cycle at some * speed to achieve today's recommended TSS. * * Pairs well with gitgraph to show workouts as heatmap. * * Added some unicode flare when you increase your freshhold and FTP. * * first working code finished on: Thu Feb 28 21:51:24 CST 2019 */ #include <stdio.h> #include <stdlib.h> #include <time.h> #include <string.h> #include <assert.h> // When you project what your future TSS values should be, you need to add an // appendix onto the array read from the file, and calculate the required TSS // for each of those future days. Even if you only display a week of // requirements, you need more than 1 week to calculate the TSS values // correctly. Therefore, APPEND_LEN (where the calculation is done) is 14 days, // but the INVISIBLE_INDEX (the number of days on the end of the appendix that // are not displayed because the values will be incorrect) is 7. #define APPEND_LEN 14 #define INVISIBLE_APPENDIX 7 void rolling_average(double* array, double* target, unsigned n, unsigned interval){ for(unsigned i = 0; i < n; i++){ if(i < interval){ if(i == 0) target[i] = array[i]; else target[i] = (target[i - 1] * i + array[i]) / (i + 1); } else target[i] = target[i - 1] + (array[i] - array[i - interval]) / interval; } } unsigned line_count(FILE *fp){ if(fp == NULL){ puts("line_count(): fp is NULL. Why?"); exit(1); } // Count lines in file. unsigned count = 0; while(!feof(fp)){ if(fgetc(fp) == '\n') count++; } rewind(fp); return count; } double sec_goal(double ftp, double speed, double tss); void recommendation(double curr_ftp, double speed, double v, char* str); // takes UNIX timestamp and prints it as a date in yyyy-mm-dd format. void tstodate(time_t t); int main(int argc, char **argv){ FILE *fp; char c; unsigned i, j, k, array_size, *duration; long long unsigned *ts; double *np, *ftp, *ifact, *tss, *ctl, *atl, *tsb; double min_tsb; char folder_location[4096]; assert(APPEND_LEN >= INVISIBLE_APPENDIX); // open config file. if((fp = fopen("/home/korgan/code/cyclecoach/config","r")) == NULL){ printf("can't find /home/korgan/code/cyclecoach/config file. creating..."); if((fp = fopen("/home/korgan/code/cyclecoach/config","w")) == NULL){ printf("failed.\n"); exit(1); } // set ./wahoo_csv_files as default location of your csv files. fprintf(fp, "/PATH/TO/TSS/LOG/GOES/HERE/tss.log"); fclose(fp); puts("done.\nPut path to tss.log in config file and run cyclecoach again."); exit(0); } // get folder location from config file. fgets(folder_location, 4098, fp); fclose(fp); folder_location[strcspn(folder_location, "\n")] = 0; // open tss.log if((fp = fopen(folder_location, "r")) == NULL){ printf("can't open %s\n", folder_location); exit(1); } // count lines in tss.log. array_size = line_count(fp); // skip over header line. while((c = fgetc(fp)) != '\n' && c != EOF); // if file is empty, we're done. if(array_size == 0){ puts("tss.log is empty :/"); fclose(fp); exit(0); } // Otherwise, malloc space for tss data + a future block of time. unsigned new_size = array_size + APPEND_LEN; if((ts = malloc(new_size * sizeof(long long unsigned))) == NULL){ puts("malloc failed"); exit(1); } if((duration = malloc(new_size * sizeof(unsigned))) == NULL){ puts("malloc failed"); exit(1); } if((np = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } if((ftp = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } if((ifact = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } if((tss = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } if((ctl = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } if((atl = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } if((tsb = malloc(new_size * sizeof(double))) == NULL){ puts("malloc failed"); exit(1); } // read tss.log into arrays. for(i = 0; i < array_size; i++){ fscanf(fp, "%llu %lf %u %lf %lf %lf %lf %lf %lf", &ts[i], &np[i], &duration[i], &ftp[i], &ifact[i], &tss[i], &ctl[i], &atl[i], &tsb[i]); } fclose(fp); // get minimum threshold from command line if it's there. if(argc == 2){ // do error check later. min_tsb = atof(argv[1]); } else{ // find lowest fresh-hold within last 42 days. Only use values where // the next tss isn't zero; if it is zero, then you might have reached // a burnout. You're only looking for the lowest tsb that you can // maintain. This part could be made more sophisticated later, say by // finding freshholds that can be maintained for a minimum amount of // time. unsigned start = 0; if(array_size >= 42) start = array_size - 42; min_tsb = tsb[start]; for(i = start + 1; i < array_size; i++){ if(tsb[i] < min_tsb && (i + 1) < array_size && tss[i + 1] > 1) min_tsb = tsb[i]; } } printf("freshhold: %.3lf\n", min_tsb); // grab last ftp value before amending array_size. double curr_ftp = ftp[array_size - 1]; // amend array_size to include the future. array_size = new_size; // figure out highest tss than can be done per day to stay within freshhold. for(k = array_size - APPEND_LEN; k < array_size; k++){ for(i = 0; i <= 100; i++){ // fill appendix with value i. for(j = k; j < array_size; j++){ tss[j] = i; } // calculate atc, ctl, tsb for appendix. rolling_average(tss, ctl, array_size, 42); rolling_average(tss, atl, array_size, 7); // calculate tsb. for(j = 0; j < array_size; j++) tsb[j] = ctl[j] - atl[j]; // find lowest tsb in the appendix. unsigned lowest_tsb = k; for(j = k + 1; j < array_size; j++){ if(tsb[j] < tsb[lowest_tsb]) lowest_tsb = j; } if(tsb[lowest_tsb] < min_tsb) break; } if(i) i--; tss[k] = i; } // recalculate atc, ctl, tsb for appendix. So this is overkill since 6 out // of 7 of them have already been calculated in the above process, but the // last one won't be correct. Instead of just fixing that last one, I'll // just do this. Makes it easier if I were to adjust APPEND_LEN later. rolling_average(tss, ctl, array_size, 42); rolling_average(tss, atl, array_size, 7); // recalculate tsb. for(j = 0; j < array_size; j++) tsb[j] = ctl[j] - atl[j]; // put in future timestamps. for(j = array_size - APPEND_LEN; j < array_size; j++){ ts[j] = ts[j - 1] + 86400; } // display it. unsigned limit = 0; if(array_size > APPEND_LEN * 2) limit = array_size - (APPEND_LEN * 2); printf("\nTIMESTAMP | NP | mins | FTP | IF | TSS | CTL | ATL | TSB\n"); for(i = limit; i < array_size; i++){ // print timestamp as date. tstodate(ts[i]); printf("%7.3lf %5u %8.3lf %5.3lf %7.3lf %7.3lf %7.3lf %6.3lf\n", np[i], duration[i] / 60, ftp[i], ifact[i], tss[i], ctl[i], atl[i], tsb[i]); if(i == array_size - APPEND_LEN - 1){ puts("--------------------------------FUTURE--------------------------------"); } if(i == array_size - INVISIBLE_APPENDIX - 1) break; } // figure out longest streak. unsigned streak = 0; unsigned longest = 0; for(i = 0; i < array_size - APPEND_LEN; i++){ if(tss[i] >= 1.0){ streak++; } else{ if(streak > longest) longest = streak; streak = 0; } } // figure out current streak; streak = 0; for(i = array_size - APPEND_LEN - 1; tss[i] >= 1.0; i--) streak++; if(streak > longest) longest = streak; printf("\nlongest streak: %u\ncurrent streak: %u\n", longest, streak); // detect an FTP increase and report if there is one. if(ftp[array_size - APPEND_LEN - 1] > ftp[array_size - APPEND_LEN - 2]) puts("New FTP! 🌈"); // If today's freshhold is the same as the minimum freshhold, then I'll // *assume* that today's workout was the one that set it. if(min_tsb >= tsb[array_size - APPEND_LEN - 1]) puts("New freshhold! 🌈"); free(duration); free(np); free(ftp); free(ifact); free(ctl); free(atl); free(tsb); // print a basic report. // If you've already worked out today, then no advice needed. Otherwise, // recommend a tss to aim for today. long long unsigned current_time = time(NULL) / 86400 * 86400; long long unsigned last_time = ts[array_size - APPEND_LEN - 1] / 86400 * 86400; if(current_time != last_time){ double speed = 25.2; // It would be better if this were set dynamically, but oh well. double tss_goal = tss[array_size - APPEND_LEN]; double curr_ctl = ctl[array_size - APPEND_LEN - 1]; printf("\nRecommendations @ %.1f:", speed); recommendation(curr_ftp, speed, tss_goal, "\nprogress"); recommendation(curr_ftp, speed, curr_ctl, "\nmaintain"); speed = 27; printf("\nRecommendations @ %.1f:", speed); recommendation(curr_ftp, speed, tss_goal, "\nprogress"); recommendation(curr_ftp, speed, curr_ctl, "\nmaintain"); } else{ puts("today is done :)"); system("gnuplot /home/korgan/code/cyclecoach/gnuplotscript"); } free(ts); free(tss); } double sec_goal(double ftp, double speed, double tss){ if(speed < 1.0) return 0; double denom = 0.00472112 * speed * speed * speed + 3.25888 * speed; denom *= denom; return (tss * 36 * ftp * ftp) / denom; } void tstodate(time_t t){ const char *format = "%Y-%m-%d"; struct tm lt; char res[32]; localtime_r(&t, &lt); strftime(res, sizeof(res), format, &lt); printf("%s ", res); } // Given ftp, speed, and tss or fitness, will tell you how long you need to // cycle to achieve it. void recommendation(double curr_ftp, double speed, double v, char* str){ double time_goal = sec_goal(curr_ftp, speed, v); // round up. if((time_goal - (int)time_goal) >= 0.5) time_goal += 0.5; printf(str); printf(": "); if(time_goal >= 60) printf("%.0lf TSS ≈ %.0lf mins at %.1f km/h.", v, time_goal / 60, speed); else printf("rest day"); }
C
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> int main(){ int t; scanf("%d",&t); for(int a0 = 0; a0 < t; a0++){ char *s = (char *)malloc(10240 * sizeof(char)), *stack = (char *)malloc(10240 * sizeof(char)); scanf("%s",s); int top = -1; bool is_balanced = true; for (int s_i = 0; s[s_i]; ++s_i) { if (s[s_i] == '}') { if (stack[top] == '{') --top; else { is_balanced = false; break; } } else if (s[s_i] == ']') { if (stack[top] == '[') --top; else { is_balanced = false; break; } } else if (s[s_i] == ')') { if (stack[top] == '(') --top; else { is_balanced = false; break; } } else stack[++top] = s[s_i]; } if (is_balanced && top == -1) printf("YES\n"); else printf("NO\n"); free(s); free(stack); } return 0; }
C
/*#include <stdio.h> int main() { int data1, data2; data1 = 5; //data1 5 data2 = data1; //data2 data1 printf("data1 = %d , data2 = %d \n", data1, data2); } */
C
/******************************************************************************* 《 算法设计与分析 》课内上机实验题目 - 分治法求解 '找伪币' 问题 < 作者 > 刘伟 < 编写日期 > 2016-01-20 < 版本号 > v1.0 < 备注 > 使用标准 C 代码实现 *******************************************************************************/ // 使用的库定义 ... #include <stdio.h> #include <stdlib.h> #include <time.h> #define ARRAY_SIZE 16 #define TRUE 1 #define FALSE 0 int CallTimes = 0; // 生成包含 'N' 个硬币重量的数组( 含 1 枚伪币 ), 并返回伪币位置 ... int CreateRandomCoinWeightArray( int *p, int N ) { int i, kt; int TrueCoinWeight, FakeCoinWeight; int IsStop; // 生成随机数种子 ... srand( ( unsigned )time( NULL ) ); // 生成随机真币重量值( 在 50 至 100 之间 ) ... TrueCoinWeight = 50 + rand( ) % ( 100 - 50 ); // 生成随机伪币位置( 在 0 ~ N-1 之间 ) ... kt = rand( ) % N; // 设置真币重量 ... for( i = 0; i < N; i++ ) if ( i != kt ) *( p + i ) = TrueCoinWeight; // 生成 1 个比真币略轻的伪币重量值 ... IsStop = FALSE; while( !IsStop ) { FakeCoinWeight = 50 + rand( ) % ( 100 - 50 ); // 设置满足条件的伪币重量值 ... if ( ( TrueCoinWeight > FakeCoinWeight ) && ( TrueCoinWeight - FakeCoinWeight <= 5 ) ) { IsStop = TRUE; *( p + kt ) = FakeCoinWeight; } } // 返回伪币位置 ... return kt; } // 计算数组中硬币重量和 ... int CalcCoinTotalWeight( int ArrayData[], int kb, int ke ) { int i, TotalWeight = 0; for( i = kb; i <= ke; i++ ) TotalWeight += ArrayData[ i ]; return TotalWeight; } // 采用分治法找到伪币( 假定伪币一定存在且只有 1 枚 ) ... // kb - (子)数组左边界( begin ) // ke - (子)数组右边界( end ) int FindFakeCoin( int ArrayData[], int kb, int ke ) { int LWeight, RWeight; CallTimes++; printf( "< 第 %d 次查找 > \n", CallTimes ); // 请将下面的代码补充完毕, 使程序可以正确运行 ... // ...... LWeight=CalcCoinTotalWeight(ArrayData,kb,(kb+ke)/2); RWeight=CalcCoinTotalWeight(ArrayData,(kb+ke)/2+1,ke); if(LWeight>RWeight) { if((kb+1)!=ke) return FindFakeCoin(ArrayData,(kb+ke)/2+1,ke); else return ke; } else { if((kb+1)!=ke) return FindFakeCoin(ArrayData,kb,(kb+ke)/2); else return kb; } } void main( void ) { int ArrayData[ ARRAY_SIZE ]; int i, k, FakeCoinPos; // 生成包含 'N' 个硬币重量的数组( 含 1 枚伪币 ), 并返回伪币位置 ... k = CreateRandomCoinWeightArray( ArrayData, ARRAY_SIZE ); // 输出随机数组内容 ... printf( "< 生成的硬币重量数组值为( 含 1 枚伪币 ) > : \n" ); for( i = 0; i < ARRAY_SIZE; i++ ) printf( "%d\n", ArrayData[ i ] ); printf( "\n" ); printf( "< 第 %d 枚为伪币 > \n", ( k + 1 ) ); printf( "\n" ); // 采用分治法找到伪币位置 ... FakeCoinPos = FindFakeCoin( ArrayData, 0, ARRAY_SIZE - 1 ); printf( "< 找到第 %d 枚为伪币 > \n", ( FakeCoinPos + 1 ) ); printf( "\n" ); // 等待用户输入任意一键返回 ... system( "PAUSE" ); }
C
#define _CRT_SECURE_NO_WARNINGS 1 #include <stdio.h> #include <malloc.h> // ݽṹ struct PolyNode { int coef; // ʽϵ int expon; // ʽָ struct PolyNode* link; }; typedef struct PolyNode* Polynomial; // int Compare(int x, int y) { if (x > y) return 1; else if (x < y) return -1; else return 0; } void Attach(int coef, int expon, Polynomial* pRear) { Polynomial P; P = (Polynomial)malloc(sizeof(struct PolyNode)); P->coef = coef; P->expon = expon; P->link = NULL; (*pRear)->link = P; *pRear = P; // ޸pRearֵ } Polynomial ReadPoly() // ʽ { int N = 0; int coef,expon; struct PolyNode* Rear; struct PolyNode* P; struct PolyNode* t; printf("ʽ"); scanf("%d", &N); // ʽ P = (struct PolyNode*)malloc(sizeof(struct PolyNode)); P->link = NULL; Rear = P; while (N--) { printf("ϵָ"); scanf("%d %d", &coef, &expon); // һһϵָ Attach(coef, expon, &Rear); // 㡣 } t = P; P = P->link; free(t); return P; } Polynomial Mult(Polynomial P1, Polynomial P2) //ʽ { Polynomial t1, t2, P,Rear,tmp; int expon, coef; if (!P1 || !P2) // P1P2һΪָ룬 return NULL; t1 = P1; t2 = P2; P = (Polynomial)malloc(sizeof(struct PolyNode)); Rear = P; while (t2) {// P1һP2õʼʽ Attach(t1->coef * t2->coef, t1->expon + t2->expon, &Rear); t2 = t2->link; } t1 = t1->link; while (t1) { t2 = P2; Rear = P; while (t2) { expon = t1->expon + t2->expon; coef = t1->coef * t2->coef; while (Rear->link && Rear->link->expon > expon) Rear = Rear->link; if (Rear->link && Rear->link->expon == expon) { if (Rear->link->coef + coef) Rear->link->coef = Rear->link->coef + coef; else { tmp = Rear->link; Rear->link = tmp->link; free(tmp); } } else { tmp = (Polynomial)malloc(sizeof(struct PolyNode)); tmp->link = Rear->link; tmp->coef = coef; tmp->expon = expon; Rear->link = tmp; Rear = Rear->link; } t2 = t2->link; } t1 = t1->link; } t2 = P; P = P->link; free(t2); return P; } Polynomial Add(Polynomial P1, Polynomial P2) // ʽ { Polynomial P, PRear,t1,t2,tmp,t; t1 = P1; t2 = P2; P = (Polynomial)malloc(sizeof(struct PolyNode)); PRear = P; while (t1 && t2) { switch (Compare(t1->expon, t2->expon)) { case 1: tmp = (Polynomial)malloc(sizeof(struct PolyNode)); tmp->coef = t1->coef; tmp->expon = t1->expon; tmp->link = NULL; PRear->link = tmp; PRear = tmp; t1 = t1->link; break; case -1: tmp = (Polynomial)malloc(sizeof(struct PolyNode)); tmp->coef = t2->coef; tmp->expon = t2->expon; tmp->link = NULL; PRear->link = tmp; PRear = tmp; t2 = t2->link; break; case 0: if (((t1->coef) + (t2->coef))) { tmp = (Polynomial)malloc(sizeof(struct PolyNode)); tmp->coef = (t1->coef) + (t2->coef); tmp->expon = t1->expon; tmp->link = NULL; PRear->link = tmp; PRear = tmp; t1 = t1->link; t2 = t2->link; } break; } } while (t1) { tmp = (Polynomial)malloc(sizeof(struct PolyNode)); tmp->coef = t1->coef; tmp->expon = t1->expon; tmp->link = NULL; PRear->link = tmp; PRear = tmp; t1 = t1->link; } while (t2) { tmp = (Polynomial)malloc(sizeof(struct PolyNode)); tmp->coef = t2->coef; tmp->expon = t2->expon; tmp->link = NULL; PRear->link = tmp; PRear = tmp; t2 = t2->link; } t = P; P = P->link; free(t); return P; } void PrintPoly(Polynomial P) // ӡʽ { int flag = 0; // ʽ if (P == NULL) { printf("ʽΪ\n"); return; } while (P) { if (flag == 0) flag = 1; else printf(" "); printf("%d %d", P->coef, P->expon); P = P->link; } } int main() { Polynomial P1, P2, PP, PS; // ʽ1 P1 = ReadPoly(); // ʽ2 P2 = ReadPoly(); // ˷㲢˳ PP = Mult(P1, P2); PrintPoly(PP); printf("\n"); // ӷ㲢˳ PS = Add(P1, P2); PrintPoly(PS); return 0; }
C
/* Shared Memory This module implements a method to use shared memory. The backing data structure is a block of memory, internally represented as an array of chars The first element of this array will represent the index of the array - 2 to start any and all write operations on. The second element of this array will represent the index of the array -1 to start any and all read operations on. Both will be clocked to MAX_ELEM - 2 */ #include <sys/mman.h> #include "shared_mem.h" #include <sys/types.h> #include <sys/shm.h> #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <fcntl.h> int getMemSize() { return sizeof('a') * SM_MAX_ELEM + SM_RES_BLOC; } struct SharedMemBlock createSharedBlock() { struct SharedMemBlock block; printf("Creating memory Block\n"); int memFd; int init = 1; // if init gets turned to 0, initialization steps will not be taken if(memFd = shm_open("OS", IPC_CREAT | IPC_EXCL, 0666) < 0) { switch(errno) { case EEXIST: printf("Mem Block already exists. No init needed.\n"); memFd = shm_open("OS", O_CREAT, 0666); init = 0; break; default: printf("Error in allocating shared memory"); exit(1); } } char* shmStart = mmap(0, getMemSize(), PROT_WRITE, MAP_SHARED, memFd,0); if (init == 1) { // initialize the memory printf("Initializing Shared data block\n"); shmStart[0] = (char) 0; shmStart[1] = (char) 0; } block.writeIndex = shmStart; block.readIndex = shmStart + 1; block.shmid = memFd; block.start = shmStart + 2; block.len = SM_MAX_ELEM; printf("Block Created\n"); return block; } void detach(struct SharedMemBlock block) { // shmdt(block.writeIndex); } void removeShardBlock(struct SharedMemBlock block) { shm_unlink("OS"); } int writeTo(struct SharedMemBlock block, char* data, int dataLen) { int in = (int) *block.writeIndex; int out = (int) *block.readIndex; if (!((in + dataLen) % SM_MAX_ELEM < out || in + dataLen >= out)) { return -1; } // write to array for (int i = 0; i < dataLen; i++) { block.start[(in + i) % block.len] = data[i]; } block.writeIndex[0] = (in + dataLen) % block.len; return 1; } int readFrom(struct SharedMemBlock block, char* buffer, int buffLen) { int in = (int) *block.writeIndex; int out = (int) *block.readIndex; if (in == out) { return -1; } int index = 0; while (out % block.len != in && index < buffLen) { buffer[index] = block.start[out % block.len]; out++; index++; } block.readIndex[0] = (out) % block.len; if (in != out) { return 0; // represents non-empty buffer } return 1; } void updateBlock(struct SharedMemBlock block, int newWrite, int newRead) { } int calcNextIndex(int currIndex, int steps) { return 1; } void printBlock(struct SharedMemBlock b) { printf("Write: %i\tRead:%i\n", (int) *(b.writeIndex), (int) *(b.readIndex)); printf("Shared Block\n"); for (int i = 0; i <= 10 && i < b.len; i++) { printf("%i:\t%i\n", i, b.start[i]); } } /* void run(int parent) { struct SharedMemBlock b = createSharedBlock(); printBlock(b); if (parent == 1) { char arr[2]; readFrom(b, arr, 2); printf("%s\n", arr); printBlock(b); removeSharedBlock(b); } else { char arr[3] = {'H','i','\0'}; writeTo(b, arr, 3); } } void main() { if (fork() == 0) { printf("Child"); run(0); } else { sleep(3); run(1); } } */
C
#include<stdio.h> int main() { long long int a,b,c,d; scanf("%lld %lld %lld %lld",&a,&b,&c,&d); if((a+b>c&&a+c>b&&b+c>a)||(a+b>d&&a+d>b&&b+d>a)||(c+b>d&&c+d>b&&b+d>c)||(a+c>d&&a+d>c&&c+d>a)) printf("S\n"); else printf("N\n"); return 0; }
C
/* * @file scheduler.h * * Created on: Sep 14, 2020 * Author: Roberto Baquerizo */ #ifndef __SCHEDULER_H___ #define __SCHEDULER_H___ #include <stdint.h> #include <stdbool.h> //! Value for idle event #define EVENT_IDLE (0) //! Value for take a temperature measurement event #define EVENT_MEASURE_TEMPERATURE (1UL << 1) //! Used for signaling events static volatile uint8_t event; void schedulerInit(); bool schedulerMain( uint8_t _event ); uint8_t schedulerGetEvent(); void schedulerSetEventMeasureTemperature(); void schedulerClearEvent(); //! eventsPresent() //! @brief Reports whether there any events to process //! //! @param void //! @returns true if there are events to process, false otherwise static inline bool eventsPresent() { return ( (event > EVENT_IDLE) ? true : false ); } #endif // __SCHEDULER_H___
C
#include<stdio.h> #include<string.h> int main() { char str1[100]; int len,i; scanf( "%s", str1 ); len = strlen(str1); for(i = len - 1; i >= 0; i--) { printf("%c", str1[i]); } return 0; }
C
#include <stdio.h> typedef struct{ int den; int num; }Fracao; void exibefracao(Fracao x); Fracao somafracao(Fracao x, Fracao y); Fracao multiplica(Fracao x, Fracao y); Fracao subtrai(Fracao x, Fracao y); int main(void) { Fracao a; Fracao b; Fracao c; scanf("%d %d", &a.num, &a.den); scanf("%d %d", &b.num, &b.den); exibefracao(a); c = (somafracao(a, b)); printf("%d/%d\n", c.num, c.den); c = multiplica(a, b); printf("%d/%d\n", c.num, c.den); c = subtrai(a, b); printf("%d/%d\n", c.num, c.den); return 0; } void exibefracao(Fracao x){ printf("%d/%d\n", x.num, x.den); } Fracao somafracao(Fracao x, Fracao y){ Fracao z; int den = x.den*y.den; int num = (x.num*y.den)+(x.den*y.num); z.den = den; z.num = num; return z; } Fracao multiplica(Fracao x, Fracao y){ Fracao z; int den = x.den*y.den; int num = x.num*y.num; z.den = den; z.num = num; return z; } Fracao subtrai(Fracao x, Fracao y){ Fracao z; int den = x.num*y.den; int num = x.den*y.num; z.den = den; z.num = num; return z; }
C
#include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <string.h> #include <signal.h> #include <sys/wait.h> #include "transform.h" int main(int argc, char * argv[]) { loadConf(argv[argc - 2]); apllyFilters(argc, argv); } void loadConf(char * name) { int conf = open(name, O_RDONLY); char buffer[60]; for (int i = 0; i < 5 ; i++) { readln(conf, buffer, 60); char * subString = strtok(buffer, " "); filtros[i].nome = malloc(sizeof(subString)); strcpy(filtros[i].nome , subString); subString = strtok(NULL, " "); filtros[i].exec = malloc(sizeof(subString)); strcpy(filtros[i].exec, subString); } } ssize_t readln(int fd, char *line, size_t size) { //ler byte a byte do fd(descritor de ficheiro) int next_pos = 0; int read_bytes = 0; while (next_pos < size && read(fd, line + next_pos, 1) > 0) { read_bytes++; // - até encontrar \n if (line[next_pos] == '\n') break; next_pos++; } //retornar o numero de bytes lidos return read_bytes; } void apllyFilters(int nArgs, char ** args) { char * path = args[nArgs - 1]; //create pipes int nPipes = nArgs - 6; int pipes[nPipes][2]; for (int i = 0; i < nPipes; i++) { pipe(pipes[i]); } for (int i = 0; i < nArgs - 5; i++) { if (fork() == 0) { if (i == 0 && i == nArgs - 6) { //setup input int input = open(args[1], O_RDWR); dup2(input, 0); close(input); //setup output int output = open(args[2], O_WRONLY | O_CREAT , 0666); dup2(output, 1); close(output); } //first filter else if (i == 0) { //setup input int input = open(args[1], O_RDWR); dup2(input, 0); close(input); //setup output dup2(pipes[i][1], 1); } //last filter else if(i == nArgs - 6) { //setup input dup2(pipes[i - 1][0], 0); //setup output int output = open(args[2], O_WRONLY | O_CREAT , 0666); dup2(output, 1); close(output); } //middle filters else { //setup input dup2(pipes[i - 1][0], 0); //setup output dup2(pipes[i][1], 1); } //close pipes for (int k = 0; k < nPipes; k++) { close(pipes[k][0]); close(pipes[k][1]); } path = args[nArgs - 1]; for (int k = 0; k < 5; k++) { if(strcmp(args[i + 3], filtros[k].nome) == 0) { strcat(path, filtros[k].exec); execlp(path, filtros[k].exec, NULL); } } } } }
C
#include <stdio.h> #include <stdlib.h> #include <ctype.h> #define LINE_SIZE 10 int main(int argc, char *argv[]) { FILE *fp; int offset = 0; int ch; char chars[LINE_SIZE+1]; if(argc != 2) { fprintf(stderr, "Usage: %s filename\n", argv[0]); exit(EXIT_FAILURE); } if((fp = fopen(argv[1], "rb")) != NULL) { int bytes_width; printf("Offset "); bytes_width = LINE_SIZE * 3 - 1; printf("%*s", (bytes_width) / 2 + 3, "Bytes"); printf("%*s", (bytes_width) / 2 - 2, " "); printf(" %*s\n", LINE_SIZE, "Characters"); printf("------ "); for(int i = 0; i < bytes_width; i++) putchar('-'); printf(" "); for(int i = 0; i < LINE_SIZE; i++) putchar('-'); printf("\n"); while((ch = fgetc(fp)) != EOF) { if((offset % LINE_SIZE) == 0) { if(offset != 0) { chars[LINE_SIZE] = '\0'; putchar(' '); puts(chars); } printf("%6d ", offset); } printf("%02X ", ch); chars[(offset % LINE_SIZE)] = isprint(ch) ? ch : '.'; offset++; } for(int i = offset % LINE_SIZE ; i != 0 && i < LINE_SIZE; i++) printf("%2s ", " "); chars[(offset % LINE_SIZE)] = '\0'; printf(" %s\n", chars); fclose(fp); } else { fprintf(stderr, "Failed to open %s\n", argv[1]); exit(EXIT_FAILURE); } return 0; }
C
#include <stdio.h> #include <unistd.h> #include "mymalloc.h" typedef struct Node { int size; // The size of this chunk of memory int is_free; // Whether it is free(1) or empty(0) struct Node *next; // A pointer to the next node struct Node *prev; // A pointer to the previous node } *Node; // Keeps track of the first and last node of the LL static Node ll_first; static Node ll_last; Node add_node(int size) { ll_last->next = (Node*)sbrk(sizeof(struct Node)+size); ll_last->next->prev = ll_last; ll_last->next->size = size; ll_last->next->next = NULL; ll_last->next->is_free = 0; ll_last = ll_last->next; return ll_last; } Node first_fit(int size) { // Set current node to the beginning of the LL Node curr = ll_first; while (curr != NULL) { // When the allocated space request is the same size as the first fit found if((curr->is_free == 1) && curr->size == size) { curr->is_free = 0; curr->size; return curr; } // When there is enough free space, we can simply put the node in // and set the size to the new size if ((curr->is_free == 1) && (curr->size > size)) { curr->is_free = 0; curr->size = size; return curr; } curr = curr->next; } // If it gets to here, no space could be found. We need to increase heap space return (void*)(add_node(size)+1); } void *my_firstfit_malloc(int size) { Node node; // The current heap is empty, so we must add a new node // And set the attributes to reflect that if (ll_first == NULL) { ll_first = (Node*)sbrk(size+sizeof(struct Node)); ll_first->is_free = 0; ll_first->prev = NULL; ll_first->next = NULL; ll_first->size = size; ll_last = ll_first; return (void*)ll_first+sizeof(struct Node); } else { // Else find first first space allocation for the request node = first_fit(size); // No new space can be found, so we increase heap space if (node == NULL) { return (void*)add_node(size)+sizeof(struct Node); } // Otherwise, we add the node normally else { node->is_free = 0; return (void*)node; } } } void my_free(void *ptr) { Node node = (Node*)(ptr-sizeof(struct Node)); int n; // If the ptr is null or the node is already free if (node->is_free || ptr == NULL) return; // If the node is in between the first and the last node if (node != ll_first && node != ll_last) { // Left shfts previous node by one then logical ORs it to the next node // returns neighbors n = ((node->prev->is_free)<<1)|(node->next->is_free); // both neighboring nodes are already free if (n == 3) { node->prev->size = node->prev->size + node->size + node->next->size + 2*sizeof(struct Node); node->prev->next = node->next->next; node->next->next->prev = node->prev; } // Previous node is free else if (n == 2) { node->prev->size = node->prev->size + node->size + 16; node->prev->next = node->next; node->next->prev = node->prev; } // Next ndoe is free else if (n == 1) { node->size = node->size + node->next->size+16; node->next->next->prev = node; node->next = node->next->next; node->is_free = 1; } // Neither is free else if (n == 0) { // We can just free that node node->is_free = 1; } } else { // Only 1 node, we can easily free the node if (ll_first == ll_last) { sbrk(-(ll_first->size - sizeof(struct Node))); ll_first = NULL; ll_last = ll_first; } // More than one node to free else { if (node == ll_first) { if (node->next->is_free) { // If the next node is the end of the LL if (node->next == ll_last) { // We can decrease heap size sbrk(0-ll_first->size - ll_last->size - 2*sizeof(struct Node)); } ll_first->size = ll_first->next->size + sizeof(struct Node); ll_first->is_free = 1; ll_first->next->next->prev = ll_first; ll_first->next = ll_first->next->next; } // Else just set the first node as free else { ll_first->is_free = 1; } } // Same as above but in the case the node is the last node if (node == ll_last) { if (ll_last->prev->is_free) { if (ll_last->prev == ll_first) { sbrk(0-ll_last->size - ll_last->prev->size - 2*sizeof(struct Node)); ll_first = NULL; ll_last = ll_first; } else { sbrk(0-ll_last->size - ll_last->prev->size - 2*sizeof(struct Node)); ll_last = ll_last->prev->prev; ll_last->next = NULL; } } else { sbrk(0 - ll_last->size - sizeof(struct Node)); ll_last = ll_last->prev; ll_last->next = NULL; } } } } }
C
/* * LCD.c * * Created on: 2013-7-13 * Author: Archimedes &Chen Yuzheng */ #include <msp430f5438a.h> #include "LCD.h" //extern const unsigned char shuzi_table[]; #define LCD_DataIn P8DIR=0x00 //ݿڷΪ #define LCD_DataOut P8DIR=0xFF //ݿڷΪ #define LCD2MCU_Data P8IN #define MCU2LCD_Data P8OUT #define LCD_CMDOut P3DIR|=BIT0+BIT4+BIT5 #define LCD_RS_H P3OUT|=BIT0 #define LCD_RS_L P3OUT&=~BIT0 #define LCD_RW_H P3OUT|=BIT5 #define LCD_RW_L P3OUT&=~BIT5 #define LCD_EN_H P3OUT|=BIT4 #define LCD_EN_L P3OUT&=~BIT4 #define LCD_RST_H P11OUT|=BIT0 #define LCD_RST_L P11OUT&=~BIT0 #define Point_Draw 0 #define Point_Clear 1 /************************ * * * *******************/ /******************************************* ƣdelay_1us ܣʱԼ1usʱ ֵ ********************************************/ void delay_50us(void) { unsigned int i; for(i = 50;i > 0;i--) _NOP(); } /******************************************* ƣdelay_1ms ܣʱԼ1msʱ ֵ ********************************************/ void delay_1ms(void) { unsigned int i; for(i = 500;i > 0;i--) _NOP(); } /******************************************* ƣdelay_nms ܣʱN1msʱ n--ʱ ֵ ********************************************/ void delay_nms(unsigned int n) { unsigned int i; for(i = n;i > 0;i--) delay_1ms(); } /******************************************* ƣWrite_Cmd ܣҺд cmd-- ֵ ********************************************/ void Write_Cmd(unsigned char cmd) { unsigned char lcdtemp = 0; LCD_RS_L; LCD_RW_H; LCD_DataIn; do //æ { LCD_EN_H; delay_50us(); lcdtemp = LCD2MCU_Data; LCD_EN_L; } while(lcdtemp & 0x80); LCD_DataOut; LCD_RW_L; MCU2LCD_Data = cmd; LCD_EN_H; delay_50us(); LCD_EN_L; } /******************************************* ƣWrite_Data ܣҺдʾ dat--ʾ ֵ ********************************************/ void Write_Data(unsigned char dat) { unsigned char lcdtemp = 0; LCD_RS_L; LCD_RW_H; LCD_DataIn; do //æ { LCD_EN_H; delay_50us(); lcdtemp = LCD2MCU_Data; LCD_EN_L; } while(lcdtemp & 0x80); LCD_DataOut; LCD_RS_H; LCD_RW_L; MCU2LCD_Data = dat; LCD_EN_H; _NOP(); LCD_EN_L; } /**************************** read data ***********************/ unsigned int Read_Data(void) { unsigned int mcu_data; LCD_RS_L; LCD_RW_H; LCD_DataIn; do //æ { LCD_EN_H; delay_50us(); mcu_data = LCD2MCU_Data; LCD_EN_L; }while(mcu_data & 0x80); LCD_RS_H; delay_50us(); LCD_EN_H; //dummy read delay_50us(); LCD_EN_L; delay_50us(); LCD_EN_H; //E߶Ч delay_50us(); mcu_data=LCD2MCU_Data; mcu_data<<=8; LCD_EN_L; delay_50us(); LCD_EN_H; //E߶Ч delay_50us(); mcu_data+=LCD2MCU_Data; LCD_EN_L; return(mcu_data); } /******************************************* ƣIni_Lcd ܣʼҺģ ֵ ********************************************/ void Ini_Lcd(void) { /////////////////////////////////////// LCD_RST_L; //λLCD delay_1ms(); //֤λҪʱ LCD_RST_H; //ָLCD _NOP(); //LCD_PSB_H; //LCDΪ8λͨ //////////////////////////////////////// LCD_CMDOut; //Һƶ˿Ϊ delay_nms(500); Write_Cmd(0x30); //ָ delay_1ms(); Write_Cmd(0x02); // ַλ delay_1ms(); Write_Cmd(0x0c); //ʾ,αر delay_1ms(); Write_Cmd(0x01); //ʾ delay_1ms(); Write_Cmd(0x06); //α delay_1ms(); Write_Cmd(0x80); //趨ʾʼַ } /******************************************* ƣDisp_HZ ܣҺʾ addr--ʾλõ׵ַ pt--ָʾݵָ num--ʾַ ֵ ********************************************/ void Disp_HZ(unsigned char addr,const unsigned char * pt,unsigned char num) { unsigned char i; Write_Cmd(addr); for(i = 0;i < (num*2);i++) { Write_Data(*(pt++)); delay_50us(); } } //***********λÿʼʾͼ****************/ void LCD_draw(unsigned char X,unsigned char Y,unsigned char *tab,unsigned char wide,unsigned char high) { //YȷʼУXȷУ0-7,tabǵģ unsigned int hang,lie; Write_Cmd(0x34);//ͼʾ if (wide%8==0) wide=wide/8; else wide=wide/8+1; for(hang=0;hang<high;hang++) { if(Y+hang>31) //ַת { Write_Cmd(0x80+Y+hang-32);//дY Write_Cmd(0x88+X);//дX,(0x88-0x8f) } //Xֻд0-7 else { Write_Cmd(0x80+Y+hang);//дY Write_Cmd(0x80+X);//дX,(0x80-0x87) } for(lie=0;lie<wide;lie++) //пдݣռֽڣдֽ { Write_Data(tab[hang*wide+lie]); //ÿдwideֽ } } Write_Cmd(0x36);//ͼʾ //Write_Cmd(0x30);//صָ } void drawpoint(volatile unsigned int X,volatile unsigned int Y,unsigned int Type) { //XYTypeͣ㣬߳㣬 unsigned int lie; volatile unsigned int TempData = 0; lie =BIT0 << (15 - (X % 16)); X/=16; Write_Cmd(0x34);//ͼʾ,ָ if(Y>31) //ַת { Write_Cmd(0x80+Y-32);//дY Write_Cmd(0x88+X);//дX,(0x88-0x8f) } //Xֻд0-7 else { Write_Cmd(0x80+Y);//дY Write_Cmd(0x80+X);//дX,(0x80-0x87) } TempData = Read_Data(); //ֽڵ(16bit) switch (Type) //ԸֽڽӦ { case Point_Draw: TempData &= ~lie; break; // case Graphic_Not: // TempData ^= (1 << BX); // break; case Point_Clear: TempData |= lie; break; default: break; } if(Y>31) //ַת { Write_Cmd(0x80+Y-32);//дY Write_Cmd(0x88+X);//дX,(0x88-0x8f) } //Xֻд0-7 else { Write_Cmd(0x80+Y);//дY Write_Cmd(0x80+X);//дX,(0x80-0x87) } Write_Data(TempData>>8); Write_Data(TempData); //޸ĺֽͻLCDﵽĿ(16bit) Write_Cmd(0x36);//ͼʾ } void sel_low() { P8DIR = 0xff; P8OUT=0Xff; //P1DIR = 0xff; // P1OUT =0xff; P8OUT=0Xff; // P1OUT =0x00; }
C
#include<unistd.h> #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<sys/socket.h> #include<netinet/in.h> #include<netdb.h> #include<string.h> #define PORT 9600 int main(int argc, char *argv[]){ /* * Variables du client * * Déclarer ici les variables suivantes : * - sockfd le descripteur de socket * - structure d’adresse du serveur * - pointeur vers la structure descriptive de machine (hostent) * - zone de mémoire destinée à accueillir la chaîne * entrée au clavier * - taille de la chaîne à envoyer */ //initialisation du message initial char message[1024]; printf("Bonjour, je suis là!!!\n"); //création de socket int socketfd = socket(PF_INET, SOCK_DGRAM, 0); if(socketfd == -1){ perror("problème socket"); exit(EXIT_FAILURE); } //initialisation hostent struct hostent *hostinfo = NULL; const char *hostname = "localhost"; hostinfo = gethostbyname(hostname); if(hostinfo == NULL){ perror("Problème hostent\n"); exit(0); } // spécifier les adresses pour le socket struct sockaddr_in addresse_serveur; memset(&addresse_serveur, 0, sizeof(addresse_serveur)); addresse_serveur.sin_family = PF_INET; addresse_serveur.sin_port = htons(PORT); memcpy(&addresse_serveur.sin_addr.s_addr, hostinfo->h_addr, sizeof(hostinfo->h_addr)); // Prendre le message au clavier printf("Quel est votre message ? "); fgets(message, 1024, stdin); printf("%s\n", message); bind(socketfd, (struct sockaddr*) &addresse_serveur, sizeof(addresse_serveur)); //envoi d'un message au serveur int sendOk = sendto(socketfd, (char *)message, strlen(message), 0, (struct sockaddr *)&addresse_serveur, sizeof(addresse_serveur)); if(sendOk < 0){ perror("problème sendto()"); exit(h_errno); } printf("Message envoyé\n"); // fermeture de socket close(socketfd); return 0; }
C
//Nothings wrong i forgot toadd an & #include <stdio.h> #include <stdlib.h> #include <math.h> int main() { double minutes = 0; double years = 525600; double days = 1440; double result; double result2; printf("Please enter the number of minutes\n"); scanf( "%lf", &minutes); //nvm forgot the & key printf("\nYou have entered %lf", minutes); result = (minutes/days); result2= (minutes/years); printf("\n%lf",minutes); printf(" converted to days is %lf",result); printf(" \nconverted to years is %lf",result2); return 0; }
C
#include <stdio.h> #include <limits.h> #include <stdlib.h> #define MAX_COUNT 1000 + 3 #define MAX_SIZE 500500 + 1 typedef struct Graph { int weight; int id; } Graph; int v_count, r_count; int dist_with_start[MAX_COUNT]; int dist_with_final[MAX_COUNT]; int dist_from_catch[MAX_COUNT]; int line_mat[MAX_SIZE]; short visited[MAX_COUNT]; Graph list_s[MAX_COUNT]; int getIndex(int x, int y) { if (x < y) return (((y - 1) * y) / 2) + x; else return (((x - 1) * x) / 2) + y; } void Dijkstra(int best_v, int *distance) { for (int i = 0; i < v_count; i++) visited[i] = 0; while (1) { //находим минимальный вес for (int i = 0; i < v_count; ++i) { static int index; index = getIndex(best_v, i); //если ребро есть и если вес этого ребра + расстояние if (line_mat[index] > 0 && (line_mat[index] + distance[best_v]) <= distance[i]) distance[i] = line_mat[index] + distance[best_v]; } visited[best_v] = 1; static int best_r, check_end; best_r = INT_MAX; check_end = best_v; for (int i = 0; i < v_count; i++){ if (visited[i] == 0 && distance[i] < best_r) { best_r = distance[i]; best_v = i; } } if (best_v == check_end) break; } } int compare(const void *a, const void *b){ return ((*(Graph*)a).weight - (*(Graph*)b).weight); } int main() { FILE * input = fopen("input.txt", "r"); FILE * output = fopen("output.txt", "w"); fscanf(input, "%d ", &v_count); fscanf(input, "%d ", &r_count); for (int i = 0; i < r_count; ++i) { static int v_A, v_B, weight; fscanf(input, "%d %d %d ", &v_A, &v_B, &weight); line_mat[getIndex(v_A, v_B)] = weight; line_mat[getIndex(v_B, v_A)] = weight; } for (int i = 0; i < MAX_COUNT; ++i) { dist_with_final[i] = INT_MAX; dist_with_start[i] = INT_MAX; dist_from_catch[i] = INT_MAX; } int finish, start, catcher; fscanf(input, "%d %d %d", &finish, &start, &catcher); dist_with_final[finish] = 0; dist_with_start[start] = 0; dist_from_catch[catcher] = 0; Dijkstra(start, dist_with_start); Dijkstra(finish, dist_with_final); Dijkstra(catcher, dist_from_catch); for (int i = 0; i < v_count; ++i) { list_s[i].id = i; list_s[i].weight = dist_with_start[i]; } qsort(list_s, v_count, sizeof(Graph), compare); int max = 0, vert = 0; char flag = 1; for (int i = 0; i < v_count; i++) { //если дист с конца до итой вершины + дист с начала != кротчайшему пути значит идем мимо //идет поиск вершины которая лежит на кротчайшем пути if (dist_with_final[list_s[i].id] + dist_with_start[list_s[i].id] != dist_with_start[finish]) { continue; } //если вес вершины лежашей на кротчайшем пути = макс И ... И дист от перехватчика до точки точки на пути <= дист игрока до этой точки if (flag == 1 && list_s[i].weight == max && vert == list_s[i].id && dist_from_catch[list_s[i].id] <= dist_with_start[list_s[i].id]) fprintf(output, "%d\n", vert);//выводим for (int j = 0; j < v_count; j++) { static int index; index = getIndex(list_s[i].id, j); static int startMin; startMin = 0; //если дист до рассматриваемой точки на пути меньше чем if (dist_with_start[list_s[i].id] < dist_with_start[j]) startMin = dist_with_start[list_s[i].id]; else startMin = dist_with_start[j]; static int finalMin; finalMin = 0; if (dist_with_final[list_s[i].id] < dist_with_final[j]) finalMin = dist_with_final[list_s[i].id]; else finalMin = dist_with_final[j]; if (line_mat[index] == 0 || line_mat[index] + finalMin + startMin != dist_with_start[finish]) continue; line_mat[index] = 0; if (dist_with_start[j] >= max) { if (dist_with_start[j] == max && j != vert) flag = 0; if (dist_with_start[j] > max) { flag = 1; vert = j; } max = dist_with_start[j]; } } } fclose(input); fclose(output); return 0; }
C
#include <stdio.h> int sample(char *s); int main(int argc, char **argv) { sample("abc"); return 0; } int sample(const char *s) { printf("%s\n", s); return 0; }
C
#include "common.h" int main() { dlist *head = NULL, *tail = NULL; data_t data, n_data, g_data; int opt, status; while(1) { printf("1.insert after\n 2.insert at first\n 3.insert before\n 4.delete elements\n 7.print\n 8.Exit\n"); scanf("%d", &opt); switch(opt) { case 1: { printf("Enter the n_data\n"); scanf("%d",&n_data); printf("Enter the g_data\n"); scanf("%d",&g_data); status = insert_after(&head, &tail, n_data, g_data); if(status == SUCCESS) { printf("data inserted after \n"); } else if(status == DATA_NOT_FOUND) { printf("Data not found in the list\n"); } else { printf("data insertion unsuccessful\n"); } break; } case 2: { printf("Enter the data\n"); scanf("%d",&data); status = insert_first(&head, &tail, data); if(status == SUCCESS) { printf("Head inserted at first\n"); } else { printf("Head insertion unsuccessful\n"); } break; } case 3: { printf("Enter the n_data\n"); scanf("%d",&n_data); printf("Enter the g_data\n"); scanf("%d",&g_data); status = insert_before(&head, &tail, n_data, g_data); if(status == SUCCESS) { printf("data inserted before \n"); } else if(status == DATA_NOT_FOUND) { printf("Data not found in the list\n"); } else { printf("data insertion unsuccessful\n"); } break; } case 4: { printf("Enter the n_data\n"); scanf("%d",&n_data); status = delete_element(&head, &tail, n_data); if(status == SUCCESS) { printf("delete successful \n"); } else if(status == DATA_NOT_FOUND) { printf("Data not found in the list\n"); } else { printf("data insertion unsuccessful\n"); } break; } case 7: { print_dlist(head); break; } case 8: { exit(0); break; } default: { printf("Enter the correct option\n"); } } } }
C
/* ============================================================================ Name : Ejercicio_2-2.c Author : Version : Copyright : Your copyright notice Description : Hello World in C, Ansi-style ============================================================================ */ #include <stdio.h> #include <stdlib.h> #define CANT 4 int pedirNumero(int num[], int size); int get_ParImpar(int num[], int size, int* countPar, int* countImpar); int get_Menor(int num[], int size, int* menor); int get_MayorPar(int num[], int size, int* mayorPar); int get_Sum(int num[], int size, int* sumaPos); int get_Prod(int num[], int size, int* prodNeg); int mostrarResultado(int countPar, int countImpar, int menor, int mayorPar, int sumaPos, int prodNeg); int main(void) { setbuf(stdout, NULL); int num[CANT]; int countPar = 0; int countImpar = 0; int menor, mayorPar, sumaPos, prodNeg; pedirNumero(num, CANT); get_ParImpar(num, CANT, &countPar, &countImpar); get_Menor(num, CANT, &menor); get_MayorPar(num, CANT, &mayorPar); get_Sum(num, CANT, &sumaPos); get_Prod(num, CANT, &prodNeg); mostrarResultado(countPar, countImpar, menor, mayorPar, sumaPos, prodNeg); return 0; } int pedirNumero(int num[], int size) { int i = 0; for(i=0; i<size; i++) { printf("\nIngrese un numero --> "); scanf("%d", &num[i]); } return 0; } int get_ParImpar(int num[], int size, int* countPar, int* countImpar) { int i = 0; for(i=0; i<size;i++) { if(num[i] %2 == 0) { *countPar += 1; } else { *countImpar += 1; } } return 0; } int get_Menor(int num[], int size, int* menor) { int aux = num[0]; int i = 0; for(i=0;i < size; i++) { if(num[i] < aux) { aux = num[i]; } } *menor = aux; return 0; } int get_MayorPar(int num[], int size, int* mayorPar) { int i = 0; int flag = 0; int aux; for(i=0; i < size; i++) { if(num[i] %2 == 0 && flag == 0) { aux = num[i]; flag = 1; } if(num[i] %2 == 0 && flag == 1) { if(num[i] > aux) { aux = num[i]; } } } *mayorPar = aux; return 0; } int get_Sum(int num[], int size, int* sumaPos) { int i = 0; int aux = 0; for(i=0; i < size; i++) { if(num[i] > 0) { aux += num[i]; } } *sumaPos = aux; return 0; } int get_Prod(int num[], int size, int* prodNeg) { int i = 0; int aux = 1; for(i=0; i < size; i++) { if(num[i] < 0) { aux *= num[i]; } } *prodNeg = aux; return 0; } int mostrarResultado(int countPar, int countImpar, int menor, int mayorPar, int sumaPos, int prodNeg) { printf("a. La cantidad de numeros pares es --> %d e impares es --> %d\n", countPar, countImpar); printf("b. El menor numero ingresado es --> %d\n", menor); printf("c. El mayor numero par es --> %d\n", mayorPar); printf("d. La suma de los numeros positivos es --> %d\n", sumaPos); printf("e. El producto de los negativos es --> %d", prodNeg); printf("\t --Chau--"); return 0; }
C
#include <iostream> int get_int() { static int x = 0 ; return x++ ; } class Int { friend std::ostream& operator<<( std::ostream&, const Int& ) ; int t_ ; public: Int() : t_( get_int() ) { ; } } ; std::ostream& operator<<( std::ostream &o, const Int &i ) { o << i.t_ ; return o ; } Int a, b, c, d ; int main( int ac, char **av ) { std::cout << a << " " << b << " " << c << " " << d << std::endl ; return 0 ; }
C
#include "common.h" #include <stdio.h> #include <stdlib.h> #include <errno.h> #include <unistd.h> #include "data_types.h" #include <string.h> void check_arg_count(int argc, int count, char* usage) { if (argc < count) { printf("Insufficient arguments\n"); printf("%s", usage); printf("\n"); exit(1); } } DFA *parse_dfa(char *file_name) { int num_char, num_states, num_final_states; FILE *in_file = fopen(file_name, "r"); if (!in_file) { printf("Error opening file: %s", strerror(errno)); exit(1); } printf("File Name %s\n\n", file_name); printf("In DFA\n\n"); fscanf(in_file, "%d", &num_char); printf("Num char %d \n", num_char); fscanf(in_file, "%d", &num_states); printf("Num states %d \n", num_states); int **transition_array = (int**) malloc(sizeof(int*)*num_states); int i, j; printf("Transition Function:\n"); for (i = 0; i < num_states; i++) { printf("%d:", i); transition_array[i] = (int*) malloc(sizeof(int)*num_char); for (j = 0; j < num_char; j++) { fscanf(in_file, "%d", &transition_array[i][j]); printf("\t%d", transition_array[i][j]); } printf("\n"); } fscanf(in_file, "%d", &num_final_states); printf("Final states: %d\n", num_final_states); assert_cond(num_states >= num_final_states, " Number of final\ states is greater than number of states, Num Final: %d, Num States: %d", num_final_states, num_states); printf("Final state:\t"); int *final = (int*) malloc(sizeof(int)*num_final_states); for (i = 0; i < num_final_states; i++) { fscanf(in_file, "%d", &final[i]); assert_cond(final[i] < num_states, "final state index is greater\ than number of states. Index: %d, Total States: %d", final[i], num_states); printf("%d\t", final[i]); } printf("\n\n"); DFA *in_dfa = (DFA*) malloc(sizeof(DFA)); in_dfa->transition_func = transition_array; in_dfa->num_char = num_char; in_dfa->num_states = num_states; in_dfa->final_states = final; in_dfa->num_final_states = num_final_states; return in_dfa; } long get_page_size() { return sysconf(_SC_PAGESIZE); }
C
#include <stdio.h> int rangeBitwiseAnd(int m, int n) { int res = 0; int i; for(i = 31; i >= 0; i--){ if(((m >> i) & 1) == ((n >> i) & 1)){ res = (res << 1) + ((m >> i) & 1); }else{ break; } } return res << (i + 1); } int range_bitwise_and(int m, int n){ int i = 0; while (m != n){ m >>= 1; n >>= 1; i++; } return m << i; } int main(){ int m = 3; int n = 6; int res = rangeBitwiseAnd(m, n); printf("res: %d\n", res); }
C
/** * \addtogroup gbas * \{ * \addtogroup Sections * \{ */ #ifndef SECTIONS_H #define SECTIONS_H #include <stdio.h> #include "../common/objfile.h" /** Describes a section entry in the sections list */ typedef struct section_s { int id; /**< Section id */ section_type_t type; /**< Section type */ int offset; /**< Absolute address or offset in the bank */ int bank; /**< Bank number */ int datasize; /**< Size of the section */ int pc; /**< Program counter */ struct section_s* next; /**< Pointer to the next section in the list */ } section_t; void init_sections(); void free_sections(); section_t* get_current_section(); section_t* get_section_by_id(int id); void add_section(int pass, section_type_t type, int address, int bank); void add_opcode(int pass, int iopcode, int val); void add_data(int pass, char c); #endif /** * \} Sections * \} gbas */
C
/* ************************************************************************** */ /* LE - / */ /* / */ /* ft_printf_print.c .:: .:/ . .:: */ /* +:+:+ +: +: +:+:+ */ /* By: nepage-l <marvin@le-101.fr> +:+ +: +: +:+ */ /* #+# #+ #+ #+# */ /* Created: 2019/10/29 07:17:58 by nepage-l #+# ## ## #+# */ /* Updated: 2019/11/16 06:36:18 by nepage-l ### #+. /#+ ###.fr */ /* / */ /* / */ /* ************************************************************************** */ #include "ft_printf.h" int ft_count_lst(t_list *lst) { int count; count = 0; while (lst) { if (lst->convert == 'c') count += lst->width; else count += ft_strlen(lst->content); lst = lst->next; } return (count); } int ft_count_lstn(t_list *lst, t_list *arret) { int count; count = 0; while (lst != arret) { count += ft_strlen(lst->content); lst = lst->next; } return (count); } void ft_flagc(t_list *lst) { int i; i = 0; while (i < lst->width) ft_putchar_fd(lst->content[i++], 1); } void ft_flagn(t_list *lst, t_list *premier) { int *nbr; nbr = (int *)lst->flagn; nbr[0] = ft_count_lstn(premier, lst); } int ft_printf_print(t_list *lst) { t_list *premier; int count; premier = lst; lst = premier; while (lst) { if (lst->flag == ' ') ft_flagsp(lst); if (lst->convert == 'n') ft_flagn(lst, premier); if (lst->convert == 'c') ft_flagc(lst); else ft_putstr_fd(lst->content, 1); lst = lst->next; } count = ft_count_lst(premier); ft_lstclear(&premier, free); return (count); }
C
#include <stdio.h> int funp(int a) { return a * a; } int main() { int r = 33, sq; int (*p)(int) = NULL; p = &funp; // sq = p(r); // Two ways to call function sq = (*p)(r); // Using the fucntion pointer printf("\n\nThe square of %d is %d\n\n", r, sq); return 0; }
C
/****************************************************************************** keywords : linked list, data structures, reversing File Name : dsa_linklist_reversing.c Date of Creation : 13/11/2007 Owner : Rashi Arora Date of Modification : Reason for modification : Modifier : *******************************************************************************/ #include<stdio.h> /********************Structure Declaration *************************/ typedef struct node_s { int data; struct node_s * next; }node; /********************Function Declarations ***************************/ node * create(node *h,int val); void printlist(node * h); void del(node *h); node * reverse(node *h); node * sort(node *h,int num); /***************Function Definitions ******************/ node * create(node *h,int val) { node *q,*newnode; newnode=(node*)malloc(sizeof(node)); newnode->data=val; if(h==NULL) { h=newnode; } else { newnode->next=h; h=newnode; } return h; } void printlist(node * h) { node *p; if(h==NULL) printf("list is empty"); else { for(p=h;p!=NULL;p=p->next) printf("%d\n",p->data); } } node * reverse(node * h) { node *curr,*new,*p; curr=h; new=h->next; p=NULL; while(new!=NULL) { curr->next=p; p=curr; curr=new; new=curr->next; } curr->next=p; h=curr; return h; } /*********************Main Function *********************************/ int main() { node *head; head=NULL; int a,b,i; printf("\nEnter how many nodes"); scanf("%d",&b); for(i=1;i<=b;i++) { printf("\nEnter the value to be inserted\t"); scanf("%d",&a); head=create(head,a); } printf("\nList is\n"); printlist(head); head=reverse(head); printf("\n List after reversing is\n"); printlist(head); }
C
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "basket.h" #include "statistics.h" #include "commands.h" Player createPlayer(int id, char *name, char *team, Date birthdate, char gender) { Player newPlayer; newPlayer.id = id; strcpy_s(newPlayer.name, sizeof(newPlayer.name), name); strcpy_s(newPlayer.team, sizeof(newPlayer.team), team); newPlayer.birthDate = birthdate; newPlayer.gender = gender; newPlayer.statistics = createStatistics(0, 0, 0, 0, 0, 0); return newPlayer; } Date createDate(int day, int month, int year) { Date newDate; newDate.day = day; newDate.month = month; newDate.year = year; return newDate; }
C
#include <stdio.h> #include "lib/sbus.h" #include <stdint.h> #include <stdlib.h> #include <time.h> typedef struct test{ uint8_t input_digital_chanel_1[29]; // пакет для цифрового канала 1 uint8_t input_digital_chanel_2[31]; // пакет для цифрового канала 2 uint16_t output[18]; }test_t; int main() { sbus_digital_channel_1.sbusTrustFlag = 1; sbus_digital_channel_2.sbusTrustFlag = 1; sbus_buff.sbusTrustFlag = 1; test_t t1 = { .input_digital_chanel_1 = {17, 25, 15, 41,107,214,235, 44,169, 3, 33,187,239, 95, 95, 76,252, 16,236,190,212,237, 81, 6, 69, 77, 0, 40, 30}, .input_digital_chanel_2 = {8, 9, 15, 15, 41,107,214,235, 44,169, 3, 33,187,239, 95, 95, 76,252, 16,236,190,212,237, 81, 6, 69, 78, 0, 14, 18, 19 }, .output = {809, 717, 943,1174, 58,1602,1006, 767,1119,1929, 67,1910,1355, 987, 404, 552,2047, 0} }; parceSbus(t1.input_digital_chanel_1, 29); parceSbus(t1.input_digital_chanel_2, 31); printArrU16(t1.output, 18); printSbusSt(print, sbus_digital_channel_1); printSbusSt(print, sbus_digital_channel_2); if (memcmp(sbus_digital_channel_1, t1.output, 10) == 0) { printf("TEST DONE digital_channel_1\n"); } else { printf("TEST FAILED digital_channel_1\n"); } if (memcmp(sbus_digital_channel_2, t1.output, 10) == 0) { printf("TEST DONE digital_channel_2\n"); } else { printf("TEST FAILED digital_channel_2\n"); } }
C
#include<stdio.h> #include<stdlib.h> #include<string.h> #include<math.h> void floyd(); float weightt(int,int); float INF=10001; struct node { int label; struct node*next; float weight; }*head,*trk,*new; struct array { struct node*list; }; struct array*adj; int n; void main() { scanf("%d",&n); getchar(); if(n<1||n>1000) { printf("INVALID\n"); exit(0); } char ch; char str[100000]; int prev=0; adj=(struct array*)malloc(n*sizeof(struct array)); int i,j,v,num; for(j=0;j<n;j++) { head=NULL; num=0; prev=0; gets(str); for(i=0;i<strlen(str);) { num=0; if(str[i]>='0'&&str[i]<='9') { while(str[i]>='0'&&str[i]<='9') { num*=10; num+=str[i]-'0'; i++; } if(num>=n) { printf("INVALID"); exit(0); } new=(struct node*)malloc(sizeof(struct node)); if(num<prev) { printf("invalid"); exit(0); } prev=num; new->label=num; new->next=NULL; new->weight=INF; if(head==NULL) { head=trk=new; } else { trk->next=new; trk=new; } } else i++; } adj[j].list=head; trk=adj[j].list; } for(j=0;j<n;j++) { //printf("\nJ for weight\n"); trk=adj[j].list; float nu=0; gets(str); int temp; for(i=0;i<strlen(str);) { nu=0; temp=i; if(str[i]>='0'&&str[i]<='9') { while(str[i]>='0'&&str[i]<='9') { nu*=10; nu+=(float)(str[i]-'0'); i++; } if(str[i]=='.') { int poow=-1; i++; while(str[i]<='9'&&str[i]>='0') { nu=nu+(float)((str[i]-'0')*pow(10,poow)); poow--; i++; } } if(str[temp-1]=='-') { nu=nu*-1.0; } if(!(nu<=10000&&nu>=-10000)) { printf("invalid"); exit(0); } if(trk!=NULL) { //printf("%f\n",nu); trk->weight=nu; trk=trk->next; } } else i++; } } floyd(); } void floyd() { //printf("IN FLOYD\n"); float *distance = (float *)malloc(n * n * sizeof(float)); int k; int i, j, count = 0; for(i=0;i<n;i++) { for(j=0;j<n;j++); { if(i!=j) *(distance+i*n+j)=10001; else *(distance+i*n+j)=0; } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { //printf("%d ",weightt(i,j)); *(distance+i*n+j)=weightt(i,j); } } for(k=0;k<n;k++) { for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(*(distance+i*n+k)+*(distance+k*n+j)<*(distance+i*n+j)) { *(distance+i*n+j)=*(distance+i*n+k)+*(distance+k*n+j); } } } } for(k=0;k<n;k++) { if(*(distance+k*n+k)<0) { printf("NEGATIVE CYCLE: INVALID"); exit(0); } } for(i=0;i<n;i++) { for(j=0;j<n;j++) { if(*(distance+i*n+j)==INF) printf("INF "); else { if(*(distance+i*n+j)-(int)*(distance+i*n+j)==0) printf("%d ",(int)*(distance+i*n+j)); else printf("%f ",*(distance+i*n+j)); } } printf("\n"); } } float weightt(int s,int d) { float wt=INF; struct node*p=adj[s].list; if(s==d) return 0; while(p!=NULL) { if(p->label==d) { wt=p->weight; break; } p=p->next; } return wt; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <math.h> double pi(double start, double end) { double out = 0.0; double signo = 1; double x = 0.0; for(double i = start; i < end; i+=2.0) { x = 4.0/i; x = x * signo; signo *= -1; out += x; } return out; } int main(void) { double aux = 0.0; double _result = 0.0; double *result = &_result; double number = 2e09; //3.14159265358 int pfd[2]; pid_t pid; int r = pipe(pfd); if (r == -1) { perror("Error Pipe(...)"); exit(-1); } pid = fork(); if (pid == 0) { close(pfd[0]); double *ptr; double _pi = pi(1.0, (number/2)); ptr = &_pi; r = write(pfd[1], ptr, sizeof(double)); printf("Hola soy Hijo %f\n", _pi); close(pfd[1]); } else { close(pfd[1]); double _pi2 = pi((double)(number/2), (double)number); r = read(pfd[0], result, sizeof(double)); close(pfd[0]); _pi2 += *result; printf("Hola soy Padre %.10f\n", _pi2); } return 0; }
C
#include <stdio.h> #define N 4 #define M 5 int main(){ int a[M][N],m,n,i,j,p,f=0,flag; printf("Please enter matrix:\n"); for (i=0;i<N;i++){ for (j=0;j<M;j++){ printf("[%d][%d]:",i,j); scanf("%d",&a[i][j]); } } for (i=0;i<N;i++){ for (j=0;j<M;j++){ if (a[i][j]>a[i][f]) f=j; } flag=1; for (p=0;p<N;p++){ if (a[i][f]>a[p][f]){ flag=0; continue; } } if (flag) { printf("a[%d][%d]=%d\n",i,f,a[i][f]); break; } } if (!flag) printf("It does not exist!\n"); return 0; }
C
/** @file spi_dma.c @author Michael Hayes @date 18 December 2007 @brief Routines for interfacing to the SPI bus with DMA access. */ #ifndef SPI_DMA_H #define SPI_DMA_H #ifdef __cplusplus extern "C" { #endif #include "spi.h" /** Bitmask to select desired channel for DMA transfers. */ #define SPI_DMA_CHANNEL_MASK(channel) (SPI_CHANNEL_MASK(channel) << 16) /** Return true if DMA has finished writing a buffer. */ extern bool spi_dma_write_finished_p (spi_t spi); /** Return true if DMA has finished reading a buffer. */ extern bool spi_dma_read_finished_p (spi_t spi); /** Return true if DMA has nothing more to write. */ extern bool spi_dma_write_completed_p (spi_t spi); /** Return true if DMA has nothing more to read. */ extern bool spi_dma_read_completed_p (spi_t spi); extern bool spi_dma_write_enable_p (spi_t spi); extern bool spi_dma_read_enable_p (spi_t spi); extern void spi_dma_write_enable (spi_t spi); extern void spi_dma_write_disable (spi_t spi); extern void spi_dma_read_enable (spi_t spi); extern void spi_dma_read_disable (spi_t spi); extern void spi_dma_write_init (spi_t spi, void *buffer, uint16_t size); extern void spi_dma_read_init (spi_t spi, void *buffer, uint16_t size); extern void spi_dma_write_next (spi_t spi, void *buffer, uint16_t size); extern void spi_dma_read_next (spi_t spi, void *buffer, uint16_t size); extern void spi_dma_init (spi_t spi, void *txbuffer, void *rxbuffer, uint16_t size); extern void spi_dma_next (spi_t spi, void *txbuffer, void *rxbuffer, uint16_t size); extern void spi_dma_enable (spi_t spi); extern void spi_dma_disable (spi_t spi); #ifdef __cplusplus } #endif #endif
C
#pragma warning(disable:4996) #include <stdio.h> #include <stdlib.h> #include <string.h> typedef struct node { char name[21]; char id[11]; double score; struct node* next; }Node; Node* getnode(); void init(); void add(); void main() { Node* H, * T, * p, * q; int i, n; init(&H, &T); scanf("%d", &n); getchar(); for (i = 0; i < n; i++) { add(H, T); } p = H->next; for (; p != T; p = p->next) { printf("%s %s %.1lf\n", p->name, p->id, p->score); } p = H; for (; p != NULL;) { q = p->next; free(p); p = q; } } Node* getnode() { Node* newnode; newnode = (Node*)malloc(sizeof(Node)); newnode->next = NULL; return newnode; } void init(Node** H, Node** T) { Node* h, * t; h = getnode(); t = getnode(); h->next = t; *H = h; *T = t; } void add(Node* H, Node* T) { int i; Node* p, * q; Node* newnode; newnode = getnode(); scanf("%s", newnode->name); scanf("%s", newnode->id); scanf("%lf", &(newnode->score)); getchar(); p = H; q = p->next; for (; q != T;) { if (strcmp(newnode->id, q->id) > 0) { p = p->next; q = q->next; } else if (strcmp(newnode->id, q->id) < 0) { break; } else if (strcmp(newnode->id, q->id) == 0) { p->next = newnode; newnode->next = q->next; free(q); return; } } newnode->next = q; p->next = newnode; }
C
#include "lib.h" void read_from_file(struct Bird *birds){ FILE *file = fopen("../birds.txt", "r"); if (file == NULL) { printf("Unable to open file: %s", strerror(errno)); exit(1); } for(int i = 0; i < N; i++){ fscanf(file, "%d%s%d%d%d%d%d", &((birds + i)->LOTR), ((birds + i) ->name), &((birds + i)->home.space), &((birds + i)->home.height), &((birds + i)->home.count_of_feeders), &((birds + i)->home.if_nest), &((birds + i)->enumSex)); } fclose(file); } void random_age_generation(struct Bird *birds){ for(int i = 0; i < N; i++){ (birds + i)->age = rand() % 207 + 23; } } void print_in_console(struct Bird *birds, int count){ for(int i = 0; i < count; i++){ if((birds + i)->LOTR == 1){ printf("Is bird the Lord of the Ring: Yes\n"); }else{ printf("Is bird the Lord of the Ring: NO\n"); } printf("Name: %s\n", (birds + i)->name); printf("Age: %d months\n", (birds + i)->age); printf(" Home area: %d sm^2\n", (birds + i)->home.space); printf(" Home height: %d sm\n", (birds + i)->home.height); printf(" Home feeders amount: %d\n", (birds + i)->home.count_of_feeders); if((birds + i)->home.if_nest == 1){ printf(" Is bird's home a nest: Yes\n"); }else{ printf(" Is bird's home a nest: NO\n"); } if((birds + i)->enumSex == Male){ printf("Sex: male\n"); } else if((birds + i)->enumSex == Female) { printf("Sex: female\n"); } printf("\n"); } } int bool_compare_strings(char a[10], char b[10]){ if(strcmp(a,b) <= 0){ return 0; } else if (strcmp(a,b) > 0){ return 1; } else return 0; } struct Bird * add_bird(struct Bird *birds, struct Bird paste_bird, int pos) { if (pos < 0) printf("Error"); struct Bird *result = malloc((N + 1) * sizeof(struct Bird)); memcpy(result, birds, sizeof(struct Bird) * N); if (pos >= N) { pos = N; memcpy((result + N), &paste_bird, sizeof(struct Bird)); } else { struct Bird *buffer = malloc((N + 1) * sizeof(struct Bird)); memcpy(buffer, result + pos, sizeof(struct Bird) * (N - pos)); memcpy(result + pos, &paste_bird, sizeof(struct Bird)); memcpy(result + pos + 1, buffer, sizeof(struct Bird) * (N - pos)); free(buffer); } free(birds); return result; } struct Bird * delete_bird(struct Bird *birds, int pos){ if (pos < 0) printf("Error"); struct Bird *result = malloc((N-1) * sizeof(struct Bird)); if (pos >= N) { pos = N; memcpy(result, birds, sizeof(struct Bird) * (N-1)); } else { memcpy(result, birds, sizeof(struct Bird) * pos); memcpy(result + pos, birds+pos+1, sizeof(struct Bird) * (N-pos-1)); } free(birds); return result; } char * insert_string(char * text, char * pasted_text, int pos){ if (pos < 0) pos = 0; if (pos > strlen(text)) pos = strlen(text); //проверка корректности позиции char* new_text = malloc((strlen(text) + strlen(pasted_text))* sizeof (char)); memcpy(new_text, text, pos); memcpy(new_text + pos, pasted_text, strlen(pasted_text)); memcpy(new_text + pos + strlen(pasted_text), text + pos, strlen(text) - pos); *(new_text + strlen(pasted_text) + strlen(text)) = '\0'; return new_text; } char * delete_string(char * text, int pos1, int pos2){ if (pos1 < 0) pos1 = 0; if (pos2 >= strlen(text)) pos2 = strlen(text) - 1; if (pos1 > pos2) return "Error"; //проверка корректности позиций char* new_text = malloc((strlen(text) - (pos2 - pos1))* sizeof (char)); memcpy(new_text, text, pos1); memcpy(new_text + pos1, text + pos2 + 1, strlen(text) - pos2); return new_text; } void Demonstration_of_strings(){ char* string1 = malloc(100 * sizeof (char)); char* insertion_string = malloc(100 * sizeof (char)); char* string2 = malloc(100 * sizeof (char)); printf("Input text: "); scanf("%s", string1); printf("Input string you want to insert: "); scanf("%s", insertion_string); int position; printf("Position: "); scanf("%i", &position); char* result = insert_string(string1, insertion_string, position); printf("Result: %s\n\n", result); int pos1, pos2; printf("Input text: "); scanf("%s", string2); printf("First position to delete: "); scanf("%d", &pos1); printf("Second position to delete: "); scanf("%d", &pos2); result = delete_string(string2, pos1, pos2); printf("Result: %s\n\n\n", result); free(result); free(string1); free(insertion_string); free(string2); system("pause"); }
C
#include<stdio.h> #include<stdlib.h> int main(){ //declare variables iterators, rows, cols,2 matrices, sum matrices int rows, cols, a[100][100], b[100][100], sum[100][100], i, j; //prompt user to enter no. of rows and cols printf("Enter the number of rows(between 1 & 100) :\n"); scanf("%d",&rows); printf("Enter the number of columns(between 1 & 100) :\n"); scanf("%d",&cols); //prompt user to enter elements of matrices for(i=0;i<rows;i++) for(j=0;j<cols;j++){ printf("Enter element[%d][%d] of matrix a :\n",i+1,j+1); scanf("%d",&a[i][j]); } for(i=0;i<rows;i++) for(j=0;j<cols;j++){ printf("Enter element[%d][%d] of matrix b :\n",i+1,j+1); scanf("%d",&b[i][j]); } //calulate the sum of the matrices for(i=0;i<rows;i++) for(j=0;j<cols;j++){ sum[i][j] = a[i][j] + b[i][j]; } //display the sum printf("The sum of the 2 matrices is :\n"); for(i=0;i<rows;i++) for(j=0;j<cols;j++){ printf("%d ", sum[i][j]); if(j == (cols-1)){ printf("\n"); } } return 0; }
C
/** \file 02_test_write.c \version 01.00 \brief Driver basico de Linux - caracteristica 1 - caracteristica 2 \author Agustin Diaz Antuna \date 23/10/2018 */ /* ------------------------------------------------------------------------------ * --- include * ------------------------------------------------------------------------------ */ #include "stdio.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include "string.h" /* ------------------------------------------------------------------------------ * --- define * ------------------------------------------------------------------------------ */ #define MAX_BUFFER 256 /* ------------------------------------------------------------------------------ * --- struct * ------------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------------ * --- variables * ------------------------------------------------------------------------------ */ /* ------------------------------------------------------------------------------ * --- functions * ------------------------------------------------------------------------------ */ int main(void) { int fd, write_size = 0; char buffer[MAX_BUFFER]; bzero(buffer, MAX_BUFFER); // open driver fd = open("/dev/mi_drv", O_WRONLY); if(fd < 0) { printf("Error de open."); return 1; } printf("Escriba un mensaje:\n"); fgets(buffer, MAX_BUFFER, stdin); buffer[4] = '\0'; printf("Buffer: a%sa\n", buffer); write_size = write(fd, buffer, strlen(buffer)); if(write_size < 0) { close(fd); printf("Error de escritura, con write_size: %d\n", write_size); return 1; } printf("Escritura correcta.\n"); getchar(); close(fd); return 0; }
C
extern void __VERIFIER_error() __attribute__((noreturn)); extern void __VERIFIER_assume (int); extern int __VERIFIER_nondet_int (); #define static_assert __VERIFIER_assert #define assume __VERIFIER_assume #define LARGE_INT 1000000 #define true 1 #define false 0 #define boolean int #define MAX 8 void __VERIFIER_assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } void assert(int cond) { if (!(cond)) { ERROR: __VERIFIER_error(); } return; } int ndInt() { return __VERIFIER_nondet_int(); } int ndBool() { int x = ndInt(); assume(x == 1 || x == 0); return x; } int ndInt2(int lower, int upper) { int x = ndInt(); assume(lower <= x && x <= upper); return x; } void main(){ int x, y, flag; x=0; y=0; flag=0; while (flag < 1) { if (x<=50) y=y+1; else y=y-1; if (y<0) { flag=1; } if (flag < 1) { x=x+1; } } asssert(x<=102); assert(y<=51); }
C
#include<stdio.h> int suma(int a[], int i, int length) { if (i == length) return 0; else { return a[i] + suma(a, i + 1, length); } return 0; } int f1(int x) { int a[] = { 1, 2, 3, 4, 5 }; suma(a, 0, 5); int p = 0, y = 84; p = x / y; return p; } int function(int x) { int p = 0, y = 84; p = x / y; return p; } int main() { int x = function(10); printf("%d\n", x); int y = f1(10); printf("%d\n", y); x = function(52); printf("%d\n", x); y = f1(52); printf("%d\n", y); x = function(34); printf("%d\n", x); y = f1(34); printf("%d\n", y); x = function(525); printf("%d\n", x); y = f1(525); printf("%d\n", y); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "job.h" void sort_jobs(u_char * job_is, int leftarg, int rightarg, int comp); bool init_sorts() { //Allocate all sorts u_char j; for(j=0; j<4; j++) if(!(sorted_jobs[j] = malloc(jobs_count))) return 0; //Sort jobs in SPT1, SPT2, SPT orders for(j = 0; j < 3; j++) { job_index J; for(J = 0; J < jobs_count; J++) sorted_jobs[j][J]=J; sort_jobs(sorted_jobs[j],0,jobs_count - 1, j); } //Populate simpson's rule sorted array u_char x = 0, a; for(a = 0; a < jobs_count; a++) //All Ai <= Bi ascending SPT1 { job_index i = sorted_jobs[SPT1][a]; job J = jobs_collection[i]; if(J.TA <= J.TB) { sorted_jobs[JOHN][x] = i; ++x; } } for(a = 1; a <= jobs_count; a++) //All Ai > Bi descending SPT2 { job_index i = sorted_jobs[SPT2][jobs_count - a]; job J = jobs_collection[i]; if(J.TA > J.TB) { sorted_jobs[JOHN][x] = i; ++x; } } return 1; } void free_sorts() { u_char j; for(j=0; j<4; j++) free(sorted_jobs[j]); } bool less(job_index, job*, int); bool gret(job_index, job*, int); void sort_jobs(u_char * job_is, int leftarg, int rightarg, int comp) { int left = leftarg, right = rightarg; job * mid = &jobs_collection[job_is[(left + right) >> 1]]; while(left <= right) { while(less(job_is[left],mid,comp)) left++; while(gret(job_is[right],mid,comp)) right--; if(left <= right) { u_char J = job_is[right]; job_is[right] = job_is[left]; job_is[left] = J; left++; right--; } } if(leftarg < right) sort_jobs(job_is, leftarg, right, comp); if(left < rightarg) sort_jobs(job_is, left, rightarg, comp); } bool less(job_index j1, job* j2, int comp) { //Tie breaker is next node (modular) int tie = (comp + 1) % 3; // u_int * J1 = (u_int *) &jobs_collection[j1]; u_int * J2 = (u_int *) j2; return (J1[comp] < J2[comp] || (J1[comp] == J2[comp] && J1[tie] < J2[tie])); } bool gret(job_index j1, job* j2, int comp) { int tie = (comp + 1) % 3; u_int * J1 = (u_int *) &jobs_collection[j1]; u_int * J2 = (u_int *) j2; return (J1[comp] > J2[comp] || (J1[comp] == J2[comp] && J1[tie] > J2[tie])); } void jobs_XML() { int i; printf("\t<jobs>\n"); for(i = 0; i < jobs_count; i++) { job j = jobs_collection[i]; printf("\t\t<job id=\"%d\" A=\"%d\" B=\"%d\" T=\"%d\" />\n",i, j.TA, j.TB, j.TTot); } printf("\t</jobs>\n"); int r; printf("\t<sorts>\n"); for(r = 0; r < 3; r++) { printf("\t\t<sort type=\"%d\">\n",r); for(i = 0; i < jobs_count; i++) { int s = sorted_jobs[r][i]; job j = jobs_collection[s]; printf("\t\t\t<job id=\"%d\" A=\"%d\" B=\"%d\" T=\"%d\" />\n", s, j.TA, j.TB, j.TTot); } printf("\t\t</sort>\n"); } printf("\t</sorts>\n"); fflush(stdout); }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <winsock2.h> void Error_Handling(char *message); int main(int argc, char *argv[]) { WSADATA wsaData; SOCKET clnt_sock; SOCKADDR_IN serv_addr; char message[30]; int count = 0, index = 0, length = 0; if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) Error_Handling("WSAStartup error!"); clnt_sock = socket(PF_INET, SOCK_STREAM, 0); if (clnt_sock == INVALID_SOCKET) Error_Handling("socket() error!"); memset(&serv_addr, 0, sizeof(serv_addr));// sin_zero serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = inet_addr(argv[1]); serv_addr.sin_port = htons(atoi(argv[2])); if (connect(clnt_sock, (SOCKADDR*)&serv_addr, sizeof(serv_addr)) == -1) Error_Handling("connect() error!"); while (length = recv(clnt_sock, &message[index++], 1, 0)) { if (length == -1) Error_Handling("recv() error!"); count += length; } printf("Function Call : %d\n", count); printf("Message length: %d\n", count); closesocket(clnt_sock); WSACleanup(); return 0; } void Error_Handling(char *message) { fputs(message, stderr); fputc('\n', stderr); exit(1); }
C
#include <stdio.h> #include <stdlib.h> #include <locale.h> #define ex01 #ifdef ex01 /*1 - Escreva um programa que tenha o menu abaixo. 1 - transforma graus Celsius em Fahrenheit e Kelvin 2 - transforma graus Fahrenheit e Celsius e Kelvin 3 - transforma graus Kelvin e Celsius e Fahrenheit Cada opcao de menu deve chamar uma funcao que retorna o resultado da conversao. O resultado deve ser mostrado na funcao main(). */ //declarao float celsiusFunc(int x); float fahrenheitFunc(int x); float kelvinFunc(int x); float celsius,fahrenheit,kelvin; float C,F, K; int main(){ setlocale(LC_ALL, "Portuguese"); int op; char opcao = 's'; while(opcao == 's' || opcao == 'S') { printf("Escolha uma opo abaixo:\n"), printf("\n1 - transforma graus Celsius em Fahrenheit e Kelvin"); printf("\n2 - transforma graus Fahrenheit e Celsius e Kelvin"); printf("\n3 - transforma graus Kelvin e Celsius e Fahrenheit\n"); scanf("%d",&op); if(op==1){ celsiusFunc(C); } else if (op==2){ fahrenheitFunc(F); } else if (op==3){ kelvinFunc(K); } else{ printf("Nmero digitado invlido"); } printf("\nTecle 's' se deseja continuar\n\n"); opcao = getch(); } } //Funes float celsiusFunc(int x) { float C,F, K; printf("Escreva a temperatura em graus celsius: ");//conversao de celsius pra kelvin e fahrenheit scanf("%f",&C); F = C * 1.8 + 32;//calculo para fahrenheit K = C + 273.15;//calculo para kelvin printf("\nDe celsius pra Fahrenheit = %.2f \n", F); printf("\nDe celsius pra Kelvin = %.2f \n", K); } float fahrenheitFunc(int x) { float C,F, K; printf("Escreva a temperatura em graus fahrenhit: ");//conversao de fahrenhit pra kelvin e celsius scanf("%f",&F); C = (F-32) / 1.8;//calculo para celsius K = F + 459.67; //calculo para kelvin K = K * 5/9; //calculo para kelvin printf("\nDe Fahrenheit pra celsius = %.2f \n", C); printf("\nDe Fahrenheit pra Kelvin = %.2f \n", K); } float kelvinFunc(int x) { float C,F, K; printf("Escreva a temperatura em graus kelvin: ");//conversao de kelvin pra celsius e fahrenheit scanf("%f",&K); F = (K - 273.15) * 9/5 + 32;//calculo para fahrenheit C = K - 273.15;//calculo para celsius printf("\nDe kelvin pra Fahrenheit = %.2f \n", F); printf("\nDe kelvin pra celsius = %.2f \n", C); } #endif ex01 #ifdef ex02 /*2 - Escreva um programa que receba via teclado 2 numeros inteiros e imprima-os no video com o resultado das 4 operacoes aritmeticas. */ int num1,num2; main() { setlocale(LC_ALL, "Portuguese"); char opcao = 's'; while(opcao == 's' || opcao == 'S') { int num1, num2; printf("Digite um numero: "); scanf("%d",&num1); printf("\nDigite outro numero: "); scanf("%d",&num2); printf("\nA soma: %d\nA subtracao: %d\nA multiplicao: %d\nA diviso: %.2f",num1+num2,num1-num2,num1*num2,(float) num1/num2); printf("\nTecle 's' se deseja continuar\n\n"); opcao = getch(); } } #endif ex02 #ifdef ex03 /*3 - Reescreva o exercicio anterior utilizando operadores de atribuio composta. */ //declarao int soma(int x, int y); int subt(int x, int y); int multi(int x, int y); float divis(int x, int y); main(){ setlocale(LC_ALL, "Portuguese"); char opcao = 's'; while(opcao == 's' || opcao == 'S') { int num1, num2; printf("Digite um numero: "); scanf("%d",&num1); printf("\nDigite outro numero: "); scanf("%d",&num2); printf("\nSoma: %d\nSubtrao: %d\nMultiplicao: %d\nDivisao: %.2f", soma(num1,num2), subt(num1,num2), multi(num1, num2), divis(num1,num2)); printf("\n\nTecle 's' se deseja continuar\n\n"); opcao = getch(); } } //Funes int soma(int x, int y) { return x += y; } int subt(int x, int y) { return x -= y; } int multi(int x, int y) { return x *= y; } float divis(int x, int y) { return (float) x / (float) y; } #endif ex03 #ifdef ex04 /*4 - Escreva um programa que receba via teclado 2 numeros inteiros e execute as operacoes logicas bit a bit AND, OU, OU EXCLUSIVO e imprima-os no video no formato decimal e hexadecimal. */ main() { setlocale(LC_ALL, "Portuguese"); char opcao = 's'; while(opcao == 's' || opcao == 'S') { int num1,num2; printf("Digite um nmero: "); scanf("%d",&num1); printf("\nDigite outro nmero: "); scanf("%d",&num2); printf("\nAND\nDecimal: %d\nHexadecimal: %x",num1 & num2,num1 & num2); printf("\n\nOU\nDecimal: %d\nHexadecimal: %x",num1 | num2,num1 | num2); printf("\n\nOU EXCLUSIVO\nDecimal: %d\nHexadecimal: %x", num1 ^ num2,num1 ^ num2); printf("\nTecle 's' se deseja continuar\n\n"); opcao = getch(); } } #endif ex04 #ifdef ex05 /*5 - Escreva um programa para determinar a idade de uma pessoa, em anos, meses e dias, recebendo via teclado a data (dia, mes e ano) do seu nascimento e a data (dia, mes e ano) atual. */ int main(void) { setlocale(LC_ALL, "Portuguese"); int hdia, ndia; int hmes, nmes; int hano, nano; int dia, mes, ano; int diferenca; hdia = 0; // dia de hoje ndia = 0; // dia de nascimento hmes = 0; // mes de hoje nmes = 0; // mes de nascimento hano = 0; // ano de hoje nano = 0; // ano de nascimento char opcao = 's'; while(opcao == 's' || opcao == 'S') { printf("%s","Calculadora de Tempo de Vida \n"); printf("%s","Por favor informe a data de ""hoje?\n"); printf("%s","[dd mm aaaa]: "); scanf(" %d%d%d", &hdia, &hmes, &hano); printf(" %2d/%2d/%3d\n\n", hdia, hmes, hano); printf("%s","Por favor, informe a data de seu ""nascimento?\n"); printf("%s","[dd mm aaaa]: "); scanf(" %d%d%d", &ndia, &nmes, &nano); printf(" %2d/%2d/%3d\n\n", ndia, nmes, nano); diferenca = 365*hano + 30*hmes + hdia - 365*nano - 30*nmes - ndia; ano = diferenca/365; diferenca = diferenca%365; mes = diferenca/30; diferenca = diferenca%30; dia = diferenca; printf("%s %d %s %d %s %d %s", "Voc possui de vida:", ano, "ano(s)", mes, "mes(es)", dia, "dia(s).\n"); printf("\nTecle 's' se deseja continuar\n\n"); opcao = getch(); } } #endif ex05
C
int main(void) { int y = 8; int m = invert(y,0,1); printf("%d",m); return 0; } int invert(unsigned int x, int p, int n) { x ^= ((~(~0 << n)) << (p+1-n)); return x; }
C
/* * Program to reverse the linked list in range * * @Harsh_Garg, 1910990582, 30/08/2021 * Assignment 6 */ /** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ /* * Function that will reverse the linked list */ struct ListNode* reverseLinkedList(struct ListNode* head) { struct ListNode* previous = NULL; struct ListNode* current = head; while(current != NULL) { struct ListNode* next = current->next; current->next = previous; previous = current; current = next; } return previous; } struct ListNode* reverseBetween(struct ListNode* head, int left, int right){ if(left == right) { return head; } if(left == 1) { int count = 1; struct ListNode* ptr = head; while(count != right) { count++; ptr = ptr->next; } struct ListNode* temp = ptr->next; ptr->next = NULL; struct ListNode* newHead = reverseLinkedList(head); head->next = temp; return newHead; } else { int count = 1; struct ListNode* leftTail = head; while(count != left - 1) { count++; leftTail = leftTail->next; } struct ListNode* rightHead = leftTail; while(count != right) { count++; rightHead = rightHead->next; } struct ListNode* temp = rightHead->next; rightHead->next = NULL; rightHead = temp; struct ListNode* newHead = reverseLinkedList(leftTail->next); leftTail->next->next = rightHead; leftTail->next = newHead; return head; } }
C
// Implements a dictionary's functionality #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "dictionary.h" // Represents number of children for each node in a trie #define N 27 // Represents a node in a trie typedef struct node { bool is_word; struct node *children[N]; } node; // Represents a trie node *root; // Counter to keep track of words int size_counter = 0; // Loads dictionary into memory, returning true if successful else false bool load(const char *dictionary) { // Initialize trie root = malloc(sizeof(node)); if (root == NULL) { return false; } root->is_word = false; for (int i = 0; i < N; i++) { root->children[i] = NULL; } // Open dictionary FILE *file = fopen(dictionary, "r"); if (file == NULL) { unload(); return false; } // Buffer for a word char word[LENGTH + 1]; // Defines temp, the header of below code. node *temp = root; // Insert words into trie while (fscanf(file, "%s", word) != EOF) { // Reassigns root to temp at the begining of every word. temp = root; // Increments a counter for every word size_counter++; // Iterate over the characters in the word for (int i = 0; word[i] != 0x00; ++i) { // Creates an idex based on the character int index = (word[i] == 39) ? 26 : word[i] - 'a'; // checks if the character exists, and reassigns temp one level down if it does. if (temp->children[index]) { temp = temp->children[index]; } // If it does not exist, it gets created and assigned to temp else { temp->children[index] = malloc(sizeof(node)); temp = temp->children[index]; // Every character one level down is initialized with null for (int j = 0; j < N; ++j) { temp->children[j] = NULL; temp->is_word = NULL; } } // Validates word if it is the last character of the word. if (word[i + 1] == 0x00) { temp->is_word = true; } } } // Close dictionary fclose(file); // Indicate success return true; } // Returns number of words in dictionary if loaded else 0 if not yet loaded unsigned int size(void) { return size_counter; } // Returns true if word is in dictionary else false bool check(const char *word) { // Reassignes root to temp node *temp = root; // Iterates over the characters in the word for (int i = 0; word[i] != 0x00; ++i) { // Creates an idex based on the character, removes capitalization. int index = (word[i] < 95) ? word[i] - 'A' : word[i] - 'a'; // Checks if character is ', assigns special value if true. if (word[i] == 39) { index = 26; } // Checks if character exist if (temp->children[index]) { // Reassigns temp one level down if it does temp = temp->children[index]; // If it is the end of the word, and it is valid, returns true. if (word[i + 1] == 0x00 && temp->is_word) { return true; } } // Returns false if character does not exist. else { return false; } } return false; } bool unload_recurr(node *unload_temp); // Unloads dictionary from memory, returning true if successful else false bool unload(void) { // Uses reccursion to free all mallocs bool unloaded = unload_recurr(root); return unloaded; } // Recursive unload function. bool unload_recurr(node *unload_temp) { // Iterates over characters for (int i = 0; i < N; ++i) { // If found, calls the function on the new character node if (unload_temp->children[i]) { unload_recurr(unload_temp->children[i]); } } // When no more characters are found, frees the current caracter node free(unload_temp); return true; }
C
/*############################################################# * File Name : SimpleSection.c * Author : winddoing * Created Time : 2018年12月18日 星期二 15时17分55秒 * Description : * gcc -c SimpleSection.c -o SimpleSection.o * gcc version 7.3.0 (Ubuntu 7.3.0-27ubuntu1~18.04) *############################################################*/ int printf(const char* format, ...); int global_init_var = 84; int global_uninit_var; void func1(int i) { printf("%d\n", i); } int main(int argc, const char *argv[]) { static int static_var = 85; static int static_var2; int a = 1; int b; func1(static_var + static_var2 + a + b); return a; }
C
#include<stdio.h> #include<netinet/in.h> #include<sys/socket.h> #include<stdlib.h> #include<string.h> int main(int argc,char **argv) { int connectSd; int clntAddrLen, readLen; struct sockaddr_in clntAddr; char wBuff[BUFSIZ]; if(argc !=3) { printf("usage: %s < IP Address> <port number>\n",argv[0]); return -1; } connectSd=socket(PF_INET,SOCK_STREAM,0); printf("===========client protgram=============\n"); memset(&clntAddr,0,sizeof(clntAddr)); clntAddr.sin_family=AF_INET; clntAddr.sin_addr.s_addr=inet_addr(argv[1]); clntAddr.sin_port=htons(atoi(argv[2])); connect(connectSd,(struct sockaddr *) &clntAddr,sizeof(clntAddr)); send(connectSd,"Normal_MSG1", strlen("Normal_MSG1"),0); send(connectSd,"Normal_MSG2", strlen("Normal_MSG2"),0); send(connectSd,"Urgent_MSG", strlen("Urgent_MSG"),MSG_OOB); send(connectSd,"Normal_MSG3", strlen("Normal_MSG3"),0); close(connectSd); return 0; }
C
/* Oppgave 5.2 Konvertering fra hex til dec: Lag et program som leser inn et heksadesimalt tall hextall bruk %xi innlesingen konverterer hextalltil 101010-tallsystemet skriverer ut det konverterte tallet */ #include <stdio.h> #include <stdlib.h> int main() { int hextall; printf("les inn et heltall:\n"); scanf("%x",&hextall); printf("\ntallet i hex: %x og i desimalt: %d\n", hextall,hextall); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_CODE 4 #define MAX_REC 50 /* struct declaration */ typedef struct { float x; float y; } point_t; typedef struct { char code[MAX_CODE+1]; point_t p1; point_t p2; float area; float perimeter; } rectangle_t; /* function prototypes */ void file_read (char *, rectangle_t [], int *); void sort1 (rectangle_t [], int); void sort2 (rectangle_t [], int); void save (char *, rectangle_t [], int); /* * main program */ int main (int argc, char *argv[]) { rectangle_t rct[MAX_REC]; int rectangle_num; if (argc!=4) { fprintf (stderr, "Wrong number of parameter.\n"); return (1); } /* open files */ file_read (argv[1], rct, &rectangle_num); sort1 (rct, rectangle_num); save (argv[2], rct, rectangle_num); sort2 (rct, rectangle_num); save (argv[3], rct, rectangle_num); return (EXIT_SUCCESS); } /* * rectangle load */ void file_read (char *name, rectangle_t rct[], int *num) { FILE *fin; float x, y, l1, l2; int i; fin = fopen(name, "r"); if (fin == NULL) { fprintf (stderr, "Input file not readable!\n"); exit (0); } if (fscanf (fin, "%*d") == EOF) { fprintf (stderr, "Wrong input file format.\n"); exit (0); } *num = 0; while (fscanf(fin, "%s%f%f", name, &x, &y) != EOF && *num < MAX_REC) { for (i=0; i<*num; i++) if (strcmp(name, rct[i].code) == 0) break; if (i == *num) { /* rectangle NOT found: first point */ strcpy(rct[i].code, name); rct[i].p1.x = x; rct[i].p1.y = y; *num = *num + 1; } else { /* rectangle found: second point */ rct[i].p2.x = x; rct[i].p2.y = y; #if 0 l1 = fabs (x - rct[i].p1.x); l2 = fabs (y - rct[i].p1.y); //printf ("fabs -> %f %f\n", l1, l2); #else l1 = x - rct[i].p1.x; l2 = y - rct[i].p1.y; if (l1<0) l1 = (-l1); if (l2<0) l2 = (-l2); //printf ("if -> %f %f\n", l1, l2); #endif rct[i].area = l1 * l2; rct[i].perimeter = 2 * (l1 + l2); } } #if 0 /* data structure initialization */ for (i=0; i<*num; i++) { fprintf (stdout, "%s (%.2f,%.2f)-(%.2f,%.2f) area=%.2f perimetro=%.2f\n", rct[i].code, rct[i].p1.x, rct[i].p1.y, rct[i].p2.x, rct[i].p2.y, rct[i].area, rct[i].perimeter); } #endif fclose(fin); return; } /* * rectangle sorting */ void sort1 (rectangle_t rct[], int num_rct) { rectangle_t current; int i, j; for (i=1; i<num_rct; i++) { current = rct[i]; j = i; while ((--j >= 0) && (current.area > rct[j].area)) { rct[j+1] = rct[j]; } rct[j+1] = current; } return; } /* * rectangle sorting */ void sort2 (rectangle_t rct[], int num_rct) { rectangle_t current; int i, j; for (i=1; i<num_rct; i++) { current = rct[i]; j = i; while ((--j >= 0) && (current.perimeter > rct[j].perimeter)) { rct[j+1] = rct[j]; } rct[j+1] = current; } return; } /* * result display */ void save (char *name, rectangle_t rct[], int num_rct) { FILE *fout; int i; fout = fopen (name, "w"); if (fout == NULL) { fprintf (stderr, "Input file not readable!\n"); return; } for (i=0; i<num_rct; i++) { fprintf (fout, "%s\n", rct[i].code); } fclose (fout); return; }
C
#include<stdio.h> #include<conio.h> int main() { char s1[20],s2[10]; char *p=s1; char *q=s2; int flag=1; printf("Enter the string 1 :"); gets(s1); printf("\nEnter the string 2 : "); gets(s2); while(*p++!=*q++) flag=0; if(flag) printf("\nThe given string is equal. "); else printf("\nThe given string is not equal. "); return 0; }
C
struct TreeNode { const char* text; TreeNode* parent; int children_size; TreeNode** children; }; TreeNode item_manual_scan = {"Manual scan", NULL, 0, NULL }; TreeNode item_go_to = {"Go to", NULL, 0, NULL }; //TreeNode* menu0_children[] = {&menu0, &item11 }; //TreeNode menu0 = { "Manual", NULL, sizeof(menu0_children)/sizeof(*menu0_children), menu0_children }; TreeNode item_a0 = {"Enter a0", NULL, 0, NULL }; TreeNode item_a1 = {"Enter a1", NULL, 0, NULL }; TreeNode item_a2 = {"Enter a2", NULL, 0, NULL }; TreeNode* menu_calibration_children[] = {&item_a0, &item_a1, &item_a2 }; TreeNode menu_calibration = {"Calibration", NULL, sizeof(menu_calibration_children) / sizeof(*menu_calibration_children), menu_calibration_children }; TreeNode item_scan_units = {"scan units", NULL, 0, NULL }; TreeNode item_set_wavelength = {"set wavelength", NULL, 0, NULL }; TreeNode item_intervals = {"output_intervals", NULL, 0, NULL }; TreeNode item_set_motor_pos = {"set motor pos", NULL, 0, NULL }; TreeNode item_SPR = {"steps per rev", NULL, 0, NULL }; TreeNode item_speed = {"speed", NULL, 0, NULL }; TreeNode* menu_settings_children[] = { &item_scan_units, &item_set_wavelength, &item_intervals, &item_set_motor_pos, &item_speed, &item_SPR }; TreeNode menu_settings = {"Settings", NULL, sizeof(menu_settings_children) / sizeof(*menu_settings_children), menu_settings_children }; TreeNode* root_children[] = {&item_manual_scan, &item_go_to, &menu_settings, &menu_calibration }; TreeNode root = {"root", NULL, sizeof(root_children) / sizeof(*root_children), root_children }; void inject_parents(TreeNode* node) { for (int i = 0; i < (node->children_size); i++) { node->children[i]->parent = node; inject_parents(node->children[i]); } return; }
C
// xdz 20160321 // jl_bufferҪȳʼjl_bufferʹ #include "jl_json.h" static cJSON* s_p_root = NULL; static jl_buffer* s_p_jl_buffer = NULL; static const int s_max_buf_len = 102400; inline cJSON* debug_jl_get_val(cJSON* o, char* key) { if (!o) { o = s_p_root; } cJSON *p = cJSON_GetObjectItem(o, key); if (!p) { return NULL; } if (p->type == cJSON_String) { jl_debug("key:[%s],val:[%s]\n", key, p->valuestring); return p; } if (p->type == cJSON_Number) { jl_debug("key:[%s],val:[%d]\n", key, p->valueint); return p; } jl_err("warning type!\n"); return p; } inline static int read_file( int fd, jl_buffer* p_jl_buffer ) { if (fd <= 0) { jl_err("invalid fd!\n"); return -1; } if (!p_jl_buffer) { jl_err("invalid buffer!\n"); return -1; } char *buf = p_jl_buffer->buf; int max_len = p_jl_buffer->max_buf_len; int read_cnt = read(fd, buf, max_len); int status = -1; if (read_cnt == -1) { jl_err("read err [%d]!\n", errno); } else if (read_cnt == 0) { jl_err("empty file!\n"); } else { p_jl_buffer->buf_len = read_cnt; status = 0; } return status; } inline static int open_file(const char* path) { if (!path) { jl_err("invalid path!\n"); return -1; } int fd = open(path, O_RDONLY); return fd; } inline static int read_json_file( const char* path, jl_buffer* p_jl_buffer) { int fd = open_file(path); if (fd <= 0) { return -1; } int ret = read_file(fd, p_jl_buffer); fail: close(fd); return ret; } cJSON* jl_json_get_object( cJSON* p_father, const char* section) { if (!section) { jl_err("arg invalid!\n"); return NULL; } if (!p_father) { p_father = s_p_root; } return cJSON_GetObjectItem(p_father, section); } int jl_init_json(const char* path) { if (!path) { jl_err("invalid path!\n"); return -1; } s_p_jl_buffer = jl_create_buffer(s_max_buf_len); if (!s_p_jl_buffer) { jl_err("create buffer err!\n"); return -1; } int ret = read_json_file(path, s_p_jl_buffer); if (ret < 0) { jl_err("read json file err!\n"); return -1; } s_p_root = cJSON_Parse(s_p_jl_buffer->buf); if (!s_p_root) { jl_err("parse file err!\n"); return -1; } return 0; } int jl_json_exit() { jl_free_buffer(s_p_jl_buffer); cJSON_Delete(s_p_root); return 0; }
C
#include <stdio.h> #include <stdlib.h> struct node { int day; int price; int span; }; struct node *stack; int top=-1; void pop() { if(top==-1) return; top--; } int findSpan(int X) { int count=1; while(stack[top].price<=X&&top!=-1) { count++; pop(); } return count; } int main() { int n,i; scanf("%d",&n); stack=(struct node *)malloc(n*sizeof(struct node)); for(i=0;i<n;i++) { stack[i].day=i; scanf("%d",&stack[i].price); stack[i].span=findSpan(stack[i].price); top=i; } printf("Day\tPrice\tSpan\n"); while(top!=-1) { printf(" %d\t %d\t %d\n",stack[top].day,stack[top].price,stack[top].span); pop(); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include "url.h" int get_url(char *url) { char proto[100],user[100],pass[100],host[100],path[1000]; int port; int ret; int s; struct sockaddr_in sin; char addr[4]; char buf[64000]; char request_line[10000]; int n; ret = parse_url(url,proto,user,pass,host,&port,path); if(ret<0){ fprintf(stderr,"can't parse URL[%s]\n",url); return -1; } if(!isdigit(host[0])){ struct hostent *hent; hent = gethostbyname(host); if(!hent){ perror("gethostbyname"); return -1; } memcpy(&sin.sin_addr,hent->h_addr,hent->h_length); }else{ int a1,a2,a3,a4; sscanf(host,"%d.%d.%d.%d",a1,a2,a3,a4); addr[0] = a1;addr[1] = a2;addr[2] = a3;addr[3] = a4; memcpy(&sin.sin_addr,addr,4); } s = socket(PF_INET,SOCK_STREAM,0); /* sin.sin_len = sizeof(sin); */ sin.sin_family = AF_INET; sin.sin_port = port; ret = connect(s,&sin,sizeof(sin)); if(ret<0){ perror("connect:"); exit(1); } sprintf(request_line,"GET %s HTTP/1.0\r\n\r\n",path); write(s,request_line,strlen(request_line)); while((n=read(s,buf,sizeof(buf)))>0){ write(1,buf,n); } close(s); return 0; } int usage(void) { puts("usage: wgetc URLs..."); } int main(int argc,char *argv[]) { while(++argv,--argc){ char *argp = *argv; if(*argp=='-'){ argp++; if(*argp == 'h'){ usage();exit(1); }else{ usage();exit(1); } }else{ break; } } if(argc==0){usage();exit(1);} while(argc>0){ get_url(*argv); argv++; argc--; } }
C
/*编程题目内容:网易云课堂作业 对数字求特征值是常用的编码算法,奇偶特征是一种简单的特征值。 对于一个整数,从个位开始对每一位数字编号,个位是1号,十位是2号,以此类推。 这个整数在第n位上的数字记作x,如果x和n的奇偶性相同,则记下一个1,否则记下一个0。 按照整数的顺序把对应位的表示奇偶性的0和1都记录下来,就形成了一个二进制数字。 比如,对于342315,这个二进制数字就是001101。 这里的计算可以用下面的表格来表示: 数字 3 4 2 3 1 5 数位 6 5 4 3 2 1 数字奇偶 奇 偶 偶 奇 奇 奇 数位奇偶 偶 奇 偶 奇 偶 奇 奇偶一致 0 0 1 1 0 1 二进制位值32 16 8 4 2 1 按照二进制位值将1的位的位值加起来就得到了结果13。 你的程序要读入一个非负整数,整数的范围是[0,100000],然后按照上述算法计算出表示奇偶性的那个二进制数字,输出它对应的十进制值。 提示:将整数从右向左分解,数位每次加1,而二进制值每次乘2。 输入格式: 一个非负整数,整数的范围是[0,100000]。 输出格式: 一个整数,表示计算结果。 输入样例: 342315 输出样例: 13 答:*/ #include <stdio.h> int main() { int a = 0;//输入的整数 int b = 10; int c = 0;//拆分取数 int n = 1;//位数 int d = 1;//二进制位值 int sum = 0;//二进制总和 scanf("%d", &a); do { c = a % b; if ((c + n) % 2 == 0){ sum = sum + d; } else { sum = sum; } n ++; d = d * 2; a = a / b; } while( a > 0); printf("%d", sum); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> int N=100; double i=0.2; void grid(double **p) { int x,y,x1,x2,z=0; double eps=1e-7,d=0; x1=(int)N/2*(1-i); x2=(int)N/2*(1+i); while(fabs(p[1][1]-d)>eps) { for(x=1; x<N-1; x++) for(y=1; y<N-1; y++) if(x>=x2 || x<=x1 || y>=x2 || y<=x1) { if(x==1 && y==1) d=p[x][y]; p[x][y]=(p[x+1][y]+p[x-1][y]+p[x][y+1]+p[x][y-1])/4; } z++; } printf("\n %d \n",z); } void print(double **a) { int i,k; for(i=0; i<N; i++) { for(k=0; k<N; k++) printf("%-4.0lf ",a[i][k]); printf("\n"); } printf("\n"); return; } int main() { double **p; double f2=100, f1=500; int x,y,x1,x2; FILE *f_out1; f_out1=fopen("potential.txt","w"); //////////////// p=(double **)malloc(sizeof(double *)*(N+1)); for(x=0; x<N+1; x++) p[x]=(double *)malloc(sizeof(double)*(N+2)); for (x=0; x<N; x++) for(y=0; y<N; y++) p[x][y]=0; ///////////// for (x=0; x<N; x++) { p[0][x]=f1; p[x][0]=f1; p[N-1][x]=f1; p[x][N-1]=f1; } x1=(int)N/2*(1-i); x2=(int)N/2*(1+i); for(x=1; x<N-1; x++) for(y=1; y<N-1; y++) { if((x<x2 && x>x1)&&(y<x2 &&y>x1)) p[x][y]=f2; else p[x][y]=(f2+f1)/2; } grid(p); // print(p); for (x=0; x<N; x++) for(y=0; y<N; y++) fprintf(f_out1,"%d %d %lf\n",x,y,p[x][y]); // print(p); return 0; }
C
#ifndef _LOGGING_H_ #define _LOGGING_H_ #include <stdbool.h> #include <stdint.h> #include <stdlib.h> /** * Type of log. Numbering is used as indexes in arrays and other numerical operations. Treat as define statements * Maximum 32 fields */ typedef enum { Log_Type_Log = 0, /*!< Log with no specific type */ Log_Type_Error, /*!< Error of unspecified kind */ Log_Type_Debug, /*!< Debug log of unspecified kind */ Log_Type_RC5, /*!< Log from RC5 task - EVENT */ Log_Type_Speed, /*!< Speed logging */ log_Type_SpeedOrdered, /*!< Ordered speed logging */ Log_Type_Telemetry, /*!< Logging telemetry aka position */ Log_Type_Camera, /*!< Logging camera events */ Log_Type_Drive, /*!< Log from taskDrive - EVENT */ } Log_Type; /** * Holder for all log settings used */ typedef struct { union { struct { /*!< This struct contains indivisible fields, may be masked by flags from the second struct */ bool enableLog : 1; /*!< Enable flag for "log" logs - Log_Type_None */ bool enableError : 1; /*!< Enable flag for error logs - Log_Type_Error */ bool enableDebug : 1; /*!< Enable flag for debug logs - Log_Type_Debug */ bool enableRC5 : 1; /*!< Enable flag for RC5 logs - Log_Type_RC5 */ bool enableSpeed : 1; /*!< Enable flag for current speed logging - Log_Type_Speed */ bool enableSpeedOrdered :1; /*!< Enable flag for ordered speed logging - Log_Type_SpeedOrdered */ bool enableTelemetry :1; bool enableCamera :1; bool enableDrive : 1; }; uint32_t smallFlags; }; union { struct { /*!< This struct contains flags that enable specific masks */ bool enableAll : 1; /*!< Enable flag for all logging */ bool enableEvents : 1; /*!< Enable flag for events logs */ }; uint32_t bigFlags; }; } Log_Settings_Struct; /** * Checks if specific type of log is enabled in settings * @param settings Current log settings * @param type Log type to check * @retval true if log is enabled in settings, false otherwise */ bool isLogEnabled(const volatile Log_Settings_Struct *settings, const Log_Type type); /** * Prepares given message inserting appropriate prefix at the beginning. * @param msg Pointer to the beginning of string that will contain log text. Must be of appropriate length * @param type Type of log to prepare * @retval Pointer to the first character in msg that should be written with log text. Before that is log prefix */ char* prepareLogMessage(char *msg, Log_Type type); /** * Returns the length of the prefix that will be appended to log of specified type. * This function should be used to allocate enough space for prefix and log content * @param type Type of log to check * @retval Length of prefix for the specified type of log */ size_t getLogPrefixLength(Log_Type type); #endif /* _LOGGING_H_ */
C
#include <stdio.h> int main() { int numbers[20]; for (int i = 0; i < 20; ++i) numbers[i] = i * i; for (int i = 0; i < 20; ++i) printf("%i ", numbers[i]); printf("\n"); }
C
#include<stdio.h> void main() { int a[100],b[100],i,n; printf("请输入数组元素个数(不大于100):"); scanf("%d",&n); printf("请输入数组:"); for(i=0;i<n;i++) {printf("a[%d]=",i+1); scanf("%d",&a[i]); } printf("原数组为:\n"); for(i=0;i<n;i++) printf("%d ",a[i]); printf("\n"); for(i=0;i<n;i++) //再建立一个数组存放它的逆序数组 b[i]=a[n-1-i]; printf("逆序列为:"); for(i=0;i<n;i++) printf("%d ",b[i]); printf("\n"); }
C
#include <stdlib.h> #include <stdint.h> #include <avr/io.h> #include <avr/pgmspace.h> #include <avr/interrupt.h> #include <util/delay.h> #include "../common/ds_cmd.h" #include "../common/ds_frame.h" /* this pin must be connected to * the RC. * Two identical resistors must also * be placed between this connector * and VCC/GND to pull the voltage to * a middle value when not driven * by the microcontroller: * RC o * | * GND o--[R2]-+-[R1]--o VCC * | * R1==R2 o µC */ #define OUTPUT_DDR DDRA #define OUTPUT_PORT PORTA #define OUTPUT_BIT PA0 #define BIT_DELAY 50 #define FRAME_DELAY 100 static void set_tri_state(int8_t s) { switch (s) { case 0: /* neutral */ OUTPUT_DDR &= ~(1<<OUTPUT_BIT); break; case 1: /* max */ OUTPUT_DDR |= (1<<OUTPUT_BIT); OUTPUT_PORT |= (1<<OUTPUT_BIT); break; case -1: /* min */ OUTPUT_DDR |= (1<<OUTPUT_BIT); OUTPUT_PORT &= ~(1<<OUTPUT_BIT); break; } } static void transmit_byte(uint8_t b) { uint8_t i; for (i=0; i<8; i++) { uint8_t x = ((b&(1<<i)) != 0); if (x) { set_tri_state(1); } else { set_tri_state(-1); } _delay_ms(BIT_DELAY); /* only drop to neutral if the next bit * is the same */ if (i == 7 || ( (b&(1<<(i+1))) != 0)==x) { set_tri_state(0); _delay_ms(BIT_DELAY); } } } static void send_frame(uint8_t cmd, uint8_t *payload, uint8_t l) { uint8_t chk = 0; chk ^= cmd; transmit_byte(cmd); uint8_t i; /* transmit payload and/or filler bytes */ for (i=0; i<DS_FRAME_PAYLOAD_SIZE; i++) { uint8_t b = (i>=l ? 0x00 : payload[i]); chk ^= b; transmit_byte(b); } /* send checksum */ transmit_byte(chk); /* and wait for the frame delay */ _delay_ms(FRAME_DELAY); } int main(void) { /* we like to transmit PINB to the other side, enable pullups */ PORTB |= (1<<PB0 | 1<<PB1 | 1<<PB2 | 1<<PB3 | 1<<PB4 | 1<<PB5 | 1<<PB6 | 1<<PB7); while (1) { /* check switches and construct frame */ uint8_t sw_payload[2]; sw_payload[0] = PINB; // read values sw_payload[1] = 0xFF; // we do not mask any values send_frame(DS_CMD_OUTPUT_PINS, sw_payload, 2); } }
C
#include "BinarySearchTree.h" Node* createNewNode(ValueT input) { Node* node = (Node*)malloc(sizeof(Node)); node->data = input; node->left = NULL; node->right = NULL; return node; } Node* insert(Node* treeHead, ValueT input) { if (treeHead == NULL) return createNewNode(input); if (input >= treeHead->data) treeHead->right = insert(treeHead->right, input); else treeHead->left = insert(treeHead->left, input); return treeHead; } int lookup(Node* treeHead, ValueT target) { if (treeHead == NULL) return 0; if (target == treeHead->data) return 1; if (target >= treeHead->data) return lookup(treeHead->right, target); else return lookup(treeHead->left, target); } int size(Node* treeHead) { if (treeHead == NULL) return 0; return size(treeHead->left) + 1 + size(treeHead->right); } int findMaxDepth(Node* treeHead) { int rightDepth, leftDepth; if (treeHead == NULL) return 0; rightDepth = findMaxDepth(treeHead->right); leftDepth = findMaxDepth(treeHead->left); if (rightDepth >= leftDepth) return rightDepth + 1; else return leftDepth + 1; } ValueT minValue(Node* treeHead) { Node* iterator = treeHead; while (iterator->left != NULL) iterator = iterator->left; return iterator->data; } ValueT maxValue(Node* treeHead) { Node* iterator = treeHead; while (iterator->right != NULL) iterator = iterator->right; return iterator->data; } void printTree(Node* treeHead) { if (treeHead == NULL) return; printTree(treeHead->left); printf("%d\n", treeHead->data); printTree(treeHead->right); } int isBST(Node* treeHead) { return isBSTUtil(treeHead, minValue(treeHead), maxValue(treeHead)); } int isBSTUtil(Node* treeHead, ValueT min, ValueT max) { if (treeHead == NULL) return 1; if (treeHead->data < min || treeHead->data > max) return 0; return isBSTUtil(treeHead->left, min, treeHead->data) && isBSTUtil(treeHead->right, treeHead->data, max); } Node* destoryTree(Node* treeHead) { if (treeHead == NULL) return NULL; treeHead->left = destoryTree(treeHead->left); treeHead->right = destoryTree(treeHead->right); free(treeHead); return NULL; }
C
#include<stdio.h> #include<stdlib.h> #include<sys/stat.h> #include<unistd.h> #include<limits.h> #include<string.h> #include<dirent.h> #include<fcntl.h> #include<time.h> #include<grp.h> #include<pwd.h> #include<langinfo.h> #include<stdint.h> #include<locale.h> #include <ctype.h> #include <sys/types.h> #include <sys/wait.h> #define length 1024 #define len 63 #include"pwd_code.c" #include"echo_code.c" #include"ls_code.c" #include"cd_code.c" #include"pinfo_code.c" #include"process_code.c" #include"env.c" void sig_handler(int signo) { if (signo == SIGINT) printf("received SIGINT\n"); } int main() { if (signal(SIGINT, sig_handler) == SIG_ERR) printf("\ncan't catch SIGINT\n"); int flag=0,p; char *username=getenv("USER"); char hostname[HOST_NAME_MAX+1]; int host_flag=gethostname(hostname,HOST_NAME_MAX); if(host_flag<0) { printf("Could not get hostname"); exit(0); } char* prev_dir=malloc(sizeof(char) * 1024); char home_dir[1000]; char dir[1000]="<"; strcat(dir,username); strcat(dir,"@"); strcat(dir,hostname); strcat(dir,":~"); strcpy(home_dir,dir); int i; char input[length+1], cwd[length+1], home[length+1]; char* relative=malloc(sizeof(char) * 1024); char* token[1024]; for (i=0; i<1024; i++) token[i]=(char *)malloc(1024 * sizeof(char)); char* temp=malloc(sizeof(char) * 1024); if(getcwd(home, len)==NULL)// gets the current working directory in variable home { printf ("Can not get present working directory\n");//if getcwd couldnt get the present working directory } while(1) { printf("%s>",dir); fgets(input,length,stdin);//scanning the input stream i=0; token[0]=strtok(input," \t\n\v\f\r");//split the input stream into separate words while(token[i]!=NULL) { i++; token[i]=strtok(NULL, " \t\n\v\f\r"); } token[i+1]=NULL; pid_t pID = waitpid(p,NULL,WNOHANG); while(pID > 0) { printf("Background-Process %d has exited\n",pID); pID = 0; } if(!strcmp(token[0],"kjob")) { kjob_func(token); } if(!strcmp(token[0],"jobs")) { jobs_func(token); } if(!strcmp(token[0],"overkill")) { overkill_func(token); } if(!strcmp(token[0], "pwd")) { pwd_func(home); } else if(!strcmp(token[0], "echo")) { echo_func(token); } else if(!strcmp(token[0], "cd")) { flag=cd_func(token,flag,home,prev_dir,temp,dir,home_dir); } else if(!strcmp(token[0], "ls")) { ls_func(token); } else if(!strcmp(token[0], "pinfo")) { pinfo_func(token); } else if(!strcmp(token[0], "setenv")) { //printf("Will execute setenv\n"); setenv_func(token); } else if(!strcmp(token[0], "unsetenv")) { //printf("Will execute setenv\n"); unsetenv_func(token); } else if(!strcmp(token[0],"fg")) { fg_func(token); } else if(!strcmp(token[0],"bg")) { bg_func(token); } else if(!strcmp(token[0],"quit")) { exit(0); } else { p=process_func(token, input); } } void handler(int sig) { int pid = getpid(); kill(pid,SIGTSTP); return; } return 0; }
C
#include <stdio.h> #include <stdlib.h> void ordenar(int vect[], int tam, int ordenar ); void mostrarvector(int[], int); int main() { int x[]={34,4,23,12,7}; ordenar(x,5, 1); mostrarvector(x,5); return 0; } void ordenar(int vect[], int tam, int criterio) { int i,j,aux; for(i=0; i<(tam-1); i++) { for(j=i+1; j<tam; j++) { if(vect[i]<vect[j] && criterio==0) { aux=vect[i]; vect[i]=vect[j]; vect[j]=aux; } if(vect[i]>vect[j] && criterio==1) { aux=vect[i]; vect[i]=vect[j]; vect[j]=aux; } } } } void mostrarvector(int vect[], int tam) { int i; for(i=0; i<tam; i++) { printf("%d ",vect[i]); } printf("\n\n"); }
C
/* ----------------------------------------------------------------------- *Test smithy card * * cardtest1: cardtest1.c dominion.o rngs.o * gcc -o cardtest1 -g cardtest1.c dominion.o rngs.o $(CFLAGS) * ----------------------------------------------------------------------- */ #include "dominion.h" #include "dominion_helpers.h" #include <string.h> #include <stdio.h> #include <assert.h> #include "rngs.h" int main() { int i; int seed = 1000; int numPlayer = 2; int finalDeck; struct gameState state; int card_set_1[10] = {adventurer, council_room, feast, gardens, mine , remodel, smithy, village, baron, great_hall}; initializeGame(numPlayer, card_set_1, seed, &state); printf("Now testing smithy\n"); finalDeck = state.deckCount[0] - 3; state.hand[0][0] = smithy; state.handCount[0] = 1; playSmithy(0, &state); if (state.handCount[0] != 3) { printf("TEST FAILED: Handcount incorrect!\n"); } if (state.deckCount[0] != finalDeck) { printf("TEST FAILED: Final deck count incorrect!\n"); } for (i = 0; i < 3; i++) { if (state.hand[0][i] < 0 || state.hand[0][i] > great_hall) { printf("TEST FAILED: Invalid card in hand!\n"); } } printf("Testing smithy complete!\n\n"); return 0; }
C
#include <stdio.h> int main() { float precoCombustivel = 1.90, kmInicial = 0, kmFinal = 0, litrosGastos = 0, money = 0; float consumo = 0, lucro = 0, gasolina = 0; printf("Digite a quilometragem no início do dia: \n"); scanf("%f", &kmInicial); printf("Digite a quilometragem no final do dia: \n"); scanf("%f", &kmFinal); printf("Digite quantos litros de combustível foram gastos: \n"); scanf("%f", &litrosGastos); printf("Digite o total de dinheiro recebido desse dia: \n"); scanf("%f", &money); consumo = (kmFinal - kmInicial) / litrosGastos; gasolina = consumo * precoCombustivel; lucro = money - gasolina; printf("Sua média de consumo do dia = %.2f km/L \n", consumo); printf("Seu lucro do dia = %.2f \n", lucro); return 0; }
C
#include <avr/io.h> #include <avr/interrupt.h> extern int coches; int contador=2; long contador2=21; /*===============================================================*/ /* Interrupción temporal que gestiona el estado del led */ /*===============================================================*/ ISR(TIMER5_OVF_vect){ if(coches==0) //si no hay ningún coche en el lavadero se enciende el led 0.5seg y se mantiene apagado durante 10seg { contador2--; //Decremento de la cuenta de tiempo if(contador2==20){ PORTB &= 0b11111101;//Apagar led } if(contador2==1){ PORTB |=0b00000010; //Encender led } if(contador2 ==0){ contador2 =21; } } else{//si hay algún coche en el lavadero se enciende y apaga el led cada medio segundo contador--; if(contador==1){ PORTB &= 0b11111101; //Apagar led } if(contador==0){ PORTB |=0b00000010; //Encender led contador=2; } } } void luzdeestado(){ //Configuración del led como salida y del timer que gestiona su funcionamiento cli(); DDRB|=0b00000010; TCCR5B=0x03; TIMSK5 =0x01; sei(); }
C
/*************************************************************************\ * Copyright (C) Michael Kerrisk, 2019. * * * * This program is free software. You may use, modify, and redistribute it * * under the terms of the GNU General Public License as published by the * * Free Software Foundation, either version 3 or (at your option) any * * later version. This program is distributed without any warranty. See * * the file COPYING.gpl-v3 for details. * \*************************************************************************/ /* Listing 23-5 */ /* ptmr_sigev_signal.c This program demonstrates the use of signals as the notification mechanism for expirations of a POSIX timer. Each of the program's command-line arguments specifies the initial value and interval for a POSIX timer. The format of these arguments is defined by the function itimerspecFromStr(). The program establishes a handler for the timer notification signal, creates and arms one timer for each command-line argument, and then pauses. Each timer expiration causes the generation of a signal, and, when invoked, the signal handler displays information about the timer expiration. Kernel support for Linux timers is provided since Linux 2.6. On older systems, an incomplete user-space implementation of POSIX timers was provided in glibc. */ #define _POSIX_C_SOURCE 200809L #include <signal.h> #include <time.h> #include <string.h> #include <stdlib.h> #include "../../book-src/lib/tlpi_hdr.h" #define TIMER_SIG SIGRTMAX /* Our timer notification signal */ #define BUF_SIZE 1000 /* Convert a string of the following form to an itimerspec structure: "value.sec[/value.nanosec][:interval.sec[/interval.nanosec]]". Optional components that are omitted cause 0 to be assigned to the corresponding structure fields. */ void itimerspecFromStr(char *str, struct itimerspec *tsp) { char *dupstr, *cptr, *sptr; dupstr = strdup(str); cptr = strchr(dupstr, ':'); if (cptr != NULL) *cptr = '\0'; sptr = strchr(dupstr, '/'); if (sptr != NULL) *sptr = '\0'; tsp->it_value.tv_sec = atoi(dupstr); tsp->it_value.tv_nsec = (sptr != NULL) ? atoi(sptr + 1) : 0; if (cptr == NULL) { tsp->it_interval.tv_sec = 0; tsp->it_interval.tv_nsec = 0; } else { sptr = strchr(cptr + 1, '/'); if (sptr != NULL) *sptr = '\0'; tsp->it_interval.tv_sec = atoi(cptr + 1); tsp->it_interval.tv_nsec = (sptr != NULL) ? atoi(sptr + 1) : 0; } free(dupstr); } /* Return a string containing the current time formatted according to the specification in 'format' (see strftime(3) for specifiers). If 'format' is NULL, we use "%c" as a specifier (which gives the' date and time as for ctime(3), but without the trailing newline). Returns NULL on error. */ char *currTime(const char *format) { static char buf[BUF_SIZE]; /* Nonreentrant */ time_t t; size_t s; struct tm *tm; t = time(NULL); tm = localtime(&t); if (tm == NULL) return NULL; s = strftime(buf, BUF_SIZE, (format != NULL) ? format : "%c", tm); return (s == 0) ? NULL : buf; } int main(int argc, char *argv[]) { struct itimerspec ts; struct sigaction sa; struct sigevent sev; timer_t *tidlist; int j; if (argc < 2) usageErr("%s secs[/nsecs][:int-secs[/int-nsecs]]...\n", argv[0]); tidlist = calloc(argc - 1, sizeof(timer_t)); if (tidlist == NULL) errExit("malloc"); /* Create and start one timer for each command-line argument */ sev.sigev_notify = SIGEV_SIGNAL; /* Notify via signal */ sev.sigev_signo = TIMER_SIG; /* Notify using this signal */ for (j = 0; j < argc - 1; j++) { itimerspecFromStr(argv[j + 1], &ts); sev.sigev_value.sival_ptr = &tidlist[j]; /* Allows handler to get ID of this timer */ if (timer_create(CLOCK_REALTIME, &sev, &tidlist[j]) == -1) errExit("timer_create"); printf("Timer ID: %ld (%s)\n", (long)tidlist[j], argv[j + 1]); if (timer_settime(tidlist[j], 0, &ts, NULL) == -1) errExit("timer_settime"); } siginfo_t si; sigset_t signalsToWait; sigemptyset(&signalsToWait); sigaddset(&signalsToWait, TIMER_SIG); sigprocmask(SIG_BLOCK, &signalsToWait, NULL); printf("TimerSIG: %d [min %d]\n", TIMER_SIG, SIGRTMIN); for (;;) { int s = sigwaitinfo(&signalsToWait, &si); if(s < 0) { errExit("sigwaitinfo"); } timer_t *tidptr; tidptr = si.si_value.sival_ptr; printf("[%s] Got signal %d\n", currTime("%T"), s); printf(" *sival_ptr = %ld\n", (long)*tidptr); printf(" timer_getoverrun() = %d\n", timer_getoverrun(*tidptr)); } }
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: messageQueue.h * Author: Jeremy Fleitz * * Created on May 10, 2016, 12:02 AM */ #ifndef MESSAGEQUEUE_H #define MESSAGEQUEUE_H #ifdef __cplusplus extern "C" { #endif #define HIGHEST_PRIORITY 0 #define DEFAULT_PRIORITY 5 #define LOW_PRIORITY 9 typedef enum { MSG_LAMP, MSG_SOLENOID, MSG_SOUND, MSG_DISPLAY, MSG_EVENT } message_type; struct message_struct { int commandID; int commandValue; int priority; message_type messageType; struct message_struct *next; }; void InitializeQueue(struct message_struct **queue); struct message_struct PopHeadOff(struct message_struct **queue); int DeleteQueue(struct message_struct **queue); struct message_struct* AddToQueueWithPriority(struct message_struct **queue, message_type messageType, int commandID, int commandValue, int priority); int SomethingInQueue(struct message_struct *queue); #ifdef __cplusplus } #endif #endif /* MESSAGEQUEUE_H */