language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#ifndef TEXTBUFFER_H #define TEXTBUFFER_H typedef struct textbuffer *TB; /* Allocate a new textbuffer whose contents is initialised with the text given * in the array. */ TB newTB (char text[]); /* Free the memory occupied by the given textbuffer. It is an error to access * the buffer afterwards. */ void releaseTB (TB tb); /* Allocate and return an array containing the text in the given textbuffer. */ char *dumpTB (TB tb); /* Return the number of lines of the given textbuffer. */ int linesTB (TB tb); /* Swap the two given lines in the textbuffer. * * - The program is to abort() with an error message if line 'pos1' or line * 'pos2' is out of range. The first line of a textbuffer is at position 0. */ void swapTB (TB tb, int pos1, int pos2); /* Merge 'tb2' into 'tb1' at line 'pos'. * * - Afterwards line 0 of 'tb2' will be line 'pos' of 'tb1'. * - The old line 'pos' of 'tb1' will follow after the last line of 'tb2'. * - After this operation 'tb2' can not be used anymore (as if we had used * releaseTB() on it). * - The program is to abort() with an error message if 'pos' is out of range. */ void mergeTB (TB tb1, int pos, TB tb2); /* Copy 'tb2' into 'tb1' at line 'pos'. * * - Afterwards line 0 of 'tb2' will be line 'pos' of 'tb1'. * - The old line 'pos' of 'tb1' will follow after the last line of 'tb2'. * - After this operation 'tb2' is unmodified and remains usable independent * of 'tb1'. * - The program is to abort() with an error message if 'pos' is out of range. */ void pasteTB (TB tb1, int pos, TB tb2); /* Cut the lines between and including 'from' and 'to' out of the textbuffer * 'tb'. * * - The result is a new textbuffer (much as one created with newTB()). * - The cut lines will be deleted from 'tb'. * - The program is to abort() with an error message if 'from' or 'to' is out * of range. */ TB cutTB (TB tb, int from, int to); /* Copy the lines between and including 'from' and 'to' of the textbuffer * 'tb'. * * - The result is a new textbuffer (much as one created with newTB()). * - The textbuffer 'tb' will remain unmodified. * - The program is to abort() with an error message if 'from' or 'to' is out * of range. */ TB copyTB (TB tb, int from, int to); /* Remove the lines between and including 'from' and 'to' from the textbuffer * 'tb'. * * - The program is to abort() with an error message if 'from' or 'to' is out * of range. */ void deleteTB (TB tb, int from, int to); /* Search every line of tb for each occurrence of str1 and replaces them * with str2 */ void replaceText (TB tb, char* str1, char* str2) ; /* Bonus Challenges */ char* diffTB (TB tb1, TB tb2) ; void undoTB (TB tb) ; void redoTB (TB tb) ; #endif
C
#include <stdio.h> #include <stdbool.h> #include <stm32f4xx.h> #include "uart.h" #include "flash.h" #define FLASH_USER_START_ADDR ADDR_FLASH_SECTOR_2 #define FLASH_USER_END_ADDR ADDR_FLASH_SECTOR_5 void print_flash(uint32_t start_address, uint32_t end_address) { uint32_t addr = start_address; uint32_t data_read; while (addr < end_address) { char s[30] = {0}; data_read = *(uint32_t *)addr; sprintf(s, "%p: %u\n\r", addr, data_read); usart_puts(s); addr += 4; } } int main(void) { usart3_init(); char s[50] = {0}; FLASH_Unlock(); //unlock the flash before writting data FLASH_ClearFlag(FLASH_FLAG_EOP | FLASH_FLAG_OPERR | FLASH_FLAG_WRPERR | FLASH_FLAG_PGAERR | FLASH_FLAG_PGPERR|FLASH_FLAG_PGSERR); uint32_t start_sector = get_internal_flash_sector(FLASH_USER_START_ADDR); uint32_t end_sector = get_internal_flash_sector(FLASH_USER_END_ADDR); /* erase the flash sector */ int i; for (i = start_sector; i < end_sector; i += 8) { //device voltage range supposed to be between 2.7V and 3.6V, the operation will be done by word while(FLASH_EraseSector(i, VoltageRange_3) != FLASH_COMPLETE); } /* write data into flash */ uint32_t addr = FLASH_USER_START_ADDR; uint32_t test_data_word = '#'; //decimal = 35 while (addr < FLASH_USER_END_ADDR) { if (FLASH_ProgramWord(addr, test_data_word) == FLASH_COMPLETE) { addr += 4; } else { while (1); //error occurred } } bool flash_op_failed = false; /* verify the data */ addr = FLASH_USER_START_ADDR; uint32_t data_read; while (addr < FLASH_USER_END_ADDR) { data_read = *(uint32_t *)addr; if(data_read != test_data_word) { flash_op_failed = true; } addr = addr + 4; } FLASH_Lock(); //remember to lock the flash after writting data if(flash_op_failed == false) { usart_puts("flash write succeed.\n\r" "print the last 10 written word to flash:\n\r"); uint32_t *print_addr_start = (uint32_t *)FLASH_USER_END_ADDR - 10; uint32_t *print_add_end = (uint32_t *)FLASH_USER_END_ADDR; print_flash((uint32_t)print_addr_start, (uint32_t)FLASH_USER_END_ADDR); } else { usart_puts("flash write failed.\n\r"); } return 0; }
C
#include <pthread.h> #include <stdio.h> #include <signal.h> #include <semaphore.h> #include <limits.h> pthread_t t1, t2, t3, t4, t5, t6, t7, t8, t9, t10; sem_t x; sem_t b1; sem_t b2; int global = 0; int pthread_cnt = 0; void* helperFun(void* args){ for(int i = 0; i <= 10; i++){ sem_wait(&x); global++; if (global == pthread_cnt){ sem_wait(&b2); sem_post(&b1); } sem_post(&x); sem_wait(&b1); sem_post(&b1); printf("pThread ID: %d, Global Int: %d\n\n", (int)pthread_self()%5,i); sem_wait(&x); global--; if (global == 0) { sem_wait(&b1); sem_post(&b2); } sem_post(&x); sem_wait(&b2); sem_post(&b2); } return NULL; } int main() { sem_init(&x, 0, 1); sem_init(&b1, 0, 0); sem_init(&b2, 0, 1); pthread_cnt = 10; //cerate the pthreads pthread_create(&t1, NULL, helperFun, NULL); pthread_create(&t2, NULL, helperFun, NULL); pthread_create(&t3, NULL, helperFun, NULL); pthread_create(&t4, NULL, helperFun, NULL); pthread_create(&t5, NULL, helperFun, NULL); pthread_create(&t6, NULL, helperFun, NULL); pthread_create(&t7, NULL, helperFun, NULL); pthread_create(&t8, NULL, helperFun, NULL); pthread_create(&t9, NULL, helperFun, NULL); pthread_create(&t10, NULL, helperFun, NULL); //join pthreads pthread_join(t1, NULL); pthread_join(t2, NULL); pthread_join(t3, NULL); pthread_join(t4, NULL); pthread_join(t5, NULL); pthread_join(t6, NULL); pthread_join(t7, NULL); pthread_join(t8, NULL); pthread_join(t9, NULL); pthread_join(t10, NULL); printf("The final Global Int: %d\n\n", global); return 0; } /*From running a few time and seeing the output I can say that the thread ID is random and incrementing the global int doesn't affect the final results. I'm having trouble getting the final Global Int to read 100 with the way I wrote this code. */
C
#include <stdio.h> #define T 10 /* 2. Desenvolva um programa que faça a leitura de 10 valores no vetor A. Construir um vetor B do mesmo tipo, observando a seguinte formatação: a. Se o valor do índice for par, o valor deverá ser multiplicado por 5; b. Se o valor do índice for ímpar, deverá ser somado com 5. c. Ao final mostrar os conteúdos dos dois vetores invertidos (listar ao contrário). */ int main(){ int vetorA[T] = {0}; int vetorB[T] = {0}; for(int i = 0; i < T; i++){ int valor = 0; printf("Digite um valor: "); scanf("%d", &vetorA[i]); } for(int j = 0; j < T; j++){ vetorB[j] = j % 2 == 0 ? vetorA[j] * 5 : vetorA[j] + 5; } for(int k = (T - 1); k >= 0; k--){ printf(" Indice: %d | Vetor A: %d | Vetor B: %d \n", k, vetorA[k], vetorB[k] ); } }
C
// ESCLAVO Comunicacin SPI //#include <18F4550.H> #include <16F887.H> #device adc=8 #fuses XT, NOWDT, NOPROTECT, BROWNOUT, PUT, NOLVP #use delay(crystal=4000000) #use rs232(baud=9600, xmit=PIN_C6, rcv=PIN_C7) #byte SSPBUF = 0x13 // Direccin del Registro para 16F877 //#byte SSPBUF = 0xFC9 // Direccin del Registro para 18F4550 // Modos de comunicacin SPI #define SPI_MODE_0 (SPI_L_TO_H | SPI_XMIT_L_TO_H) #define SPI_MODE_1 (SPI_L_TO_H) #define SPI_MODE_2 (SPI_H_TO_L) #define SPI_MODE_3 (SPI_H_TO_L | SPI_XMIT_L_TO_H) // Comandos SPI de este esclavo #define LEER_ADC 1 #define LEER_CONTADOR 2 #define LEER_INTERRUPTOR 3 // Definicin del PIN donde se conecta el interruptor. #define SWITCH_PIN PIN_B4 // Variable global para almacenar el ADC int8 pot; // Interrupcin por SPI donde se analiza las solicitudes del Maestro #int_ssp void ssp_isr(void) { int8 comando; static int8 contador = 0; comando = SSPBUF; //Toma el valor del buffer SPI y lo almacena en comando switch(comando) // Verifica la instruccin del maestro { case LEER_ADC: SSPBUF = pot; break; case LEER_CONTADOR: SSPBUF = contador; contador++; break; case LEER_INTERRUPTOR: SSPBUF = input(SWITCH_PIN); break; } } //====================================== void main() { // Configura AN0 como analoga //setup_adc_ports(AN0); //18F4550 setup_adc_ports(sAN0); //16F887 setup_adc(ADC_CLOCK_DIV_8); set_adc_channel(0); delay_us(20); pot = read_adc(); //Inicializa el hardware SSP para ser un SPI esclavo en Modo 0 setup_spi(SPI_SLAVE | SPI_MODE_0); // Habilita las interrupciones clear_interrupt(INT_SSP); enable_interrupts(INT_SSP); enable_interrupts(GLOBAL); // Actualiza la lectura analoga cada 100ms while(1) { pot = read_adc(); delay_ms(100); } }
C
#include <stdio.h> int main() { int n, i, j, s = 0; int a[10][10]; printf("Enter the size of Identity Matrix : "); scanf("%d",&n); printf("Enter the matrix elements : "); for(i = 0; i < n ; i++) { for(j=0; j< n; j++) { scanf("%d",&a[i][j]); } } printf("\nMatrix is : "); for(i = 0; i < n ; i++) { printf("\n"); for(j=0; j< n; j++) { if(i == j) s += a[i][j]; printf("%d\t",a[i][j]); } } printf("\nSum of Main Diagonal is %d",s); return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <math.h> //Segunda escritura del programa, sigue mandando error //Empec con esto a las 6 de la maana, son las 8 y no hay progreso, ni con Switch ni con else o for //Este ejercicio es posible, pero por el momento, algo se escapa de mis manos //Sospecho ligeramente que la falla esta en el primer for, ya que es un ciclo //Ahora, escribire el programa de manera que solamente lea una llave, a ver que sucede int main() { int keyquant,x,a,r,keyone,keytwo,num1; r=0; printf("Debes de estar desesperado como para venir a buscar mi ayuda, novato\n"); printf("\nPrimero, introduce la cantidad de llaves que necesitas\n"); printf("\nLuego, las llaves, separadas por comas\n"); scanf("\n%d\n", &keyquant); for (x=0;x<=keyquant;x++) { printf("\nAhora, introduzca la llave que necesita\n"); scanf("\n%d,%d\n", &keyone, &keytwo); if (keyone<keytwo) num1=1; if (keyone>keytwo); num1=2; switch (num1) { case 1: for (a=0;a<keyone;a++) { if (keyone%a==0) r++; } if (r==2) { printf("\nNO"); } else { printf("\nSI"); } break; case 2: for (a=0;a<keytwo;a++) { if (keyone%a==0) r++; } if (r==2) { printf("\nNO"); } else { printf("\nSI"); } break; } } return 0; }
C
#include <reg52.h> #define uchar unsigned char #define uint unsigned int sbit ADDR0 = P1^0; sbit ADDR1 = P1^1; sbit ADDR2 = P1^2; sbit ADDR3 = P1^3; sbit ENLED = P1^4; signed long frequency=0; bit start=0; //ʱģʽ unsigned char Pulse = 0; unsigned char T0RH=0; unsigned char T0RL=0; unsigned char code LedChar[] = { //ʾַת 0xC0, 0xF9, 0xA4, 0xB0, 0x99, 0x92, 0x82, 0xF8, 0x80, 0x90, 0x88, 0x83, 0xC6, 0xA1, 0x86, 0x8E }; unsigned char LedBuff[6] = { //ʾ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }; /* һ޷ų͵ʾϣnum-ʾ */ void ShowNumber(unsigned long num) { signed char i; unsigned char buf[6]; for (i=0; i<6; i++) //ѳתΪ 6 λʮƵ { buf[i] = num % 10; num = num / 10; } for (i=5; i>=1; i--) //λ 0 תΪո 0 ˳ѭ { if (buf[i] == 0) LedBuff[i] = 0xFF; else break; } for ( ; i>=0; i--) //ʣλʵתΪʾַ { LedBuff[i] = LedChar[buf[i]]; } } /* ̬ܶɨˢºڶʱже */ void LedScan() { static unsigned char i = 0; //̬ɨ P0 = 0xFF; //ʾ switch (i) { case 0: ADDR2=0; ADDR1=0; ADDR0=0; i++; P0=LedBuff[0]; break; case 1: ADDR2=0; ADDR1=0; ADDR0=1; i++; P0=LedBuff[1]; break; case 2: ADDR2=0; ADDR1=1; ADDR0=0; i++; P0=LedBuff[2]; break; case 3: ADDR2=0; ADDR1=1; ADDR0=1; i++; P0=LedBuff[3]; break; case 4: ADDR2=1; ADDR1=0; ADDR0=0; i++; P0=LedBuff[4]; break; case 5: ADDR2=1; ADDR1=0; ADDR0=1; i=0; P0=LedBuff[5]; break; default: break; } } void ConfigTimer0(unsigned int ms) { unsigned long tmp; tmp=11059200/12; tmp=(tmp*ms)/1000; tmp=65536-tmp; tmp=tmp+36; //Ƶ36100 1000 10000 Ƶ2410 000020 0000 Ƶ5830 0000 T0RH=(unsigned char)(tmp>>8); T0RL=(unsigned char)tmp; TMOD&=0xF0; TMOD|=0x01; TH0=T0RH; TL0=T0RL; ET0=1; TR0=1; } void main() { P3 = 0xFF; EA = 1; //ʹж ENLED = 0; //ѡܽʾ ADDR3 = 1; ConfigTimer0(1); //T0ʱ1ms TMOD = 0x51; // T0ʱT1Ϊģʽ 1 TH1=0x00; TL1=0x00; ET1=1; TR1=1; LedBuff[0] = LedChar[0]; //ϵʾ0 while(1) { if(start==1) { TR1=1; // TR0 = 1; start=0; //رλ ֤1ʱ Pulse = 0; } ShowNumber(frequency); } } void time0() interrupt 1 //T0ʱ { static unsigned int i=0; TH0=T0RH; TL0=T0RL; //TH0 = 0xFC; //¼سֵ,ʱ1ms //TL0 = 0x67; i++; LedScan(); //ʾɨ躯 if(i>=1000) { i=0; TR1=0; //ֹͣ TR0=0; //ֹͣʱ frequency = ((Pulse*65535)+(TH1*256)+TL1); //Ƶֵ 1 Pulse=0; TH1=0; //ֵ TL1=0; TH0=T0RH; TL0=T0RL; //TH0 = 0xFC; //¼سֵ,ʱ1ms //TL0 = 0x67; start=1; //ʱ //TR1=1; } } void Time1() interrupt 3 //T1 { TH1=0; TL1=0; TR1=1; Pulse++; }
C
#include<stdio> #include<conio.h> int main(){ int n,i,j,temp; int array[5]={3,4,7,8,9}; for(i=0;i<=n;i++){ for(j=1;j<=n-1;j++) { temp = arr[j]; arr[j] = arr[j-1]; arr[j-1] = temp; j--; } printf("Sorted list in assanding orderd:\n",arr(i)); } }
C
#include "../api.h" #include <stdio.h> static int integer_add(jack_state_t *state) { printf("\nInside add call\n"); jack_dump_state(state); int sum = 0; for (int i = 0; i < state->stack->top; ++i) { sum += jack_get_integer(state, i); } jack_new_integer(state, sum); return 1; } int jack_test(jack_state_t *state) { jack_new_function(state, integer_add, 0); jack_new_integer(state, 1); jack_new_integer(state, 2); jack_new_integer(state, 3); printf("\nBefore add function call\n"); jack_dump_state(state); int retc = jack_function_call(state, -4, 3); printf("\nAfter add function call\n"); jack_dump_state(state); jack_popn(state, retc + 1); jack_new_list(state); jack_new_symbol(state, "numbers!"); jack_list_push(state, -2); int i; for (i = 0; i < 5; ++i) { jack_new_integer(state, i); jack_list_push(state, -2); } printf("\nBefore forward iter\n"); jack_dump_state(state); jack_dup(state, -1); jack_list_forward(state); printf("\nAfter forward iter\n"); jack_dump_state(state); while (true) { printf("\nBefore iteration\n"); jack_dump_state(state); int retn = jack_function_call(state, -1, 0); printf("\nAfter iteration\n"); jack_dump_state(state); if (jack_get_type(state, -1) == Nil) { jack_popn(state, retn + 1); break; } jack_popn(state, retn); } printf("\nBefore iter function call\n"); jack_dump_state(state); jack_dup(state, -1); jack_list_backward(state); printf("\nAfter iter function call\n"); jack_dump_state(state); while (true) { int retn = jack_function_call(state, -1, 0); printf("\nAfter iteration\n"); jack_dump_state(state); if (jack_get_type(state, -1) == Nil) { jack_popn(state, retn + 2); break; } jack_popn(state, retn); } jack_new_map(state, 10); // map.name = "Tim Caswell" jack_new_symbol(state, "Tim Caswell"); jack_map_set_symbol(state, -2, "name"); // map.age = 32 jack_new_integer(state, 32); jack_map_set_symbol(state, -2, "age"); // print map.age jack_map_get_symbol(state, -1, "age"); printf("\nage = %ld\n", jack_get_integer(state, -1)); jack_pop(state); printf("\nBefore map iter\n"); jack_dump_state(state); jack_map_iterate(state); printf("\nAfter map iter\n"); jack_dump_state(state); while (true) { int retn = jack_function_call(state, -1, 0); printf("\nAfter iteration\n"); jack_dump_state(state); if (jack_get_type(state, -1) == Nil) { jack_popn(state, retn + 1); break; } jack_popn(state, retn); } jack_new_boolean(state, true); jack_new_boolean(state, false); jack_dump_state(state); jack_popn(state, state->stack->top); jack_dump_state(state); jack_new_symbol(state, "eat some memory!"); jack_new_symbol(state, "numbers!"); for (i = 0; i < 0x10000; ++i) { jack_new_list(state); jack_dup(state, -3); jack_list_insert(state, -2); jack_new_integer(state, 42); jack_list_push(state, -2); jack_new_list(state); jack_dup(state, -3); jack_list_push(state, -2); jack_list_insert(state, -2); jack_pop(state); } return 0; }
C
int main() { int x[1000],y[1000],i=1,j,k,num[1000]={0},max=0; cin>>x[0]; while(cin.peek()!='\n'){ cin.get(); cin>>x[i++]; } for(j=0;j<i;j++){ cin.get(); cin>>y[j]; } for(k=0;k<1000;k++) for(j=0;j<i;j++) { if(k>=x[j]&&k<y[j]) num[k]++; } for(j=0;j<1000;j++) if(num[j]>max)max=num[j]; cout<<i<<" "<<max; return 0; }
C
//另一个思路是,全部先bw间隔放好,之后把-添加进去! #include<stdio.h> #define MAX 200 int main() { int n,m; scanf("%d%d",&n,&m); char chess[MAX][MAX]; int i,j; for(i=0; i<n; i++) { scanf("%s",chess[i]); } char chess2[MAX][MAX]; for(i=0; i<n; i++) { for(j=0; j<m; j++) { if((i+j) % 2 == 0 ) { chess2[i][j]='B'; } else { chess2[i][j]='W'; } } } /* for(i=0; i<n; i++) { for(j=0; j<m; j++) { printf("%c",chess2[i][j]); } printf("\n"); } */ for(i=0; i<n; i++) { for(j=0; j<m; j++) { if (chess[i][j]=='-') { chess2[i][j]='-'; } } } for(i=0; i<n; i++) { for(j=0; j<m; j++) { printf("%c",chess2[i][j]); } printf("\n"); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <pthread.h> #include <semaphore.h> #include <unistd.h> #define SIZE 100 void* reader(void* param); void* writer(void* param); FILE* inout; sem_t mutex, wrt; int data = 0, readcount = 0; char task[SIZE][SIZE]; int main(int argc, char *argv[]) { int N = atoi(argv[2]); int i = 0; int j = 0; pthread_t r[N], w; sem_init(&mutex, 0, 1); sem_init(&wrt, 0, 1); if (argc != 3) { fprintf(stderr, "usage: ./threads [input file r/w] [# of Reader threads]\n"); return -1; } inout = fopen(argv[1],"r+"); if (inout == NULL) { printf("input file invalid\n"); exit(1); } for (i = 0; i < N/2; i++) { pthread_create(&r[i], NULL, (void*)reader, (void*)i); } pthread_create(&w, NULL, (void*)writer, (void*)0); for (j = i; j < N; j++) { pthread_create(&r[j], NULL, (void*)reader, (void*)j); } for (i = 0; i < N / 2; i++) { pthread_join(r[i], NULL); } pthread_join(w, NULL); for (j = i; j < N; j++) { pthread_join(r[j], NULL); } fclose(inout); return 0; } void* reader(void* param) { int c = (int)param; int g = 0; printf("\nreader % d is made\n", c); sem_wait(&mutex); readcount++; if (readcount == 1) sem_wait(&wrt); sem_post(&mutex); /*Critcal Section */ printf("\nreader % d is reading\n", c); fseek(inout, 0, SEEK_SET); for (g=0; g <=c; g++) { fgets(task[c], SIZE, inout); } sleep(1); printf("\nreader % d finished reading: %d\n", c, atoi(task[c])); /* critical section completd */ sem_wait(&mutex); readcount--; if (readcount == 0) sem_post(&wrt); sem_post(&mutex); } void* writer(void* param) { int i = (int)param; char name[10] = { 'L','e','s','s','o','n','s','\0' }; printf("\nWriter %d made\n", i); sem_wait(&wrt); printf("\nwriter %d is writing\n", i); fseek(inout, 0, SEEK_END); fputs(name, inout); sleep(1); printf("\nwriter %d is finished writing\n", i); sem_post(&wrt); }
C
/*-------------------------------------------------------------------------* * File: mstimer.c *-------------------------------------------------------------------------* * Description: * Using a timer, provide a one millisecond accurate timer. *-------------------------------------------------------------------------*/ /*-------------------------------------------------------------------------* * Includes: *-------------------------------------------------------------------------*/ #include <stdbool.h> #include <sys/time.h> #include <time.h> #include <stdio.h> #include "../hardware/GS_HAL.h" /*-------------------------------------------------------------------------* * Globals: *-------------------------------------------------------------------------*/ /* 32-bit counter of current number of milliseconds since timer started */ volatile uint32_t G_msTimer; struct timeval t1,t2; /*---------------------------------------------------------------------------* * Routine: MSTimerInit *---------------------------------------------------------------------------* * Description: * Initialize and start the one millisecond timer counter. * Inputs: * void * Outputs: * void *---------------------------------------------------------------------------*/ void MSTimerInit(void) { gettimeofday(&t1, NULL); } /*---------------------------------------------------------------------------* * Routine: MSTimerGet *---------------------------------------------------------------------------* * Description: * Get the number of millisecond counters since started. This value * rolls over ever 4,294,967,296 ms or 49.7102696 days. * Inputs: * void * Outputs: * uint32_t -- Millisecond counter since timer started or last rollover. *---------------------------------------------------------------------------*/ uint32_t MSTimerGet(void) { uint32_t elapsedTime=0; gettimeofday(&t2, NULL); elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms return elapsedTime; } /*---------------------------------------------------------------------------* * Routine: MSTimerDelta *---------------------------------------------------------------------------* * Description: * Calculate the current number of milliseconds expired since a given * start timer value. * Inputs: * uint32_t start -- Timer value at start of delta. * Outputs: * uint32_t -- Millisecond counter since given timer value. *---------------------------------------------------------------------------*/ uint32_t MSTimerDelta(uint32_t start) { return MSTimerGet() - start; } /*---------------------------------------------------------------------------* * Routine: MSTimerDelay *---------------------------------------------------------------------------* * Description: * Routine to idle and delay a given number of milliseconds doing * nothing. * Inputs: * uint32_t ms -- Number of milliseconds to delay * Outputs: * void *---------------------------------------------------------------------------*/ void MSTimerDelay(uint32_t ms) { //uint32_t start = MSTimerGet(); //while (MSTimerDelta(start) < ms) { //} usleep(ms*1000); } /*-------------------------------------------------------------------------* * End of File: mstimer.c *-------------------------------------------------------------------------*/
C
#include <cs50.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> int shift(char c); string error_message = "Usage: ./vigenere keyword\n"; int main(int argc, string argv[]) { //check if argv has an input if(argv[1] == NULL) { printf("%s", error_message); return 1; } //assign length of argv[1] to variable int key_length = strlen(argv[1]); //check numbers of arguments if(argc == 2) { //loop for strings of argv for(int i = 0; i < key_length; i++) { //check if each char in argv is alphabetical int isalpha = isalpha(argv[1][i]); if(isalpha != 0) { //if alpha //do nothing } else { printf("%s", error_message); return 1; } } } else { printf("%s", error_message); return 1; } string plain_text = get_string("Input plain text: "); //find out length of plain_text int plaintext_length = strlen(plain_text); //allocate another slot for plaintext, ready to be converted to cipher string cipher_text = plain_text; printf("ciphertext: "); //iterate over each char of plain_text for(int i = 0, j = 0; i < plaintext_length; i++) { int key = shift(argv[1][j]); int n, x; //check if each character is upper or lower case n = isupper(cipher_text[i]); if(n != 0 ) { n = 65; } else { n = 97; } //shift plaintext in ciphertext entry to ints x = isalpha(plain_text[i]); if(x != 0) { cipher_text[i] = (shift(cipher_text[i]) + key) % 26 + n; j = (j + 1) % key_length; printf("%c", cipher_text[i]); } else { printf("%c", plain_text[i]); } } printf("\n"); } int shift(char c) { //check for uppercase if(c >= 65 && c <= 90) { c -= 65; } if(c >= 97 && c <= 122) { c -= 97; } else { // } return c; }
C
#ifndef _ELEMENT_A #define _ELEMENT_A typedef int ElementA; void afficherElementA(ElementA e); /* Preconditions : aucune Postconditions : e est affiche a l'ecran sans retour a la ligne */ int estInferieurElementA(ElementA e1, ElementA e2); /* Preconditions : aucune Resultat : 1 si e1 < e2, 0 sinon */ int estSuperieurElementA(ElementA e1, ElementA e2); /* Preconditions : aucune Resultat : 1 si e1 > e2, 0 sinon */ int estSuperieurOuEgalElementA(ElementA e1, ElementA e2); /* Preconditions : aucune Resultat : 1 si e1 >= e2, 0 sinon */ int estEgalElementA(ElementA e1, ElementA e2); /* Preconditions : aucune Resultat : 1 si e1 == e2, 0 sinon */ #endif
C
/*定义函数数组*/ /*函数数组的成员必须是同一种类型的函数,即形参相同,但是函数名不同, 返回值不同会产生警告,但是可以通过编译运行*/ #include <stdio.h> int fun1( int a,int b ) { return a+b; } float fun2( int a,int b) { return a-b; } int main( ) { int (* fun_arry[ 2 ] )(int,int); fun_arry[ 0 ]=fun1; fun_arry[ 1 ]=fun2; int a=5,b=8; printf( "%d\n",fun_arry[ 0 ]( a,b )); printf( "%d\n",fun_arry[ 1 ]( a,b)); return 0; }
C
#include "c4_5.h" /* compute the GAIN of class variable when it is divided into several subsets by attribute variable */ //function: compute gain for class variable divided by boolean attribute variable //arguments: // attribvar - attribute variable // classvar - class variable // n - length of dataset float gainCompute_Bool(const bool* attribvar, const bool* classvar, int n) { float l_fGain = 0.0f; int i; //compute entropy of classvar float l_fOrigEntropy = entropyCompute_Bool(classvar, n); //divide classvar in two subset by attribvar int l_iTrues = 0; for(i=0; i<n; i++) { if(true == attribvar[i]) { l_iTrues++; } } bool* l_pbSubClassvar1 = (bool *)malloc(l_iTrues * sizeof(bool)); bool* l_pbSubClassvar2 = (bool *)malloc((n - l_iTrues) * sizeof(bool)); int c1=0, c2=0; for(i=0; i<n; i++) { if(true == attribvar[i]) { l_pbSubClassvar1[c1++] = classvar[i]; } else { l_pbSubClassvar2[c2++] = classvar[i]; } } //compute entropy for subsets float l_fEntropy1 = entropyCompute_Bool(l_pbSubClassvar1, l_iTrues); float l_fEntropy2 = entropyCompute_Bool(l_pbSubClassvar2, (n - l_iTrues)); l_fGain = l_fOrigEntropy - (((float)l_iTrues/(float)n)*l_fEntropy1 + ((float)(n - l_iTrues)/(float)n)*l_fEntropy2); //release memory free(l_pbSubClassvar1); free(l_pbSubClassvar2); l_pbSubClassvar1 = NULL; l_pbSubClassvar2 = NULL; return l_fGain; } //function: compute gain for class variable divided by categorical attribute variable //arguments: // attribvar - attribute variable // classvar - class variable // n - length of dataset float gainCompute_Catg(const int* attribvar, const bool* classvar, int n) { float l_fGain = 0.0f; return l_fGain; } //function: compute gain for class variable divided by categorical attribute variable //arguments: // attribvar - attribute variable // classvar - class variable // n - length of dataset float gainCompute_Num(const float* attribvar, const bool* classvar, int n) { float l_fGain = 0.0f; return l_fGain; }
C
#include "apue.h" #include <stdio.h> #include <unistd.h> #include <pthread.h> pthread_mutex_t hashlock = PTHREAD_MUTEX_INITIALIZER; int total = 0; void* tfn(void * arg) { int num = *((int *) arg); long d2num = 3*num; pthread_mutex_lock(&hashlock); printf("In thread %lu arg:%d.\n", (unsigned long)pthread_self(), num); total += num; printf("Thread over!!! arg:%d\n", num); pthread_mutex_unlock(&hashlock); return (void*)(d2num); } int main(int argc, char* argv[]) { pthread_t tid; int num; void* tret; while(scanf("%d", &num) == 1){ pthread_create(&tid, NULL, tfn, (void*) &num); pthread_join(tid, &tret); //why 2 * ? printf("Thread exit code: %ld\n", (long)tret); } pthread_mutex_destroy(&hashlock); printf("Main thread %lu is over.\n",(unsigned long)pthread_self()); printf("total: %d", total); }
C
#include "pawn.h" #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include "board.h" #include "communicator.h" #include "types.h" /** * Returns the position where a pawn should be moved to. * * @param game_board The reference to the game board. * @param current_position The reference to the current position of the pawn to move. * * @return The suggested position. * * @private */ coords_t get_next_position(board_t* game_board, coords_t* current_position){ coords_t position; int orientation; boolean valid; do{ valid = 1; /* Pick a random direction. */ orientation = (int)lrand48() % 5; switch ( orientation ){ case 1: { if ( current_position->y == 0 ){ /* Position would be out of the board (top). */ valid = 0; }else{ position.x = current_position->x; position.y = current_position->y - 1; } }break; case 2: { if ( current_position->x == game_board->width ){ /* Position would be out of the board (right). */ valid = 0; }else{ position.x = current_position->x + 1; position.y = current_position->y; } }break; case 3: { if ( current_position->y == game_board->height ){ /* Position would be out of the board (bottom). */ valid = 0; }else{ position.x = current_position->x; position.y = current_position->y + 1; } }break; case 4: { if ( current_position->x == 0 ){ /* Position would be out of the board (left). */ valid = 0; }else{ position.x = current_position->x - 1; position.y = current_position->y; } }break; default: { valid = 0; }break; } }while( valid == 0 ); /* Set the 1D based index corresponding to the generated position. */ position.index = compute_index(game_board, &position); return position; } /** * Informs the master process that a flag has been conquered. * * @param game_board The reference to the game board. * @param player_pseudo_name The pawn owner player's pseudo name. * * @private */ void signal_achievement(board_t* game_board, char player_pseudo_name){ message_t message; /* Create the message. */ message.message_type = 9; message.player_pseudo_name = player_pseudo_name; send_message(game_board->coordinator_mq_id, &message); } /** * Informs the master process that the pawn has moved. * * @param game_board The reference to the game board. * @param player_pseudo_name The pawn owner player's pseudo name. * * @private */ void notify_movement(board_t* game_board, char player_pseudo_name){ message_t message; if ( game_board->round_in_progress == 1 ){ /* Create the message. */ message.message_type = 10; message.player_pseudo_name = player_pseudo_name; send_message(game_board->coordinator_mq_id, &message); } } /** * Generates and place the given pawns. * * @param game_board The reference to the game board. * @param player_pseudo_name The pseudo name associated to the player pawn will belong to. * @param game_board_shm_id The ID of the shared memory segment where the game board has been allocated at. * @param max_moves The maximum number of moves a pawn can do during a round. * * @return A structure representing the pawn spawned. */ pawn_t spawn_pawn(board_t* game_board, char player_pseudo_name, int game_board_shm_id, unsigned int max_moves){ pid_t pawn_pid; int pawn_mq_id; pawn_t pawn; /* Allocate a new message queue for the pawn that is going to be generated. */ pawn_mq_id = generate_message_queue(); pawn_pid = fork(); if ( pawn_pid == -1 ){ printf("Cannot fork process, aborting.\n"); exit(5); }else if ( pawn_pid == 0 ){ unsigned int available_moves; boolean has_conquered_flag; board_t* local_game_board; coords_t next_position; message_t message; coords_t position; available_moves = max_moves; /* Attach the game board to current process memory. */ local_game_board = get_board(game_board_shm_id); /* Pick a random position where the pawn will be placed to. */ position = get_random_position(game_board, 0); /* Place the pawn on the game board according tot he generated random position. */ place_pawn(local_game_board, &position, player_pseudo_name); while(1){ message = receive_message(pawn_mq_id); switch ( message.message_type ){ case 8: { while ( available_moves > 0 ){ if ( game_board->round_in_progress != 1 ){ break; } /* Get the position where the pawn should be moved to. */ next_position = get_next_position(local_game_board, &position); /* Move the pawn and check if a flag is present in its new position. */ has_conquered_flag = move_pawn(local_game_board, &position, &next_position, player_pseudo_name); position = next_position; available_moves--; /* Inform the master process the pawn has moved. */ notify_movement(local_game_board, player_pseudo_name); if ( has_conquered_flag == 1 ){ available_moves = 0; /* Signal the master process a flag has been captured. */ signal_achievement(local_game_board, player_pseudo_name); } } }break; case 11: { exit(0); } case 12: { available_moves = max_moves; }break; } } }else{ /* Setup pawn's information. */ pawn.mq_id = pawn_mq_id; pawn.pid = pawn_pid; } return pawn; } /** * Sends a given message to all the pawns contained in the given pawn list. * * @param pawn_list A reference to the list of all the pawns the given message will be sent to. * @param pawn_count The amount of pawns in the given list. * @param message A reference to the message to send. */ void broadcast_message_to_pawns(pawn_t* pawn_list, unsigned int pawn_count, message_t* message){ unsigned int i; for ( i = 0 ; i < pawn_count ; i++ ){ send_message(pawn_list[i].mq_id, message); } } /** * Sends a message containing a plain numeric signal to all the pawns contained in the given pawn list. * * @param pawn_list A reference to the list of all the pawns the given signal will be sent to. * @param pawn_count The amount of pawns in the given list. * @param message A reference to the message to send. */ void broadcast_signal_to_pawns(pawn_t* pawn_list, unsigned int pawn_count, unsigned short type){ message_t message; unsigned int i; /* Prepare the message properties. */ message.message_type = type; message.player_pseudo_name = 0; for ( i = 0 ; i < pawn_count ; i++ ){ send_message(pawn_list[i].mq_id, &message); } }
C
#include <stdio.h> #include <sys/stat.h> int main (void) { if (mkfifo("minhaFifo", S_IRUSR | S_IWUSR) == 0) { puts ("FIFO criada com sucesso"); } if (mkfifo("minhaFifo2", S_IRUSR | S_IWUSR) == 0) { puts ("FIFO criada com sucesso"); } if (mkfifo("minhaFifo3", S_IRUSR | S_IWUSR) == 0) { puts ("FIFO criada com sucesso"); } }
C
# include <stdio.h> # pragma warning (disable:4996) // Լ Ű 迭 (迭 ũ ) void print_array(int arr[], int size) { for (int i = 0; i < size; i++) printf("%d ", arr[i]); printf("\n"); } // ϴ Լ // ־ ׸ ϴ void sort_array(int arr[], int size) { int index_min, tmp; for (int i = 0; i < size - 1; i++) { index_min = i; for (int j = i + 1; j < size; j++) { if (arr[index_min] > arr[j]) index_min = j; } if (i != index_min) { tmp = arr[i]; arr[i] = arr[index_min]; arr[index_min] = tmp; } printf("i = %d ϶ : ", i); print_array(arr, size); } } int main(void) { int data[] = { 51,31,28,17,46 }; int size = sizeof(data) / sizeof(data[0]); printf("\n"); sort_array(data, size); }
C
/* x_unmou.c - x_unmou */ #include <conf.h> #include <kernel.h> #include <io.h> #include <name.h> /*------------------------------------------------------------------------ * x_unmou - (command unmount) remove a prefix from the namespace table *------------------------------------------------------------------------ */ COMMAND x_unmou(stdin, stdout, stderr, nargs, args) int stdin, stdout, stderr, nargs; char *args[]; { if (nargs != 2) { fprintf(stderr, "use: unmount prefix\n"); return(SYSERR); } if (unmount(args[1]) == SYSERR) { fprintf(stderr, "unmount fails.\n"); return(SYSERR); } return(OK); }
C
#ifndef _COMPRESS_H_ #define _COMPRESS_H_ // 256 ascii character + 1 pseudo-EOF #define MAX_LEAF 257 #include <stdbool.h> #include <stdio.h> // leaf node. typedef struct h_node { int id; // ASCII code. pseudo-EOF is 256 int count; // times of character char code[30]; // Huffman code struct h_node* parent; struct h_node* left; struct h_node* right; }h_node; // some global information. typedef struct info { h_node* leaf_node[MAX_LEAF]; int size; h_node* root; }info; // map table, from character ascii code to huffman code. typedef struct table { int id; char* code; }table; // compression. // open input file. FILE* open_file(int argc, char* path); // count the number of times every character occurs. int count_times(FILE* file, int* count); // deal with empty file. void empty_file(char* arg); // use character and its times to create leaf node. void create_leaf(info* base, int* count); // use leaf nodes to create Huffman tree. void create_tree(info* base); // create map table. void create_table(h_node* node, bool left, table* tb); // get character's huffman code. void get_huffman_code(info* base, table* tb); // compress file from comand line and output compressed file void compress(FILE* file, char* path, table* tb, info* base); // find huffman code from map table by ascii code. char* find(int ch, int size, table* tb); // internal functions : int empty(h_node** arr, int size); int top(h_node** arr, int size); void pop(h_node** arr, int index); void push(h_node* node, h_node** arr, int size); // decompression // rebuild huffman tree from compressed file. void rebuild_tree(h_node* root, FILE* file); // decompression from compressed file use huffman tree. void decompress(h_node* root, char* path, FILE* file); #endif // _COMPRESS_H_
C
#include "bmp.h" #include <stdio.h> #include <stdlib.h> #include <sys/time.h> //Print info about how to use the app void usage(){ printf( "Usage: progName <infile> <outfile> [parallel] [threshold] [filter]\n" ); printf( "<infile> = Input bmp file\n" ); printf( "<outfile> = Output bmp file\n" ); } int main(int argc, char **argv) { if (argc < 3) { usage(); return 1; } char *inputFileName = argv[1]; char *outputFileName = argv[2]; Image *image = (Image *) malloc(sizeof(Image)); if (image == NULL) { fprintf(stderr, "Out of memory\n"); return(-1); } if (ImageLoad(inputFileName, image)==-1) { printf ("Can't read the image\n"); return -1; } struct timeval startTimeOfDay, finishTimeOfDay; gettimeofday (&startTimeOfDay, NULL); printf("Apply Filter\n"); int x,y; for (y=0;y<3*image->sizeY;y+=3) { for (x=0;x<3*image->sizeX;x+=3) { int i = y*image->sizeX + x; //image->data[i] = 0; int tmp = image->data[i]; image->data[i] = image->data[i+1]; image->data[i+2] = image->data[i+2]; image->data[i+1] = tmp; } } //for each pixle for (y=0;y<3*image->sizeY;y+=3) { for (x=0;x<3*image->sizeX;x+=3){ int *intensityCount = (int *) malloc( 20); int *averageR = (int *) malloc( 20); int *averageG = (int *) malloc( 20); int *averageB = (int *) malloc( 20); int tempX, tempY, finX, finY; if(y < 15){ tempY = 0; } else{ tempY = y - 15; } if(x < 15){ tempX = 0; } else{ tempX = x - 15; } if(y > (3*image->sizeY - 15)){ finY = 3*image->sizeY; } else{ finY = y + 15; } if(x > (3*image->sizeX - 15)){ finX = 3*image->sizeX; } else{ finX = x + 15; } int x2, y2; //for each pixle with in radius 5 //for loop is broken for(y2 = tempY; y2 < finY; y2 += 3){ for(x2 = tempX; x2 < finX; x2 +=3){ int i = y2*image->sizeX + x2; int curIntensity = (int)(((double)(image->data[i] + image->data[i + 1] + image->data[i + 2])/3)/255) * 20; intensityCount[curIntensity]++; averageR[curIntensity] += image->data[i]; averageG[curIntensity] += image->data[i+1]; averageB[curIntensity] += image->data[i+2]; } } int k; int maxIndex, curMax; curMax = 0; for(k=0;k<20;++k){ if(intensityCount[k] > curMax){ curMax = intensityCount[k]; maxIndex = k; } } int i = y*image->sizeX + x; image->data[i] = averageR[maxIndex]/curMax; image->data[i + 1] = averageB[maxIndex]/curMax; image->data[i + 2] = averageG[maxIndex]/curMax; free(intensityCount); free(averageB); free(averageG); free(averageR); } } if (ImageSave(outputFileName, image)==-1) return(-1); free(image); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* split.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: user42 <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/08 23:21:54 by user42 #+# #+# */ /* Updated: 2021/03/08 23:21:56 by user42 ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/minishell.h" int is_sep(char c, t_a *a) { int i; i = 0; while (a->sep[i]) { if (c == a->sep[i]) return (1); i++; } return (0); } void ft_split_sh(t_a *a) { int i; int k; int counter; i = 0; k = 0; a->raw = malloc(sizeof(*a->raw) * (1 + 1000)); //revenir dessus avec la meme fonction ft_split_sh mais sans malloc pour obtenir k if (!a->raw) return ; a->backup = a->line; a->raw[k].str = 0; a->raw[k].type = 0; while (a->line[i]) { a->sep = a->backup_sep; if (a->line[i] == ' ') { while (is_sep(a->line[i + 1], a) && a->line[i] == ' ') //on avance sur ' ' et on stop au sep diff de ' ' ou au dernier ' ' (a->line)++; } //ici on se retrouve donc systematiquement sur le premier element if (a->line[i] == ' ' || !is_sep(a->line[i], a)) // si c'est pas un sep, le sep est un espace; { a->raw[k].type = ' '; if (a->line[0] == ' ') (a->line)++; if (a->line[0] == '\0') //si on fini par un espace on ne malloc rien break ; counter = 0; while (!is_sep(a->line[counter], a) && a->line[counter] != '\0') counter++; a->raw[k].str = malloc(sizeof(char) * (counter + 1)); if (!a->raw[k].str) set_backup_and_exit(a, "Error\nMalloc Failed\n"); while (counter > 0) { a->raw[k].str[i] = a->line[0]; i++; counter--; (a->line)++; } a->raw[k].str[i] = 0; i = 0; } else if (ft_strlen(a->line) > 1 && a->line[0] == '>' && a->line[1] == '>') { a->raw[k].type = '#'; a->raw[k].str = malloc(sizeof(char) * 3); a->raw[k].str[0] = '>'; a->raw[k].str[1] = '>'; a->raw[k].str[2] = 0; (a->line)++; (a->line)++; } else if (a->line[i] == '|' || a->line[i] == ';' || a->line[i] == '<' || a->line[i] == '>') { a->raw[k].type = a->line[i]; a->raw[k].str = malloc(sizeof(char) * 2); a->raw[k].str[0] = a->line[i]; a->raw[k].str[1] = 0; (a->line)++; } else if (a->line[i] == '"' || a->line[i] == '\'') { a->raw[k].type = a->line[i]; if (a->line[i] == '"') { (a->line)++; counter = 0; while (a->line[counter] != '"' && a->line[counter] != '\0') counter++; if (a->line[counter] == '\0') set_backup_and_exit(a, "Error\nEnding quote missing\n"); a->raw[k].str = malloc(sizeof(char) * (counter + 1)); if (!a->raw[k].str) set_backup_and_exit(a, "Error\nMalloc Failed\n"); while (counter > 0) { a->raw[k].str[i] = a->line[0]; i++; counter--; (a->line)++; } a->raw[k].str[i] = 0; i = 0; } else //a->line[i] == '\'' { (a->line)++; counter = 0; while (a->line[counter] != '\'' && a->line[counter] != '\0') counter++; if (a->line[counter] == '\0') set_backup_and_exit(a, "Error\nEnding quote missing\n"); a->raw[k].str = malloc(sizeof(char) * (counter + 1)); if (!a->raw[k].str) set_backup_and_exit(a, "Error\nMalloc Failed\n"); while (counter > 0) { a->raw[k].str[i] = a->line[0]; i++; counter--; (a->line)++; } a->raw[k].str[i] = 0; i = 0; } (a->line)++; //on depasse la deuxieme quote } else { write(1, "@@@@@@@@@@", 10);//erreur si on imprime des @ } k++; a->raw[k].str = 0; //on termine toujours pas un 0 pour simplement free jusqu'au dernier 0 a->raw[k].type = 0; } a->sep = a->backup_sep; a->line = a->backup; }
C
#include <stdio.h> int main() { void *a; int da = 1; a = (void *)&da; printf("da=%d\n", da); printf("a=%d\n", *(int *)a); }
C
// // Created by Thiago on 03/04/2021. // #ifndef ALGORITMO_TCC_2_OPTIMAL_H #define ALGORITMO_TCC_2_OPTIMAL_H #include "../data_structures/solution.h" #include "../data_structures/optmized-matrix.h" #include "../utils/distance.h" /** * Realiza o movimento 2-Optimal em uma solução, que consiste em retirar duas arestas não-adjacentes do grafo e * reconstruir o ciclo hamiltoniano novamente. Uma aresta A, indicado por um número inteiro N, liga os vértices N e N+1 * @param solution - Ponteiro para a Solução * @param distance_matrix - Ponteiro para a matriz de distâncias. * @param edge_1 - Primeira aresta do grafo. * @param edge_2 - Segunda aresta do grafo. * @throws Erro caso as arestas sejam adjacentes (exemplo: 0 e 1) * @example * two_optimal_move(solution, distance_matrix, 0, 2) // Remove as arestas que ligam o vértice 0 ao 1, e a aresta que * liga o vértice 2 ao 3 */ void two_optimal_move(Solution &solution, const int * distance_matrix, size_t edge_1, size_t edge_2, int size = SIZE); /** * Realiza o movimento 2-Optimal em uma solução utilizando arestas aleatórias * @param solution - Ponteiro para a Solução * @param distance_matrix - Ponteiro para a matriz de distâncias. */ void two_optimal_move(Solution &solution, const int * distance_matrix, int size = SIZE); /** * Realiza a busca local 2-Optimal, retornando a solução com a melhor FO * @param solution - Ponteiro para a Solução * @param distance_matrix - Ponteiro para a matriz de distâncias. * @return A solução com melhor FO */ Solution two_optimal(Solution &solution, const int * distance_matrix, int size = SIZE, int strategy = BEST_IMPROVEMENT); /** * Realiza a busca local 2-Optimal com a estrutura em matriz otimizada, retornando a solução com a melhor FO * @param matriz_distancias * @param optimized_matrix * @param strategy * @return */ Solution two_optimal_2(const int * matriz_distancias, OptimizedMatrix &optimized_matrix, int strategy); /** * Constrói e retorna uma solução vizinha aplicando o movimento 2-optimal em posições definidas * @param solution - Ponteiro para a Solução * @param distance_matrix - Ponteiro para a matriz de distâncias. * @param edge_1 - Primeira aresta do grafo. * @param edge_2 - Segunda aresta do grafo. * @return Uma solução vizinha construída com o movimento 2-optimal */ Solution build_two_optimal(Solution solution, const int * distance_matrix, size_t edge_1, size_t edge_2, int size = SIZE); OptimizedSolution build_two_optimal(OptimizedMatrix optimized_matrix, const int * distance_matrix, int vertex_1, int vertex_2); /** * Constrói e retorna uma solução vizinha aplicando o movimento 2-optimal em posições aleatórias * @param solution - Ponteiro para a Solução * @param distance_matrix - Ponteiro para a matriz de distâncias. * @return Uma solução vizinha construída com o movimento 2-optimal */ Solution build_two_optimal(Solution solution, const int * distance_matrix, int size = SIZE); int test_two_optimal(); #endif //ALGORITMO_TCC_2_OPTIMAL_H
C
#include <stdio.h> #include <string.h> int main(){ char abc[] = "When the going gets tough, the tough stay put!"; char check[20]; int count = 0; scanf("%[^\n]",check); int i,j,iscorr; /*for(i=0;i<strlen(abc);i++){ if(check[i] <= 'Z') check[i] += 22; }*/ for(i = 0;i<strlen(abc);i++){ iscorr = 1; for(j = 0;j<strlen(check);j++){ if(abc[i+j] != check[j]) iscorr = 0; //printf("compare %c|%c iscorr == %d",abc[i+j],check[j],iscorr); if(iscorr == 0) break; } //printf("\n"); if(iscorr == 1)count ++; } printf("%d",count); }
C
#include <stdio.h> /* 定义一个double a[3][4]; (1)打印第一维数组每个元素的起始地址 (2)打印第二维数组每个元素的起始地址 (3)打印第一维数组的地址地址 (4)从键盘输入数组,输出每个元素的内容 (5)计算数组的大小,并输出 */ int main() { int a[4][2]={1,2,3,4,5,6,7,8}; int i,j; printf("第一维数组每个元素的起始地址:\n"); for(i=0;i<4;i++) { printf("&a[%d]=%p\n",i,&a[i]); } printf("\n===========================================\n"); for(i=0;i<4;i++) { printf("a+%d =%p\n",i,a+i); } printf("第二维数组每个元素的起始地址:\n"); for(i=0;i<4;i++) { for(j=0;j<2;j++) { printf("&a[%d][%d]=%p\t",i,j,&a[i][j]); } printf("\n"); } printf("\n===========================================\n"); for(i=0;i<4;i++) { for(j=0;j<2;j++) { printf("a[%d]+%d=%p\t",i,j,a[i]+j); } printf("\n"); } printf("第一维数组的起始地址:"); printf("&a = %p,&a+1=%p\n",&a,&a+1); return 0; }
C
typedef struct avl_node { void *data; //pointer to arbitrary data struct avl_node *left; //left pointer struct avl_node *right; //right pointer int height; //height of leaf nodes are 0; } avl_node; typedef struct avl_tree { int (*cmp_function)(void *,void *); //pointer to a function that will compare two avl_nodes void (*print_node)(avl_node *); //pointer to function that will print a given avl node struct avl_node *root; // pointer to the root of the avl tree } avl_tree; avl_tree *init_tree( int (*cmp_function)(void *,void *), void (*print_node)(avl_node *)); //inits the avl tree void print_tree(avl_tree *tree); //prints the avl tree void free_tree(avl_tree *tree); //frees the entire avl_tree int check_tree(avl_tree *tree); //checks to see if the avl_tree is correct int max_width(avl_tree *tree); avl_node *insert_tree(avl_tree *tree,void *data); //inserts data into the tree avl_node *search_tree(avl_tree *tree, void *data); void delete_tree(avl_tree *tree, void *data);
C
#include <stdio.h> #include <stdlib.h> long int* Load_File(char *Filename, int* Size){ FILE* inf = fopen(Filename, "r"); fscanf(inf, "%d", Size); //Gets size from file long int* Array = malloc(sizeof(long int) * (*Size)); //Allocs array for (int i = 0; i < *Size; i++){ //Fills array with file fscanf(inf, "%ld", &Array[i]); } fclose(inf); return Array; } int Save_File(char *Filename, long int* Array, int Size){ FILE* outf = fopen(Filename, "w"); int count = 0; fprintf(outf, "%ld\n", Size); for (int i = 0; i < Size; i++){ fprintf(outf, "%ld\n", Array[i]); count -= -1; } fclose(outf); free(Array); return count; }
C
//a program to convert celsius to fahrenheit #include <stdio.h> int main (void) { float temp_f; //float for more precision + this variable will represent the temperature in fahrenheit float temp_c; //float for more precision + this variable will represent the temperature in celsius printf ("Please enter the temperature in Celsius: "); //request that user input temperature in Celsius scanf ("%f", &temp_c); //assigns the users input to variable temp_c temp_f = (1.8 * temp_c) + 32; //takes the users input and converts it to fahrenheit printf ("The temperature in Fahrenheit is %f.\n", temp_f); //displays the conversion to the user return 0; }
C
// // main.c // identity matrix // // Created by Pushpa Jain on 20/01/21. // Copyright © 2021 Pushpa Jain. All rights reserved. // #include <stdio.h> void main() { int i,j,a[3][3],flag=1; printf("enter matrix values"); for(i=0; i<3; i++) { for(j=0; j<3; j++) { scanf("%d",&a[i][j]); } } for(i=0; i<3; i++) { for(j=0; j<3; j++) { if(i==j&&a[i][j]==1) { flag=1; } else if(i!=j&&a[i][j]==0) { flag=1; } else { flag=0; } } } if(flag==1) { printf("identity matrix"); } else { printf("not a identity"); } printf("\n"); }
C
#include "../ft_printf.h" char *ft_itoa_hexa(t_tab *tab, char *s, unsigned long n, int base) { int l; l = 0; if (n == 0) { s[l] = '0'; l++; } while (n > 0) { if (base > 10 && (n % base >= 10)) { if (tab->hexa == 0) s[l] = (n % base) + 87; else s[l] = (n % base) + 87 - 32; } else s[l] = ((n % base) + '0'); l++; n = n / base; } s[l] = '\0'; return (s); } int ft_len_n_base(unsigned int n, int base) { int i; i = 0; if (n == 0) { i += 1; return (i); } while (n > 0) { i++; n /= base; } return (i); } void ft_form_hexa(t_tab *tab) { unsigned int j; int len; char *num; j = va_arg(tab->args, unsigned int); len = ft_len_n_base(j, 16); num = (char *)malloc(sizeof(char) * (len + 1)); if (!num) return ; num = ft_itoa_hexa(tab, num, j, 16); while (num && len-- > 0) tab->len += write(1, &num[len], 1); free(num); } char *ft_unsigned_itoa(unsigned int n) { char *s; int len; len = ft_len_n_base(n, 10); s = (char *)malloc(sizeof(char) * (len + 1)); if (s == NULL) return (NULL); s[len] = '\0'; len--; while (len >= 0) { s[len] = ((n % 10) + '0'); n = n / 10; len--; } return (s); }
C
#include<stdio.h> int fact(); int main() { int n; printf("enter any number"); scanf_s("%d", &n); printf("The factorial of %d is %d", n, fact(n)); getch(); return 0; } int fact(int a) { if (a > 1) return a * fact(a - 1); else return 1; }
C
#include <stdio.h> int cnt(int n){ if(n <= 0) return 0; return n*n+cnt(n-1); } int main(void){ int n; scanf("%d", &n); printf("%d\n", cnt(n)); return 0; }
C
#pragma once struct FCoordinate; struct ICoordinate { int x = 0; int y = 0; inline ICoordinate add(const ICoordinate other) const { return ICoordinate{this->x + other.x, this->y + other.y}; } inline ICoordinate operator+(const ICoordinate other) const { return this->add(other); } }; struct FCoordinate { float x = 0; float y = 0; inline FCoordinate add(const FCoordinate other) const { return FCoordinate{this->x + other.x, this->y + other.y}; } inline FCoordinate operator+(const FCoordinate other) const { return this->add(other); } static inline FCoordinate fromInt(const ICoordinate& other) { FCoordinate res; res.x = (float)other.x; res.y = (float)other.y; return res; } };
C
#include <stdio.h> #include <string.h> #include <ctype.h> #include <stdlib.h> #include <curl/curl.h> #include <json/json.h> #define SPACE ' ' //Function used by libcurl to allocate memory to data received from the HTTP response struct MemoryStruct { char *memory; size_t size; }; static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct MemoryStruct *mem = (struct MemoryStruct *)userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if(mem->memory == NULL) { /* out of memory! */ printf("not enough memory (realloc returned NULL)\n"); return 0; } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } int main () { char str[1000], *start, pv, location[1000],youtube[1000],songs[1000],cal[100],search[100],instance_type[1000],instance_name[1000],phone_number[1000],message[1000],s3_folder[100],s3_bucket_name[100]; int c, d, len=0; //Getting home directory out of configuration file FILE *fp; fp=fopen("config","rw"); if(fp == NULL) { fprintf(stderr,"Unable to open config file\n"); return 1; } int i=0; char cfg_line[1000]; cfg_line[i]=fgetc(fp); i++; while(cfg_line[i-1]!='\n'&&cfg_line[i-1]!=EOF) { cfg_line[i]=fgetc(fp); i++; } cfg_line[i-1]='\0'; char * HOME_DIR = strchr(cfg_line, '='); HOME_DIR = HOME_DIR+2; //Get preferred media player from config file i=0; char media_player[1000]; media_player[i]=fgetc(fp); i++; while(media_player[i-1]!='\n'&&media_player[i-1]!=EOF) { media_player[i]=fgetc(fp); i++; } media_player[i-1]='\0'; char * M_P = strchr(media_player, '='); M_P = M_P+2; //----------------------- //Get preferred Webbrowser out of config file i=0; char webbrowser[1000]; webbrowser[i]=fgetc(fp); i++; while(webbrowser[i-1]!='\n'&&webbrowser[i-1]!=EOF) { webbrowser[i]=fgetc(fp); i++; } webbrowser[i-1]='\0'; char * WebBrowser = strchr(webbrowser, '='); WebBrowser = WebBrowser+2; fclose(fp); //Inform user about preferred media player, as to config file char preferred_media_player[1000]; sprintf(preferred_media_player,"say Your preferred media player is %s",M_P); system(preferred_media_player); //Inform user about preferred web browser, as to config file char preferred_webbrowser[1000]; sprintf(preferred_webbrowser,"say Your preferred webbrowser is %s",WebBrowser); system(preferred_webbrowser); do { int i1=0,j1=0; system("tput setaf 3; echo How can I help you?"); char * x="Hey, How can I help you?"; system("tput setaf 6"); //printf("%s\n",x); fgets (str, 1000, stdin); if ((strlen(str)>0) && (str[strlen (str) - 1] == '\n')) str[strlen (str) - 1] = '\0'; //change uppercase letters in str to lowercase for convenience int i, s = strlen(str); for (i = 0; i < s; i++) str[i] = tolower(str[i]); char buf[9999]; char buffer[9999]; char buff[9999]; char weather[9999]; char song[9999]; //--------------------------------------------------------------------------------------------------------------------- //Artificial Intelligence char example[1000]; strcpy(example,str); int compare[10]; char split[10][10]={0}; int k=0,n,j=0,w=0,g=0,go=0,me=0,res=0,c=0,u=0,h=0,temp=0,hos=0,ins=0,wa=0,db=0,yt=0,s3=0; char result[20]; int weather_score=0,greeting_score=0,media_score=0,google_score=0,youtube_score=0,help_score=0,hospital_score=0,restaurant_score=0,instance_score=0,whatsapp_score=0,rds_score=0,s3_score=0; //for weather--------------- char *weather_class[10][10]={{"please","show","outside","condition"}, {"how"," ","weather","today"}, {"weather"," ","desired","place"}}; //for Ec2 instance------------ char *instance_class[10][10]={{"please","launch","an","ec2","instance"}, {"launch"," ","ec2","instance"}, {"create"," ","ec2","instance"}}; //for S3 bucket------------ char *s3_class[10][10]={{"please","create","a","s3","bucket"}, {"create"," ","s3","bucket"}, {"launch"," ","s3","bucket"}}; //for Whatsapp----------- char *whatsapp_class[10][10]={{"please","a","write","whatsapp","message"}, {"type"," ","whatsapp","message"}, {"type"," ","whatsapp","msg"}}; //for RDS----------- char *rds_class[10][10]={{"please","launch","a","rds","instance"}, {"Launch"," ","rds","instance"}, {"create"," ","database","instance"}}; //for greeting-------------- char *greeting_class[10][10]={{"hey","how","are","you"}, {"how"," "," ","doing"}, {"hello","there"," "," "}}; //for google---------------- char *google_class[10][10]={{"open","google","for","me"}, {"I","want","search","browse"}, {"can","you","open","google"}}; //for media----------------- char *media_class[10][10]={{"can","you","list","media"}, {"video","listen","play","music"}, {"play","something","nice","song "}}; //for Restaurant char *restaurant_class[10][10]={{"Please","find","some","restaurants"}, {"Find"," ","some","restaurants"}, {"Show"," "," ","restaurants"}, {"Find","places","to","eat"}}; //for Hospital char *hospital_class[10][10]={{"Please","find","some","hospitals"}, {"Find"," ","some","hospitals"}, {"Show"," "," ","hospitals"}, {"hospitals","near","","me"}}; //for youtube---------------- char *youtube_class[10][10]={{"open","youtube","for","me"}, {"I","want","search","youtube"}, {"can","you","open","youtube"}}; for(int i=0;i<strlen(example);i++) { if(example[i]==' ') { if(example[i+1]!=' ') { split[k][j]='\0'; j=0; k++; } continue; } else { split[k][j++]=example[i]; } } split[k][j]='\0'; weather_score=0,greeting_score=0,media_score=0,google_score=0,youtube_score=0,help_score=0,hospital_score=0,restaurant_score=0,instance_score=0,whatsapp_score=0,rds_score=0; //For Weather--------------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(weather_class[b][c],split[v])== 0) { w++; } } } weather_score=w; //for ec2---- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(instance_class[b][c],split[v])== 0) { ins++; } } } instance_score=ins; //for s3---- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(s3_class[b][c],split[v])== 0) { s3++; } } } s3_score=s3; //for youtube---- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(youtube_class[b][c],split[v])== 0) { yt++; } } } youtube_score=yt; //for Whatsapp---- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(whatsapp_class[b][c],split[v])== 0) { wa++; } } } whatsapp_score=wa; //For Greeting----------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(greeting_class[b][c],split[v])== 0) { g++; } } } greeting_score=g; //For RDS----------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(rds_class[b][c],split[v])== 0) { db++; } } } rds_score=db; //For Google------------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(google_class[b][c],split[v])== 0) { go++; } } } google_score=go; //For Media--------------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(media_class[b][c],split[v])== 0) { me++; } } } media_score=me; //For Restaurant----------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(restaurant_class[b][c],split[v])== 0) { res++; } } } restaurant_score=res; //For Hospital----------------------------------- for(int v=0;v<=k;v++) for(int b=0;b< 3 ;b++) { for(int c=0;c< 4 ;c++) { if(strcmp(hospital_class[b][c],split[v])== 0) { hos++; } } } hospital_score=hos; j1=0; int k1=0; int score[10]={whatsapp_score,instance_score,hospital_score,greeting_score,google_score,restaurant_score,weather_score,rds_score,youtube_score,s3_score}; for(i1=0;i1<=9;i1++) { //printf("%d",score[i1]); if(k1<=score[i1]) {k1=score[i1]; j1=i1; //printf("%d",j1); } } if(j1==0){ strcpy(result,"whatsapp"); } else if(j1==1) strcpy(result,"instance"); else if(j1==2) strcpy(result,"hospital"); else if(j1==3) strcpy(result,"greeting"); else if(j1==4) strcpy(result,"google"); else if(j1==5) strcpy(result,"restaurant"); else if(j1==6) strcpy(result,"weather"); else if(j1==7) strcpy(result,"rds"); else if(j1==8) strcpy(result,"youtube"); else if(j1==9) strcpy(result,"s3"); if((strcmp(result, "greeting") == 0)) { system("say I am good"); printf("I am good \n"); } else if(strcmp(str, "firefox") == 0 || strcmp(str, "open firefox") == 0 || strcmp(str,"run firefox") == 0 || strcmp(str, "start firefox") == 0) { system("say opening firefox"); system("firefox"); } else if((strcmp(str, "vlc") == 0) || (strcmp(str, "open vlc") == 0) || (strcmp(str,"run vlc") == 0) || (strcmp(str, "start vlc") == 0)) { system("say opening vlc"); system("vlc"); } // Weather else if((strcmp(result, "weather") == 0)) { printf("Please enter location to get weather forecast \n" ); fgets (location, 1000, stdin); system("say showing weather"); sprintf(weather,"curl wttr.in/\%s",location); system(weather); } //instance else if((strcmp(result,"instance")==0)) { system("tput bold; echo -----------------------------------------------------------------------------------------Input------------------------------------------------------------------------------------------"); system("tput bold; echo Enter the instance type"); fgets (instance_type, 1000, stdin); printf("\n"); system("tput bold; echo Enter the instance name"); fgets (instance_name, 1000, stdin); printf("\n"); sprintf(buf, "%s http://13.127.98.80/cgi-bin/testec2.py?j=t2.micro&l=%s", WebBrowser,instance_name); system(buf); } //S3 else if((strcmp(result,"s3")==0)) { system("tput bold; echo -----------------------------------------------------------------------------------------Input------------------------------------------------------------------------------------------"); system("tput bold; echo Enter the bucket name"); fgets (s3_bucket_name, 100, stdin); printf("\n"); sprintf(buf,"aws s3api create-bucket --create-bucket-configuration LocationConstraint=ap-south-1 --query {\"Location:Location\"} --output text --bucket %s",s3_bucket_name); system(buf); /*printf("\n\nIf you want to sync the bucket with a folder press1 otherwise press2\n"); int choice; scanf("%d",&choice); if(choice==1){ system("tput bold; echo Enter the folder path"); fgets (s3_folder, 100, stdin); printf("\n"); buf="aws s3 sync "+s3_folder+" s3://"+s3_bucket_name; system(buf); system("echo Synced Successfully"); }*/ } //Whatsapp else if((strcmp(result,"whatsapp")==0)) { system("tput bold; echo -----------------------------------------------------------------------------------------Input------------------------------------------------------------------------------------------"); printf("Enter the phone number "); fgets(phone_number, 1000, stdin); printf("\n"); printf("Enter the message "); fgets(message,1000,stdin); system("say writing the message"); sprintf(buf, "%s http://web.whatsapp.com/send?phone=%s&text=%s", WebBrowser,phone_number,message); system(buf); } //RDS else if((strcmp(result,"rds")==0)) { system("tput bold; echo Wait for few seconds RDS instance is launching"); sprintf(buf, "%s http://65.0.74.63/cgi-bin/rdstest.py", WebBrowser); system(buf); } else if((strcmp(result,"youtube")==0)) { fgets (search, 1000, stdin); //------------------------------------------------- start = malloc(strlen(str)+1); pv = 0;//previous character for(d=c=0; search[c]; ++c) { if(search[c] == SPACE) { if(pv != SPACE) start[d++] = '+'; pv = SPACE; } else { pv = start[d++] = search[c]; } } start[d] = '\0'; //-------------------------------- sprintf(buff,"say searching youtube for \%s",search); system(buff); sprintf(buf, "%s https://www.youtube.com/results?search_query=\%s", WebBrowser,start); system(buf); } else if((strcmp(result, "media") == 0)) { system("say here are the list of available media"); printf("Here are the list of available media\n"); char * sys_cmd1; char sys_cmd[1000]; sys_cmd1 = "ls "; sprintf(sys_cmd,"%s%s%s",sys_cmd1,HOME_DIR,"media/"); system(sys_cmd); system("say which media do you want me to play"); printf("Which media do you want me to play? \n"); fgets (songs, 1000, stdin); sprintf(song,"%s %smedia/\%s",M_P,HOME_DIR,songs); system(song); } //Restaurant else if((strcmp(result,"restaurant"))==0) { find_restaurants(); } //Hospital else if((strcmp(result,"hospital"))==0) { find_hospitals(); } //Help else if((strcmp(str, "help") == 0)) { char * help1 = "less "; char help[1000]; sprintf(help,"%s%s%s",help1,HOME_DIR,"help.txt"); system(help); } else if((strcmp(result, "google") == 0)) { /*if( (google_score==0) && (greeting_score==0) && (weather_score==0) && (media_score==0)) { // fgets (search, 1000, stdin); //------------------------------------------------- start = malloc(strlen(str)+1); pv = 0;//previous character for(d=c=0; str[c]; ++c) { if(str[c] == SPACE) { if(pv != SPACE) start[d++] = '+'; pv = SPACE; } else { pv = start[d++] = str[c]; } } start[d] = '\0'; //-------------------------------- sprintf(buff,"say Do you mean \%s",str); system(buff); sprintf(buf, "%s https://www.google.co.in/search?q=%s&ie=utf-8&oe=utf-8&client=firefox-b-ab&gfe_rd=cr&ei=zkWgWc3fNeXI8AeCr5LYBw ",WebBrowser, start); system(buf); } else {*/ printf("What can I search for you on Google?\n"); fgets (search, 1000, stdin); //------------------------------------------------- start = malloc(strlen(str)+1); pv = 0;//previous character for(d=c=0; search[c]; ++c) { if(search[c] == SPACE) { if(pv != SPACE) start[d++] = '+'; pv = SPACE; } else { pv = start[d++] = search[c]; } } start[d] = '\0'; //-------------------------------- sprintf(buf, "%s https://www.google.co.in/search?q=%s",WebBrowser, start); system(buf); } } while((strcmp(str,"stop")!=0)); return 0; }
C
#include <stdlib.h> #include <stdio.h> #include <sys/sem.h> #include <sys/ipc.h> #include <sys/types.h> int main(int argc, char **argv) { key_t key = ftok("/main", 1); int semId = semget(key, 1, IPC_CREAT | 0666); struct sembuf *sops; sops->sem_num = 0; sops->sem_op = -1; sops->sem_flg = IPC_NOWAIT; pid_t child = fork(); if (child == 0) { semop(semId, sops, 1); printf("%d\n", semctl(semId, 0, GETVAL)); } else { sops->sem_op = 1; semop(semId, sops, 1); printf("%d\n", semctl(semId, 0, GETVAL)); } semctl(semId, 1, IPC_RMID, NULL); return 0; }
C
/* * strUtil.c -- * * Copyright 1989 Regents of the University of California * Permission to use, copy, modify, and distribute this * software and its documentation for any purpose and without * fee is hereby granted, provided that the above copyright * notice appear in all copies. The University of California * makes no representations about the suitability of this * software for any purpose. It is provided "as is" without * express or implied warranty. */ #ifndef lint static char rcsid[] = "$Header$ SPRITE (Berkeley)"; #endif /* not lint */ #include <ctype.h> #include <strings.h> #include "sprite.h" #include "fs.h" /* *---------------------------------------------------------------------- * * ScanLine -- * * Copy first line in ps1 to s2 replacing \n with \0. * Change ps1 to point to the 1st character of second line. * * Results: * NIL if no line is found s2 otherwise. * * Side effects: * ps1 points to next line. * *---------------------------------------------------------------------- */ char * ScanLine(ps1, s2) char **ps1, *s2; { char *s1, *retstr; retstr = s2; s1 = *ps1; while ( *s1 != '\0' && *s1 != '\n' ) { *s2++ = *s1++; } if ( *s1 == '\0' ) { return ( (char *) NIL ); } *s2 = '\0'; *ps1 = s1+1; return ( retstr ); } /* *---------------------------------------------------------------------- * * ScanWord -- * * Copy first word in *ps1 to s2 (words are delimited by white space). * Change ps1 to point to the 2nd character after the first word * (i.e. skip over the delimiting whitespace). This allows ps1 and * s2 to initially point to the same character string. * * Results: * Returns s2 or NIL if no word is found. * * Side effects: * ps1 points to the first character after the delimiting whitespace. * *---------------------------------------------------------------------- */ char * ScanWord(ps1, s2) char **ps1, *s2; { char *s1, *retstr; retstr = s2; for ( s1 = *ps1; *s1 != '\0' && isspace(*s1); s1++ ) { } while ( *s1 != '\0' && !isspace(*s1) ) { *s2++ = *s1++; } if ( *s1 == '\0' ) { return ( (char *) NIL ); } *s2 = '\0'; *ps1 = s1+1; return ( retstr ); }
C
#include <string.h> #include <stdio.h> #include <stdbool.h> #include "debug.c" #include "memory.c" typedef bool Success; typedef struct string { const char* buffer; int lenght; } String; void string_from_buffer(String *s, const char* c) { s->buffer = c; s->lenght = strlen(c); } void string_from_char(String *s, const char c) { s->buffer = &c; s->lenght = 1; } void string_sub_into(String *s, String *out, int start, int end) { assert_not(start > end, "start is bigger than end"); assert_not(start < 0, "start is little than zero"); assert_not(end > s->lenght, "end is bigger than lenght of the s"); out->buffer = s->buffer + start; out->lenght = end - start; } void string_print(String *s) { for (int i = 0; i < s->lenght; ++i) { putchar(s->buffer[i]); } } char string_get(String *s, int index) { assert(index < s->lenght, "index is bigger than lenght"); return s->buffer[index]; } bool string_is_equal(String *s1, String *s2) { if (s1->lenght != s2->lenght) return false; for (int i = 0; i < s1->lenght; ++i) { if (s1->buffer[i] != s2->buffer[i]) return false; } return true; } int string_index_of(String *s, String *c) { int lenght = s->lenght - c->lenght + 1; for (int i = 0; i < lenght; ++i) { for (int j = 0; j < c->lenght; ++j) { if (s->buffer[i+j] != c->buffer[j]) { goto string_index_of_double_continue; } } return i; string_index_of_double_continue:; } return -1; } bool string_contains(String *s, String *c) { return string_index_of(s, c) != -1; } void string_foreach(String *s, void (*f)(char)) { for (int i = 0; i < s->lenght; ++i) { (*f)(s->buffer[i]); } } int string_count_of(String *s, String *c) { int lenght = s->lenght - c->lenght + 1; int count = 0; for (int i = 0; i < lenght; ++i) { for (int j = 0; j < c->lenght; ++j) { if (s->buffer[i+j] != c->buffer[j]) { goto string_index_of_double_continue; } } count++; string_index_of_double_continue:; } return count; } static int integer_pow(int i, int j) { int value = 1; for (int k = 0; k < j; ++k) { value *= i; } return value; } int string_to_int(String *s, Success *ok) { const int base = 10; // may change in the future const int offset_of_zero = 48; int value = 0; int value_of_digit = integer_pow(base, s->lenght-1); for (int i = 0; i < s->lenght; ++i) { int number = s->buffer[i] - offset_of_zero; if (!(number < base) || number < 0) { *ok = false; return value; } value += number * value_of_digit; value_of_digit /= base; } *ok = true; return value; } #define string_to_array_macro(s, array) array[s->lenght + 1]; string_to_array(s, array) void string_to_array(String *s, char array[]) { memcpy(array, s->buffer, s->lenght); array[s->lenght] = '\0'; } void string_add(String *s1, String *s2, String *out) { int lenght = s1->lenght + s2->lenght; char *buffer = mymalloc(lenght); memcpy(buffer , s1->buffer, s1->lenght); memcpy(buffer + s1->lenght, s2->buffer, s2->lenght); out->lenght = lenght; out->buffer = buffer; } void string_repeat(String *s, int times, String *out) { out->lenght = s->lenght * times; out->buffer = mymalloc(out->lenght); for (void *i = out->buffer; (size_t)i < times; i += s->lenght) { memcpy(i, s->buffer, s->lenght); } } void string_reverse(String *s, String *out) { } void string_from_int(String *out, int number) { } //mutable string typedef struct mut_string { char* buffer; int lenght; } MutString; void string_set(MutString *s, int index, char value) { assert(index < s->lenght, "index is bigger than lenght"); s->buffer[index] = value; } void string_free(String *s) { myfree(s->buffer); } String* string_as_unmutable(MutString *s) { return (String*) s; } /* MutString* string_as_mutable(String *s) { return (MutString*) s; } */ void test_add(void); void test_int(void); void test_repeat(void); int main(void) { test_add(); } void test_add(void) { String str; String str2; string_from_buffer(&str, "hello "); string_from_buffer(&str2, "world!"); String out; string_add(&str, &str2, &out); string_print(&out); } void test_repeat(void) { String str; string_from_buffer(&str, "asd "); String out; string_repeat(&str, 3, &out); string_print(&out); } void test_int(void) { String str; string_from_buffer(&str, "12a"); Success ok; printf("number: %i, success: %i\n", string_to_int(&str, &ok), ok); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* solve_tetri.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: svigouro <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2017/06/06 16:06:22 by svigouro #+# #+# */ /* Updated: 2017/06/06 18:53:23 by svigouro ### ########.fr */ /* */ /* ************************************************************************** */ #include "fillit.h" int inside_board(t_tetri *tetrimino, int size) { return ((tetrimino->offset / 11) + tetrimino->height <= size); } int end_of_line(t_tetri *tetrimino, int size) { return ((tetrimino->offset % 11) + tetrimino->width > size); } void next_line(t_tetri *tetrimino) { tetrimino->offset += 11 - (tetrimino->offset % 11); } int possible_move(__int128 board, t_tetri *tetrimino) { return ((board & (tetrimino->tetri >> tetrimino->offset)) == 0); } int solve_tetri(__int128 board, t_tetri *tetriminos, int size) { if (!tetriminos) return (1); while (inside_board(tetriminos, size)) { if (end_of_line(tetriminos, size)) next_line(tetriminos); else { if (possible_move(board, tetriminos)) { if (solve_tetri(( board | (tetriminos->tetri >> tetriminos->offset)), tetriminos->next, size)) return (1); } (tetriminos->offset)++; } } tetriminos->offset = 0; return (0); }
C
/* *208539270 yardenbakish *208983700 tamircohen1 * initialize.c * * This function initializes all of the neccessary data structures in order to implement the K-means algorithm. * The function's caller is the function first run by our C extension * The function passes along all of the data structures forward */ #include <stdio.h> #include <stdlib.h> #include "kmeans.h" /*exec initializes all of the necessary memory structures in order to execute the algorithm as well as converts the python objects to its equivalent C type objects *The function returns the final result * * if at any point memory allocation fails, we pass along all of our pointers to a function designed to * free any allocated memory thus far */ int* exec(int* centroids, double* frame, int K, int N, int d, int I) { int i = 0, j = 0, w = 0; int *c_res; double** observations = NULL; /*nxd matrix which contains the n points*/ /*we need to keep track if centroids change between iterations thus we allocate two centroids matrices*/ double **new_centroids = NULL; double** old_centroids = NULL; double** tmp = NULL; /*sizes is a helper array used to calculate the new centroid at the end of each iteration - at any point the i'th value is the number of observations assigned to the i'th cluster*/ int* sizes = NULL; sizes = calloc(K, sizeof(int)); if (sizes == NULL) freeArray_byFlag(frame, sizes, observations, new_centroids, old_centroids, tmp, K, 0); observations = calloc(N, sizeof(double *)); if (observations == NULL) freeArray_byFlag(frame, sizes, observations, new_centroids, old_centroids, tmp, K, 0); new_centroids = calloc(K, sizeof(double *)); if (new_centroids == NULL) freeArray_byFlag(frame, sizes, observations, new_centroids, old_centroids, tmp, K, 0); old_centroids = calloc(K, sizeof(double *)); if (old_centroids == NULL) freeArray_byFlag(frame, sizes, observations, new_centroids, old_centroids, tmp, K, 0); i = 0, j = 0; /*as learned in class, now observation is contiguous thanks to frame variable*/ for (i = 0; i < N; i++) { observations[i] = frame + i * d; } i = 0, j = 0; for (i = 0; i < K; i++) { w = centroids[i]; new_centroids[i] = calloc(d, sizeof(double)); if (new_centroids[i] == NULL) freeArray_byFlag(frame, sizes, observations, new_centroids, old_centroids, tmp, K, 0); old_centroids[i] = calloc(d, sizeof(double)); if (old_centroids[i] == NULL) freeArray_byFlag(frame, sizes, observations, new_centroids, old_centroids, tmp, K, 0); /*we copy the coordinates of the initial observations to the cluster matrices where w is an observation*/ for (j = 0; j < d; j++) { new_centroids[i][j] = observations[w][j]; old_centroids[i][j] = observations[w][j]; } } /*we call for iterate function upon completing the initialization of all data structures needed*/ c_res = iterate(K, N, d, I, observations, new_centroids, old_centroids, sizes, frame); /*return final result*/ return c_res; }
C
#include<stdio.h> // #include<string.h> void main(){ int arr[] = {12, 11, 13, 5, 6,8,8,40,12}; int pos=0,temp,temp2; int n = sizeof(arr)/sizeof(arr[0]); while(pos!=(n-1)){ pos=0; for(int i=0;i<n-1;i++){ temp = arr[i]; if(arr[i]>arr[i+1]){ arr[i]=arr[i+1]; arr[i+1]=temp; } else { pos++; } } } for(int k=0;k<n;k++) { printf("%d \n",arr[k]); } }
C
#include "tcpSvr.h" char *FindMessageTrailer(unsigned char *Buf, int len, unsigned char ch, int charset) { register int i; UCHAR *p = Buf+len,*pAscii; for(i=len; i>=0 ; i--,p--) { if(*p==ch){ int tLen = len - (p+1 - Buf); if(tLen) { if(charset == CHARSET_EBCDIC){ pAscii = (UCHAR *)malloc(tLen+1); EbcdicToAscii(p+1,pAscii,tLen); }else if(charset == CHARSET_IBM1388){ pAscii = (UCHAR *)malloc(tLen+1); IBM1388Decode(p+1,pAscii,&tLen); }else{ pAscii = p+1; } if(isBufferPrint((char*)pAscii,tLen)) { if(charset!=CHARSET_ASCII) { free(pAscii); } return (char*)p; } } } } return NULL; }
C
//+Dep3_prog1basico+// #incluide <studio.h> int main[] [ int a,b,c; printf ("\n escribe el valor de a"); scanf("%d,&a"); printf ("\n escribe el valor de b"); scanf("%d,&b"); printf ("\n escribe el valor de c"); scanf("%d,&c"); a = a+ 1; b = b+ 2; c = c+ c; printf ("\n\n ahora el valor de a es %d;a"); printf ("\n\n ahora el valor de b es %d;b"); printf ("\n\n ahora el valor de c es %d;c"); return 0; ]
C
#include <stdio.h> #include <time.h> int main_condition(void) { /* // źٰ . л / Ϲ (Ϲ : 20) int age = 15; //if() {...} else {...} if (age >= 20) { printf("Ϲ Դϴ."); } else { printf("л Դϴ."); }*/ // ʵл(8-13) л(14-16) л(17-19)? // if/ else if/ else /* int age = 8; if (age >= 8 && age <= 13) { printf("ʵлԴϴ.\n"); } else if (age >= 14 && age <= 16) { printf("лԴϴ.\n"); } else if (age >= 17 && age <= 19) { printf("лԴϴ.\n"); } else { printf("л ƴմϴ.\n"); }*/ //break / continue //1 30 ִ ݿ 1 5 ǥ մϴ. /* for (int i = 1; i <= 30; i++) { if (i >= 6) { printf(" л Ŀ ǥ ϰڽϴ.\n"); break; } printf("%d л ǥ غ ϼ.\n", i); }*/ /* //7 л Ἦ, 7ϰ 6 10 ǥϼ for (int i = 1; i <= 30; i++) { if (i >= 6 && i <= 10) { if (i == 7) { printf("%d л ἮԴϴ.\n", i); continue; } printf("%d л ǥ غ ϼ.\n", i); } }*/ //&& AND , || OR /*int a = 10; int b = 11; int c = 12; int d = 13; if (a == b && c == d) { printf("a b , c d ϴ.\n"); } else { printf(" ٸϴ.\n"); }*/ /* //0 1 2 srand(time(NULL)); int i = rand() % 3; //0 - 2 ȯ if (i == 0) { printf("\n"); } else if (i == 1) { printf("\n"); } else if (i == 2) { printf("\n"); } else { printf("\n"); }*/ //switch() ޾ //case , ݵ break Բ Ͽ Ѵ. /*srand(time(NULL)); int i = rand() % 3; //0-2ȯ switch (i) { case 0:printf("\n"); break; case 1:printf("\n"); break; case 2:printf("\n"); break; default:printf("\n"); break; }*/ /* int age = 28; switch (age) { case 8: printf("ʵл Դϴ.\n"); break; case 9: printf("ʵл Դϴ.\n"); break; case 10: printf("ʵл Դϴ.\n"); break; case 11: printf("ʵл Դϴ.\n"); break; case 12: printf("ʵл Դϴ.\n"); break; case 13: printf("ʵл Դϴ.\n"); break; case 14: printf("л Դϴ.\n"); break; case 15: printf("л Դϴ.\n"); break; case 16: printf("л Դϴ.\n"); break; case 17: printf("л Դϴ.\n"); break; case 18: printf("л Դϴ.\n"); break; case 19: printf("л Դϴ.\n"); break; default: printf("л ƴմϴ.\n"); break; }*/ /* int age = 28; switch (age) { case 8: case 9: case 10: case 11: case 12: case 13: printf("ʵл Դϴ.\n"); break; case 14: case 15: case 16: printf("л Դϴ.\n"); break; case 17: case 18: case 19: printf("л Դϴ.\n"); break; default: printf("л ƴմϴ.\n"); break; }*/ //Up and Down srand(time(NULL)); int num = rand() % 100 + 1; // 1-100 printf(" : %d\n", num); int answer = 0; // int chance = 5; //ȸ while (chance > 0) //1=, 0= while 1 ־ ˴ϴ. { printf(" ȸ %d \n", chance--); printf("ڸ . (1-100) : "); scanf_s("%d", &answer); if (answer > num) { printf("DOWN!\n\n"); } else if (answer < num) { printf("UP!\n\n"); } else if (answer == num) { printf("Դϴ!\n\n"); break; } else { printf(" ߻߽ϴ.\n\n"); } if (chance == 0) { printf(" ȸ ϼ̳׿, ƽ Ͽϴ.\n"); break; } } return 0; }
C
/** * Esse programa recebe um nmero inteiro como entrada e * diz se esse nmero primo ou no. Essa soluo no * traz otimizaes. O procedimento para testar se um nmero * primo ser verificar se eles possui algum divisor inteiro at n/2. */ //Incluso das bibliotecas #include<stdio.h> //Funo Principal de um programa em C int main() { //DEclarao de Variveis int numero; //Guarda o numero recebido int divisor; //Divisor que ser testado int numDivisores; //Registra o nmero de divisores do nmero //Inicializao de Variveis divisor = 2; //Primeiro divisor a ser testado numDivisores = 0; //Todo numero inicia com zero divisores //Leitura de numero printf("Digite um numero inteiro positivo: "); scanf("%d", &numero); //Teste de primalidade while(divisor <= numero/2) { if(numero%divisor == 0) numDivisores++; //Incrementa numDivisores cada vez que "numero" for divisvel divisor++; //Atualiza "divisor" para o proximo candidato a divisor } if(numDivisores != 0 || numero == 1) printf("\nO numero nao e' primo!\n"); else printf("\nO numero e' primo!\n"); return 0; }
C
/* * tosfs/tosfs.h * * * (c) 2012 David Picard - [email protected] * */ #ifndef __TOSFS__ #define __TOSFS__ #include <linux/types.h> #define TOSFS_MAGIC 0x1b19b10c #define TOSFS_BLOCK_SIZE 4096 #define TOSFS_SUPERBLOCK 0 #define TOSFS_INODE_BLOCK 1 #define TOSFS_ROOT_INODE 1 #define TOSFS_ROOT_BLOCK 2 #define TOSFS_MAX_NAME_LENGTH 32 #define TOSFS_INODE_SIZE sizeof(struct tosfs_inode) #define tosfs_set_bit(bitmap, block_no) bitmap|=(1<<block_no); /* superblock on disk */ struct tosfs_superblock { __u32 magic; /* magic number */ __u32 block_bitmap; /* bitmap for block (32 blocks) */ __u32 inode_bitmap; /* bitmap for inode (32 inodes) */ __u32 block_size; /* set to 4096 bytes */ __u32 blocks; /* number of blocks, set to 32 */ __u32 inodes; /* number of ino, max = 32 */ __u32 root_inode; /* root inode inode */ }; /* on disk inode */ struct tosfs_inode { __u32 inode; /* inode number */ __u32 block_no; /* block number for data. 1 block per file. should be inode+TOSFS_INODE_BLOCK */ __u16 uid; /* user id */ __u16 gid; /* group id */ __u16 mode; /* mode (fil, dir, etc) */ __u16 perm; /* permissions */ __u16 size; /* size in byte (max 1 block) */ __u16 nlink; /* link (number of hardlink) */ }; /* dentry struct on disk */ struct tosfs_dentry { __u32 inode; /* inode number */ char name[TOSFS_MAX_NAME_LENGTH]; /* name of file */ }; /* inode cache */ //yypstruct tosfs_inode inode_cache[32*TOSFS_INODE_SIZE]; struct tosfs_inode *inode_cache; /* --- PRINTF_BYTE_TO_BINARY macro's --- */ #define PRINTF_BINARY_PATTERN_INT8 "%c%c%c%c%c%c%c%c" #define PRINTF_BYTE_TO_BINARY_INT8(i) \ (((i) & 0x80ll) ? '1' : '0'), \ (((i) & 0x40ll) ? '1' : '0'), \ (((i) & 0x20ll) ? '1' : '0'), \ (((i) & 0x10ll) ? '1' : '0'), \ (((i) & 0x08ll) ? '1' : '0'), \ (((i) & 0x04ll) ? '1' : '0'), \ (((i) & 0x02ll) ? '1' : '0'), \ (((i) & 0x01ll) ? '1' : '0') #define PRINTF_BINARY_PATTERN_INT16 \ PRINTF_BINARY_PATTERN_INT8 PRINTF_BINARY_PATTERN_INT8 #define PRINTF_BYTE_TO_BINARY_INT16(i) \ PRINTF_BYTE_TO_BINARY_INT8((i) >> 8), PRINTF_BYTE_TO_BINARY_INT8(i) #define PRINTF_BINARY_PATTERN_INT32 \ PRINTF_BINARY_PATTERN_INT16 PRINTF_BINARY_PATTERN_INT16 #define PRINTF_BYTE_TO_BINARY_INT32(i) \ PRINTF_BYTE_TO_BINARY_INT16((i) >> 16), PRINTF_BYTE_TO_BINARY_INT16(i) #define PRINTF_BINARY_PATTERN_INT64 \ PRINTF_BINARY_PATTERN_INT32 PRINTF_BINARY_PATTERN_INT32 #define PRINTF_BYTE_TO_BINARY_INT64(i) \ PRINTF_BYTE_TO_BINARY_INT32((i) >> 32), PRINTF_BYTE_TO_BINARY_INT32(i) /* --- end macros --- */ #endif /* __TOSFS__ */
C
#include <stdint.h> #include "inc/tm4c123gh6pm.h" #define SIZE 128 uint32_t SrcBuf[SIZE],DestBuf[SIZE]; int main(void){ volatile uint32_t delay; uint32_t i,t; PLL_Init(); // now running at 80 MHz SYSCTL_RCGCGPIO_R |= SYSCTL_RCGC2_GPIOF; // enable Port F clock delay = SYSCTL_RCGCGPIO_R; // allow time to finish GPIO_PORTF_DIR_R |= 0x0E; // make PF3-1 output (PF3-1 built-in LEDs) GPIO_PORTF_AFSEL_R &= ~0x0E; // disable alt funct on PF3-1 GPIO_PORTF_DEN_R |= 0x0E; // enable digital I/O on PF3-1 // configure PF3-1 as GPIO GPIO_PORTF_PCTL_R = (GPIO_PORTF_PCTL_R&0xFFFF000F)+0x00000000; GPIO_PORTF_AMSEL_R = 0; // disable analog functionality on PF DMA_Init(); // initialize DMA channel 30 for software transfer t = 0; while(1){ for(i=0;i<SIZE;i++){ SrcBuf[i] = i; DestBuf[i] = 0; } while(DMA_Status()); // wait for idle DMA_Transfer(SrcBuf,DestBuf,SIZE); for(i=0;i<SIZE;i++) { printf("Dest at %d is %d \n",i,DestBuf[i]); } for(delay = 0; delay < 600000; delay++){ } } }
C
#include "lists.h" /** * reverse_listint - function that reverses a listint_t linked list. * @head: Pointer to the head of the list. * * Return: a pointer to the first node of the reversed list. */ listint_t *reverse_listint(listint_t **head) { listint_t *temp, *cursor; temp = *head; cursor = *head; *head = NULL; while (cursor != NULL) { cursor = cursor->next; temp->next = *head; *head = temp; temp = cursor; } return (*head); }
C
#include"List.h" void SlistPrint(SlistNode *Plist) { while (Plist->next) { printf("%d->", Plist->data); Plist = Plist->next; } printf("NULL\n"); } SlistNode* SlistBuyNode(SLTdataType x) { SlistNode * SlistnewNode = NULL; SlistnewNode = (SlistNode*)malloc(sizeof(SlistNode)); SlistnewNode->data = x; SlistnewNode->next = NULL; return SlistnewNode; } void SlistPushBack(SlistNode **pPlist, SLTdataType x)//β { SlistNode *SlistnewNode = SlistBuyNode(x); SlistNode *tail = *pPlist; if (*pPlist == NULL) { *pPlist = SlistnewNode; } while (tail) { tail->next; } tail->next = SlistnewNode; } void SlistPushFront(SlistNode **pPlist, SLTdataType x)//ͷ { SlistNode * SlistnewNode = SlistBuyNode(x); if (*pPlist == NULL) { SlistnewNode = *pPlist; } else { SlistnewNode->next = *pPlist; } } void SlistPopBack(SlistNode *pPlist)//βɾ { //1 0 more if (pPlist == NULL) { return NULL; } else if (pPlist->next == NULL) { free(pPlist); } else if (pPlist->next != NULL) { SlistNode *tail = pPlist; while (tail->next) { tail = tail->next; } free(tail); } } void SlistPopfront(SlistNode *pPlist)//ͷɾ { if (pPlist == NULL || pPlist->next == NULL) { free(pPlist); } else { SlistNode *front = pPlist->next; free(pPlist); } } void SlistFind(SlistNode *pPlist, SLTdataType x) { // } void SlistRevise(SlistNode *pPlist, SLTdataType x) { //ҵ滻 }
C
#include <stdio.h> #include <stdlib.h> void selectionSort(int a[100], int n){ int min,temp; for (int i=0;i<n-1;i++){ min = i; for(int j=i+1;j<n;j++){ if(a[j]<a[min]){ min=j; } } temp=a[i]; a[i]=a[min]; a[min]=temp; } } int main(){ int x; printf("\nEnter size of array: "); scanf("%d",&x); int arr[x]; printf("\nEnter elements of array: "); for(int i=0;i<x;i++){ scanf("%d",&arr[i]); } selectionSort(arr,x); printf("\nSorted array: "); for(int i=0;i<x;i++){ printf("%d ",arr[i]); } return 0; }
C
#include "paging.h" #include "../cpu/isr.h" #include "../kernel/panic.h" #include "../drivers/screen.h" #include "../libc/string.h" #include "../libc/mem.h" /* State for managing physical pages. */ // Current position (stack pointer) in physical addr stack. static uintptr_t stack_phys_loc = STACK_PADDR; // Max position of current addr stack. static uintptr_t stack_phys_max = STACK_PADDR; static uintptr_t phys_ptr; /* State for managing virtual pages (and mappings). */ static uintptr_t* page_dir = (uintptr_t *) PAGE_DIR_VADDR; static uintptr_t* page_tables = (uintptr_t*) PAGE_TABLE_VADDR; // This is the page directory we're using right now. static page_dir_t* current_dir; static int paging_enabled; static void handle_page_fault (registers_t *regs); /* Function definitions for physical paging. */ void paging_init(uintptr_t phys_start) { // Physical manager init. Ensure init page allocation is page-aligned. phys_ptr = (phys_start + PAGE_SIZE) & PAGE_MASK; /* Virtual manager init. */ uint32_t i; // Register page fault handler. register_interrupt_handler(INT_PAGE_FAULT, handle_page_fault); // Create and initialize a page directory. page_dir_t* dir = (page_dir_t *) alloc_phys_page(); memset(page_dir, 0, PAGE_DIR_SIZE); /* First 4 MB are getting identity mapped so our kernel doesn't die at the hands of the MMU. */ dir[0] = alloc_phys_page() | FL_PAGE_PRESENT | FL_PAGE_RW; uintptr_t* table = (uintptr_t *) (dir[0] & PAGE_MASK); // We're filling up the entire page table. for (i = 0; i < PAGE_TABLE_NUM_ENTRIES; i++) { // We multiply by PAGE_SIZE to zero out the attribute bits. table[i] = (i * PAGE_SIZE) | FL_PAGE_PRESENT | FL_PAGE_RW; } // Now allocate and initialize the second-last table. dir[PAGE_TABLE_NUM_ENTRIES - 2] = alloc_phys_page() | FL_PAGE_PRESENT | FL_PAGE_RW; table = (uintptr_t*) (dir[PAGE_TABLE_NUM_ENTRIES - 2] & PAGE_MASK); memset(table, 0, PAGE_SIZE); // Last entry of the second-last table points to the directory itself. table[PAGE_TABLE_NUM_ENTRIES - 1] = ((uintptr_t) dir) | FL_PAGE_PRESENT | FL_PAGE_RW; switch_page_dir(dir); enable_paging(); /* Map the page table that has the physical stack, otherwise the MMU will complain when we first try to free a physical page. */ uint32_t table_index = PAGE_DIR_INDEX((STACK_PADDR >> 12)); page_dir[table_index] = alloc_phys_page() | FL_PAGE_PRESENT | FL_PAGE_RW; memset((void*) page_tables[table_index * PAGE_TABLE_NUM_ENTRIES], 0, PAGE_SIZE); paging_enabled = 1; } uintptr_t alloc_phys_page() { /* If virtual paging is enabled, use the stack, otherwise use the dumb method. */ if (paging_enabled) { // Sanity check. if (stack_phys_loc == STACK_PADDR) { panic("Out of memory: stack physical location is at STACK_PHYS_ADDR"); } // Allocate page from stack. phys_ptr -= sizeof(intptr_t); uintptr_t *stack = (uintptr_t *) stack_phys_loc; return *stack; } else { return phys_ptr += PAGE_SIZE; } } int free_phys_page(uintptr_t p) { /* We don't want to free early allocated pages, since they contain important structures */ if (p < phys_ptr) { return ENOTINSTACK; } if (stack_phys_max <= stack_phys_loc) { /* If the stack's out of space, map the page into the current address space for extra stack space. */ vpage_map(stack_phys_max, p, FL_PAGE_PRESENT | FL_PAGE_RW); stack_phys_max += PAGE_SIZE; } else { uintptr_t* stack = (uintptr_t *) stack_phys_loc; *stack = p; stack_phys_loc += sizeof(uintptr_t); } return SUCCESS; } /* Function definitions for virtual paging. */ void enable_paging() { uint32_t cr0; __asm__ __volatile__("mov %%cr0, %0" : "=r" (cr0)); cr0 |= CR0_PAGING_ENABLE_BIT; __asm__ __volatile__("mov %0, %%cr0" : : "r" (cr0)); } void switch_page_dir(page_dir_t* dir) { current_dir = dir; __asm__ __volatile__("mov %0, %%cr3" : : "r" (dir)); } void vpage_map(uintptr_t virt_addr, uintptr_t phys_addr, uint32_t flags) { uintptr_t virt_page = virt_addr / PAGE_SIZE; uintptr_t table_index = PAGE_DIR_INDEX(virt_page); // Find the right page table to put virt_addr in. if (page_dir[table_index] == 0) { // We need to create the page table for this page. page_dir[table_index] = alloc_phys_page() | FL_PAGE_PRESENT | FL_PAGE_RW; memset((void*) page_tables[table_index * PAGE_TABLE_NUM_ENTRIES], 0, PAGE_SIZE); } // Now that we know the page table exists, update the page table entry. page_tables[virt_page] = (phys_addr & PAGE_MASK) | flags; } void vpage_unmap(uintptr_t virt_addr) { uintptr_t virt_page = virt_addr / PAGE_SIZE; page_tables[virt_page] = 0; __asm__ __volatile__("invlpg (%0)" : : "a" (virt_addr)); } int vpage_get_mapping(uintptr_t virt_addr, uintptr_t* phys_addr) { uintptr_t virt_page = virt_addr / PAGE_SIZE; uint32_t table_index = PAGE_DIR_INDEX(virt_addr); // Find page table for virt_addr. if (page_dir[table_index] == 0) { return ENOMAPPING; } if (page_tables[virt_page] != 0) { if (phys_addr) { *phys_addr = page_tables[virt_page] & PAGE_MASK; } return SUCCESS; } return ENOMAPPING; } static void handle_page_fault (registers_t *regs) { uint32_t cr2; char strbuf[128]; __asm__ __volatile__("mov %%cr2, %0" : "=r" (cr2)); kprint("Page fault at address "); itoa(regs->eip, strbuf); kprint(strbuf); kprint(" Error code: "); itoa(regs->err_code, strbuf); kprint(strbuf); panic("Page fault complete"); }
C
#include <stdio.h> int i = 5; char text[255]; void foo(void); int main(void) { printf(" %i ", i); foo(); printf(" %i \n", i); return 0; }
C
#include <stdio.h> #include <ctype.h> int main(int counter, char *words[]) { for (int i = 1; i<counter; ++i){ for (int j=0; words[i][j]!=0; ++j) { if(isupper(words[i][j])){ words[i][j]= tolower(words[i][j]); printf("_"); } printf("%c", words[i][j]); } printf("\n"); } return 0; }
C
#include "heap_debug.h" #include "node_debug.h" #include "allocator_debug.h" #include <string.h> /* static inline void push_(BlockHeader** tgt, BlockHeader* b) { */ /* b->next = *tgt; */ /* *tgt = b; */ /* } */ /* static inline BlockHeader* pop_(BlockHeader** src) { */ /* BlockHeader* b = *src; */ /* *src = b->next; */ /* return b; */ /* } */ static BlockHeader* allocNewRootBlock_(RootStack* rs) { if (rs->extra == 0) { BlockHeader* b = allocBlockUnits(rs->a, 1); if (b != 0) SLIST_PUSH(rs->top, b); return b; } else { SLIST_PUSH(rs->top, rs->extra); rs->extra = 0; return rs->top; } } int RootStack_init(RootStack* rs, Allocator* a) { rs->a = a; rs->extra = 0; rs->top = 0; return allocNewRootBlock_(rs) != 0; } void RootStack_destroy(RootStack* rs) { freeBlocks(rs->a, rs->top); freeBlocks(rs->a, rs->extra); } Word** RootStack_push(RootStack* rs, size_t nRoots) { // todo: assumption that nRoots <= BLOCKUNIT_NUMWORDS ... BlockHeader* b = rs->top; if ((size_t)(b->lim - b->free) < nRoots) { b = allocNewRootBlock_(rs); if (b == 0) return 0; } Word** roots = (Word**)b->free; b->free += nRoots; return roots; } void RootStack_pop(RootStack* rs, size_t nRoots) { // assumes never popping more than the number of roots in top block at once BlockHeader* b = rs->top; b->free -= nRoots; if ((b->free == b->base) && (b->next != 0)) { freeBlocks(rs->a, rs->extra); SLIST_POP(rs->extra, rs->top); } } static BlockHeader* allocNewBlock_(BlockSpace* bs) { BlockHeader* b = allocBlockUnits(bs->heap->a, 1); if (b != 0) { b->owner = bs; SLIST_PUSH(bs->to, b); ++bs->numBlocks; } return b; } static BlockHeader* allocNewLargeBlock_(BlockSpace* bs, size_t nWords) { BlockHeader* b = allocBlockBytes(bs->heap->a, nWords*sizeof(Word)); if (b != 0) { b->owner = bs; insertLink_(&bs->largeTo, b); ++bs->numBlocks; } return b; } static int BlockSpace_init(BlockSpace* bs, Heap* h) { bs->heap = h; bs->to = 0; bs->largeTo = 0; bs->from = 0; bs->largeFrom = 0; bs->scan = 0; bs->pending = 0; bs->finished = 0; bs->numBlocks = 0; bs->limBlocks = 2; return allocNewBlock_(bs) != 0; } static void BlockSpace_chooseLimit(BlockSpace* bs) { if (bs->numBlocks > bs->limBlocks/2) bs->limBlocks *= 2; else if (bs->numBlocks < bs->limBlocks/4) bs->limBlocks /= 2; } static void BlockSpace_destroy(BlockSpace* bs) { freeBlocks(bs->heap->a, bs->to); freeBlocks(bs->heap->a, bs->largeTo); } int Heap_init(Heap* h, RootStack* rs, Allocator* a) { h->a = a; h->rs = rs; return BlockSpace_init(&h->bs, h); } void Heap_destroy(Heap* h) { BlockSpace_destroy(&h->bs); } #define FREE_SPACE_(bs, nWords, allocCall) do { \ if (bs->limBlocks > bs->numBlocks) { \ if ((allocCall) == 0) gcSpace(bs, nWords); \ } else gcSpace(bs, nWords); \ } while (0) Word* allocSpaceWords(BlockSpace* bs, size_t nWords) { if (nWords < BLOCKUNIT_NUMWORDS) { size_t freeWords = Block_nFreeWords(bs->to); if (freeWords < nWords) FREE_SPACE_(bs, nWords, allocNewBlock_(bs)); Word* p = bs->to->free; bs->to->free += nWords; return p; } else { // todo: limLargeBlocks ? FREE_SPACE_(bs, nWords, allocNewLargeBlock_(bs, nWords)); return bs->largeTo->free; } } Word* allocSpaceBytes(BlockSpace* bs, size_t nBytes) { return allocSpaceWords(bs, iDivCeil_(nBytes, sizeof(Word))); } Word* allocWords(Heap* h, size_t nWords) { return allocSpaceWords(&h->bs, nWords); } Word* allocBytes(Heap* h, size_t nBytes) { return allocSpaceBytes(&h->bs, nBytes); } static void gcFail_(void) {} // todo static inline Word* evacuateWords(BlockSpace* dst, Word* p, size_t nWords) { BlockHeader* to = dst->to; size_t freeWords = Block_nFreeWords(to); if (freeWords < nWords) { if (to != dst->scan) SLIST_PUSH(dst->pending, to); BlockHeader* b = allocNewBlock_(dst); if (b != 0) { b->x.scan = b->free; dst->to = b; } else gcFail_(); } Word* pnew = to->free; to->free += nWords; memcpy(pnew, p, nWords*sizeof(Word)); setIndirect(p, pnew); return pnew; } static inline void evacuateLarge(BlockSpace* dst, BlockSpace* src, BlockHeader* b) { UNLINK_(src->largeFrom, b); b->flags &= ~BLOCKFLAG_COLLECTING; b->owner = dst; SLIST_PUSH(dst->pending, b); } void evacuate(BlockSpace*, Word**); static inline Word* evacuateIndirect(BlockSpace* dst, Word* ind) { Word** pp = (Word**)(ind+INDIRECT_PTR); evacuate(dst, pp); return *pp; } static inline int isLargeBlock_(BlockHeader* b) { return (b->lim-b->free) > (signed)BLOCKUNIT_NUMWORDS; } void evacuate(BlockSpace* dst, Word** pp) { Word* p = *pp; if (beingCollected(p)) { const Layout* layout = getLayout(*p); switch (layout->type) { case LAYOUT_INDIRECT: *pp = evacuateIndirect(dst, p); break; case LAYOUT_SMALL_NOPTRS: *pp = evacuateWords(dst, p, layout->x.noPtrs.nWords); break; case LAYOUT_SMALL_PTRSFIRST: *pp = evacuateWords(dst, p, layout->x.ptrsFirst.nWords); break; case LAYOUT_LARGE_NOPTRS: case LAYOUT_LARGE_PTRSFIRST: { BlockHeader* b = getBlock(p); evacuateLarge(dst, b->owner, b); } break; default: break; // todo: assert never } } } static inline Word* scavenge(BlockSpace* dst, Word* scan) { const Layout* layout = getLayout(*scan); switch (layout->type) { case LAYOUT_SMALL_NOPTRS: case LAYOUT_LARGE_NOPTRS: return scan+layout->x.noPtrs.nWords; case LAYOUT_SMALL_PTRSFIRST: case LAYOUT_LARGE_PTRSFIRST: { Word** ptr = (Word**)(scan+1); Word** ptrEnd = ptr + layout->x.ptrsFirst.nPtrs; // todo for (; ptr != ptrEnd; ++ptr) evacuate(dst, ptr); return scan+layout->x.ptrsFirst.nWords; } default: return 0; // todo: assert that this never happens }; } void scavengeBlock(BlockSpace* dst, BlockHeader* b) { Word* scan = b->x.scan; while (scan != b->free) scan = scavenge(dst, scan); b->x.scan = scan; } void scan(BlockSpace* bs) { bs->scan = 0; for (;;) { if (bs->pending != 0) SLIST_POP(bs->scan, bs->pending); else { if (bs->scan != bs->to) bs->scan = bs->to; else return; } scavengeBlock(bs, bs->scan); if (bs->scan != bs->to) { if (!isLargeBlock_(bs->scan)) SLIST_PUSH(bs->finished, bs->scan); else insertLink_(&bs->largeTo, bs->scan); } } } #define FOREACH_ROOT(rs, action) do { \ BlockHeader* b = rs->top; \ while (b != 0) { \ Word **root = (Word**)b->base, **rootLim = (Word**)b->free; \ for (; root != rootLim; ++root) action; \ b = b->next; \ } \ } while (0) static inline void evacuateRoots(BlockSpace* bs, RootStack* rs) { FOREACH_ROOT(rs, evacuate(bs, root)); } void gcSpace(BlockSpace* bs, size_t requiredWords) { bs->from = bs->to; bs->largeFrom = bs->largeTo; bs->to = 0; bs->largeTo = 0; bs->numBlocks = 0; BlockHeader* b; if ((b = allocNewBlock_(bs)) != 0) { b->x.scan = b->free; setBlocksCollecting(bs->from); setBlocksCollecting(bs->largeFrom); evacuateRoots(bs, bs->heap->rs); printf("finished roots\n"); scan(bs); printf("finished scan\n"); // garbage collection is now finished SLIST_PUSH(bs->finished, bs->to); bs->to = bs->finished; unsetBlocksCollecting(bs->from); unsetBlocksCollecting(bs->largeFrom); freeBlocks(bs->heap->a, bs->from); freeBlocks(bs->heap->a, bs->largeFrom); bs->from = 0; bs->largeFrom = 0; bs->scan = 0; bs->pending = 0; bs->finished = 0; if (requiredWords > Block_nFreeWords(bs->to)) // one should be enough if (allocNewBlock_(bs) == 0) gcFail_(); BlockSpace_chooseLimit(bs); } else gcFail_(); } void gcHeap(Heap* h, size_t requiredWords) { gcSpace(&h->bs, requiredWords); } //////////////////////////////////////////////////////////////// // debug void showRoots(FILE* out, const RootStack* rs) { size_t nRoots = 0; FOREACH_ROOT(rs, ++nRoots); fprintf(out, "nRoots=%d\n", nRoots); FOREACH_ROOT(rs, { --nRoots; fprintf(out, "-%d: ", nRoots); showAddrNode(out, *root); }); } void showBlockNodes(FILE* out, const BlockHeader* b) { showBlock(out, b); const Word* node = b->base; while (node < b->free) { showAddrNode(out, node); node += nodeSize(node); } } void showBlocksNodes(FILE* out, const BlockHeader* b) { if (b != 0) { for (;;) { showBlockNodes(out, b); b = b->next; if (b == 0) break; fprintf(out, "================\n"); } } else fprintf(out, "null\n"); } #define SHOW_BLOCK_NODES_(block) do { \ fprintf(out, "================\n"#block": "); \ showBlocksNodes(out, bs->block); \ } while (0) void showBlockSpace(FILE* out, const BlockSpace* bs) { fprintf(out, "numBlocks=%u, limBlocks=%u\n", bs->numBlocks, bs->limBlocks); SHOW_BLOCK_NODES_(to); SHOW_BLOCK_NODES_(largeTo); SHOW_BLOCK_NODES_(from); SHOW_BLOCK_NODES_(largeFrom); SHOW_BLOCK_NODES_(scan); SHOW_BLOCK_NODES_(pending); SHOW_BLOCK_NODES_(finished); } void showHeap(FILE* out, const Heap* h) { showBlockSpace(out, &h->bs); fprintf(out, "================\n"); showRoots(out, h->rs); }
C
#include "timer.h" #include "common.h" #include <stdlib.h> #include <stdint.h> #include <sys/timerfd.h> #include <sys/epoll.h> #include <unistd.h> static int timerfd; static int timerstate = TIMER_OFF; int timersetup(int epollfd) { struct epoll_event ev; timerfd = timerfd_create(CLOCK_REALTIME, 0); if (timerfd == ERR) { perror("Cannot create timerfd"); return ERR; } ev.events = EPOLLIN; ev.data.fd = timerfd; if (epoll_ctl(epollfd, EPOLL_CTL_ADD, timerfd, &ev) == ERR) { perrorf("epoll_ctl: ADD, input device"); return ERR; } return timerfd; } void timerset(int s) { int err; struct itimerspec new_value; struct timespec now; if (timerstate == s) { return; } if (s) { clock_gettime(CLOCK_REALTIME, &now); new_value.it_value.tv_sec = now.tv_sec + ((now.tv_nsec + TIMER_DELAY_NS) / TIMER_NS); new_value.it_value.tv_nsec = (now.tv_nsec + TIMER_DELAY_NS) % TIMER_NS; new_value.it_interval.tv_sec = 0; new_value.it_interval.tv_nsec = TIMER_INTERVAL_NS; } else { memset(&new_value, 0, sizeof(new_value)); } err = timerfd_settime(timerfd, TFD_TIMER_ABSTIME, &new_value, NULL); if (err == ERR) { perror("Cannot set timerfd"); exit(EXIT_FAILURE); } timerstate = s; } int timerread() { uint64_t t; int err; if (!timerstate) { return OK; } err = read(timerfd, &t, sizeof(uint64_t)); if (err != sizeof(uint64_t)) { return ERR; } return OK; }
C
#include <stdio.h> typedef struct { int x; int y; } coordonnee; void fonction(coordonnee *fi); int main() { coordonnee i; i.x = 0; i.y = 0; coordonnee *ptri = &i; printf("Avant la fonction, la structure a pour adresse %x et valeurs [%d, %d].\n", &i, i.x, i.y); // exemple de passage d'une structure fonction(ptri); printf("Apres l'appel la structure a mtnt pour adresse %x et valeurs [%d, %d].\n", &i, i.x, i.y); printf("la structure a ete modifiee dans la fonction (passage par reference)\n"); return 0; } void fonction(coordonnee *fi) { printf("Dans la fonction, la structure recue a pour adresse %x et valeurs [%d, %d].\n",&fi, fi->x, fi->y); fi->x = fi->x + 1; fi->y = fi->y + 1; printf("Apres i+1 la structure recue a pour adresse %x et valeurs [%d, %d].\n",&fi, fi->x, fi->y); return; }
C
#include <stdio.h> #include <sys/ioctl.h> int main(int argc, char *argv[]) { struct winsize ws; /* * ioctl(2)システムコールを使ってウィンドウサイズ * (ターミナルサイズ)を取得し、構造体winsize wsに * 値を保存している。 */ ioctl(1, TIOCGWINSZ, &ws); printf("ws_row: %d, ws_col: %d\n", ws.ws_row, ws.ws_col); }
C
#include <stdio.h> int main(void) { char str[5] = { 'O', 'X', 'X', 'O', 'X'}; char answer[5] = { 'O', 'O', 'X', 'O', 'X' }; int score = 0; for (int i = 0; i < 5; i++) { if (str[i] == answer[i]) { score = score + 10; } } printf(" : %d", score); }
C
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <omp.h> #include "PE_functions_15350.c" int main(int narg, char *argv[]) { char* filename; double d,eps; int n; double *xk; filename = argv[1]; d = atof(argv[2]); eps = atof(argv[3]); n = atoi(argv[4]); if (narg < 2) { printf("Filename required.\n"); printf("Running example: ./a.out filename d eps n\n"); exit(0); } printf("Reading file...\n"); double begin1 = omp_get_wtime(); read_graph_from_file(filename); double read_time1 = omp_get_wtime(); printf("Iterating true x_k...\n"); double begin2 = omp_get_wtime(); xk = PageRank_iterations(d,eps); double read_time2 = omp_get_wtime(); printf("Finding top %d values...\n",n); double begin3 = omp_get_wtime(); top_n_webpages(xk,n); double read_time3 = omp_get_wtime(); printf("Reading graph from file: took %f seconds\n", ((double)(read_time1 - begin1))); printf("PageRank iterations: took %f seconds\n", ((double)(read_time2 - begin2))); printf("Top n webpages: took %f seconds\n", ((double)(read_time3 - begin3))); double total_time = (double)(read_time3 - begin1); printf("ALL DONE!!, TOTAL TIME = %f seconds\n",total_time); return 0; }
C
/******************************************************* ** Created by Nick Major 0879292 ** A2, main ** Due: 02/13/17 *******************************************************/ #include <string.h> #include <stdio.h> #include <time.h> struct Set { double x; double y; }; int * readArray(int *size); struct Set * readSet(int *size); extern long int inversion(int A[], int size); extern long int count_inversion(int A[], int right, int left); extern void BruteHull(struct Set S[], int size); extern void QuickHull( struct Set S[], int size ); int main(int argc, const char * argv[]) { int *A; struct Set *B; int cmd = 1; int size = 0; clock_t begin; clock_t end; double time_spent; printf("Assignment #2\n\nCommands:\n\t1 - P11\n\t2 - P12\n\t3 - P21\n\t4 - P22\n\t0 - exit\n"); while( cmd > 0 && cmd < 5 ) { scanf("%d", &cmd); switch( cmd ) { case 1: begin = clock(); A = readArray(&size); printf("Inversions: %ld\n", inversion(A, size)); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("Ex time: %4f seconds\n\n", time_spent); break; case 2: A = readArray(&size); begin = clock(); printf("Inversions: %ld\n", count_inversion(A, 0, size-1)); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("Ex time: %4f seconds\n\n", time_spent); break; case 3: B = readSet(&size); BruteHull(B, size); break; case 4: B = readSet(&size); QuickHull(B, size); break; } } return 0; } int * readArray(int *size) { char fileName[30] = ""; FILE* file = NULL; char line[100] = ""; static int A[50005]; int i = 0; printf("Enter file name: "); scanf("%s", fileName); while(!(file = fopen(fileName, "r"))) { printf("Enter file name: "); scanf("%s", fileName); } while (fgets(line, sizeof(line), file)) { sscanf(line, "%d %d %d %d %d", &A[i], &A[i+1], &A[i+2], &A[i+3], &A[i+4]); i = i + 5; } printf("\n"); fclose(file); *size = i; return A; } struct Set * readSet(int *size) { char fileName[30] = ""; FILE* file = NULL; char line[100] = ""; static struct Set B[30005]; int i = 0; printf("Enter file name: "); scanf("%s", fileName); while(!(file = fopen(fileName, "r"))) { printf("Enter file name: "); scanf("%s", fileName); } while (fgets(line, sizeof(line), file)) { sscanf(line, "%lf %lf", &B[i].x, &B[i].y); i ++; } printf("\n"); fclose(file); *size = i; return B; }
C
#include<stdio.h> struct MY_TYPE { short int value; int stuff; } MY_TYPE; void main() { struct MY_TYPE MY_TYPE; MY_TYPE.value = 15; MY_TYPE.stuff = 13; function(); { extern struct MY_TYPE MY_TYPE; printf("%d", MY_TYPE.value); } printf("\n\n%d %d", MY_TYPE.value, MY_TYPE.stuff); } void function(){ MY_TYPE.value = 420; }
C
#include<stdio.h> void fibonacci(int n); int main(){ int n; printf("enter n"); scanf("%d",&n); printf("fibonacci series"); printf("\n%d\n",0); fibonacci(n); } void fibonacci(int n) { static int first=0,second=1,sum;//else for each recursion first is 0 and second is 1. //static keeps only one intialized copy till end of program.seems to work only in c if(n>0) { sum=first+second; first=second; second=sum; printf("%d\n",first); fibonacci(n-1); } }
C
#include<stdio.h> #include<string.h> #include<stdlib.h> #include<assert.h> #include<getWord.h> #include"ht.h" struct KVpair* array; //hold all the wordpairs int arrayIndex = 0; int main( int argc, char **argv){ FILE* fp; char* myWord; //streaming word char* fHalf; //first part of word pair char* sHalf; //second part of word pair char* wordPair; int* val; int flag = 0; int numLine = 0; //number of output line to print int k = 0; if(argc==1){ printf("\nNO FILE DETECTED!\n"); printf("\nUsage: ./wordpairs -number_of_line list_of_file_name \n\n"); return(0); } else { if(argv[1][0]=='-'){ //detect the number of printed lines if(argc>2){ for(int i=0; i<strlen(argv[1]); i++){ argv[1][i] = argv[1][i+1]; } argv[1][strlen(argv[1])] = '\0'; numLine = atoi(argv[1]); //convert to integer if(numLine<=0){ printf("\nNumber of Printed WordPairs Must Be Greater Than Zero.\n\n"); return(0); } } else { printf("\nNO FILE DETECTED!\n"); printf("\nUsage: ./wordpairs -number_of_line list_of_file_name \n\n"); return(0); } } } if(numLine==0){ //filename starts at argv[1] k=1; } else { //filename starts at argv[2] k=2; } struct Ht* hashTable = htNew(123); //hash table with 123 size while(k<argc){ //open and read fp = fopen(argv[k], "r"); if(fp==NULL){ //file not found printf("\nError: <%s> NOT FOUND\n\n", argv[k]); return(0); } while((myWord = getNextWord(fp))!= NULL){ if(!flag){ fHalf = malloc(sizeof(char)*(strlen(myWord)+1)); strcpy(fHalf, myWord); flag++; } else { sHalf = malloc(sizeof(char)*(strlen(myWord)+1)); strcpy(sHalf, myWord); //combine two words into pair seperated by space wordPair = malloc(sizeof(char)*(strlen(fHalf)+strlen(sHalf)+2)); strcpy(wordPair, fHalf); strcat(wordPair, " "); strcat(wordPair, sHalf); //check if the wordpairs exist val = (int*)htSearch(hashTable, wordPair); if(val!=NULL){ //wordpairs already exists assert(*val>=1); (*val)++; free(wordPair); } else { //insert wordpairs into table val = (int*)malloc(sizeof(int)); *val = 1; if(htInsert(hashTable, wordPair, val)){ printf("Insert Fail\n") ; } } free(fHalf); //free and reallocate fHalf for another usage fHalf = malloc(sizeof(char)*strlen(sHalf)+1); strcpy(fHalf, sHalf); free(sHalf); } free(myWord); }//end of while(getNextWord); if(hashTable->count!=0) free(fHalf); if(hashTable->count==0){ printf("\nFile <%s> Is Either Empty Or Contains Only One Word.\n\n", argv[k]); return(0); } //close file, reset flag, increment to read next file fclose(fp); flag = 0; k++; }//end of while(k<argv); //printf("Size: count: %d, tblSize: %d\n", hashTable->count, hashTable->size); //convert hash table into one array array = (struct KVpair*)malloc(sizeof(struct KVpair)*(hashTable->count)); htApply(hashTable, makeArray); //sort array in decreasing order qsort(array, hashTable->count, sizeof(struct KVpair), cmpFunc); //set the limit of how many wordpairs should be printed int limitLine = 0; if(numLine!=0){ if(numLine>hashTable->count){ limitLine = hashTable->count; } else { limitLine = numLine; } } else { limitLine = hashTable->count; } //print to stdout for(int i=0; i<limitLine; i++){ printf("%10d %s\n", *(int*)array[i].value, array[i].key); } //delete hash table and array htDelete(hashTable, delFunc); free(array); return(0); }//end of main //----------------------------------------------------------------------------- // // make array // void makeArray(char* key, void* value){ array[arrayIndex].key=key; array[arrayIndex].value=value; arrayIndex++; } //----------------------------------------------------------------------------- // // compare 2 integer // int cmpFunc(const void *temp1, const void *temp2){ const struct KVpair *t1 = temp1; const struct KVpair *t2 = temp2; return(-(*(int*)(t1->value) - *(int*)(t2->value))); // negative = (temp1->value > temp2->value) // positive = (temp1->value < temp2->value) } //----------------------------------------------------------------------------- // // delete function // void delFunc(char* key, void* value){ free(key); free(value); } //-----------------------------------------------------------------------------
C
#include<stdio.h> int show(int n,int m) { int s,b,i,j,k; s=0; j=n; while(j!=0) { i=j%10; i=i*i*i; s=s+i; j=j/10; } if(s==n) { printf("%d is a armstrong no.",n); } else { printf("%d is not a armstrong no.", n ); } } int main() { int a,b; printf("enter two no. "); scanf("%d", &a); show(a,b); return 0; }
C
// // ex5_task6.c // Infor2_Exercise // // Created by 谭特 on 17/5/7. // Copyright © 2017年 谭特. All rights reserved. // #include <stdlib.h> #include <stdio.h> #define black 0 #define red 1 struct rbNode { int key; int color; struct rbNode* left; struct rbNode* right; struct rbNode* parent; }; struct rbTree { int bh; struct rbNode *root; struct rbNode *nil; }; struct rbTree* rb_initialize() { struct rbTree* tree; struct rbNode* node; tree = (struct rbTree*) malloc(sizeof(struct rbTree)); tree->nil = (struct rbNode*) malloc(sizeof(struct rbNode)); tree->nil->parent = tree->nil; tree->nil->left = tree->nil; tree->nil->right = tree->nil; tree->nil->color = black; tree->nil->key = -2; tree->root = tree->nil; tree->bh = 0; return tree; } void rb_leftRotate(struct rbTree* T, struct rbNode* x) { // your implementation goes here struct rbNode* s = x->right; x->right = s->left; s->parent = x->parent; if(s->left != NULL) {s->left->parent = x;} if(x->parent == NULL) {T->root = s;} else if(x->parent->left == x) {x->parent->left = s;} else {x->parent->right = s;} s->left = x; x->parent = s; } void rb_rightRotate(struct rbTree* T, struct rbNode* y) { // your implementation goes here struct rbNode* s = y->left; y->left = s->right; s->parent = y->parent; if(s->right != NULL) {s->right->parent = y;} if(y->parent == NULL) {T->root = s;} else if(y->parent->left == y) {y->parent->left = s;} else {y->parent->right = s;} s->right = y; y->parent = s; } void rb_insertFixup(struct rbTree* T, struct rbNode* z) { struct rbNode* y; while (z->parent->color == red) { if (z->parent == z->parent->parent->left) { /* non-mirrored cases */ y = z->parent->parent->right; if (y->color == red) { /* case 1 */ z->parent->color = black; y->color = black; z->parent->parent->color = red; z = z->parent->parent; } else { if (z == z->parent->right) { /* case 2 */ z = z->parent; rb_leftRotate(T, z); } z->parent->color = black; /* case 3 */ z->parent->parent->color = red; rb_rightRotate(T, z->parent->parent); } } else { /* mirrored cases */ y = z->parent->parent->left; if (y->color == red) { /* case 1m */ z->parent->color = black; y->color = black; z->parent->parent->color = red; z = z->parent->parent; } else { if (z == z->parent->left) { /* case 2m */ z = z->parent; rb_rightRotate(T, z); } z->parent->color = black; /* case 3m */ z->parent->parent->color = red; rb_leftRotate(T, z->parent->parent); } } } if (T->root->color == red) { T->bh += 1; } T->root->color = black; } void rb_insert(struct rbTree* tree, int key) { struct rbNode *oneDelayed = tree->nil; struct rbNode *insertPlace = tree->root; struct rbNode *nodeToInsert = (struct rbNode*) malloc(sizeof(struct rbNode)); nodeToInsert->key = key; nodeToInsert->color = red; nodeToInsert->left=tree->nil; nodeToInsert->right=tree->nil; nodeToInsert->parent=tree->nil; while (insertPlace != tree->nil) { oneDelayed = insertPlace; if (nodeToInsert->key < insertPlace->key) { insertPlace = insertPlace->left; } else { insertPlace = insertPlace->right; } } if (oneDelayed == tree->nil) { tree->root = nodeToInsert; } else if (oneDelayed->key < nodeToInsert->key) { oneDelayed->right = nodeToInsert; nodeToInsert->parent = oneDelayed; } else { oneDelayed->left = nodeToInsert; nodeToInsert->parent = oneDelayed; } rb_insertFixup(tree, nodeToInsert); } void rb_printRecursive(struct rbNode *root, struct rbTree *tree) { if (root == tree->nil) { return; } rb_printRecursive(root->left, tree); printf(" %d (%s) -- %d\n", root->key, (root->color==red?"RED":"BLACK"), root->left->key); rb_printRecursive(root->right, tree); printf(" %d (%s) -- %d\n", root->key, (root->color==red?"RED":"BLACK"), root->right->key); } void rb_print(struct rbTree *tree) { printf("graph g {\n"); rb_printRecursive(tree->root, tree); printf("}\n"); } struct rbNode* rb_search(struct rbTree* T, int q) { struct rbNode* x = T->root; if (x == T->nil) { return x; } while (x->key != q) { if (q < x->key) { x = x->left; } else { x = x->right; } if (x == T->nil) { return x; } } return x; } int main(int argc, char **argv) { struct rbTree *t1; t1 = rb_initialize(); rb_insert(t1, 10); rb_insert(t1, 1); rb_insert(t1, 11); rb_insert(t1, 9); rb_insert(t1, 5); rb_insert(t1, 13); rb_print(t1); return 0; }
C
#include <stdio.h> unsigned int rotate_left(unsigned int i, int n); unsigned int rotate_right(unsigned int i, int n); int main(){ unsigned int n = 5; printf("%u, %u\n", n, rotate_left(n, 3)); printf("%u, %u\n", n, rotate_right(n, 3)); return 0; } unsigned int rotate_left(unsigned int i, int n){ unsigned int result; result = (i << n) | (i >> (sizeof(int) * 8) - n); return result; } unsigned int rotate_right(unsigned int i, int n){ unsigned int result; result = (i << (sizeof(int) * 8) - n) | (i >> n); return result; } /* full solution #include <stdio.h> #include <string.h> unsigned int rotate_left(unsigned int i, int n); unsigned int rotate_right(unsigned int i, int n); char *byte_to_binary_str(int byte); void print_int_bits(int value); int main(void) { int shift_amt = 4; unsigned int value = 0x12345678; printf("\nOriginal value\n"); print_int_bits(value); printf("Hex\t%x\n\n", value); printf("\nRotated left by %d bit(s)\n", shift_amt); print_int_bits(rotate_left(value, shift_amt)); printf("Hex\t%x\n\n", rotate_left(value, shift_amt)); printf("\nRotated right by %d bit(s)\n", shift_amt); print_int_bits(rotate_right(value, shift_amt)); printf("Hex\t%x\n\n", rotate_right(value, shift_amt)); return 0; } unsigned int rotate_left(unsigned int i, int n) { return (i << n) | (i >> (sizeof(int) * 8) - n); } unsigned int rotate_right(unsigned int i, int n) { return (i << (sizeof(int) * 8) - n) | (i >> n); } char *byte_to_binary_str(int byte) { static char bit_string[9]; bit_string[0] = '\0'; int mask; for (mask = 0x80; mask > 0; mask >>= 1) { // Check if the mask bit is set strcat(bit_string, byte & mask ? "1" : "0"); } return bit_string; } void print_int_bits(int value) { static int i; printf("Binary\t"); for (i = sizeof(int) - 1; i >= 0; i--) { printf("%s ", byte_to_binary_str(value >> (i * 8))); } printf("\n"); } */
C
#define MCU 'attiny84' #define F_CPU 1000000UL #include "include/macros.h" #include <avr/io.h> #include <avr/interrupt.h> #include <stdio.h> #include <stdlib.h> #include <util/delay.h> #define ENCODER_A PA1 //PCINT1 #define ENCODER_B PA2 //PCINT2 #define ENCODER_PIN PINA #define ENCODER_DDR DDRA #define ADC_IN PA0 //ADC0 #define ADC_CHANNEL 0 #define DRIVER_PWM PB2 #define DRIVER_A PB1 #define DRIVER_B PB0 #define DRIVER_PORT PORTB #define DRIVER_DDR DDRB //global variables for position update volatile long encoderValue = 0; volatile uint8_t seqstore = 0; volatile uint8_t pinpair = 0; //function declarations void initADC(void); uint16_t readADC(uint8_t channel); void initValues(uint16_t * arr, uint8_t size, uint16_t value); void storeNewADC(uint16_t * arr, uint8_t size, uint8_t channel); uint16_t getAverage(uint16_t * arr, uint8_t size); void initMotorDriverIO(void); void initTimer0PWM(void); void initPCInterrupts(void); ISR(PCINT0_vect) { //variables to store encoder states uint8_t MSB; uint8_t LSB; //find state of encoder a if(bit_is_set(ENCODER_PIN,ENCODER_A)){ MSB=1; }else{ MSB=0; } //find state of encoder b if(bit_is_set(ENCODER_PIN,ENCODER_B)){ LSB=1; }else{ LSB=0; } //this instance pair pinpair = (MSB << 1) | LSB; seqstore = seqstore << 2; //shift the next sequence step seqstore |= pinpair; if (seqstore == 0b10000111){ encoderValue++; //this is the seq ccw: (11) 10 00 01 11 } if (seqstore == 0b01001011){ encoderValue--; //this is the seq cw: (11) 01 00 10 11 } return; } int main(void) { //initialize functions (ADC, PWM, I/O) initADC(); initMotorDriverIO(); initTimer0PWM(); initPCInterrupts(); //which arm is being used: 1 true, 0 flase uint8_t front_arm = 0; //gearmotor characteristics float cpr = 8400.0/4; float chain_ratio; float range_of_motion; if(front_arm){ chain_ratio = (16.0)*(12.0/9.0)*(12.0/11.0); range_of_motion = 190.0; }else{ chain_ratio = (16.0)*(12.0/9.0)*(12.0/10.0); range_of_motion = 215.0; } float max_desired_count = (cpr*chain_ratio)*(range_of_motion/360.0); float ADC_multiplier = max_desired_count/1023.0; float slowdown_count = 750.0; float target_buffer = 50.0; //set up moving average array and init values to zero uint8_t arraySize = 32; uint16_t ADC_values [arraySize]; uint16_t * ADC_pointer; ADC_pointer = &ADC_values[0]; initValues(ADC_pointer, arraySize, 0); //avg value variable uint16_t ADC_avg; //positon variables long desiredCount; long countError; //local variable for current encoder count long localEncoderCount; if(front_arm){ cli(); encoderValue = 1000; sei(); }else{ cli(); encoderValue = 1000; sei(); } while(1) { // Read ADC storeNewADC(ADC_pointer, arraySize, ADC_CHANNEL); ADC_avg = getAverage(ADC_pointer, arraySize); // Convert ADC to desired encoder count desiredCount = (float)ADC_avg * ADC_multiplier; //update local variable cli(); localEncoderCount = encoderValue; sei(); // Compare desired count to actual count countError = desiredCount - localEncoderCount; // Translate error to a PWM duty: not within 90 degrees, go 100, otherwise scale down if(countError > slowdown_count){ OCR0A = 255; set_bit(DRIVER_PORT, DRIVER_A); clear_bit(DRIVER_PORT, DRIVER_B); }else if(countError<=slowdown_count && countError>target_buffer){ OCR0A = 255 * (countError/(float)slowdown_count); set_bit(DRIVER_PORT, DRIVER_A); clear_bit(DRIVER_PORT, DRIVER_B); }else if(countError<=target_buffer && countError>=-target_buffer){ OCR0A = 0; set_bit(DRIVER_PORT, DRIVER_A); clear_bit(DRIVER_PORT, DRIVER_B); }else if(countError<-target_buffer && countError>=-slowdown_count){ OCR0A = 255 * -(countError/(float)slowdown_count); clear_bit(DRIVER_PORT, DRIVER_A); set_bit(DRIVER_PORT, DRIVER_B); }else if(countError < -slowdown_count){ OCR0A = 255; clear_bit(DRIVER_PORT, DRIVER_A); set_bit(DRIVER_PORT, DRIVER_B); } } return(0); } void initADC(void) { // reference voltage on VCC, do nothing ADCSRA |= (1 << ADPS0) | (1 << ADPS2); // ADC clock prescaler /32 ADCSRA |= (1 << ADEN); // enable ADC } uint16_t readADC(uint8_t channel) { //read ADC value from channel (ADC0 to ADC 5) ADMUX = (0b11000000 & ADMUX) | channel; ADCSRA |= (1 << ADSC); loop_until_bit_is_clear(ADCSRA, ADSC); return (ADC); } void initValues(uint16_t * arr, uint8_t size, uint16_t value){ uint8_t i; //copy 'value' into each element of array for(i=0;i<size;i++){ *arr = value; arr++; } } void storeNewADC(uint16_t * arr, uint8_t size, uint8_t channel){ uint8_t i; arr = arr + (size-1); //starting with last element of array, store value from the previous element for (i=0;i<(size-1);i++){ *arr = *(arr-1); arr--; } //read ADC for newest value into array *arr = readADC(channel); } uint16_t getAverage(uint16_t * arr, uint8_t size){ uint8_t i; uint16_t avg; uint32_t sum = 0; //sum all elements in array for(i=0;i<size;i++){ sum = sum + *arr; arr++; } //calculate avg and return avg = sum / size; return avg; } void initTimer0PWM(void){ //fast pwm clear on match TCCR0A |= (1 << WGM00) | (1 << WGM01); TCCR0A |= (1<<COM0A1); //no clock scale TCCR0B |= (1<<CS00); //setup for output DRIVER_DDR |= (1<<DRIVER_PWM); } void initMotorDriverIO(void){ //set for output DRIVER_DDR |= (1<<DRIVER_A); DRIVER_DDR |= (1<<DRIVER_B); //init to zero DRIVER_PORT &= ~(1<<DRIVER_A); DRIVER_PORT &= ~(1<<DRIVER_B); } void initPCInterrupts(void){ //set pins for input ENCODER_DDR &= ~(1<<ENCODER_A); ENCODER_DDR &= ~(1<<ENCODER_B); //enable PCINT0_vect GIMSK |= (1<<PCIE0); //enable PCINT on PCINT1 and PCINT2 PCMSK0 |= (1 << PCINT1) | (1<< PCINT2); //enable global interrupts sei(); }
C
#include<stdio.h> int main(){ int t; scanf("%d",&t); while(t--){ int n; scanf("%d",&n); int array[n]; for(int i=0;i<n;i++) scanf("%d",&array[i]); int zero_count = 0,j=1; for(int i=0;i<n;i++){ if(array[i]==0) zero_count++; else if(array[i]==array[j]){ array[i] = 2*array[i]; array[j] = 0; //zero_count++; } j++; } for(int i=0;i<n;i++){ if(array[i]!=0) printf("%d ",array[i]); } for(int i=0;i<zero_count;i++) printf("%d ",0); printf("\n"); } }
C
#include<stdio.h> #include<stdlib.h> typedef struct Node { int data; struct Node* next; struct Node* prev; }Node; // create a node with given integer Node* NewNode(int data){ Node* new_node = (Node*)malloc(sizeof(Node)); new_node->data = data; new_node->next = NULL; new_node->prev = NULL; return new_node; } // print a linkedlist given the head node void PrintLList(Node* node){ while(node!=NULL){ printf("%d ", node->data); node = node->next; } } Node* SortedInsert(Node *head,int data){ Node* current = head; Node* prev=NULL; if(current==NULL){ head = NewNode(data); } else if(current->data > data){ // in the beginning as head node head = NewNode(data); head->next = current; current->prev = head; } else{ // it can be in the middle or at the end // if at end current will be NULL and prev number will be the last element while(current && data > current->data){ prev = current; current = current->next; } Node* temp = NewNode(data); prev->next = temp; temp->prev = prev; if(current){ temp->next = current; current->prev = temp; } } return head; } int main(){ Node* head = NULL; head = SortedInsert(head, 3); PrintLList(head); printf("\n"); head = SortedInsert(head, 1); PrintLList(head); printf("\n"); head = SortedInsert(head, 2); PrintLList(head); printf("\n"); head = SortedInsert(head, 4); PrintLList(head); }
C
#ifndef F_CPU #define F_CPU 4915200 #include <stdio.h> #include <avr/io.h> #include <stdlib.h> #include <util/delay.h> #include "oled.h" #include "buttons.h" #include "adc.h" #include "highscore.h" int char_selector = 0; int array_pos = 0; volatile uint8_t *score_data = (uint8_t *) 0x1C00; //OLED Data start address volatile uint8_t *score_name = (uint8_t *) 0x1C09; //OLED Data start address #define name ( (uint8_t(*)[4]) (score_name) ) // Each name is 4 bytes long. volatile char* player_name = (uint8_t *) 0x1C30; // Name of current player (selected by writing it in with create_name()) uint8_t highscores_n = 0; // Number of recorded scores void highscore_sram_init(){ for (uint8_t i=0; i <5; i++){ score_data[i] = 0x00; } for (uint8_t j=0; j <50; j++){ score_name[j] = 0x00; } } void highscore_save_sram(char* word, uint8_t score){ uint8_t placement = highscore_check_sram(score); if(placement != 255){ // Score is not lower than all other scores for (uint8_t j=5; j>placement; j--){ score_data[j] = score_data[j-1]; for (uint8_t k=0; k<4; k++){ name[j][k] = name[j-1][k]; // Name[player ranking][player name character(iterate 0-3)] } } score_data[placement] = score; for (uint8_t i=0; i<4; i++){ name[placement][i] = word[i]; } } highscores_n++; } uint8_t highscore_check_sram(uint8_t score){ for (uint8_t i = 0; i < 5;i++){ if (score > score_data[i]){ return i; } } return 255; } void highscore_display_sram(){ OLED_clear_all(); OLED_home(); OLED_pos(0,25); OLED_print_all("Highscores"); for (uint8_t i=0; i<highscores_n; i++){ OLED_pos(i+2,30); OLED_print_number(i+1); OLED_pos(i+2,40); for (uint8_t j=0; j<4; j++){ OLED_print_char(name[i][j]); } OLED_pos(i+2,80); OLED_print_number(score_data[i]); } } void highscore_create_name() { OLED_clear_all(); OLED_update(); clear_name_in_sram(); char_selector = 0; array_pos = 0; OLED_pos(3,0); OLED_print_all("Name: "); _delay_ms(500); while(!(ADC_read(JOY_LR) >= 240 || ADC_read(JOY_LR) <= 10) ){ OLED_update(); OLED_pos(3,40); OLED_print_all(player_name); OLED_pos(5,30); OLED_print_char(letter_select()); _delay_ms(200); if(BUTTON_R && array_pos < 4) { player_name[array_pos] = letter_select(); array_pos += 1; } if(BUTTON_L && array_pos >= 0) { player_name[array_pos] = ' '; array_pos -= 1; player_name[array_pos] = ' '; if (array_pos <= 0){ array_pos = 0; } } } } char* highscore_get_player_name(){ return player_name; } char letter_select(){ char letter = 'A'; //starts select on A if (ADC_read(JOY_DU) >= 240) { //move UP if (char_selector <= 0){ char_selector = 25; return(letter + char_selector); } char_selector -= 1; } if (ADC_read(JOY_DU) <= 10) { //move DOWN if (char_selector >= 25){ char_selector = 0; return(letter + char_selector); } char_selector += 1; } return(letter + char_selector); } void clear_name_in_sram(){ for(int i = 0; i < 4; i++){ player_name[i] = ' '; } } #endif //F_CPU
C
/* make sure to set Env.DEBUG on! */ /* this file is meant to stress test the compile-time evaluation of * constant expressions and to make sure that the compiler figures out * the sizes of types. * * Note: all type sizes are rounded up to the nearest multiple of 4 bytes. * this is simplifies any alignment requirements, as well as follows * ANSI standards, which stipulate minimum sizes only. */ typedef enum _foo { FOO, BAR = 10 + 1 - 1, BAZ } foo; int main(int arr5[][BAR][BAZ], int (*FOO /* expect warning */ )(void *, int BAZ /* no warning expected */)) { int arr1[1 ? ((1 - 2) < 0 ? 4 /* this */ : 5) : 6]; int arr2[3]; int arr3[BAR], *arr4; int arr6[BAR][BAZ]; int arr7["hello"[0]]; int arr8['h']; int arr9[] = {1, 2, -3}; int arr10[][2][2] = {{{1,0},{0,1}},{{1,0},{0,1}},{{1,0},{0,1}},{{1,0},{0,1}}}; /* enum sizes */ sizeof FOO; sizeof BAR; sizeof(enum _foo); sizeof(foo); /* basic types */ sizeof(char); sizeof(unsigned char); sizeof(int); sizeof(unsigned int); sizeof(long int); sizeof(float); sizeof(double); sizeof(long double); /* basic pointer types */ sizeof(char *); sizeof(unsigned char *); sizeof(int *); sizeof(unsigned int *); sizeof(long int *); sizeof(float *); sizeof(double *); sizeof(long double *); /* array sizes */ sizeof arr1; /* expect 16 */ sizeof arr2; /* expect 12 */ sizeof arr3; /* expect: 4 * 10 = 40 */ sizeof arr4; /* pointer size */ sizeof arr5; /* pointer size */ sizeof arr6; /* expect 10 * 11 * 4 = 440 */ sizeof arr7; /* expect 416 */ sizeof arr8; /* expect 416 */ sizeof arr9; /* expect 12 */ sizeof arr10; /* expect 64 */ }
C
#include "clipper.h" void clip(render_context *rc, int width, int height) { } // int i, i1, i3; // bool c1, c2, c3; // Vec3 *p1, *p2, *p3, r1, r2, nr1, nr2; // Vec2 tr1, tr2; // Vec3 oob = {-1, -1, 0}; // for(i1 = 0, i3 = 0; i1 < rc->mlist->len; i1++, i3++) { // // c1 = false; c2 = false; c3 = false; // p1 = &rc->vlist->data[i3]; // p2 = &rc->vlist->data[i3+1]; // p3 = &rc->vlist->data[i3+2]; // // bool c1High = p1->y < 0; // bool c1Low = p1->y > height; // bool c1Left = p1->x < 0; // bool c1Right = p1->x > width; // bool p1Out = c1High || c1Low || c1Left || c1Right; // // bool c2High = p2->y < 0; // bool c2Low = p2->y > height; // bool c2Left = p2->x < 0; // bool c2Right = p2->x > width; // bool p2Out = c2High || c2Low || c2Left || c2Right; // // bool c3High = p3->y < 0; // bool c3Low = p3->y > height; // bool c3Left = p3->x < 0; // bool c3Right = p3->x > width; // bool p3Out = c3High || c3Low || c3Left || c3Right; // // /* new tris and ordering // * tris are in order p1,p2,p3 // * let's say p1 is clipped into points r1, r2 // * new tris should be r1,p2,p3 (ordering works because r1 near p1), // * r1, p3, r2 (ordering works again?) */ // else if(c1) { // r1 = clip1(*p1, *p2, width, height, c1High, c1Low, c1Left, c1Right); // r2 = clip1(*p1, *p3, width, height, c1High, c1Low, c1Left, c1Right); // // interp normals and shit // double t1 = (p1.x - r1.x)/(p1.x - p2.x); // nr1 = vec3lerp(rc->nlist->data[i3], rc->nlist->data[i3+1], t1); // tr1 = vec2lerp(rc->tlist->data[i3], rc->tlist->data[i3+1], t1); // double t2 = (p1.x - r2.x)/(p1.x - p3.x); // nr2 = vec3lerp(rc->nlist->data[i3], rc->nlist->data[i3+2], t2); // tr2 = vec2lerp(rc->tlist->data[i3], rc->tlist->data[i3+2], t2); // *p1 = r1; // &rc->nlist->data[i3] = nr1; // &rc->tlist->data[i3] = tr1; // &rc->p // } // } //} // //void clip_line(Vec3 *p1, Vec3 *p2, int width, int height) { // bool c1High = p1->y < 0; // bool c1Low = p1->y > height; // bool c1Left = p1->x < 0; // bool c1Right = p1->x > width; // bool p1Out = c1High || c1Low || c1Left || c1Right; // // bool c2High = p2->y < 0; // bool c2Low = p2->y > height; // bool c2Left = p2->x < 0; // bool c2Right = p2->x > width; // bool p2Out = c2High || c2Low || c2Left || c2Right; // // if(p1Out) clip1(p1, *p2, width, height, c1High, c1Low, c1Left, c1Right); // if(p2Out) clip1(p2, *p1, width, height, c2High, c2Low, c2Left, c2Right); //} // //void clip1(Vec3 c, Vec3 o, int width, int height, bool U, bool D, bool L, bool R) { // // 2 point form: (y-y1)(x2-x1) = (x-x1)(y2-y1) // if(U) { // clip against y=0 // c = {-c.y*(o.x-c.x)/(o.y-c.y)+c.x, 0}; // } // if(L) { // clip against x=0 // c = {0, -c.x*(o.y-c.y)/(o.x-c.x)+c.y}; // } // if(D) { // clip against y=H // c = {(height - c.y)*(o.x-c.x)/(o.y-c.y)+c.x, height}; // } // if(R) { // clip against x=W // c = {width, (width-c.x)*(o.y-c.y)/(o.x-c.x)+c.y}; // } // return c; //}
C
#include<stdio.h> #include<time.h> #include<stdlib.h> #define NUMBER 20000 int main(void){ clock_t t_start,t_end; t_start = clock(); srand((unsigned)time(NULL)); int data[NUMBER]={0}; //乱数生成 for(int i=0;i<NUMBER;i++){ data[i]=rand(); } //基数ソート int flag=1; for(int keta=1;keta<5;keta++){ for(int i=0;i<NUMBER;i++){ int j=i; while(((data[j-1]/keta)>(data[j]/keta)) && (j>0)){ int tmp = data[j]; data[j] = data[j-1]; data[j-1] = tmp; j--; } } } //表示 for(int i=0;i<NUMBER;i++){ printf("[%d]=%d\n",i,data[i]); } t_end=clock(); printf("実行時間:%f\n",(double)(t_end-t_start)/CLOCKS_PER_SEC); return 0; }
C
#include <stdio.h> #include <cs50.h> int main(void) { // int numbers[50]; -- Cannot do that, user might want to enter 51 //Array is a chunk of memory int *numbers = NULL; //numbers really is just a pointer to the chunk of memory, there is no array; this pointer points to 0x00. // you can point this pointer to any chunk of memory, small or big int capacity=0; int size=0; while (true) { int number = get_int("Number: "); // Get number from human. if (number == INT_MAX) //EOF or Ctrl+D by user { break; } if (size == capacity) { numbers = realloc(numbers, sizeof(int) * (size + 1)); capacity++; //if realloc fails to allocate memory, that's why we take it in a temp pointer and check // allocate the pointer to a bigger memory heap, return new address of the chunk of memory } numbers[size] = number; size++; } for (int i = 0; i<size; i++) { printf("You inputted %i\n", numbers[i]); } free(numbers); }
C
#include <SDL.h> #include <SDL_net.h> #include <stdio.h> #include <string.h> #include "TCP.h" #include "game.h" #include "definition.h" void sendMessage(int player_id, char incommingMsg[]) { IPaddress ip; TCPsocket client; char completeMsg[100] = "HELLO"; int portNr = SENDPORT + player_id; //varje spelare skickar via sin egna Port sprintf(completeMsg, "Player %d: %s", player_id, incommingMsg); //lgger ihop meddelandet med spelares Alias //write the ip of the host SDLNet_ResolveHost(&ip, SERVERIP, portNr); client = SDLNet_TCP_Open(&ip); SDLNet_TCP_Send(client, completeMsg, strlen(completeMsg) + 1); SDLNet_TCP_Close(client); } void imConnected(int player_id) { IPaddress ip; TCPsocket client; int portNr = CONNECTPORT + player_id; //varje spelare skickar via sin egna Port //write the ip of the host SDLNet_ResolveHost(&ip, SERVERIP, portNr); while(1) { client = SDLNet_TCP_Open(&ip); SDL_Delay(1000); SDLNet_TCP_Send(client, 1, 20); SDLNet_TCP_Close(client); } } void createDemonCL(int id, const char * function, void(*f)(int)) //spelarens id, namnet p funktionen, sjlva funktionen { SDL_Thread *TCPThread = NULL; printf("ID %d \n", id); TCPThread = SDL_CreateThread(f, function, id); if (NULL == TCPThread) { printf("\nSDL_CreateThread failed: %s\n", SDL_GetError()); } else { printf("\nYou've created a demon, you monster!\n"); } } void listenForMessage(int player_id) { IPaddress ip; TCPsocket client; //write the ip of the host SDLNet_ResolveHost(&ip, SERVERIP, RECVPORT + player_id); while (1) { client = SDLNet_TCP_Open(&ip); char listenMessage[1000] = ""; SDLNet_TCP_Recv(client, &listenMessage, 1000); //recv on socket client, store in listenmsg, the incomming msg max length 1000 SDLNet_TCP_Close(client); addMessageToDisplay(renderer, listenMessage, MSG_DURATION); } return 0; } int connect(int currentID) { IPaddress ip; TCPsocket client; //write the ip of the host printf("testing connection\n"); if (SDLNet_ResolveHost(&ip, SERVERIP, INITPORT) == -1) { printf("Couldn't resolve host during the connection!\n"); SDL_Delay(4000); exit(1); } client = SDLNet_TCP_Open(&ip); int player_id = 0; printf("Player id %d\n", player_id); SDLNet_TCP_Recv(client, &player_id, 100); SDLNet_TCP_Close(client); printf("player id: %d\n", player_id); createDemonCL(player_id, "listenForMessage", listenForMessage); createDemonCL(player_id, "imConnected", imConnected); return player_id; }
C
#include "cmsis_os2.h" // CMSIS RTOS header file #include "Objects.h" #include "Board_GLCD.h" #define XOFFSETT 16*12 #define YOFFSETT 0 #define XOFFSETM 32 #define YOFFSETM 24*2 #define XOFFSETW 0 #define YOFFSETW 297 #define CHARWIDTH 16 #define CHARHEIGHT 24 #define LCDX 320 #define LCDY 240 #define __MAX_TIME 86400 const char nm[11] = {'N','O',' ','M','E','S','S','A','G','E','S'}; //('N','O',' ','M','E','S','S','A','G','E','S'); const char del[7] = {'D','e','l','e','t','e','?'}; /*---------------------------------------------------------------------------- * Thread 'Print': Print Messages *---------------------------------------------------------------------------*/ void thdPrint (void *argument); osThreadId_t tid_thdPrint; // thread id void printTime(void); void printMessage(void); void printWatch(void); const int line_width = 16; const int line_height = 3; int Init_thdPrint (void) { tid_thdPrint = osThreadNew (thdPrint, NULL, NULL); if (!tid_thdPrint) return(-1); return(0); } void thdPrint (void *argument) { while (1) { //print 30 times per second osDelay(osKernelGetTickFreq()/30); //OH BABY A TRIPLE ... OH YEA //print text message printMessage(); //print time on top right printTime(); //print stopwatch on bottom left printWatch(); osThreadYield(); } } //print message with timestamp and conditional delete prompt //oh boy it's a big one void printMessage(void){ uint16_t x = XOFFSETM; uint16_t y = YOFFSETM; uint32_t t = NULL; osStatus_t status; //only print message section on update status = osSemaphoreAcquire(semMSG, 0); if(status != osOK) return; //time message was received is stored uint32_t hourMSD, hourLSD, minuteMSD, minuteLSD, secondMSD, secondLSD; if(current == NULL){ int index; //print "NO MESSAGE' for(index = 0; index<11; index++){ GLCD_DrawChar(x, y, nm[index]); x += CHARWIDTH; } //overwrite remaining message space for(int i = index/line_width; i<line_height; i++){ for(int j = index%line_width; j<line_width; j++){ GLCD_DrawChar(x, y, ' '); x += CHARWIDTH; index++; } x = XOFFSETM; y += CHARHEIGHT; } //overwrite timestamp x = XOFFSETM; y = YOFFSETM+4*CHARHEIGHT; GLCD_DrawChar( x+(0*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(1*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(2*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(3*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(4*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(5*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(6*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(7*CHARWIDTH),y, ' '); x = XOFFSETM+6*CHARWIDTH; y = YOFFSETM+5*CHARHEIGHT; for(int i = 0; i<7; i++){ GLCD_DrawChar(x,y,' '); x+=CHARWIDTH; } } //if current != NULL else{ int index; //get scroll value osMutexAcquire(mutScroll, osWaitForever); int scr = scroll; osMutexRelease(mutScroll); //set starting index based on scroll value index = scr*line_width; //somehow, copying into a local array crashes the code /* char c[160]; osMutexAcquire(mutDLL, osWaitForever); for(int i = 0; i<160; i++){ c[i] = current->str[i]; } osMutexRelease(mutDLL); */ x = XOFFSETM+6*CHARWIDTH; y = YOFFSETM+5*CHARHEIGHT; status = osSemaphoreAcquire(semDelete, NULL); //if about to delete message if(status == osOK) { //reset semaphore for next print osSemaphoreRelease(semDelete); //write characters to prompt user for(int i = 0; i<7; i++){ GLCD_DrawChar(x,y,del[i]); x+=CHARWIDTH; } } //if not about to delete message else{ //overwrite delete message space for(int i = 0; i<7; i++){ GLCD_DrawChar(x,y,' '); x+=CHARWIDTH; } } //reset x and y to starting values x = XOFFSETM; y = YOFFSETM; //access Doubly Linked List to read string osMutexAcquire(mutDLL, osWaitForever); //write whole message for(int i = 0; i<line_height; i++){ for(int j = 0; j<line_width; j++){ //if a character, write character if((current->str[index]>0x1F) && (current->str[index]<0x7F)) GLCD_DrawChar(x, y, current->str[index]); //if not a character, write empty space else GLCD_DrawChar(x, y, ' '); x += CHARWIDTH; index++; } x = XOFFSETM; y += CHARHEIGHT; } if(current!=NULL) t = current->time; else t = NULL; osMutexRelease(mutDLL); x = XOFFSETM; y += CHARHEIGHT; //if there is a time, write the time if(t != NULL){ secondLSD = (t%10)+0x30; t/=10; secondMSD = (t%6)+0x30; t/=6; minuteLSD = (t%10)+0x30; t/=10; minuteMSD = (t%6)+0x30; t/=6; hourLSD = (t%10)+0x30; t/=10; if(t) hourMSD = t+0x30; else hourMSD = ' '; GLCD_DrawChar( x+(2*CHARWIDTH),y, ':'); GLCD_DrawChar( x+(5*CHARWIDTH),y, ':'); GLCD_DrawChar( x+(0*CHARWIDTH),y, hourMSD); GLCD_DrawChar( x+(1*CHARWIDTH),y, hourLSD); GLCD_DrawChar( x+(3*CHARWIDTH),y, minuteMSD); GLCD_DrawChar( x+(4*CHARWIDTH),y, minuteLSD); GLCD_DrawChar( x+(6*CHARWIDTH),y, secondMSD); GLCD_DrawChar( x+(7*CHARWIDTH),y, secondLSD); } //if there is not a time, write empty space else{ GLCD_DrawChar( x+(2*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(5*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(0*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(1*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(3*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(4*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(6*CHARWIDTH),y, ' '); GLCD_DrawChar( x+(7*CHARWIDTH),y, ' '); } } } //print time at top right of screen void printTime(void){ uint32_t t; uint32_t hourMSD, hourLSD, minuteMSD, minuteLSD, secondMSD, secondLSD; // calculated digits for display //get clock time osMutexAcquire(mutClkTime, osWaitForever); t = ClkTime; osMutexRelease(mutClkTime); //divide the clock into digits secondLSD = (t%10)+0x30; t/=10; secondMSD = (t%6)+0x30; t/=6; minuteLSD = (t%10)+0x30; t/=10; minuteMSD = (t%6)+0x30; t/=6; hourLSD = (t%10)+0x30; t/=10; if(t) hourMSD = t+0x30; else hourMSD = ' '; //draw digits GLCD_DrawChar( XOFFSETT+(2*CHARWIDTH),YOFFSETT*CHARHEIGHT, ':'); GLCD_DrawChar( XOFFSETT+(5*CHARWIDTH),YOFFSETT*CHARHEIGHT, ':'); GLCD_DrawChar( XOFFSETT+(0*CHARWIDTH),YOFFSETT*CHARHEIGHT, hourMSD); GLCD_DrawChar( XOFFSETT+(1*CHARWIDTH),YOFFSETT*CHARHEIGHT, hourLSD); GLCD_DrawChar( XOFFSETT+(3*CHARWIDTH),YOFFSETT*CHARHEIGHT, minuteMSD); GLCD_DrawChar( XOFFSETT+(4*CHARWIDTH),YOFFSETT*CHARHEIGHT, minuteLSD); GLCD_DrawChar( XOFFSETT+(6*CHARWIDTH),YOFFSETT*CHARHEIGHT, secondMSD); GLCD_DrawChar( XOFFSETT+(7*CHARWIDTH),YOFFSETT*CHARHEIGHT, secondLSD); } //print stopwatch at bottom left of screen void printWatch(void){ uint32_t t; int32_t minuteMSD, minuteLSD, secondMSD, secondLSD, hsecondMSD, hsecondLSD; // calculated digits for display //get stopwatch time osMutexAcquire(mutWatchTime, osWaitForever); t = WatchTime; osMutexRelease(mutWatchTime); //divide the stopwatch into digits hsecondLSD = (t%10)+0x30; t/=10; hsecondMSD = (t%10)+0x30; t/=10; secondLSD = (t%10)+0x30; t/=10; secondMSD = (t%6)+0x30; t/=6; minuteLSD = (t%10)+0x30; t/=10; minuteMSD = (t%6)+0x30; t/=6; //draw digits GLCD_DrawChar( XOFFSETW+(2*CHARWIDTH),YOFFSETW*CHARHEIGHT, ':'); GLCD_DrawChar( XOFFSETW+(5*CHARWIDTH),YOFFSETW*CHARHEIGHT, '.'); GLCD_DrawChar( XOFFSETW+(0*CHARWIDTH),YOFFSETW*CHARHEIGHT, minuteMSD); GLCD_DrawChar( XOFFSETW+(1*CHARWIDTH),YOFFSETW*CHARHEIGHT, minuteLSD); GLCD_DrawChar( XOFFSETW+(3*CHARWIDTH),YOFFSETW*CHARHEIGHT, secondMSD); GLCD_DrawChar( XOFFSETW+(4*CHARWIDTH),YOFFSETW*CHARHEIGHT, secondLSD); GLCD_DrawChar( XOFFSETW+(6*CHARWIDTH),YOFFSETW*CHARHEIGHT, hsecondMSD); GLCD_DrawChar( XOFFSETW+(7*CHARWIDTH),YOFFSETW*CHARHEIGHT, hsecondLSD); }
C
#include <stdlib.h> #include <string.h> #include "line.h" #include "asmbl.h" #include "misc.h" #include "symbols.h" #include "opcodes.h" #include "globals.h" symbol_t *init_macro(); symbol_t *init_data(enum SYMBOL type); symbol_t *init_code(); symbol_t * init_symbol(enum SYMBOL type) { symbol_t *sym; switch (type) { case SYMBOL_MACRO: sym = init_macro(); if(sym) return sym; break; case SYMBOL_DATA_STRING: sym = init_data(SYMBOL_DATA_STRING); if(sym) return sym; break; case SYMBOL_DATA_NUMBERS: sym = init_data(SYMBOL_DATA_NUMBERS); if(sym) return sym; break; case SYMBOL_CODE: sym = init_code(); if(sym) return sym; break; default: break; } return NULL; } void free_symbol(symbol_t *sym) { if(!sym || !sym->symbol) return; switch (sym->type) { case SYMBOL_MACRO: SAFE_FREE(sym->symbol->macro->name) SAFE_FREE(sym->symbol->macro) SAFE_FREE(sym->symbol) SAFE_FREE(sym) return; case SYMBOL_DATA_STRING: SAFE_FREE(sym->symbol->directive) SAFE_FREE(sym->symbol) SAFE_FREE(sym) return; case SYMBOL_DATA_NUMBERS: SAFE_FREE(sym->symbol->directive->nums) SAFE_FREE(sym->symbol->directive) SAFE_FREE(sym->symbol) SAFE_FREE(sym) return; case SYMBOL_CODE: /* SAFE_FREE(sym->symbol->instruction->source->op->name) */ /* SAFE_FREE(sym->symbol->instruction->destination->op->name) */ if(sym->symbol->instruction->source->op) SAFE_FREE(sym->symbol->instruction->source->op) if(sym->symbol->instruction->destination->op) SAFE_FREE(sym->symbol->instruction->destination->op) if(sym->symbol->instruction->source) SAFE_FREE(sym->symbol->instruction->source) if(sym->symbol->instruction->destination) SAFE_FREE(sym->symbol->instruction->destination) if(sym->symbol->instruction) SAFE_FREE(sym->symbol->instruction) if(sym->symbol) SAFE_FREE(sym->symbol) if(sym) SAFE_FREE(sym) return; case SYMBOL_ENTRY: SAFE_FREE(sym->symbol->directive) SAFE_FREE(sym->symbol) SAFE_FREE(sym) return; default: return; } } /* Initialize symbol struct for the macro lines. */ symbol_t * init_macro() { symbol_t *macro_symbol = (symbol_t *)malloc(sizeof(symbol_t)); union symbol_un *symbol = (union symbol_un *)malloc(sizeof(union symbol_un)); macro_t *macro = (macro_t *)malloc(sizeof(macro_t)); char *name = (char *)malloc(sizeof(char)*MACRO_LEN); if (!macro_symbol || !symbol || !macro || !name) return NULL; macro->name = name; symbol->macro = macro; macro_symbol->symbol = symbol; macro_symbol->type = SYMBOL_MACRO; return macro_symbol; } /* Initialize symbol struct for the data lines. */ symbol_t * init_data(enum SYMBOL type) { symbol_t *data_symbol = (symbol_t *)malloc(sizeof(symbol_t)); union symbol_un *symbol = (union symbol_un *)malloc(sizeof(union symbol_un)); directive_t *directive = (directive_t *)malloc(sizeof(directive_t)); char *data = NULL; int *nums = NULL; if(data_symbol && symbol && directive) { /* Connecting the data objects together */ symbol->directive = directive; data_symbol->symbol = symbol; /* for .string */ if(type == SYMBOL_DATA_STRING) { data =(char *)malloc(sizeof(char)*LINE_LEN); if(data) { directive->data = data; data_symbol->type = SYMBOL_DATA_STRING; return data_symbol; } return NULL; } /* for .data */ if (type == SYMBOL_DATA_NUMBERS) { nums = (int *)malloc(sizeof(int)*LINE_LEN); if(nums) { directive->nums = nums; data_symbol->type = SYMBOL_DATA_NUMBERS; return data_symbol; } return NULL; } } SAFE_FREE(data_symbol) SAFE_FREE(data) SAFE_FREE(directive) return NULL; } /* Initialize symbol struct for the code lines. */ symbol_t * init_code() { symbol_t *data_symbol = (symbol_t *)malloc(sizeof(symbol_t)); union symbol_un *symbol = (union symbol_un *)malloc(sizeof(union symbol_un)); struct operand *source = (struct operand *)malloc(sizeof(struct operand)); struct operand *destination = (struct operand *)malloc(sizeof(struct operand)); union op *dst_op = (union op *)malloc(sizeof(union op *)); union op *src_op = (union op *)malloc(sizeof(union op *)); instruction_t *code = (instruction_t *)malloc(sizeof(instruction_t)); if(!data_symbol || !symbol || !code || !source || !destination || !src_op || !dst_op) { SAFE_FREE(data_symbol) SAFE_FREE(symbol) SAFE_FREE(code) SAFE_FREE(source) SAFE_FREE(destination) SAFE_FREE(dst_op) SAFE_FREE(src_op) return NULL; } src_op->name = NULL; dst_op->name = NULL; destination->op = dst_op; source->op = src_op; code->source = source; code->destination = destination; symbol->instruction = code; data_symbol->symbol = symbol; return data_symbol; } symbol_node * next_node(symbol_node **list, char *name, int value, enum SYMBOL property) { char *node_name; symbol_node *tmp, *node; node = (symbol_node *)calloc(sizeof(symbol_node), 1); tmp = *list; node_name = (char *)malloc(sizeof(char)*strlen(name)); if(!node || !node_name) return NULL; strcpy(node_name, name); node->name = node_name; node->value = value; node->property = property; node->next = NULL; if(!(*list)) { (*list)->name = node_name; (*list)->value = value; (*list)->property = property; (*list)->next = NULL; SAFE_FREE(node) return *list; } /* The list is not empty; get the last node andn set it */ while(tmp) { /* reached the end of the linked list */ if(!tmp->next) { tmp->next = node; /* setting the new node */ break; } else tmp = tmp->next; /* proceeds to the next node */ } return *list; } int search_list(const symbol_node *list, char *name, int *value, int *property) { char s[LINE_LEN]; symbol_node **tmp = (symbol_node **) &list; if(!name) return ERROR; strcpy(s, name); while((*tmp)) { if(strcmp_hash((*tmp)->name, s) && (*tmp)->property & ~(SYMBOL_ENTRY | SYMBOL_EXTERNAL)) { if(property) *property = (*tmp)->property; if(value) *value = (*tmp)->value; return (*tmp)->value; } (*tmp) = (*tmp)->next; } return ERROR; } int search_list_property(const symbol_node *list, char *name, int *value, int property) { char s[LINE_LEN]; symbol_node **tmp = (symbol_node **) &list; if(!name) return ERROR; strcpy(s, name); while((*tmp)) { if(strcmp_hash((*tmp)->name, s) && ((*tmp)->property == property)) { if(value) *value = (*tmp)->value; return (*tmp)->value; } (*tmp) = (*tmp)->next; } return ERROR; } void free_list(symbol_node **list) { symbol_node **tmp = list; while(*tmp) { *list = (*list)->next; if((*tmp)->name) SAFE_FREE((*tmp)->name) if(*tmp) SAFE_FREE(*tmp) *tmp = *list; } } void update_data(symbol_node *list) { symbol_node *tmp = list; while (tmp) { if(tmp->property & (SYMBOL_DATA_NUMBERS | SYMBOL_DATA_STRING)) tmp->value += IC + 100; tmp = tmp->next; } }
C
#include <stdlib.h> int random_int(int ceiling) { return rand() % ceiling; } size_t random_index(size_t ceiling) { size_t high = (size_t) rand(); size_t low = (size_t) rand(); size_t big = (high << 32) | low; return big % ceiling; }
C
// Name: Christopher Boyd // Date: April 6, 2020 // Title: Lab5 - matrix task // Description: Computes the dot product of matrices A and B as matrix C. // One thread is created per row. // ---------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <time.h> #include <pthread.h> // Defines matrix dimensions of 1024x1024 #define N 1024 #define M 1024 #define L 1024 pthread_t threads[N]; pthread_mutex_t lock; void *con(void*); double matrixA[N][M]; double matrixB[M][L]; double matrixC[N][L]; int main() { // Initialize lock pthread_mutex_init(&lock, NULL); // Fill 2d arrays with rand values: srand(time(NULL)); for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { matrixA[i][j] = rand(); } } for (int i = 0; i < M; i++) { for (int j = 0; j < L; j++) { matrixB[i][j] = rand(); } } int i; int tNum = 0; // Create threads for (i = 0; i < N; i++) { pthread_create(&threads[i], NULL, con, &tNum); } // Wait for all threads to complete their processing for (i = 0; i < N; i++) { pthread_join(threads[i], NULL); } printf("\nOperations complete! Here is matrix C:\n"); // Print results of matrix multiplication for (int l = 0; l < N; l++) { for (int m = 0; m < L; m++) { printf(" [ %.*f ] ", 0, matrixC[l][m]); } printf("\n"); } return 0; } void *con(void* args) { // args value represents the current column num to operate on. // Each thread requires a UNIQUE value. This is a critical section. pthread_mutex_lock(&lock); // Set alias for easier use int *row = (int *) args; // Loop performs math on the matrices to create matrixC for (int j = 0; j < L; j++) { double temp = 0; for (int k = 0; k < M; k++) { temp += matrixA[*row][k] * matrixB[k][j]; } matrixC[*row][j] = temp; } *row += 1; pthread_mutex_unlock(&lock); return 0; }
C
/* #include<stdio.h> #include<string.h> */ #include<sys/types.h> #include<sys/stat.h> #include<fcntl.h> #include<unistd.h> #include "ft.h" void ft_putstr_fd(int fd, char *str) { write(fd, str, ft_strlen(str)); } int main() { int fd; fd = open("42", O_WRONLY | O_CREAT | O_APPEND, S_IRUSR | S_IWUSR); if (fd == -1) { ft_putstr("open() failed\n"); } ft_putnbr(fd); if (close(fd) == -1) { ft_putstr("close() failed\n"); return (1); } return (0); }
C
/* mon_cnf_file.c * part of watchlist_monitor * uses inotify to monitor the config file for changes, reloads it when changed * uses kill(child_pid,SIGUSR1) to signal the reload. */ #include "watchlist_monitor.h" #include <sys/inotify.h> #include <sys/select.h> #define EVENT_SIZE (sizeof(struct inotify_event)) #define EVENT_BUF_LEN ( 1024 * (EVENT_SIZE+16)) int monitor_config_file(pid_t child_pid) { int inotify_fd; int watch_fd; int length=0; char in_buf[EVENT_BUF_LEN]; struct stat FileInfo; struct inotify_event *event = ( struct inotify_event * ) &in_buf; if (debug) puts("#### starting monitor_config_file thread ####"); if ((inotify_fd=inotify_init() )<0) { // error puts("inotify_init failed!"); return(EXIT_FAILURE); } watch_fd=inotify_add_watch(inotify_fd,config_file_name,IN_ATTRIB); for(;;) { if ((length=read(inotify_fd,in_buf,EVENT_BUF_LEN)) < 0) { puts("inotify read failed!"); return(EXIT_FAILURE); } if (debug) printf("#### mon_cnf_file has read %d bytes ####\n",length); if (event->mask & IN_ATTRIB) { if (debug) puts("#### signaling reload of config file ####"); // kill(child_pid,SIGUSR1); if ((stat(config_file_name, &FileInfo)<0) || (ParseConfig(prog)>0)) { printf("Error reading config file %s\n",config_file_name); return(EXIT_FAILURE); } printf ("Reloaded config file\n"); } } // end FOR close(inotify_fd); return(EXIT_SUCCESS); }
C
/** * \file funciones.c * \brief * \details Descripcion detallada del archivo * \author * \date 23-09-2017 09:54:06 */ int contm1 = 0 ;int ninguna = 0 ;int m0 = 0 ;int Flagcorriente = 0 ; #include "funciones.h" //Implementacion Switch-Case /** * \fn void maquina_estado() * \brief Implementacion Switch-Case * \details * \author * \date 23-09-2017 09:54:06 */ void maquina_estado() { static int estado = TRANSFORMAR; switch(estado) { case TRANSFORMAR: if((ninguna==0)) { m0max=ang_to_m0(); Feed_to_m1cont()(); contm1=0; estado = CONTANDO; } break; case CONTANDO: if((contm1<contm1max)) { contm1=contm1+1(); estado = CONTANDO; } if((contm1==contm1max) && (m0<m0max)) { m0=m0+DELTA(); estado = MOVER; } if((contm1==contm1max) && (m0>m0max)) { m0=m0-DELTA(); estado = MOVER; } break; case MOVER: if((m0!=m0max)) { estado = CONTANDO; } if((m0==m0max) || (Flagcorriente==1)) { estado = SALIR; } break; case SALIR: break; default: estado = TRANSFORMAR; } } //Funciones asociadas a los eventos /** * \fn int ang_to_m0(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ int ang_to_m0(void) { int res = 0 ; //Codigo propio de la funcion return res; } //Funciones asociadas a las acciones /** * \fn void M0MAX(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ void M0MAX(void) { //Codigo propio de la funcion } /** * \fn void m0max=ang_to_m0()(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ void m0max=ang_to_m0()(void) { //Codigo propio de la funcion } /** * \fn void Feed_to_m1cont()(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ void Feed_to_m1cont()(void) { //Codigo propio de la funcion } /** * \fn void contm1=contm1+1(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ void contm1=contm1+1(void) { //Codigo propio de la funcion } /** * \fn void m0=m0+DELTA(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ void m0=m0+DELTA(void) { //Codigo propio de la funcion } /** * \fn void m0=m0-DELTA(void) * \brief Resumen * \details Detalles * \author * \date 23-09-2017 09:54:06 */ void m0=m0-DELTA(void) { //Codigo propio de la funcion }
C
/* 09 Stereo Test.c Run 2 sound processes, one for each channel. Play a brief tone in each ear, one from each process. Then, create a tone that fades in volume and frequency from left to right. */ #include "simpletools.h" // Library includes #include "badgetools.h" #include "sound.h" sound *audioL, *audioR; // Pointers for audio processes int main() // Main function { badge_setup(); // Set up badge systems audioL = sound_run(9, -1); // Run left audio process audioR = sound_run(-1, 10); // Run right audio process oledprint("L "); sound_note(audioL, 0, C4); // Play the C4 note on left pause(500); // ...for 0.5 s sound_note(audioL, 0, 0); // Stop the note pause(100); // ...for 0.1 s oledprint(" R "); sound_note(audioR, 0, A4); // Play the C4 note on the right pause(500); // ...for 0.5 s sound_note(audioR, 0, 0); // Stop the note pause(100); // ...for 0.1 s oledprint(" FADE "); screen_auto(OFF); // Auto-oLED update off for speed for(int v = 127; v > -1; v--) // Vol fade L->R, f declines { line(127-v,32, 127-v, 64, 1); // Draw white line screen_update(); // Update display sound_freq(audioL, 0, 440 + v); // Left frequency sound_freq(audioR, 0, 440 + v); // Right frequency sound_volume(audioL, 0, v); // Left volume sound_volume(audioR, 0, 127 - v); // Right volume pause(20); // ...for 20 ms line(127-v,32, 127-v, 64, 0); // Draw black line screen_update(); // Update display } for(int v = 127; v > -1; v--) // Fade to 0 in right ear { // f continues decline line(127, 64-(v/4), 127, 64, 1); // Draw white line screen_update(); // Update display sound_volume(audioR, 0, v); // Right volume sound_freq(audioR, 0, 440 - 127 + v); // Right frequency pause(20); // For 20 s line(127, 64-(v/4), 127, 64, 0); // Draw black line screen_update(); // Update display } }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> struct county{ char *longName; char *shortName; unsigned int population; }; struct town{ char *name; unsigned int population; struct county aCounty; }; int main(void) { //declare variables to read files FILE *file_towns; FILE *file_counties; //declare array of structs to store information struct county *c=NULL; struct town *t=NULL; //Since it's a pointer one must use dinamic allocation to set the number of data to enter in the pointer c=malloc( 4 *sizeof(struct county)); t=malloc(5*sizeof(struct town)); //declare temporal variables to store information from files unsigned int uint; char temp[25]; //since char *name, char *longName, and char *shortName are pointers, they need to point to a data in memory //otherwise the data is overwritten. char County_long[4][10]; char County_short[4][10]; char Town_name[5][15]; //declare variables to use as counters int i,j; //----------COUNTIES.TXT FILE--------- //open the file using fopen file_counties=fopen("counties.txt","r"); //check that the file opens correctly if (!file_counties) { //if not, display message printf("Cannot open file. Please make sure the file is on correct folder\n"); return 1; } //set i to 0 i=0; //While the file has not read the end of the file (feof is true when it reach the end of the file) while (!feof(file_counties)){ //Take the first value and store it on County_long[i] fscanf(file_counties, "%s", County_long[i]); //set the value of the longName (c+i)->longName=County_long[i]; //Take the next value and store it on County_short[i] fscanf(file_counties, "%s", County_short[i]); //set the value of the shortName (c+i)->shortName=County_short[i]; //Take the last value and store it on c[i].population fscanf(file_counties, "%d", &(c+i)->population); //increase i in one unit i++; } //Close file fclose(file_counties); //-------------TOWN.TXT FILE---------- //open the file using fopen file_towns=fopen("towns.txt", "r"); //check that the file opens correctly if (!file_towns) { //if not, display message printf("Cannot open file. Please make sure the file is on correct folder\n"); return 1; } //set i to 0 i=0; //While the file has not read the end of the file (feof is true when it reach the end of the file) while (!feof(file_towns)){ //Take the first value and store it on Town_name[i] fscanf(file_towns, "%s", Town_name[i]); //set the value of the name (t+i)->name=Town_name[i]; //Take the next value and store it on t[i].population fscanf(file_towns, "%d", &(t+i)->population); //take the last value and store it on temp fscanf(file_towns, "%s", temp); //in a loop from 0 to 3 for(j=0;j<4;j++){ //check if the value of temp matches the longName value in c if(strcmp(temp,(c+j)->longName)==0){ //strcmp returns true if bth strings are equal //set the appropiate values (t+i)->aCounty.longName=(c+j)->longName; (t+i)->aCounty.shortName=(c+j)->shortName; (t+i)->aCounty.population=(c+j)->population; } } //increase i i++; } //close file fclose(file_towns); //------------DISPLAY INFO---------- //use %-15s to aling the headers of each value printf("%-15s %-15s %-15s %-15s %-10s\n","Town Name","Population" ,"County's Name","Short Name","Population"); printf("-----------------------------------------------------------------------------\n"); //Display all the info stored in t for(i=0;i<5;i++){ //Notice that (t+i)->aCountry and then .longName,.shortName,.population because the struct in the definition of the town struct is not a pointer printf("%-15s %-15d %-15s %-15s %-10d\n",(t+i)->name,(t+i)->population,(t+i)->aCounty.longName,(t+i)->aCounty.shortName,(t+i)->aCounty.population); } return 0; }
C
#include <Windows.h> #include <process.h> // #include <stdlib.h> struct MyStruct { int num; }; void run(void *p) { int *px = (int *)p; //ָ͵ת //printf("߳%d\n",*px); char str[100] = { 0 }; sprintf(str," ߳%d",*px); MessageBox(0, str, "߳", 0); } void main01() { /*for (int i = 0; i < 5; i++) //run(NULL);*/ for (int i = 0; i < 5; i++) { _beginthread(run, 0, &i); Sleep(1000); } system("pause"); }
C
#include <stdio.h> int main(){ long int query; while (scanf("%ld", &query) != EOF) { if(query == 2){ query = 0; } else{ query = (query + 1) / 2; query = 3 * ((2 * query * query) - 1) - 6; } printf("%ld\n", query); } return 0; }
C
#include <stdio.h> #include <stdlib.h> #define SPACE ' ' #define TAB '\t' /* K&R 1-20 detab: replaces tabs with spaces */ int Spaces(int N, int position); int main( int argc, char *argv[] ) { int N; //columns per tabstop int position, spaces, c, a; // N is set via command line or defaults to 5 if (argc < 2) N = 5; else N = atoi(argv[1]); position = 1; while ((c = getchar()) != EOF) { if (c == TAB) { spaces = Spaces(N, position); for (a = spaces; a > 0; --a) { putchar(SPACE); ++position; } } else if (c == '\n') { position = 1; putchar('\n'); } else { putchar(c); ++position; } } return 0; } int Spaces(int N, int position) { if (position % N == 0) return 1; else return (N + 1) - (position % N); }
C
#include <stdio.h> #include <string.h> #define M 10000 #define N 1000 char buf[M]; char *A[N]; void swap(char *a[], int i, int j) { char *tmp = a[i]; a[i] = a[j]; a[j] = tmp; } int partition(char *a[], int l, int r) { int i, j; for (j=l, i=l+1; i<=r; i++) if (strcmp(a[i],a[l])<0) swap(a, i, ++j); swap(a, l, j); return j; } void sort(char *a[], int l, int r) { if (l>=r) return; int k = partition(a, l, r); sort(a, l, k-1); sort(a, k+1, r); } int main() { int i, j=0; for (i=0; i<N; i++) { A[i] = &buf[j]; if (scanf("%s", A[i])==EOF) break; j += strlen(A[i])+1; } sort(A, 0, i-1); for (j=0; j<i; j++) printf("%s\n", A[j]); return 0; }
C
#define NRANSI #include "nrutil.h" void bcuint(double y[], double y1[], double y2[], double y12[], double x1l, double x1u, double x2l, double x2u, double x1, double x2, double *ansy, double *ansy1, double *ansy2) { void bcucof(double y[], double y1[], double y2[], double y12[], double d1, double d2, double **c); int i; double t,u,d1,d2,**c; c=matrix(1,4,1,4); d1=x1u-x1l; d2=x2u-x2l; bcucof(y,y1,y2,y12,d1,d2,c); if (x1u == x1l || x2u == x2l) nrerror("Bad input in routine bcuint"); t=(x1-x1l)/d1; u=(x2-x2l)/d2; *ansy=(*ansy2)=(*ansy1)=0.0; for (i=4;i>=1;i--) { *ansy=t*(*ansy)+((c[i][4]*u+c[i][3])*u+c[i][2])*u+c[i][1]; *ansy2=t*(*ansy2)+(3.0*c[i][4]*u+2.0*c[i][3])*u+c[i][2]; *ansy1=u*(*ansy1)+(3.0*c[4][i]*t+2.0*c[3][i])*t+c[2][i]; } *ansy1 /= d1; *ansy2 /= d2; free_matrix(c,1,4,1,4); } #undef NRANSI /* (C) Copr. 1986-92 Numerical Recipes Software 9.1-5i. */
C
#include<stdlib.h> #include<stdio.h> #define TAM 8 int main(){ int vetor[TAM]; int i, numero = 0, alteracoes = 0; for(i= 0; i < TAM; i++){ printf("Digite um numero para entrar no vetor: "); scanf("%d", &numero); vetor[i] = numero; } printf("\n"); printf("Vetor antes da ordenacao:\n"); for(i = 0; i < TAM; i++){ numero = vetor[i]; printf("%d ", numero); } alteracoes = 1; int temporario = 0; while(alteracoes > 0){ alteracoes = 0; for(i = 0; i < TAM-1; i++){ if(vetor[i] > vetor[i + 1]){ temporario = vetor[i]; vetor[i] = vetor[i + 1]; vetor[i + 1] = temporario; alteracoes = alteracoes + 1; } } } printf("\n"); printf("\nResultado da ordenação:\n"); for(i= 0; i < TAM; i++){ numero = vetor[i]; printf("%d ", numero); } printf("\n"); return 0; }
C
#include<stdio.h> #define SIZE 150 struct student { int roll; unsigned int marks[2]; unsigned int total; char name[15]; }; struct student inputStudentDetails(); void printStudentDetails(struct student); void updateTotal(struct student *); struct student getTopper(struct student [], int); //struct student getTopper(struct student *, int); int main() { struct student l[SIZE]; struct student s; int i, n; printf("enter number of students (<%d) \n", SIZE); scanf("%d",&n); if(n > SIZE) { printf("error \n"); return 0; } for(i=0; i<n; i++) { printf("\nGive roll number, name, mark1, mark2 of student %d\n", i+1); l[i]=inputStudentDetails(); printf("\n"); updateTotal(&l[i]); } s=getTopper(l, n); printf("\nDetails of the topper \n"); printf("\n Roll No.\tName\t\tMark1\tMark2\tTotal\n"); printStudentDetails(s); } struct student inputStudentDetails() /*Input details of one student and return it */ { struct student s; scanf("%d", &s.roll); scanf("%14s", s.name); scanf("%d", &s.marks[0]); scanf("%d", &s.marks[1]); return s; } void printStudentDetails(struct student s) /*Print details of student s */ { printf("%7d\t", s.roll); printf("\t%s\t", s.name); printf("%2d\t", s.marks[0]); printf("%2d\t", s.marks[1]); printf("%2d\n", s.total); } void updateTotal(struct student *ps) /*Update the total marks of one student whose address is the parameter */ { (*ps).total=(*ps).marks[0]+(*ps).marks[1]; } struct student getTopper(struct student sl[], int n) /*Get the details of the student maximum total marks among students in list sl of size n*/ { int maxpos=0, i; for(i=1; i<n; i++) if(sl[i].total > sl[maxpos].total) maxpos=i; return sl[maxpos]; } /* struct student getTopper(struct student sl[], int n) { struct student s; int i; s=sl[0]; for(i=1; i<n; i++) { if(sl[i].total > s.total) s=sl[i]; } return s; } */
C
/* Uiversal_queue.c -- ʵļ */ #include "Uiversal_queue.h" /* Proclaim local functions */ static Node * makeNode (const Item * const pi) ; /* Define interface functions */ Bool Initialize_Q (Queue * const pq) { *pq = (struct queue *) malloc (sizeof (struct queue)) ; if (NULL == *pq) return FALSE ; (*pq) -> front = (*pq) -> rear = NULL ; (*pq) -> current = 0 ; return TRUE ; } Bool IsEmpty_Q (const Queue * const pq) { return 0 == (*pq) -> current ; } Bool Insert_Q (Queue * const pq, const Item * const pi) { Node * new_node ; new_node = makeNode (pi) ; if (NULL == new_node) return FALSE ; else { if (IsEmpty_Q (pq)) (*pq) -> front = (*pq) -> rear = new_node ; else { (*pq) -> rear -> next = new_node ; (*pq) -> rear = (*pq) -> rear -> next ; } (*pq) -> current++ ; return TRUE ; } } Bool Delete_Q (Queue * const pq, Item * const pi) { Node * scan, * temp ; if (IsEmpty_Q (pq)) return FALSE ; else if (1 == (*pq) -> current) { *pi = (*pq) -> front -> item ; free ((*pq) -> front) ; (*pq) -> front = (*pq) -> rear = NULL ; (*pq) -> current-- ; return TRUE ; } else { scan = (*pq) -> front ; if (pi -> leavings == scan -> item.leavings) { *pi = (*pq) -> front -> item ; (*pq) -> front = (*pq) -> front -> next ; free (scan) ; (*pq) -> current-- ; return TRUE ; } else { while (scan) { if (pi -> leavings == scan -> next -> item.leavings) break ; else scan = scan -> next ; } if (pi -> leavings == scan -> next -> item.leavings) { temp = scan -> next ; scan -> next = scan -> next -> next ; free (temp) ; (*pq) -> current-- ; return TRUE ; } else return FALSE ; } } } void Traversal_Q (const Queue * const pq, void (* pfun) (const Item * const pi)) { Node * scan ; scan = (*pq) -> front ; while (scan) { (* pfun) (&scan -> item) ; scan = scan -> next ; } } void Release_Q (const Queue * const pq) { Node * scan, * temp ; scan = (*pq) -> front ; while (scan) { temp = scan ; scan = scan -> next ; free (temp) ; } } /* Define local functions */ static Node * makeNode (const Item * const pi) { Node * new_node ; new_node = (Node *) malloc (sizeof (Node)) ; if (NULL == new_node) return NULL ; else { new_node -> item = *pi ; new_node -> next = NULL ; return new_node ; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* lem_free.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gartanis <[email protected]> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/08/28 16:19:30 by gartanis #+# #+# */ /* Updated: 2020/08/28 16:19:34 by gartanis ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/lemin.h" void links_free(t_links *links, int size) { t_node *adjacent; t_node *tmp; int i; i = -1; tmp = NULL; adjacent = NULL; while (++i < (size + 1)) { adjacent = links->adjace[i]; while (adjacent) { tmp = adjacent; adjacent = adjacent->next; tmp->name = NULL; free(tmp); } links->adjace[i] = NULL; } free(links->adjace); links->visited = NULL; } void rooms_free(t_rooms *rooms) { t_node *tmp; tmp = NULL; while (rooms->head) { tmp = rooms->head; rooms->head = rooms->head->next; free(tmp->name); tmp->name = NULL; free(tmp); } rooms->head = NULL; rooms->start = NULL; rooms->end = NULL; tmp = NULL; } void paths_free(t_path **paths) { int i; if (paths) { i = -1; while (paths[++i]) free(paths[i]); } } void lemin_free(t_lemin *lemin) { if (lemin->links) { links_free(lemin->links, lemin->rooms->total); free(lemin->links); } if (lemin->rooms) { rooms_free(lemin->rooms); free(lemin->rooms); } if (lemin->node) free(lemin->node); if (lemin->paths) { paths_free(lemin->paths); free(lemin->paths); } if (lemin->str) { free((*lemin->str)); free(lemin->str); } }
C
#include<stdio.h> int main() { //code int testcase; scanf("%d",&testcase); for(int i = 0; i < testcase; i++) { // int c1[10000], c2[10000]; int score1 = 0, score2 = 0; int n1, n2; scanf("%d %d",&n1, &n2); int c1[n1] , c2[n2]; for(int j = 0; j < n1; j++) { scanf("%d",&c1[j]); } for(int j = 0; j < n1; j++) { // scanf("%d",&c1[j]); score1 += c1[j]; } for(int k = 0; k < n2; k++) { scanf("%d",&c2[k]); } for(int k = 0; k < n2; k++) { // scanf("%d",&c2[k]); score2 += c2[k]; } if(score1 > score2) { printf("C1\n"); } else { printf("C2\n"); } } return 0; }
C
///////////////////////////////////////////////////////////////////////////// #include <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> struct triple_s { char **data; int maxlen; int len; }; void sss_print(struct triple_s *sss) { printf("%d\n", sss->len); for(int i = 0; i < sss->len; i++) { printf("%s\n", sss->data[i]); } } // sss_create() creates a new SSS ADT // effects: allocates memory (you must call sss_destroy) // time: O(1) struct triple_s *sss_create(void) { struct triple_s *obj = malloc(sizeof(struct triple_s)); obj->len = 0; obj->maxlen = 1; obj->data = malloc(obj->maxlen * sizeof(char *)); return obj; } // sss_destroy(sss) destroys sss // requires: sss is valid (not NULL) // effects: sss is no longer valid // time: O(n) void sss_destroy(struct triple_s *sss) { assert(sss); for (int i = 0; i < sss->len ; i++) { free(sss->data[i]); } free(sss->data); free(sss); } // sss_search(sss, s) finds the index of s in sss // note: returns -1 if s does not appear in the sss // time: O(m*logn) int sss_search(const struct triple_s *sss, const char *s) { int low = 0; int high = sss->len - 1; if(sss->len == 0) return -1; while (low <= high) { int mid = (low + high) / 2; int result = strcmp(sss->data[mid], s); if (result == 0) { return mid; } else if (result < 0) { low = mid + 1; } else { high = mid - 1; } } return -1; } // sss_add(sss, s) adds s to sss in the correct index (lexicographically) // notes: if s already exists, there is no effect // when s is added, the indices of words that lexicographically // follow s will be changed (+1) because s is added into the "middle" // effects: may modify sss // time: O(n + m*logn) void sss_add(struct triple_s *sss, const char *s) { //int present = 0; int lenm = strlen(s); int insert = sss->len; // creating array to copy original s into if(sss_search(sss, s) != -1) { return; } char *temp = malloc((lenm + 1) * sizeof(char)); // copying s into temp strcpy(temp, s); // doubling strategy if(sss->len == sss->maxlen) { sss->maxlen *= 2; sss->data = realloc(sss->data, sss->maxlen * sizeof(char *)); } //present = sss_search(sss, s); //if(sss_search(sss, s) == -1) { for(int i = 0; i < sss->len; i++) { int result = strcmp(sss->data[i], s); if(result > 0) { insert = i; break; } } // changing indices for(int i = sss->len; i > insert; i--) { sss->data[i] = sss->data[i - 1]; } sss->data[insert] = temp; sss->len++; } // sss_add_follows(sss, s) adds s to the "end" of the sss // requires: s lexicographically follows all strings already in sss // effects: modifies sss // time: O(m) [amortized] void sss_add_follows(struct triple_s *sss, const char *s) { // doubling strategy if(sss->len == sss->maxlen) { sss->maxlen *= 2; sss->data = realloc(sss->data, sss->maxlen * sizeof(char *)); } int lenm = strlen(s); char *temp = malloc((lenm + 1) * sizeof(char)); sss->len++; strcpy(temp, s); sss->data[sss->len - 1] = temp; } // sss_remove(sss, s) removes s from sss (if it exists) // notes: if s is removed, the indices of words that lexicographically // follow s will be changed (-1) // effects: may modify sss // time: O(n + m*logn) void sss_remove(struct triple_s *sss, const char *s) { int index = sss_search(sss, s); if(index == -1) { return; } free(sss->data[index]); for(int i = index; i < sss->len - 1; i++) { //sss->data[i] = sss->data[i + 1]; sss->data[i] = sss->data[i + 1]; } //free(sss->data[sss->len - 1]); sss->len--; //sss->data = realloc(sss->data, sss->len * sizeof(char *)); } // sss_count(sss) gets the number of strings in sss // time: O(1) int sss_count(const struct triple_s *sss) { return sss->len; } // sss_get(sss, idx) retrieves a pointer to the string in sss // at the given idx (index) // requires: 0 <= idx < sss_count(sss) // time: O(1) const char *sss_get(const struct triple_s *sss, int idx) { assert((0 <= idx) && (idx < sss_count(sss))); return sss->data[idx]; }
C
/***************************************************************************** AUTH: William Payne * FILE: g_command.c * LAST MOD: 15/10/18 * PURPOSE: Functions for GCommand structs *****************************************************************************/ #include "g_command.h" #include "file_io.h" /*STATIC FUNCTION FORWARD DECLARTIONS*/ /*GCOMMAND FUNCTIONS*/ /*Having the following function declared as static forces you to use them by dereferencing a function pointer in the GCommand structs allowing for better validation*/ /** * rotate(): * --- --- --- * Calculates the angle from the 'command' data and either adds or * subtracts it from the current angle stored in 'pen'. */ static int rotate( Pen *pen, GCommand *command); /** * move(): * --- --- * Moves the cursor place by passing the coordinate data from * calculatePosition() to pen->positon. */ static int move(Pen *pen, GCommand *command); /** * draw(): * --- --- * Calculates the start and end position for line() to draw the pattern stored * in 'pen' onto the terminal. */ static int draw(Pen *pen, GCommand *command); /** * colourFG(): * --- --- --- * Sets the pen FG field to the command data and calls setFgColour in effects.c */ static int colourFG(Pen *pen, GCommand *command); /** * colourBG(): * --- --- --- * Sets the pen BG field to the command data and calls setBgColour in effects.c */ static int colourBG(Pen *pen, GCommand *command); /** * changePattern(): * --- --- --- --- * Sets the pen field 'pattern' the command data. */ static int changePattern(Pen *pen, GCommand *command); /*==END OF COMMAND FUNCTIONS==*/ /** * allocateDouble(): * --- --- --- --- * Allocates enough memory to hold a double to the GCommand and assigns the * value at data to that memory. */ static int allocateDouble(char *data, GCommand *gCommand); /** * allocateInt(): * --- --- --- --- * Allocates enough memory to hold an int to the GCommand and assigns the value * at data to that memory. */ static int allocateInt(char *data, GCommand *gCommand); /** * allocateChar(): * --- --- --- --- * Allocates enough memory to hold a double and assigns the value * at data to that memory. */ static int allocateChar(char *data, GCommand *gCommand); /***************************************************************************** * FUNCTION: createGCommand *----------------------------------------------------------------------------- * IMPORTS: * type(char*) ~ Contains the type of graphic command. * data(char*) ~ Contains the data for the graphic command. * newGCommand(GCommand**) ~ New GCommand to be allocated memory and data. * * EXPORTS: * status(int) ~ Number indicating status of the function (errorcode) * * PURPOSE: * Creates a GCommand struct and allocates the correct data depending on the * imported String 'type'. * * ERROR CODES: * 0 = Success. * 1 = Invalid type. * 2 = Invalid data. * * NOTES: * newGCommand will be NULL if an error occurs. * newGCommand needs to be freed before the end of the program. *****************************************************************************/ int createGCommand(char *type, char *data, GCommand **newGCommand) { int status = 0; CommandFunc commandFuncPtr = NULL; AllocateFunc allocaterPtr = NULL; /*Formatting type to uppercase to match predefined type constants*/ capitalize(type); /*Find and validate GCommand type*/ if(strcmp(type, ROTATE) == 0) { /*Giving each command a function pointer to its command function prevents the need of using another if/switch statement to call the function*/ commandFuncPtr = &rotate; allocaterPtr = &allocateDouble; } else if(strcmp(type, MOVE) == 0) { commandFuncPtr = &move; allocaterPtr = &allocateDouble; } else if(strcmp(type, DRAW) == 0) { commandFuncPtr = &draw; allocaterPtr = &allocateDouble; } else if(strcmp(type, FG) == 0) { commandFuncPtr = &colourFG; allocaterPtr = &allocateInt; } else if(strcmp(type, BG) == 0) { commandFuncPtr = &colourBG; allocaterPtr = &allocateInt; } else if(strcmp(type, PATTERN) == 0) { commandFuncPtr = &changePattern; allocaterPtr = &allocateChar; } else { /*ERROR - Type was invalid, could not get ALLOCATOR*/ status = 1; } /*Constructing newGCommand*/ if(status == 0) { /*Allocating heap memory for GCommand struct*/ *newGCommand = (GCommand*)malloc(sizeof(GCommand)); /*Assigning the command function*/ (*newGCommand)->executer = (VoidFunc)commandFuncPtr; /*Attempt to allocate and assign data to GCommand data*/ if((*allocaterPtr)(data,*newGCommand) == 1) { /*ERROR - Data was invalid*/ status = 2; freeCommand(*newGCommand); } } return status; } /***************************************************************************** * STATIC FUNCTION: rotate *----------------------------------------------------------------------------- * IMPORTS: * pen(Pen*) ~ Pen struct tracks data for line() function. * command(GCommand*) ~ GCommand struct contains the command data. * * EXPORTS: * '0' ~ No errors. * * PURPOSE: * Calculates the angle from the 'command' data and either adds or * subtracts it from the current angle stored in 'pen'. * * NOTES: * I'm pretty sure calculating the principal angle is pointless. * It could be easily validated if by adding or subtracting 360 off the angle * until it is within the range of -360 to +360 but its more if/else statements * and more processing that will only help in very extreme circumstances. *****************************************************************************/ static int rotate( Pen *pen, GCommand *command) { /*Converting angle to clockwise*/ pen->angle += -1*(*(double*)(command->data)); return 0; } /***************************************************************************** * STATIC FUNCTION: move *----------------------------------------------------------------------------- * IMPORTS: * pen(Pen*) ~ Pen struct tracks data for line() function. * command(GCommand*) ~ GCommand struct contains the command data. * * EXPORTS: * '0' ~ No errors. * * PURPOSE: * Moves the cursor place by passing the coordinate data from * calculatePosition() to pen->positon. * * ERROR CODES: * '0' ~ No errors. * * NOTES: I'm having trouble with the cursors accuracy, currently the realign * function appears to be solving the problem but choosing a tolerance * to realign on is not fully clear. * *****************************************************************************/ static int move(Pen *pen, GCommand *command) { double distance; Coord currPos = pen->position; Coord newPos = NEW_COORD; char logEntry[LOG_ENTRY_LENGTH]; distance = *(double*)(command->data); /*Finding new cursor position.*/ calculatePosition(&newPos, &pen->realPos, distance, pen->angle); /*assigning the new cursor position to the pen struct*/ pen->realPos = newPos; pen->position.pos[0] = rounds(newPos.pos[0]); pen->position.pos[1] = rounds(newPos.pos[1]); /*If the the coordinates current position is to far out of line with its real position reset it.*/ realign(&pen->realPos, &pen->position); /*LOGGING---------------------------------------------------------------*/ formatLog(logEntry, DRAW, &currPos, &newPos); tlog(logEntry); /*TurtleGraphicsDebug*/ #ifdef DEBUG penDown(); fprintf(stderr,"%s",logEntry); #endif return 0; } /***************************************************************************** * STATIC FUNCTION: draw *----------------------------------------------------------------------------- * IMPORTS: * pen(Pen*) ~ Pen struct tracks data for line() function. * command(GCommand*) ~ GCommand struct contains the command data. * * EXPORTS: * '0' ~ No errors. * * PURPOSE: * Calculates the start and end position for line() to draw the pattern stored * in 'pen' onto the terminal. * * ERROR CODES: * 0 ~ No errors. * * NOTES: * -- *****************************************************************************/ static int draw(Pen *pen, GCommand *command) { int x1, y1, x2, y2; double distance; Coord currPos = pen->position; Coord realPos = pen->realPos; Coord newPos = NEW_COORD; Coord startPos = realPos; char logEntry[LOG_ENTRY_LENGTH]; distance = *(double*)(command->data); /*Calculating the end point of line to be drawn*/ /*The distance is reduced by one to remove a pattern plot at the final position of the cursor - this has to be corrected after the plot*/ calculatePosition(&newPos, &currPos, distance-1, pen->angle); /*Getting rounded coordinates for the line function*/ x1 = rounds(currPos.pos[0]); y1 = rounds(currPos.pos[1]); x2 = rounds(newPos.pos[0]); y2 = rounds(newPos.pos[1]); /*Plotting the a line to the terminal*/ line(x1, y1, x2, y2, &plotter, (void*)&(pen->pattern)); /*Moving and correcting cursors location after plot*/ calculatePosition(&newPos, &startPos, distance, pen->angle); pen->position.pos[0] = rounds(newPos.pos[0]); pen->position.pos[1] = rounds(newPos.pos[1]); pen->realPos = newPos; /*if the cursor has moved to far away from its real position it is realigned*/ realign(&pen->realPos, &pen->position); /*LOGGING---------------------------------------------------------------*/ formatLog(logEntry, DRAW, &startPos, &newPos); tlog(logEntry); /*TurtleGraphicsDebug*/ #ifdef DEBUG penDown(); fprintf(stderr,"%s",logEntry); #endif return 0; } /***************************************************************************** * STATIC FUNCTION: colourFG *----------------------------------------------------------------------------- * IMPORTS: * pen(Pen*) ~ Pen struct tracks data for line() function. * command(GCommand*) ~ GCommand struct contains the command data. * * EXPORTS: * '0' ~ status. * * PURPOSE: * Sets the pen FG field to the command data and calls setFgColour() * * NOTES: * This function has no effect in TurtleGraphicSimple. *****************************************************************************/ static int colourFG(Pen *pen, GCommand *command) { /*SKIPS IN TurtleGraphicsSimple*/ #ifndef SIMPLE pen->fg = *(int*)(command->data); setFgColour(pen->fg); #endif return 0; } /***************************************************************************** * STATIC FUNCTION: colourBG *----------------------------------------------------------------------------- * IMPORTS: * pen(Pen*) ~ Pen struct tracks data for line() function. * command(GCommand*) ~ GCommand struct contains the command data. * * EXPORTS: * '0' ~ status. * * PURPOSE: * Sets the pen FG field to the command data and calls setBgColour() * * NOTES: * This function has no effect in TurtleGraphicSimple. *****************************************************************************/ static int colourBG(Pen *pen, GCommand *command) { /*SKIPS IN TurtleGraphicsSimple*/ #ifndef SIMPLE pen->bg = *(int*)(command->data); setBgColour(pen->bg); #endif return 0; } /***************************************************************************** * STATIC FUNCTION: changePattern *----------------------------------------------------------------------------- * IMPORTS: * pen(Pen*) ~ Pen struct tracks data for line() function. * command(GCommand*) ~ GCommand struct contains the command data. * * EXPORTS: * '0' ~ status. * * PURPOSE: * Sets the pen field 'pattern' the command data * *****************************************************************************/ static int changePattern(Pen *pen, GCommand *command) { pen->pattern = *(char*)(command->data); return 0; } /***************************************************************************** * FUNCTION: plotter *----------------------------------------------------------------------------- * IMPORTS: * plotData(void*) ~ A void pointer to a char that will be printed. * * EXPORTS: * none * * PURPOSE: * Prints a single character to the terminal (Will be used as a call back * function in effects.c). * * NOTES: * plotData is void to allow any data to be passed through to a PLOTTER func. *****************************************************************************/ void plotter(void *plotData) { printf("%c", *(char*)plotData); } /***************************************************************************** * STATIC FUNCTION: allocateDouble *----------------------------------------------------------------------------- * IMPORTS: * data(char*) ~ A String containing data for the GCommand Struct. * gCommand(GCommand*) ~ The GCommand struct. * * EXPORTS: * status(int) ~ Number representing the ERROR codes. * * PURPOSE: * Allocates enough space on the heap to hold the data for the * GCommand Struct and reads the data into that space. * * ERROR CODES: * 0 = No errors. * 1 = Invalid data. * * NOTES: * - 'data' should point to a string containing a single double value. * - I've chosen not to validate for very large numbers. I dont see it being * a big problem from the tests ive run. *****************************************************************************/ static int allocateDouble(char *data, GCommand *gCommand) { int status = 0; gCommand->data = malloc(sizeof(double)); if((sscanf(data,"%lf",(double*)gCommand->data)) == 0) { /*If no items are scanned the data is invalid*/ status = 1; } return status; } /***************************************************************************** * STATIC FUNCTION: allocateInt *----------------------------------------------------------------------------- * IMPORTS: * data(char*) ~ A String containing data for the GCommand Struct * gCommand(GCommand*) ~ The GCommand struct * * EXPORTS: * status(int) ~ Number representing the ERROR codes. * * PURPOSE: * Allocates enough space on the heap to hold the data for the * GCommand Struct and reads the data into that space. * * ERROR CODES: * 0 = No errors. * 1 = Invalid data. * * NOTES: * - 'data' should point to a String containing a single int value. * - I've chosen not to validate for very large numbers. I dont see it being a * a big problem from the tests ive run. *****************************************************************************/ static int allocateInt(char *data, GCommand *gCommand) { int status = 0; gCommand->data = malloc(sizeof(int)); if((sscanf(data,"%d",(int*)gCommand->data)) == 0) { /*If no items are scanned the data is invalid*/ status = 1; } return status; } /***************************************************************************** * STATIC FUNCTION: allocateChar *----------------------------------------------------------------------------- * IMPORTS: * data(char*) ~ A String containing data for the GCommand Struct * gCommand(GCommand*) ~ The GCommand struct * * EXPORTS: * status(int) ~ Number representing the ERROR codes. * * PURPOSE: * Allocates enough space on the heap to hold the data for the * GCommand Struct and reads the data into that space. * * ERROR CODES: * 0 = No errors. * 1 = Invalid data. * * NOTES: * - 'data' should point to a single char. *****************************************************************************/ static int allocateChar(char *data, GCommand *gCommand) { int status = 0; gCommand->data = malloc(sizeof(char)); if(sscanf(data,"%c",(char*)gCommand->data) == 0) { /*If no items are scanned the data is invalid*/ status = 1; } return status; } /***************************************************************************** * FUNCTION: freeCommand *----------------------------------------------------------------------------- * IMPORTS: * gCommand(void*) ~ Graphics Command to be freed * * EXPORTS: * status(int) ~ Number representing the error code. * * PURPOSE: * Frees heap memory from 'data' then frees the gCommand from the heap * * NOTES: * The function takes in a void pointer so that is matches FreeFunc data * type used by the generic LinkedList struct. *****************************************************************************/ void freeCommand(void *gCommand) { free(((GCommand*)gCommand)->data); free(((GCommand*)gCommand)); }